java 使用 GZIP、JSON 响应和 JQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/706412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 13:27:20  来源:igfitidea点击:

Use GZIP, JSON responses and JQuery

javajqueryjsonjspgzip

提问by Sergio del Amo

However, I want to compress my responses with GZIP wheren possible. I tried using the Compression filter codeavailable for free download in the headfirst site. It works great for html, images, css and javascript.

但是,我想尽可能使用 GZIP 压缩我的响应。我尝试使用headfirst 站点中可免费下载的压缩过滤器代码。它适用于 html、图像、css 和 javascript。

I post the filter next. It checks if GZIP is an accepted encoding and it adds gzip as Content-Encoding. See: wrappedResp.setHeader("Content-Encoding", "gzip");

我接下来发布过滤器。它检查 GZIP 是否是可接受的编码,并将 gzip 添加为内容编码。看:wrappedResp.setHeader("Content-Encoding", "gzip");

public class CompressionFilter implements Filter {

  private ServletContext ctx;
  private FilterConfig cfg;

    /**
     * The init method saves the config object and a quick reference to the
     * servlet context object (for logging purposes).
     */
  public void init(FilterConfig cfg) 
     throws ServletException {
    this.cfg = cfg;
    ctx = cfg.getServletContext();
    //ctx.log(cfg.getFilterName() + " initialized.");
  }

        /**
         * The heart of this filter wraps the response object with a Decorator
         * that wraps the output stream with a compression I/O stream.
         * Compression of the output stream is only performed if and only if
         * the client includes an Accept-Encoding header (specifically, for gzip).
         */
      public void doFilter(ServletRequest req,
                   ServletResponse resp,
                   FilterChain fc)
         throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        // Dose the client accept GZIP compression?
        String valid_encodings = request.getHeader("Accept-Encoding");
        if ( (valid_encodings != null) && (valid_encodings.indexOf("gzip") > -1) ) {

          // Then wrap the response object with a compression wrapper
          // We'll look at this class in a minute.
          CompressionResponseWrapper wrappedResp = new CompressionResponseWrapper(response);

          // Declare that the response content is being GZIP encoded.
          wrappedResp.setHeader("Content-Encoding", "gzip");

          // Chain to the next component (thus processing the request)
          fc.doFilter(request, wrappedResp);

          // A GZIP compression stream must be "finished" which also
          // flushes the GZIP stream buffer which sends all of its
          // data to the original response stream.
          GZIPOutputStream gzos = wrappedResp.getGZIPOutputStream();
          gzos.finish();
          // The container handles the rest of the work.

          //ctx.log(cfg.getFilterName() + ": finished the request.");

        } else {
          fc.doFilter(request, response);
          //ctx.log(cfg.getFilterName() + ": no encoding performed.");
        }   
      }

      public void destroy() {
          // nulling out my instance variables
          cfg = null;
          ctx = null;
      }
    }

I was using the next code to send JSON responses in Struts web application.

我正在使用下一个代码在 Struts Web 应用程序中发送 JSON 响应。

public ActionForward get(ActionMapping mapping,
    ActionForm     form,
    HttpServletRequest request,
    HttpServletResponse response) {
       JSONObject json = // Do some logic here
       RequestUtils.populateWithJSON(response, json);
       return null;         
}

public static void populateWithJSON(HttpServletResponse response,JSONObject json) {
    if(json!=null) {
        response.setContentType("text/x-json;charset=UTF-8");       
        response.setHeader("Cache-Control", "no-cache");
        try {
             response.getWriter().write(json.toString());
        } catch (IOException e) {
            throw new ApplicationException("IOException in populateWithJSON", e);
        }               
    }
 }

It works fine without compression but if I compress JSON responses, I can not see my JSON objects anymore. I handle JSON Ajax calls with JQuery with code snippets as follows:

它在没有压缩的情况下工作正常,但如果我压缩 JSON 响应,我就看不到我的 JSON 对象了。我使用 JQuery 处理 JSON Ajax 调用,代码片段如下:

    $.post(url,parameters, function(json) {
    // Do some DOM manipulation with the data contained in the JSON Object
}, "json");

If I see the response with Firebug it is empty.

如果我看到 Firebug 的响应,它是空的。

Should I refractor my compression filter to skip compression in JSON responses? or there is a workaround to this?

我应该折射我的压缩过滤器以跳过 JSON 响应中的压缩吗?或者有解决方法吗?

For me, it looks like JQuery does not recognize the response as JSON because I am adding the Gzip compression.

对我来说,JQuery 似乎无法将响应识别为 JSON,因为我正在添加 Gzip 压缩。

回答by Will Dean

If I see the response with Firebug it is empty.

如果我看到 Firebug 的响应,它是空的。

There's your clue - it's not a JQuery problem, it's server-side. (I'm afraid I can't help you with that, other than to suggest you stop looking at the client-side)

这就是你的线索——这不是 JQuery 问题,而是服务器端的问题。(恐怕我帮不了你,除了建议你停止看客户端)

There's no problem gzipping ajax responses - if you can't see the response in Firebug, then JQuery can't see it either.

gzip ajax 响应没有问题 - 如果您在 Firebug 中看不到响应,那么 JQuery 也看不到它。

回答by Akash Kava

you have to add one more header "content-encoding: gzip" if you are compressing it.

如果要压缩它,则必须再添加一个标题“内容编码:gzip”。

回答by StaxMan

Have you tried with an explicit java-based client to ensure it's a problem with jQuery or browser? If java client fails, something is wrong with server response.

您是否尝试过使用基于 Java 的显式客户端来确保它是 jQuery 或浏览器的问题?如果 java 客户端失败,则服务器响应有问题。

But I am guessing that whereas browser can deal with uncompression with direct requests, this is perhaps not applied to Ajax calls.

但我猜测虽然浏览器可以处理直接请求的解压缩,但这可能不适用于 Ajax 调用。

It's an interesting question, I hope we'll get a more definitive answer. :)

这是一个有趣的问题,我希望我们能得到一个更明确的答案。:)