Setup Jetty GzipHandler programmatically

∥☆過路亽.° 提交于 2019-12-05 14:40:50
Sairam Krish

We could use GzipFilter and achieve this result. Jetty documentation of GzipFilter provides list of parameters supported with lot of details. To enable it programmatically, refer this question.

GzipFilter is basically a server side filter and is very efficient in handling compression needs.

Sample Filter configuration

<filter>
 <filter-name>GZipFilter</filter-name>
 <display-name>Jetty's GZip Filter</display-name>
 <description>Filter that zips all the content on-the-fly</description>
 <filter-class>org.mortbay.servlet.GzipFilter</filter-class>
 <init-param>
  <param-name>mimeTypes</param-name>
  <param-value>text/html</param-value>
 </init-param>
</filter>

<filter-mapping>
 <filter-name>GZipFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>

Here is how I configured the GzipHandler in Jetty 9.3.7:

GzipHandler gzipHandler = new GzipHandler();
gzipHandler.setIncludedMimeTypes("text/html", "text/plain", "text/xml", 
            "text/css", "application/javascript", "text/javascript");
gzipHandler.setHandler(myHandler);
handlerList.addHandler(gzipHandler);

In this case, myHandler was an instance of ResourceHandler. By default, the Gzip Handler only gzips responses to GET requests with a response code in the 200 range.

For the next person that comes along, here's how to enable request decompression, where handler is a class the extends org.eclipse.jetty.server.handler.AbstractHandler. The important parts for request decompression are includeMethods, which defaults to GET only, and the inflateBuffer, which needs to be > 0 but defaults to 0. The Code:

    //create server using given threadpool
    Server server = new Server(8080);

    GzipHandler gzipHandler = new GzipHandler();
    gzipHandler.setIncludedMethods("PUT", "POST", "GET");
    gzipHandler.setInflateBufferSize(2048);
    gzipHandler.setHandler(handler);
    server.setHandler(gzipHandler);

    server.start();
    server.join();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!