gpt4 book ai didi

java - response.setContentType() 在 Java Filter 中重置

转载 作者:太空宇宙 更新时间:2023-11-04 06:39:40 30 4
gpt4 key购买 nike

我试图在过滤器中将 gzip 压缩文件的内容类型设置为正确的 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()正在重置内容类型。

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

我没有任何其他过滤器。

最佳答案

我在 this answer 的帮助下解决了这个问题:

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;
}

这不是一个很好的解决方法,但它确实有效。

关于java - response.setContentType() 在 Java Filter 中重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24846178/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com