Issue
The servlet API defines a GenericServlet
which accepts ServletRequest
objects, and subclasses it to HttpServlet
which accepts HttpServletRequest
. However, Filter.doFilter
seems to accept only ServletRequest
. Is there filter class specific to HTTP requests? If not
- Why? Since HTTP is the only method common to all web compoments, wouldn't it make sense to have an HTTP-specific filter, just like servlets? What is the rationale?
- How should I pass the
ServletRequest
to theHttpServletRequestWrapper
? Do I have to downcast it manually, or is there a more appropriate way?
Solution
You're not the only one who wished this for ages. There's actually no reasonable rationale for this. The upcoming Servlet 4.0 (part of Java EE 8) will therefore as per spec issue 141 finally come with a javax.servlet.http.HttpFilter
. It's currently already implemented in Tomcat 9. The method signature is:
protected void doFilter(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain)
Until then, your best bet is baking a HttpFilter
yourself, or if you happen to use a JSF+CDI based web application, grab OmniFaces HttpFilter
(which is open source, so you could use it as inspiration for baking on your own), which happens to have the following signature:
public void doFilter(HttpServletRequest request,
HttpServletResponse response,
HttpSession session,
FilterChain chain)
Whereby the session
is null
if it isn't created yet.
As to your secondary question,
How should I pass the
ServletRequest
to theHttpServletRequestWrapper
? Do I have to downcast it manually, or is there a more appropriate way?
Just look at existing code snippets here for several real world exapmles.
Answered By - BalusC