Search This Blog

Monday, 20 January 2014

Mapping a Filter directly to a Servlet

I guess we have all used filters in our web projects. The common approach that I have followed is specifying the URL patterns to be intercepted by the filter.
<filter>
    <filter-name>someFilter</filter-name>
    <filter-class>com.filter.SomeFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>someFilter</filter-name>
    <url-pattern>*.do</url-pattern>
</filter-mapping>
All urls having the .do extension will now pass through the filter. There is also one more way to specify the filter pattern.
Something that I had forgotten about. Or not known. (I can't decide which!) Instead of URL pattern we can directly associate a servlet name with a filter. That means if a URL is mapped to the said servlet, than it will be intercepted by the filter.
Consider the below snippet:
<servlet>
    <servlet-name>DoServlet</servlet-name>
    <servlet-class>com.servlet.DoServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>DoServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>


<filter-mapping>
    <filter-name>someFilter</filter-name>
    <servlet-name>DoServlet</servlet-name>
</filter-mapping>
As seen here any url that maps to the DoServlet will be intercepted by the someFilter instance.
Just like multiple URL patterns, we are free to provide multiple servlet-names using multiple filter mapping elements.
In fact we can even combine the two techniques in one filter-mapping element:
<filter-mapping>
    <filter-name>someFilter</filter-name>
    <url-pattern>*.do</url-pattern>
    <servlet-name>DoServlet</servlet-name>
</filter-mapping>

3 comments: