小编典典

response.setContentType()在Java过滤器中重置

java

我试图在过滤器中将压缩文件的内容类型设置为正确的mime类型,而不是application / gzip。这是我的一些代码:

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,  FilterChain filterChain) throws IOException, ServletException
{
    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;

    String reqUrl = request.getRequestURI();
    if (reqUrl.endsWith(gzExt))
    {
        response.setHeader("Content-Encoding", "gzip");
        response.setContentType("text/javascript");

        System.out.println("Set header " +reqUrl +", " + response.getContentType() );

        filterChain.doFilter(request, response);

        System.out.println("Header now: " + reqUrl + ", " + response.getContentType() );
        return;
    }
}

输出:

Set header /test.js.gz, text/javascript
Header now: /test.js.gz, application/x-gzip

在浏览器中,我看到content-encoding正确设置为gzip,但content- type仍为application/x-gzip。似乎filterChain.doFilter()正在重置内容类型。

知道如何永久重置内容类型吗?

我没有其他过滤器。


阅读 624

收藏
2020-11-30

共1个答案

小编典典

我借助以下答案解决了它:

private class ForcableContentTypeWrapper extends HttpServletResponseWrapper
{
    public ForcableContentTypeWrapper(HttpServletResponse response)
    {
        super(response);
    }

    @Override
    public void setContentType(String type)
    {
    }
    public void forceContentType(String type)
    {
        super.setContentType(type);
    }
}

然后将我上面的代码更改为:

    if (reqUrl.endsWith(gzExt))
    {
        ForcableContentTypeWrapper newResponse = new ForcableContentTypeWrapper(response);
        newResponse.setHeader("Content-Encoding", "gzip");
        newResponse.forceContentType("text/javascript");
        filterChain.doFilter(request, newResponse);
        return;
    }

它不是一个很好的解决方法,但它可以工作。

2020-11-30