Servlet过滤器调用,但在Jetty上被忽略

时间:2014-08-10 18:59:42

标签: jetty servlet-filters

我无法在Jetty上运行这个非常基本的ServletFilter(目标是6.1.25,但我也尝试过8.1.10)。

我可以在日志中看到实际调用过滤器并且标题值设置没有错误,但它们不会出现在客户端,因此会忽略或覆盖这些值。

更奇怪的是,当另外设置GzipFilter时,过滤器工作并且标头值在客户端变得可见(仅适用于压缩请求)。

有人可以复制这个,或者告诉我我做错了什么?

这是过滤器:

public class AppCacheFilter implements Filter{

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    chain.doFilter(request, response);

    System.out.println("response: " + httpResponse);
    httpResponse.setHeader("Cache-Control", "max-age=2,public");
    httpResponse.setHeader("X-Powered-By", "X-Power");
    httpResponse.setHeader("Warning", "Whatever");
    System.out.println("response: " + httpResponse);

}

public void init(FilterConfig filterConfig) throws ServletException {}
public void destroy() {}
}

这是web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
  <filter>
    <filter-name>AppCacheFilter</filter-name>
    <display-name>AppCache Filter</display-name>
    <filter-class>de.socsoc.filter.AppCacheFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>AppCacheFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

1 个答案:

答案 0 :(得分:0)

httpResponse.setHeader()之前移动chain.doFilter(request, response)来电,如下所示:

HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;

System.out.println("response: " + httpResponse);
httpResponse.setHeader("Cache-Control", "max-age=2,public");
httpResponse.setHeader("X-Powered-By", "X-Power");
httpResponse.setHeader("Warning", "Whatever");
System.out.println("response: " + httpResponse);

chain.doFilter(request, response);

一般情况下,如果您已经在响应中写了一些内容,则不应添加标题。某些服务器会向您提供“已提交响应”错误消息,有些服务器可能会默默地忽略您添加的标头。通过在chain.doFilter()前面移动它,您可以确保没有内容写入响应,并且可以安全地设置标题。