[英]Log only http servlet response headers
This is a question related to Capture and log the response body . 这是与Capture相关的问题并记录响应正文 。 What if I only want to log the response headers, and not the entire body?
如果我只想记录响应头而不是整个身体怎么办? Is there a different approach than described in the linked question?
是否有与链接问题中描述的方法不同的方法?
You'd like to override the HttpServletResponse#addHeader()
and HttpServletResponse#setHeader()
method instead. 您想要覆盖
HttpServletResponse#addHeader()
和HttpServletResponse#setHeader()
方法。
public void doFilter(ServletRequest request, final ServletResponse response, FilterChain chain) throws IOException, ServletException {
final Map<String, List<String>> headers = new HashMap<String, List<String>>();
chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {
@Override public void setHeader(String name, String value) {
List<String> values = new ArrayList<String>();
values.add(value);
headers.put(name, values);
super.setHeader(name, value);
}
@Override public void addHeader(String name, String value) {
List<String> values = headers.get(name);
if (values == null) {
values = new ArrayList<String>();
headers.put(name, values);
}
values.add(value);
super.addHeader(name, value);
}
});
logger.log(headers);
}
There are indeed more methods which sets the headers, but in a bit decent servletcontainer implementation they all delegate to this one method (I've verified it in both Tomcat and Glassfish). 确实有更多的方法来设置标题,但是在一个不错的servletcontainer实现中,它们都委托给这个方法(我已经在Tomcat和Glassfish中验证了它)。
Alternatively, you can also make use of servletcontainer specific logging capabilities. 或者,您也可以使用servletcontainer特定的日志记录功能。 Tomcat for example seems to support logging of response headers by a valve .
例如,Tomcat似乎支持通过阀门记录响应头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.