views:

132

answers:

2

How to gzip an ajax response with Struts2? I tried to create a filter but it didn't work. At client-side I'm using jQuery and the ajax response I'm expecting is in json.

This is the code I used on server:

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gz = new GZIPOutputStream(out);
    gz.write(json.getBytes());
    gz.close();

I'm redirecting the response to dummy jsp page defined at struts.xml.

The reason why I want to gzip the data back is because there's a situation where I must send a relatively big sized json back to the client.

Any reference provided will be appreciated.

Thanks.

+4  A: 

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 OutputStream of 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 nut:

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

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

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

(note that you would like to set the content type and character encoding as well)

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.xml: HTTP connector reference. This way you can just write to the response without worrying about gzipping it.

BalusC
A: 

If your response is JSON I would recommend using the struts2-json plugin http://struts.apache.org/2.1.8/docs/json-plugin.html and setting the enableGZIP param to true.

Dinesh