Brian
Brian

Reputation: 1989

Can a servlet filter distinguish between and filter out unauthorized POST, GET, DELETE, etc. requests?

We have some REST endpoints (e.g., /getalleuropeancars or /getalljapanesecars or /getallamericancars). These endpoints are all GET only.

Right now, each annotated endpoint class has its own code for checking for unauthorized methods (which is everything except GET). We would like one class to handle all unauthorized methods; you know, code re-use and all that.

Will a filter be able to distinguish between "GET /getalleuropeancars" and "POST /getalleuropeancars" and "DELETE /getalleuropeancars" and redirect to the proper place? Looking at servlet filters, it seems that they can only detect different URL paths, not different HTTP methods.

<url-pattern>/getalleuropeancars</url-pattern>
<url-pattern>/getalljapanesecars</url-pattern>
<url-pattern>/getallamericancars</url-pattern>

So, is a servlet-filter what we need?

Upvotes: 0

Views: 1341

Answers (1)

Jose Martinez
Jose Martinez

Reputation: 11992

Yes a Servlet Filter can do it. There are two things here, one is mapping the Filter to all the paths (url-patterns) you want it to filter. Second is to have it filter out the non-GET methods. Below is the code of a Filter that filters out non-GET requests. Jus fill in the //return error with your own code for returning an error.

public class OnlyGetsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest sr, ServletResponse sr1, FilterChain fc) throws IOException, ServletException {
        HttpServletRequest hsr = (HttpServletRequest) sr;
        if (!"GET".equals(hsr.getMethod())) {
            //return error
        } else {
            fc.doFilter(sr, sr1);
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig fc) throws ServletException {
    }

}

Upvotes: 1

Related Questions