views:

456

answers:

3

Why aren't cookies able to be referenced from a servlet filter? It just seems beyond me that J2EE 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).

+2  A: 

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

ChssPly76
+4  A: 

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.

jjnguy
+3  A: 

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.

MetroidFan2002