Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Servlet filters: is there `doFilter(HttpServletRequest)`

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 the HttpServletRequestWrapper? Do I have to downcast it manually, or is there a more appropriate way?
like image 364
blue_note Avatar asked Feb 28 '26 14:02

blue_note


1 Answers

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 the HttpServletRequestWrapper? 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.

like image 151
BalusC Avatar answered Mar 03 '26 13:03

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!