Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This is a question related to Capture and log the response body. 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
217 views
Welcome To Ask or Share your Answers For Others

1 Answer

You'd like to override the HttpServletResponse#addHeader() and HttpServletResponse#setHeader() method instead.

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).

Alternatively, you can also make use of servletcontainer specific logging capabilities. Tomcat for example seems to support logging of response headers by a valve.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...