Thursday, 27 September 2018

Introducing Servlet 4.0 Server Push

Posted by Naveen Katiyar On 06:32 No comments
In this article, We would be talking about Server Push Technology which was actually part of HTTP/2 spec.
Most important feature of Servlet 4.0 due to HTTP/2 is the implementation of the server push capability. The concept behind this technique is that if the client/browser requests a certain resource, the server assumes in advance, that some other related resources also may be requested  soon. Because of this assumption, it pushes them into cache(called 'cache push') before they are actually needed.For example, it is very much likely that when a Web page is loaded, it may eventually request a CSS file or some image. The server proactively starts pushing the bytes of these assets simultaneously without the need for the client to make an explicit request.

Servlet 4.0 Server Push

Servlet 4.0 is part of JAVA EE 8 and hence it would require JAVA 9+ along with Spring 5.x. Tomcat 9 supports HTTP/2 but it must be configured to use TLS. Tomcat 9 would be available only in Spring Boot 2.1.0  but it has not released yet and hence we would be using milestone version in our article.

Enable TLS support in Spring boot is just a matter of few properties in application.properties.Just use below ones to enable it:

#enable/diable https
server.ssl.enabled=true
server.ssl.key-store: classpath:keystore.jks
server.ssl.key-store-password: tomcatssl
server.ssl.keyStoreType: JKS
server.ssl.keyAlias: tomcatssl
server.port=8443

In case, you are not aware of how to generate keystore.jks, please follow this link

To enable http2 support in tomcat, below property needs to be added.
server.http2.enabled=true


After configuring our Server with TLS, we are good to go for exposing our endpoint which would be powered by HTTP/2 Push Technology.

@GetMapping(path = "/serviceWithPush")
public String serviceWithPush(HttpServletRequest request,PushBuilder pushBuilder) {
if (null != pushBuilder) {
    pushBuilder.path("resources/OnlineJavaPapers.png")
       .push();
}
return "index";
}

We will also configure another endpoint similar to above which would basically use traditional pull technology and will try to figure out the difference on client browser.

@GetMapping(path = "/serviceWithoutPush")
    public String serviceWithoutPush() {
       return "index";
    }

Using firefox devtool we can confirm that for serviceWithPush endpoint only one request was initiated from broswer:


Whereas when we call serviceWithoutPush then there would be two requests which would be triggered.


To conclude, Server Push technology combined with proper caching technique, we can greatly enhance page load time and responsiveness of our website.

Sample code for this can be found here.

0 comments: