Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to gzip ajax requests with Struts 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.

like image 612
kaneda Avatar asked Dec 17 '22 22:12

kaneda


2 Answers

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

like image 69
BalusC Avatar answered Dec 27 '22 21:12

BalusC


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.

like image 45
Dinesh Avatar answered Dec 27 '22 23:12

Dinesh