Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 536
Zombies Avatar asked Jul 23 '09 18:07

Zombies


People also ask

How do you declare cookies in Java?

Java Cookie Example You can write cookies using the HttpServletResponse object like this: Cookie cookie = new Cookie("myCookie", "myCookieValue"); response. addCookie(cookie); As you can see, the cookie is identified by a name, " myCookie ", and has a value, " myCookieValue ".

Which method would you use to get the cookies from the response object?

public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser.

What is filter in Java EE?

public interface Filter. A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both.


3 Answers

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.

like image 76
jjnguy Avatar answered Sep 21 '22 13:09

jjnguy


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.

like image 28
MetroidFan2002 Avatar answered Sep 20 '22 13:09

MetroidFan2002


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

like image 33
ChssPly76 Avatar answered Sep 17 '22 13:09

ChssPly76