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

三世轮回 提交于 2019-12-29 05:01:19

问题


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?


回答1:


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

   }
}


来源:https://stackoverflow.com/questions/11077225/how-to-apply-a-servlet-filter-only-to-requests-with-http-post-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!