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
ServletRequest to the HttpServletRequestWrapper? Do I have to downcast it manually, or is there a more appropriate way?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
ServletRequestto 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.
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