Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 617
Kiran Avatar asked Jun 18 '12 05:06

Kiran


People also ask

How filter is used in pre and post processing of request?

A filter is an object that is invoked at the preprocessing and postprocessing of a request. It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input validation etc. The servlet filter is pluggable, i.e. its entry is defined in the web.

What do you mean by filtering request and response in servlet?

A filter is an object that can transform the header and content (or both) of a request or response. Filters differ from web components in that filters usually do not themselves create a response.

Can a filter be attached to one or more servlets?

A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. Filters typically do not themselves create responses, but instead provide universal functions that can be "attached" to any type of servlet or JSP page.


1 Answers

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()    {     } } 
like image 135
Ramesh PVK Avatar answered Oct 01 '22 08:10

Ramesh PVK