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?
相关问题
- Angular RxJS mergeMap types
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
As a quick supplement to the above 2 answers, here's how to enable dispatchOptionsRequest in a servlet 3 (no web.xml) environment as it took me a while to work out how to apply the answers above in a non-xml setup.
In a spring 3.2 / servlet 3 environment, you will have some variety of
DispatcherServlet
initializer class which is the java equivalent of web.xml; in my case it's theAbstractAnnotationConfigDispatcherServletInitializer
. Adding the following code will enable dispatchOptionsRequest:You should configure the dispatcherServlet by setting its
dispatchOptionsRequest
totrue
For Spring without web.xml file, and based on Paul Adamson answer, I just set the parameter
dispatchOptionsRequest
totrue
into the dispatcher, to process theOptions
method calls.I took the following approach:
Using Maven (or manually) pull in this dependancy:
This has an implementation to capture all the inbound OPTIONS requests. Into the web.xml file add the following config:
The problem I've seen with the /** approach is a more specific Controller implementation will override this.
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
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:
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.