Monday, 25 April 2011

Servlet filter mapping exclude pattern

Once you apply a filter to a URL pattern:
<filter-mapping>
<filter-name>theFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

there's no option in web.xml to exclude a more specific pattern such as: /public/*.

But you can put the exclusion logic in the filter itself:
<filter>
<filter-name>theFilter</filter-name>
<filter-class>org.demo.CustomServletFilter</filter-class>
<init-param>
<param-name>excludePatterns</param-name>
<param-value>public/*</param-value>
</init-param>
</filter>


And in the filter code:
public void init(FilterConfig cfg) throws ServletException {
this.excludePatterns = cfg.getInitParameter("excludePatterns");
.
.
.
}

public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
String url = request.getRequestURL().toString();
if (matchExcludePatterns(url)) {
chain.doFilter(request, response);
return;
}
.
.
.
}

2 comments:

  1. Thank you for this. This was very helpful

    ReplyDelete
  2. "Great blog created by you. I read your blog, its best and useful information. You have done a great work. Super blogging and keep it up.php jobs in hyderabad.
    "

    ReplyDelete