Search code examples
javajakarta-eeservlet-filterssitemesh

why do we check for filters to be applied twice in sitemesh and other places?


The simple flow diagram of sitemesh (here) shows that they check whether its the first time the filter is being applied or not. I have seen this check in the code of other filters too. I am unable to understand a situation where the same filter can be applied twice for the same request. Please explain.


Solution

  • As of Servlet 2.4, filters can be applied to a request invoked via the request dispatcher also. If the filter is specified to run on includes, or forwards for example it could be executed multiple times. e.g.

    <filter-mapping>
      <filter-name>Logging Filter</filter-name>
      <url-pattern>/products/*</url-pattern>
      <dispatcher>FORWARD</dispatcher>
      <dispatcher>INCLUDE</dispatcher>
      <dispatcher>REQUEST</dispatcher>
      <dispatcher>ERROR</dispatcher>
    </filter-mapping>
    

    So, for example, when a request is handled by a servlet and that servlet forwards the request somewhere else

    httpServletRequest.getRequestDispatcher("/products/somewhereElse").forward(httpServletRequest, httpServletResponse);
    

    , then the filter may run twice. Once for the original request and then again for the forward providing the URL path and dispatcher configuration allows.