【问题标题】:Optimize performance :Passing large JSON from Servlet to JSP优化性能:将大型 JSON 从 Servlet 传递到 JSP
【发布时间】:2014-06-05 09:41:35
【问题描述】:

我必须将一个由 json 对象组成的 json 数组从 servlet 传递到 jsp 页面。这种数据传输会减慢页面响应速度。在将大型 json 从 servlet 传递到 jsp 时,有什么方法可以优化性能。

代码如下:

    request.setAttribute("jsonStringForDataTable", jsonArrayForDataTable);
    response.setContentType("text/plain");             
    response.setContentLength(jsonArrayForDataTable.toString().getBytes().length);
    ServletOutputStream out=response.getOutputStream();
    out.print(jsonArrayForDataTable.toString().replace('_',' '));
    out.close();
...

非常感谢任何帮助

【问题讨论】:

    标签: json performance jsp servlets


    【解决方案1】:

    您使用的是 ajax,对吗?很难说,因为您正在设置该请求属性,就好像要转发到一个 jsp 一样,但是您正在直接写入响应。如果这是 ajax,如果客户端接受,您可以使用 gzip 压缩响应。您必须尝试一下才能知道它是否会在您的情况下加快速度。您将通过取决于原始内容的比例减少响应的大小,但您将增加服务器(以及必须解压缩响应的客户端)上的处理器工作量。

    ServletOutputStream out = response.getOutputStream();
    response.setContentType("application/json");
    String strVal = jsonArrayForDataTable.toString().replace('_',''));
    
    if (request.getHeader("Accept-Encoding") != null && request.getHeader("Accept-Encoding").contains("gzip"))
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(strVal.length());
        GZipOutputStream gzip = new GZIPOutputStream(baos);
        gzip.write(strVal.getBytes());
        gzip.close();
    
        response.setHeader("Content-Encoding", "gzip");
        out.write(baos.toByteArray());
        baos.close();
    }
    else
    {
        out.print(strVal);
    }
    

    在客户端,您必须通过将Accept-Encoding XMLHttpRequest 标头设置为gzip 来为压缩响应做好准备。浏览器会解压成json字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-25
      • 2012-05-03
      • 2011-05-20
      • 2013-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多