我在从我的Java Servlet返回压缩响应(GZip)到JSP时遇到问题。
I am having trouble in returning compressed response (GZip) from my Java Servlet, to a JSP.
流程:
注意事项:
结果:
任何人都可以帮助我指出正确的方向。
Can anyone help point me out, in the right direction please?
推荐答案
压缩的响应字符串在请求对象中设置为属性,控制权传递给JSP
您不应该将JSON响应转发到JSP。您应该将JSON纯文字打印到响应中,并在JSP Android应用中使用 JavaScript / Ajax代码调用返回JSON的servlet的网址。另请参见如何使用Servlet和Ajax?。
You shouldn't have forwarded a JSON response to a JSP. You should have printed the JSON plain to the response and have the JavaScript/Ajax code in your JSP Android app to call the URL of the servlet which returns the JSON. See also How to use Servlets and Ajax?.
至于GZIP压缩,你不应该自己做。让服务器自己做。
As to the GZIP compression, you shouldn't do it yourself. Let the server do itself.
修复您的代码以删除所有手动尝试压缩响应,它应该最终基本上看起来像这样:
Fix your code to remove all manual attempts to compress the response, it should end up to basically look like this:
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String json = createItSomehow(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); }最后编辑服务器配置以启用自动GZIP压缩。在例如Tomcat的情况下,这将是 compression =on < Connector> server.xml file:
That's all, if you let your Android app call the URL of the servlet, it'll retrieve the JSON string.
Finally edit the server configuration to turn on automatic GZIP compression. In case of for example Tomcat, that would be a matter of adding compression="on" to the <Connector> element in Tomcat's /conf/server.xml file:根据文档,可压缩mime类型默认为 text / html,text / xml,text / plain 。您可以将此配置为添加 application / json 。
<Connector ... compression="on">
As per the documentation, the compressable mime types defaults to text/html,text/xml,text/plain. You can configure this to add application/json.
无关具体问题,响应字符编码必须设置为 UTF-8 ,这是根据JSON规范。
Unrelated to the concrete problem, the response character encoding must be set to UTF-8 which is as per the JSON specification.
更多推荐
无法压缩发送到JSP的Java服务器响应
发布评论