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).
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 ".
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.
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.
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? :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With