2

I know that in JavaEE, filters can intercept any request to a servlet. But Interceptors in Spring MVC are not exactly the same. If you look at the diagram below, you will see that Interceptors come after Dispatcher Servlet.

Let me give you an example before I ask my question.

I have a controller, which has 2 methods in it that are mapped to two different requests. One accepts GET requests and other accepts POST requests. Now if I add an interceptor in my web application, that interceptor will sit before Controller. Meaning that before controller method is hit, first a request will hit my interceptor's preHandle method.

Now say that in my app, two controllers methods look like this:

@Controller
public class myController{

@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test1(){      
    return "abc";
}

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String test1(){      
    return "xyz";
}

And lets say I have a simple interceptor like this:

public class URLInterceptors extends HandlerInterceptorAdapter  {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("REQUESTED SERVLET PATH IS: " + request.getServletPath());   
        return true;    
    }   
}

Now, if I make a GET request to /test, my interceptor is hit and it prints the servlet path, but when I make a GET request to /login, I know it will fail because my method that handles /login mapping accepts only POST requests, however before it throws '405 Request method 'GET' not supported' error, it should at least hit first my interceptor? It doesn't. I I don't want to change POST to GET. So the question is why?

enter image description here

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Faraz
  • 6,025
  • 5
  • 31
  • 88

1 Answers1

4

Part of this is explained in

In summary, the DispatcherServlet attempts to find an appropriate handler for your request by using a HandlerMapping (see your graphic). These handlers are actually adapters that wrap the actual handler method (a @RequestMapping annotated method in this case) with the interceptors you've registered. If this handler is found, then the DispatcherServlet can proceed, invoke interceptors, and, if required, invoke your handler method.

In your case, because your @RequestMapping is restricted to POST requests and your request is a GET, the DispatcherServlet fails to find an appropriate handler and therefore returns an error before it's had a chance to invoke any interceptors.

Note that the javadoc states

A HandlerInterceptor gets called before the appropriate HandlerAdapter triggers the execution of the handler itself.

but your DispatcherServlet never found a handler to begin with.

You might want to consider using a Servlet Filter instead.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724