这是我的过滤器:
public class SimpleFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
// where is the httpResponse.getHeaderNames()?
chain.doFilter(request, response);
}
@Override
public void destroy() {}
}
我使用的是Servlet 2.5 。
我可以设置标头,验证响应中是否存在某个标头,但我无法获取所有标头。在HttpServletRequest中,此方法存在(httpServletRequest.getHeaderNames()
)。
那么,HttpServletResponse中的getHeaderNames()
等价于哪里?
谢谢!
答案 0 :(得分:0)
这真的很奇怪......似乎2.5 api中没有这个访问器(参见javadoc here)
作为一种解决方法,您可以使用过滤器将响应包装在具有getter的包装器中(确保包装器过滤器先运行)。
例如
public class MyResponseWrapper extends HttpServletResponseWrapper {
private Set<String> headerNames = new HashSet<String>();
public MyResponseWrapper(HttpServletResponse delegate) {
super(delegate);
}
public void addHeader(String name, String value) {
super.addHeader(name, value);
headerNames.add(name);
}
public Set<String> getHeaderNames() {
return Collections.immutableSet(headerNames);
}
}
public class WrapperFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, new MyResponseWrapper(response));
}
}
然后你可以在更远的地方呼叫((MyResponseWrapper) response).getHeaderNames()
。我意识到这有点儿hacky:)