Is there any way to read cookies from the response object in Java?

Viewed 35947

It doesn't seem that HttpServletResponse exposes any methods to do this.

Right now, I'm adding a bunch of logging code to a crufty and ill-understood servlet, in an attempt to figure out what exactly it does. I know that it sets a bunch of cookies, but I don't know when, why, or what. It would be nice to just log all the cookies in the HttpServletResponse object at the end of the servlet's execution.

I know that cookies are typically the browser's responsibility, and I remember that there was no way to do this in .NET. Just hoping that Java may be different...

But if this isn't possible -- any other ideas for how to accomplish what I'm trying to do?

Thanks, as always.

4 Answers

Cookies are sent to the client in the "Set-Cookie" response header. Try this:

private static void logResponseHeaders(HttpServletResponse httpServletResponse) {

    Collection<String> headerNames = httpServletResponse.getHeaderNames();

    for (String headerName : headerNames) {
        if (headerName.equals("Set-Cookie")) {
            log.info("Response header name={}, header value={}", headerName, httpServletResponse.getHeader(headerName));
        }
    }
}
Related