Using separate filters for seperate servlet requests; prevent filter being invoked by a forward on the servlet

I want to use 2 filters for 2 seperate servlets. The 1st filter is for 1st servlet: foodtypeServlet and the 2nd filter is for 2nd servlet: menuServlet. In 2nd filter, when there is error, I want to forward to foodtypeServlet. But the problem is, when I forward to foodtypeServlet, then the filter this servlet get executed as well. I don't want it to get executed. How can I achieve it?

Upvotes: 2

Views: 231

Answers (1)

BalusC
BalusC

Reputation: 1108972

This is not the default behaviour assuming that the filters are mapped as follows:

<filter-mapping>
    <filter-name>foodtypeFilter</filter-name>
    <servlet-name>foodtypeServlet</servlet-name>
</filter-mapping>
<filter-mapping>
    <filter-name>menuFilter</filter-name>
    <servlet-name>menuServlet</servlet-name>
</filter-mapping>

Filters are by default only invoked on REQUEST dispatcher, not on FORWARD, INCLUDE nor ERROR. For that you'd have to explicitly specify the <dispatcher> entries in filter mapping.

Perhaps you're using Servlet 2.3? In that ancient version any filter is indeed by default invoked on a forward as well. You'd need to upgrade to at least Servlet 2.4, or to let the filter check for the presence of the javax.servlet.forward.request_uri attribute and if so, then bypass the filter call by just calling chain.doFilter(request, response).

Or perhaps you're actually redirecting instead of forwarding? In that case, you should perform a real forward instead of redirect.

Upvotes: 1

Related Questions