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

java, servlet-filters, servlets

Solution

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()
   {

   }
}

Problem

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?

Original source

Related problems