有没有办法从 Java 的响应对象中读取 cookie?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3507477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:23:59  来源:igfitidea点击:

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

javacookiesresponseservlets

提问by sangfroid

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

HttpServletResponse 似乎没有公开任何方法来做到这一点。

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.

现在,我正在向一个粗俗且难以理解的 servlet 添加一堆日志记录代码,试图弄清楚它到底做了什么。我知道它设置了一堆 cookie,但我不知道何时、为什么或什么。最好在 servlet 执行结束时将所有 cookie 记录在 HttpServletResponse 对象中。

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

我知道 cookie 通常是浏览器的责任,我记得在 .NET 中没有办法做到这一点。只是希望Java可能会有所不同......

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

但如果这是不可能的 - 关于如何完成我正在尝试做的事情的任何其他想法?

Thanks, as always.

谢谢,一如既往。

回答by Dean Povey

Your only approach is to wrap the HttpServletResponse object so that the addCookie methods can intercept and log when cookies are set. You can do this by adding a ServletFilter which wraps the existing HttpServletResponse before it is passed into your Servlet.

您唯一的方法是包装 HttpServletResponse 对象,以便 addCookie 方法可以在设置 cookie 时拦截和记录。您可以通过添加一个 ServletFilter 来完成此操作,该过滤器在将现有 HttpServletResponse 传递到您的 Servlet 之前对其进行包装。

回答by skaffman

If logging is all you're after, then I suggest writing an implemention of javax.servlet.Filterwhich wraps the supplied HttpServletResponsein a wrapper which allows you to expose the cookies after the filter executes. Something like this:

如果您只需要记录日志,那么我建议编写一个实现javax.servlet.Filter,将所提供HttpServletResponse的内容包装在一个包装器中,这样您就可以在过滤器执行后公开 cookie。像这样的东西:

public class CookieLoggingFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException ,ServletException {
        ResponseWrapper wrappedResponse = new ResponseWrapper((HttpServletResponse) response);

        filterChain.doFilter(request, wrappedResponse);

        // use a real logger here, naturally :)
        System.out.println("Cookies: " + wrappedResponse.cookies); 
    }

    private class ResponseWrapper extends HttpServletResponseWrapper {

        private Collection<Cookie> cookies = new ArrayList<Cookie>();

        public ResponseWrapper(HttpServletResponse response) {
            super(response);
        }

        @Override
        public void addCookie(Cookie cookie) {
            super.addCookie(cookie);
            cookies.add(cookie);
        }
    }

       // other methods here
}

One big caveat: This will notshow you what cookies are sent back to the browser, it will only show you which cookies the application code added to the response. If the container chooses to change, add to, or ignore those cookies (e.g. session cookies are handled by the container, not the application), you won't know using this approach. But that may not matter for your situation.

一个重要的警告:这不会向您显示哪些 cookie 被发送回浏览器,它只会向您显示应用程序代码添加到响应中的哪些 cookie。如果容器选择更改、添加或忽略这些 cookie(例如会话 cookie 由容器处理,而不是由应用程序处理),您将不会知道使用这种方法。但这对您的情况可能无关紧要。

The only way to be sure is to use a browser plugin like Live Http Headers for Firefox, or a man-in-the-middle HTTP logging proxy.

唯一可以确定的方法是使用浏览器插件,例如Live Http Headers for Firefox或中间人 HTTP 日志记录代理。

回答by acohen

I had the same problem where I was using a 3rd party library which accepts an HttpServletResponse and I needed to read back the cookies that it set on my response object. To solve that I created an HttpServletResponseWrapper extension which exposes these cookies for me after I make the call:

我在使用接受 HttpServletResponse 的第 3 方库时遇到了同样的问题,我需要读回它在我的响应对象上设置的 cookie。为了解决这个问题,我创建了一个 HttpServletResponseWrapper 扩展,它在我拨打电话后为我公开这些 cookie:

public class CookieAwareHttpServletResponse extends HttpServletResponseWrapper {

    private List<Cookie> cookies = new ArrayList<Cookie>();

    public CookieAwareHttpServletResponse (HttpServletResponse aResponse) {
        super (aResponse);
    }

    @Override
    public void addCookie (Cookie aCookie) {
        cookies.add (aCookie);
        super.addCookie(aCookie);
    }

    public List<Cookie> getCookies () {
        return Collections.unmodifiableList (cookies);
    }

} 

And the way I use it:

以及我使用它的方式:

// wrap the response object
CookieAwareHttpServletResponse response = new CookieAwareHttpServletResponse(aResponse);

// make the call to the 3rd party library 
String order = orderService.getOrder (aRequest, response, String.class);

// get the list of cookies set
List<Cookie> cookies = response.getCookies();

回答by user674669

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

Cookie 在“Set-Cookie”响应头中发送到客户端。尝试这个:

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));
        }
    }
}