我尝试从tomcat 6迁移到tomcat 8。 我必须访问 org.apache.catalina.connector.Response cookies。
在tomcat 6中有一种方法可以做到这一点 getCookies()
在Tomcat 8中不推荐使用此方法。有什么建议吗?
答案 0 :(得分:0)
考虑这个过滤器:
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
public class CookieStoringFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
if(res instanceof HttpServletResponse) {
chain.doFilter(req, new CookieStoringResponse((HttpServletResponse)res));
} else {
chain.doFilter(req, res);
}
}
public void init(FilterConfig config) throws ServletException {
}
}
它会将响应包装成名为CookieStoringResponse:
的内容import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CookieStoringResponse extends HttpServletResponseWrapper {
protected List<Cookie> cookies;
public CookieStoringResponse(HttpServletResponse response) {
super(response);
}
public void addCookie(Cookie c) {
cookies.add(c);
super.addCookie(c);
}
public List<Cookie> getCookies() {
return cookies;
}
}
安装此过滤器后(在web.xml中)
<filter>
<filter-name>cookieFilter</filter-name>
<filter-class>CookieStoringFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cookieFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
然后,您可以检查响应是否属于cookie计数类型,然后检索添加的Cookie列表:
public void doGet(HttpServetRequest req, HttpServletResponse res) {
if(res instanceof CookieStoringResponse)) {
System.out.println("I have " + ((CookieStoringResponse)res).getCookies().size() + " cookies stored");
}
}
请记住,Cookie也可以通过Header-Values设置 - 所以这可能只是一个起点。