Spring 4.1 MVC是否支持Cors?

时间:2014-09-04 20:08:34

标签: spring spring-mvc

我知道我可以通过这样的过滤器添加Cors支持:https://spring.io/guides/gs/rest-service-cors/

我不知道该指南何时创建,以及后来的版本是否内置了Cors的实现......

3 个答案:

答案 0 :(得分:4)

Create this class

public class CORSFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");

    if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
        // CORS "pre-flight" request
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    //  response.addHeader("Access-Control-Allow-Headers", "Authorization");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        response.addHeader("Access-Control-Max-Age", "1");
    }

    filterChain.doFilter(request, response);
  }
}

并将其添加到您的web.xml

<!-- Add this to your web.xml to enable "CORS" -->
<filter>
  <filter-name>cors</filter-name>
  <filter-class>tk.aalkhodiry.filters.CORSFilter</filter-class>
</filter>

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

答案 1 :(得分:3)

我不知道任何内置的弹簧CORS过滤器,但是f.e. apache有一个实现(我怀疑JBOSS,Glassfish ......没有任何)。如果您使用tomcat,请将其放在您的web.xml中:

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,HEAD,OPTIONS,PUT,DELETE</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>Content-Type,Authorization, X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
    </init-param>
    <init-param>
        <param-name>cors.exposed.headers</param-name>
        <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
    </init-param>
    <init-param>
        <param-name>cors.support.credentials</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>cors.preflight.maxage</param-name>
        <param-value>10</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>  

根据您的偏好设置参数,并且不要忘记在客户端上启用CORS。 此外,如果您使用Spring Security,请确保SS filterChain在CorsFilter设置之后(如果没有它,有时会失败)

希望这有帮助,祝你好运

答案 2 :(得分:2)

Spring Framework 4.1仅内置了对SockJS的CORS支持,并允许specify a list of allowed origins用于Websocket和SockJS。

Spring Framework 4.2 GA开始提供一流的CORS支持。有关详细信息,请参阅this blog post