Search code examples
javaembeddedjettyhttp2

How to enable http/2 on an embedded Jetty 10?


I try to enable http/2 on my Jetty 10.0.11 without luck. I use the follow code to create the ServerConnector:

HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setSendServerVersion( false );
httpConfig.setSendXPoweredBy( false );
HttpConnectionFactory http1 = new HttpConnectionFactory( httpConfig );

httpConfig.addCustomizer( new SecureRequestCustomizer( false ) ); // for https://localhost

SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
// ... load the certificate
sslContextFactory.setCipherComparator( HTTP2Cipher.COMPARATOR );

Thread.currentThread().setContextClassLoader( getClass().getClassLoader() ); // for service worker
//HTTP2CServerConnectionFactory http2 = new HTTP2CServerConnectionFactory( httpConfig );
HTTP2ServerConnectionFactory http2 = new HTTP2ServerConnectionFactory( httpConfig );
ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory();
alpn.setDefaultProtocol( http1.getProtocol() );
SslConnectionFactory ssl = new SslConnectionFactory( sslContextFactory, alpn.getProtocol() );

ServerConnector connector = new ServerConnector( this, acceptors, selectors, ssl, alpn, http2, http1 );

connector.setReuseAddress( false );
connector.setPort( port );
connector.setAcceptQueueSize( MAX_CONCURRENT_REQUESTS.get().intValue() );

I have add the follow additional libraries for http/2:

  • org.eclipse.jetty.http2:http2-server
  • org.eclipse.jetty.http2:http2-common
  • org.eclipse.jetty.http2:http2-hpack
  • org.eclipse.jetty:jetty-alpn-server
  • org.eclipse.jetty:jetty-alpn-java-server

If I try it with https://localhost the browser (Chrome) is using ever http/1.1.

  • Does http/2 does not work with localhost?
  • Does I need to add more libraries? Which?
  • What is wrong on my code?
  • Must I change some things on my servlets?

Solution

  • You don't need to re-wrap the ConnectionFactorys using AbstractConnectionFactory.getFactories(...).

    See this section of the documentation to setup HTTP/2 over TLS.

    Make sure the KeyStore contains a valid certificate, even if it is self-signed.

    You can also try to run (from your IDE) this example.