HTTP/2 in Jetty

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

1. Overview

The HTTP/2 protocol comes with a push feature that allows the server to send multiple resources to the client for a single request. Hence, it improves the loading time of the page by reducing the multiple round-trips needed to fetch all the resources.

Jetty supports the HTTP/2 protocol for both client and server implementations.

In this tutorial, we'll explore HTTP/2 support in Jetty and create a Java web application to examine the HTTP/2 Push feature.

2. Getting Started

2.1. Downloading Jetty

Jetty requires JDK 8 or later and ALPN (Application-Layer Protocol Negotiation) support for running HTTP/2.

Typically, the Jetty server is deployed over SSL and enables the HTTP/2 protocol via the TLS extension (ALPN).

First, we'll need to download the latest Jetty distribution and set the JETTY_HOME variable.

2.2. Enabling the HTTP/2 Connector

Next, we can use a Java command to enable the HTTP/2 connector on the Jetty server:

java -jar $JETTY_HOME/start.jar --add-to-start=http2

This command adds HTTP/2 protocol support to the SSL connector on port 8443. Also, it transitively enables the ALPN module for protocol negotiation:

Here, we can observe that port 8443 is configured with the HTTP/1.1 protocol and 8444 with HTTP/2.

3.3. Configure the PushCacheFilter

Next, we need a filter that pushes the secondary resources like images, JavaScript, and CSS to the client.

To do so, we can use the PushCacheFilter class available in the org.eclipse.jetty.servlets package. PushCacheFilter builds a cache of secondary resources associated with a primary resource like index.html and pushes them to the client.

Here, we observe that the protocol is h2, the initiator is Push, and the loading time is 1ms for all the images (secondary resources).

Therefore, the PushCacheFilter caches the secondary resources for http2.html, pushes them on port 8444, and provides a great improvement in the load time of the page.

6. Conclusion

In this tutorial, we've explored HTTP/2 in Jetty.

First, we examined how to start Jetty with the HTTP/2 protocol along with its configurations.

Then, we've seen a Java 8 web application with the HTTP/2 Push feature, configured with a PushCacheFilter, and observed how the load time of a page containing secondary resources improved over what we saw with the HTTP/1.1 protocol.