cookie java 对象,有什么方法从Java中的响应对象读取Cookie吗?

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.

解决方案

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

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 cookies = new ArrayList();

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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值