Servlet filters were introduced in the Servlet 2.3 spec a long time ago. They're basically classes that you can add to any Java webapp that intercept every request and can do anything you can imagine (e.g., compress output, translate, handle authentication, the only limit is yourself). They're added into the web.xml file where every webapp starts, and since every webapp framework builds off of a servlet, they can be used with every webapp regardless of the framework. And they're part of the Servlet spec, not the J2EE spec, so you don't need a bloated container to use them; you can use them in Tomcat. Basically, what I'm saying is, they're really useful wherever you are, no matter what you're doing.
To install a servlet filter in your web.xml, you'd do something like this:
<filter> <filter-name>jpa-filter</filter-name> <filter-class>com.philihp.utils.EntityManagerFilter</filter-class> </filter> <filter-mapping> <filter-name>jpa-filter</filter-name> <servlet-name>action</servlet-name> </filter-mapping>
Where the filter will filter any servlet named "action" -- which in this case is the name of my Struts 1.3 controller that I had defined earlier. Rather than specify a servlet-name, you're allowed to use a url-pattern, but according to Sun, the url-pattern has to begin with a
"/" slash, so the following does not work.
<filter-mapping> <filter-name>jpa-filter</filter-name> <url-pattern>/*.jsp</url-pattern> </filter-mapping>
JSPs are essentially servlets, compiled from JSP code the first time they're run. But you don't have to define every JSP file in your web.xml file, because they're already defined by the container. There's a servlet (in tomcat, it's the Jasper engine) mapped to
/*.jsp. In the Tomcat guts, you can find it at
conf/web.xml, which is the basis web.xml file; every webapp deployed in Tomcat is actually extended from this file
<servlet> <servlet-name>jsp</servlet-name> <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class> </servlet>
Since JSPs are essentially running as the servlet name "jsp", you can attach a servlet-filter to them with a filter-mapping similar to this:
<filter-mapping> <filter-name>jpa-filter</filter-name> <servlet-name>jsp</servlet-name> </filter-mapping>