开发者

How to gzip ajax requests with Struts 2?

How to gzip an ajax response with S开发者_如何学运维truts2? 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜