How to gzip ajax requests with struts 2?

How to gzip ajax answer with struts2? I tried to create a filter, but it did not work. On the client side, I am using jQuery and the ajax response that I expect is in json.

This is the code I used on the server:

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

I am redirecting the response to the dummy jsp page defined in struts.xml.

The reason I want to recover data is because I have to send the client a relatively large json size back.

Any link provided would be appreciated.

Thanks.

+4
source share
2 answers

You do not have to arbitrarily gzip answers. You can only gzip the response when the client has notified the server that it accepts (understands) gzipped responses. You can do this by determining if the header contains Accept-Encoding . If it is, you can safely wrap the OutputStream in a GZIPOutputStream . You only need to add a Content-Encoding header with a gzip value to tell the client which content encoding has been sent to, so that the client knows that it needs to deploy 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 also want to set the content type and character encoding, this is taken into account in the example)

You can also configure this at the application level. Since it is not clear which one you are using, here is an example of Tomcat-target: check the compression and compressableMimeType attributes of the <Connector> element in /conf/server.xml : Link to the HTTP connector . That way, you can simply write an answer without worrying about downloading it.

+6
source

If your answer is JSON, I would recommend using the struts2-json plugin http://struts.apache.org/2.1.8/docs/json-plugin.html and set the enableGZIP parameter to true.

+6
source

All Articles