Servlet Filter - Dont apply filter to a specific one
I have a web-application with login screen backed up by an Authentication Filter.
I have the following in my web.xml
<filter>
<filter-name>AuthenticationFilter</filter-name>
<display-name>AuthenticationFilter</display-name>
<filter-class>com.mycompany.secutity.AuthenticationFilter</filter-class>
</filter>
And I have the following mapping -
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
But now I want to add an exception where for a specific servlet /web/MyNewServlet
, I want to bypass the authen开发者_开发问答ctication filter. How can we do this?
There are two ways in which you could do this:
- Remap the
/*
pattern to another pattern like/subdir/*
, and thereby avoid the AuthenticationFilter from being applied against/web/MyNewServlet
. This is a cumbersome process as you might have several URLs in your web-application that now need to be remapped. I would suggest doing this early in your development, or when you do not have too many URLs to remap. - Include an exclusion rule programatically inside your Filter implementation. You will need to use
HttpServletRequest.getServletPath
and similar methods to verify if the URL fragment contains/web/MyNewServlet
, and then chain the filter to the next filter or the servlet, instead of executing the body of the filter.
Extending Vineet's idea slightly, you could add another filter, called something like DoesNotNeedAuthenticationFilter, which runs before the AuthenticationFilter, and just sets an attribute DOES_NOT_NEED_AUTHENTICATION on the request. The AuthenticationFilter can then check for that attribute, and pass any requests which have it. You can then use the normal filter mapping mechanism to apply the DoesNotNeedAuthenticationFilter to the appropriate URLs or servlets.
精彩评论