Search code examples
servletsservlet-filtersurl-pattern

How to filter requests ONLY from application context path?


Environment:

  • Jboss 5.2
  • Servlet 2.4
  • Java 7

I'm trying to execute a filter requests ONLY when the application context path is called but I didn't find any way with url-pattern, because url-pattern /* take all requests.

I would like to execute a filter when request this url http://localhost:8080/myapp but the filter is not triggered.

<filter-mapping>
    <filter-name>PrincipalFilter</filter-name>
    <url-pattern>/</url-pattern>
</filter-mapping>

I also tried with emtpy string but I got an error on parsing web.xml on deploying, maybe the server is too old.

Any ideas?


Solution

  • I also tried with emtpy string

    That's the correct solution. See also Difference between / and /* in servlet mapping url pattern.


    but I got an error on parsing web.xml on deploying, maybe the server is too old

    That'll be it. You really need to upgrade anything which is older than the previous major version (Servlet API is currently already at 4.0 and 2.4 was released in 2003, so that's even more than a decade old!), else you won't be able to upgrade with minimal effort, and you'd be forced to end up basically rewriting the entire application.

    If you really cannot upgrade, then your best bet is to listen on /* instead and simply check if request.getRequestURI() returns solely the request.getContextPath() before performing the actual logic, else just continue the filter chain without changes.