How to apply a servlet filter only to requests with HTTP POST method

Kiran picture Kiran · Jun 18, 2012 · Viewed 27.5k times · Source

In my application I want to apply a filter, but I don't want all the requests to have to go to that filter.

It will be a performance issue, because already we have some other filters.

I want my filter to apply only for HTTP POST requests. Is there any way?

Answer

Ramesh PVK picture Ramesh PVK · Jun 18, 2012

There is no readily available feature for this. A Filter has no overhead in applying to all HTTP methods. But, if you have some logic inside the Filter code which has overhead, you should not be applying that logic to unwanted HTTP methods.

Here is the sample code:

public class HttpMethodFilter implements Filter
{
   public void init(FilterConfig filterConfig) throws ServletException
   {

   }

   public void doFilter(ServletRequest request, ServletResponse response,
       FilterChain filterChain) throws IOException, ServletException
   {
       HttpServletRequest httpRequest = (HttpServletRequest) request;        
       if(httpRequest.getMethod().equalsIgnoreCase("POST")){

       }
       filterChain.doFilter(request, response);
   }

   public void destroy()
   {

   }
}