Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serve Gzipped content with Java Servlets

I was wondering if there was an easy way to serve GZipped content with Java Servlets. I already have the app up and running so the modifications needed should be too heavy.

I have access to the response object just at the end of the doPost/doGet method, so I'm looking for something like

response.setGzip(true);

It doesn't have to be that easy but it would be ideal.

Thanks a lot

like image 343
Pablo Fernandez Avatar asked Dec 07 '09 21:12

Pablo Fernandez


3 Answers

Depending on your container, the container will most likely do this for you. It may do it automatically, or you might need to manually configure it to do it for you. The advantage of this method is zero code changes. And, again, depending on container, you can conditionally enable/disable the compression based on where the request comes from or source browser.

For Tomcat, have a look at the compression attribute on the HTTP config pages (v5.5, v6.0).

like image 199
Paul Wagland Avatar answered Nov 10 '22 13:11

Paul Wagland


There are basically 2 ways:

  • Configure it in the appserver. In for example Tomcat you just need to set the compression attribute of the Connector in conf/server.xml to on.
  • Wrap the response.getOutputStream() in a new GzipOutputStream() and write to it instead.

The first way affects the whole webapp, but this really shouldn't hurt, it's almost zero effort and a big favour for performance. And, more importantingly, as opposed to the second way it actually checks the request headers if the client supports Gzip before using it. When you go for the 2nd way headlessly, then about 10% of the world wide web users wouldn't be able to access your webapplication. This is really not an oneliner task.

You can find here an advanced example of a FileServlet which supports under each Gzip and checks that based on the request headers. You may get new insights out of it.

like image 33
BalusC Avatar answered Nov 10 '22 13:11

BalusC


Look at GzipOutputStream class. Something like this:

response.setContentType(...)
GzipOutputStream os = new GzipOutputStream(response.getOutputStream);
//write to os
Writer writer = new PrintWriter(os);

Then use writer like you do usually.

like image 44
maximdim Avatar answered Nov 10 '22 13:11

maximdim