Enabling GZip compression of static content

Compressing a response is a simple way to make web applications faster. All modern browsers support GZip compression. Instead of sending the full static content file, a compressed file can be sent as a response. The browser will decompress and use the static content.

The browser can specify that it can accept the compressed content with a request header. If the server supports it, it can deliver the compressed content--again, marked with a response header.

Request Header sent from browser is as follows:

Accept-Encoding: gzip, deflate

Response Header sent from the web application is as follows:

Content-Encoding: gzip

The following snippet shows how to add a Gzip resolver to deliver compressed static content:

    registry 
.addResourceHandler("/resources/**")
.addResourceLocations("/static-resources/")
.setCachePeriod(365 * 24 * 60 * 60)
.resourceChain(true)
.addResolver(new GzipResourceResolver())
.addResolver(new PathResourceResolver());

Things to note are as follows:

  • resourceChain(true): We would want to enable Gzip compression, but would want to fall back to delivering the full file if full file was requested. So, we use resource chaining (chaining of resource resolvers).
  • addResolver(new PathResourceResolver()): PathResourceResolver: This is the default resolver. It resolves based on the resource handlers and locations configured.
  • addResolver(new GzipResourceResolver()): GzipResourceResolver: This enables Gzip compression when requested.