I'd like to intercept the OPTIONS request with my controller using Spring MVC, but it is catched by the DispatcherServlet. How can I manage that?
The HTTP OPTIONS method requests permitted communication options for a given URL or server. A client can specify a URL with this method, or an asterisk ( * ) to refer to the entire server.
Well, it uses the @RequestMapping annotation or Spring MVC configuration file to find out the mapping of the request URL to different controllers. It can also use specific request processing annotations like @GetMapping or @PostMapping.
The Spring Front controller will intercept the request and will find the appropriate handler based on the handler mapping (configured in Spring configuration files or annotation). In other words the handler mapping is used to map a request from the client to the handler.
The @RestController annotation in Spring MVC is nothing but a combination of the @Controller and the @ResponseBody annotation. It was added into Spring 4.0 to make the development of RESTful Web Services in Spring framework easier.
I added some more detail to the Bozho answer for beginners. Sometimes it is useful to let the Spring Controller manage the OPTIONS request (for example to set the correct "Access-Control-Allow-*" header to serve an AJAX call). However, if you try the common practice
@Controller public class MyController { @RequestMapping(method = RequestMethod.OPTIONS, value="/**") public void manageOptions(HttpServletResponse response) { //do things } }
It won't work since the DispatcherServlet will intercept the client's OPTIONS request.
The workaround is very simple:
You have to... configure the DispatcherServlet from your web.xml file as follows:
... <servlet> <servlet-name>yourServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>dispatchOptionsRequest</param-name> <param-value>true</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> ...
Adding the "dispatchOptionsRequest" parameter and setting it to true.
Now the DispatcherServlet will delegate the OPTIONS handling to your controller and the manageOption() method will execute.
Hope this helps.
PS. to be honest, I see that the DispatcherServlet append the list of allowed method to the response. In my case this wasn't important and I let the thing go. Maybe further examinations are needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With