Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 authenctication filter. How can we do this?

like image 779
jagamot Avatar asked Aug 22 '11 22:08

jagamot


People also ask

Can a filter be attached to one or more servlets?

A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. Filters typically do not themselves create responses, but instead provide universal functions that can be "attached" to any type of servlet or JSP page.

What is the difference between servlet and filter?

Filter provides functionality which can be “attached” to any web resource. Servlet used for performing action which needs for particular request as user login, get response based on user role, interacts with database for getting data, business logic execution, and more.

What will be the order of filter execution when the servlet is invoked?

First, it receives ServletRequest and ServletResponse object pairs for incoming requests. Depending on the counter, it then either passes them down the chain by invoking the next doFilter() method on the FilterChain object, or rejects them by generating its own response.


1 Answers

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.
like image 188
Vineet Reynolds Avatar answered Sep 19 '22 01:09

Vineet Reynolds