How to handle HTTP OPTIONS with Spring MVC?

前端 未结 5 1276
鱼传尺愫
鱼传尺愫 2020-11-29 07:28

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?

5条回答
  •  無奈伤痛
    2020-11-29 07:42

    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:

    ...
      
        yourServlet
        org.springframework.web.servlet.DispatcherServlet
        
          dispatchOptionsRequest
          true
        
        1
      
    ...
    

    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.

提交回复
热议问题