使用Spring MVC为所有API启用CORS

时间:2014-07-21 09:12:23

标签: java http spring-mvc cors

如何"轻松"配置Spring MVC,以便我的应用程序中的任何API的每个请求都返回神奇的CORS头?

例如,使用@ControllerAdvice或使用常见的AOP建议。

2 个答案:

答案 0 :(得分:2)

我解决了这个步骤:

  1. 添加Maven依赖
  2. <dependency>
      <groupId>com.thetransactioncompany</groupId>
      <artifactId>cors-filter</artifactId>
      <version>2.2.1</version>
    </dependency>
    
    1. 在web.xml中添加此参数

      <filter>
      <filter-name>CORS</filter-name>
      <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
      
      <init-param>
          <param-name>cors.allowGenericHttpRequests</param-name>
          <param-value>true</param-value>
      </init-param>
      
      <init-param>
          <param-name>cors.allowOrigin</param-name>
          <param-value>*</param-value>
      </init-param>
      
      <init-param>
          <param-name>cors.allowSubdomains</param-name>
          <param-value>false</param-value>
      </init-param>
      
      <init-param>
          <param-name>cors.supportedMethods</param-name>
          <param-value>GET, HEAD, POST, DELETE, OPTIONS</param-value>
      </init-param>
      
      <init-param>
          <param-name>cors.supportedHeaders</param-name>
          <param-value>*</param-value>
      </init-param>
      
      <init-param>
          <param-name>cors.supportsCredentials</param-name>
          <param-value>true</param-value>
      </init-param>
      
      <init-param>
          <param-name>cors.maxAge</param-name>
          <param-value>3600</param-value>
      </init-param>   
      </filter>
      

答案 1 :(得分:1)

其中一种方法是使用Interceptor类,如下所示:

  • 我没有实现拦截器设置以简化代码。

让我们为所有网址设置拦截器方法,如下所示:

 public boolean preHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler)
        throws Exception {

       request.setHeader(HttpHeaders.CONTENT_TYPE, "application/jsonp");    

       //OR

       response.addHeader(HttpHeaders.CONTENT_TYPE, "application/jsonp");
       response.setHeader("Access-Control-Allow-Origin", "*");
       response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
       response.setHeader("Access-Control-Max-Age", "3600");
       response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
}

我们必须只配置拦截器来满足Controller方法。

JSONP 是CORS通信的首选格式之一。