当前位置: 动力学知识库 > 问答 > 编程问答 >

servlets - Java EE Filters not able to get cookies?

问题描述:

Why aren't cookies able to be referenced from a servlet filter? It just seems beyond me that Java EE wouldn't allow you to sanitize cookie values:

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain)

throws ServletException, IOException {

request.

}

ServletRequest does not support getCookies (as is the case with HttpServletRequest).

网友答案:

In order to get the cookies you need to cast it to an HttpServletRequest.

HttpServletRequest httpReq = (HttpServletRequest) request;

The reason that ServletResponse class doesn't support cookies is because the protocol isn't necessarly http in a ServletRequest, you can't be sure there are Cookies. Cookies are an Http thing.

网友答案:

Servlets aren't required to be accessed via the HTTP protocol. Therefore, your servlet does not have to be an HttpServlet - it may be a servlet that sends out specific documents via FTP, for example. Because of this, the basic properties of a servlet are encapsulated in the ServletRequest and ServletResponse interfaces, but if you know that your servlet is an HTTPServlet, you may downcast these to HttpServletRequest and HttpServletResponse respectively with no chance of a ClassCastException as long as your Servlet is truly an HttpServlet.

网友答案:

You do know that you can actually cast it to HttpServletRequest, right? :-)

分享给朋友:
您可能感兴趣的文章:
随机阅读: