基于“内容长度”的Servlet过滤器中的GZip HttpServletResponse

时间:2017-08-09 20:58:44

标签: servlets servlet-filters

我有一个特定的要求,根据内容长度压缩HttpServletResponse。我正在处理的应用程序是基于Spring的,并使用JSON有效负载公开了几个服务。然而,有些有效载荷的大小非常大~2MB,但并不一致,即依赖于外部系统的响应。

我尝试过搜索,但只能在基于URL映射的Zipping上成功,而不是基于有效负载的实际大小。使用的服务器是weblogic,但不支持GZIP配置,因此希望通过Servlet过滤器实现这一点。以下是我到目前为止的过滤器中的代码,但似乎没有工作。有关如何基于Content-Length实现动态GZipping的任何指针以及最佳方法是什么?

public void doFilter(ServletRequest paramServletRequest, ServletResponse paramServletResponse, FilterChain paramFilterChain) throws IOException, ServletException {
    if ((paramServletRequest instanceof HttpServletRequest)) {
        HttpServletRequest localHttpServletRequest = (HttpServletRequest) paramServletRequest;
        HttpServletResponse localHttpServletResponse = (HttpServletResponse) paramServletResponse;

        if (supportsGzip(localHttpServletRequest)) {
            // This block is where response is being validated for
            // eligibility of compression based on "Content-Length" header
            paramFilterChain.doFilter(paramServletRequest, localHttpServletResponse);
            String contentLengthString = localHttpServletResponse.getHeader("Content-Length");
            int contentLength = contentLengthString != null && !contentLengthString.isEmpty() ? Integer.parseInt(contentLengthString) : 0;

            //GZip only if the content length is greater than 750 KB 
            if (contentLength > (750*1024)) {
                System.out.println("This should be zipped content");
                localHttpServletResponse = new GZipResponseWrapper(localHttpServletResponse);
                localHttpServletResponse.addHeader("Content-Encoding", "gzip");
                ((GZipResponseWrapper)localHttpServletResponse).finishResponse();
                return;
            }
        }

        paramFilterChain.doFilter(paramServletRequest, paramServletResponse);
    }
}

论坛的新手,并提前为任何不正确的格式/结构道歉。

0 个答案:

没有答案