Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle HTTP OPTIONS with Spring MVC?

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?

like image 1000
MaVVamaldo Avatar asked Mar 01 '12 18:03

MaVVamaldo


People also ask

How do I use HTTP options method?

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.

What process does Spring use to handle HTTP?

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.

How do you handle requests in spring?

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.

Can we use RestController in Spring MVC?

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.


1 Answers

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.

like image 84
MaVVamaldo Avatar answered Oct 08 '22 15:10

MaVVamaldo