如何仅将Servlet过滤器应用于使用HTTP POST方法的请求

28

在我的应用程序中,我想应用一个过滤器,但我不希望所有的请求都必须经过那个过滤器。

这将成为一个性能问题,因为我们已经有了一些其他的过滤器。

我想让我的过滤器仅适用于HTTP POST请求。 有没有办法?

1个回答

37

目前没有现成的功能可以实现这个。在所有HTTP方法中应用一个Filter不会造成额外开销。但是,如果Filter代码中有一些需要消耗资源的逻辑,你应该避免将这些逻辑应用于不需要的HTTP方法。

以下是示例代码:

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

   }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接