Tag Archives: Accept-Encoding

How to gzip ajax requests with Struts 2?

You shouldn’t randomly gzip responses. You can only gzip the response when the client has notified the server that it accepts (understands) gzipped responses. You can do that by determining if the Accept-Encoding request header contains gzip. If it is there, then you can safely wrap the OutputStreamof the response in a GZIPOutputStream. You only need to add the Content-Encoding header beforehand with a value of gzip to inform the client what encoding the content is been sent in, so that the client knows that it needs to ungzip it.

In a nutshell:

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
OutputStream output = response.getOutputStream();

String acceptEncoding = request.getHeader("Accept-Encoding");
if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
    response.setHeader("Content-Encoding", "gzip");
    output = new GZIPOutputStream(output);
}

output.write(json.getBytes("UTF-8"));

(note that you would like to set the content type and character encoding as well, this is taken into account in the example)

You could also configure this at appserver level. Since it’s unclear which one you’re using, here’s just a Tomcat-targeted example: check the compression and compressableMimeType attributes of the<Connector> element in /conf/server.xmlHTTP connector reference. This way you can just write to the response without worrying about gzipping it.

original:http://stackoverflow.com/questions/3631676/how-to-gzip-ajax-requests-with-struts-2