Spring and HTTP Options request

2020-03-08 02:20发布

问题:

As a follow up on this question, i am wondering how to handle OPTIONS request in a spring 3 mvc application. I dont want to write an option-handling-method for every endpoint in my spring code. But the proposed mapping of an options-handler to "/**" works only for endpoints which dont have a handler already....

So i thought about using mvc interceptors to intercept OPTIONS request to handle cross-site-access stuff. but i cannot imagine that this is the best way to do this. are there any other options such as multiple handlers with different request-methods on the same path? My feeling tells me that this should actually work..(but it doesn't)!?

回答1:

It looks like native Spring support for this is set for Spring 4 (Maybe).

However in the meantime I implemented the following:

Using Maven (or manually) pull in this dependancy:

<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>cors-filter</artifactId>
    <version>1.3.2</version>
</dependency>

This has an implementation to capture all the inbound OPTIONS requests. Into the web.xml file add the following config:

<filter>
   <filter-name>CORS</filter-name>
   <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>       
   <init-param>
      <param-name>cors.supportedHeaders</param-name>
      <param-value>Content-Type,Accept,Origin</param-value>
   </init-param>
</filter>

<filter-mapping>
   <filter-name>CORS</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

The problem I've seen with the /** approach is a more specific Controller implementation will override this.



标签: java spring http