Issue
I have a WAR file deployed to the root context (/
) on Tomcat 8, which has a servlet filter attached to it. The filter checks to see if the user is logged in and if not redirects them to the login page. I also have other contexts deployed in the same Tomcat instance at /app1
and /app2
. I want the filter in the root context to also apply to the other contexts, so I don't have to maintain three nearly identical filters (one for each context).
The problem is any URL that falls in the other contexts is not being handled by the filter in the root context. For example, the URI /foo/bar
is caught by the filter (because it doesn't correspond to one of the other contexts), but /app1/foo/bar
is not caught.
I've tried configuring the filter to catch everything by modifying the filter mapping in the web.xml file:
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
and I've also tried explicitly adding each context:
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
<url-pattern>/app1/*</url-pattern>
<url-pattern>/app2/*</url-pattern>
</filter-mapping>
but neither approach worked. I assume it's a security issue--the other contexts need to explicitly allow the root filter. How do I get this to work?
Solution
You can't get this to work. Web applications are independent. Requests are mapped to web applications before any Filters or Servlets are mapped.
You best bet with Tomcat (assuming you don't want multiple filter definitions) would be to re-implement your filter as a Tomcat Valve and configure the Valve on the Host.
Answered By - Mark Thomas
Answer Checked By - Timothy Miller (JavaFixing Admin)