我试图从tomcat 6迁移到tomcat 8.我必须访问org.apache.catalina.connector.Response cookie。
在tomcat 6中有一个方法来做getCookies()
这个方法在Tomcat 8中被弃用了。有什么build议吗?
考虑这个过滤器:
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"); } }
记住Cookies也可以通过标题值设置 – 所以这可能只是一个起点。