amarseillan
amarseillan

Reputation: 462

javax.servlet.Filter for specific request methods

Is it possible to apply filters to every POST (or combination of HTTP actions) in the application or desired mapping?

Example web.xml:

<filter>
    <display-name>AccessFilter</display-name>
    <filter-name>AccessFilter</filter-name>
    <filter-class>foo.bar.AccessFilter</filter-class>
</filter>
    <filter-mapping>
    <filter-name>AccessFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

And I have a controller that maps the following URLs:

For example.

Could I apply this filter JUST to the URLs which are POSTs?

Motivation: Only let the owners of the resources modify them, but let everyone consume them.

Upvotes: 1

Views: 2428

Answers (1)

Braj
Braj

Reputation: 46841

Check for request method in Filter as shown below and do what ever you want to do.

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
        FilterChain filterChain) throws ServletException, IOException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

    String method = httpServletRequest.getMethod(); //post or get

} 

Upvotes: 3

Related Questions