Java Spring项目中的CORS跨域开启的几种方式

在服务器端开启跨域的原理,一般都是通过在HTTP Headers中的响应头的Access-Control-Allow-Origin指定放行的域,来完成的。
Access-Control-Allow-Origin响应头指定了该响应的资源是否被允许与给定的域(origin)共享。
跨域出错,一般在浏览中会有:
'http://xxxxx' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

要开启全局跨域也有很多的方式,如下:

一.添加filter开启

可以在添加filter指定共享的域
filter类

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CrossOriginFilter implements Filter {
    private FilterConfig config = null;

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

    @Override
    public void destroy() {
        this.config = null;
    }

    /**
     * @comment 跨域的设置
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        // 表明它允许"http://xxx"发起跨域请求
        httpResponse.setHeader("Access-Control-Allow-Origin",
                config.getInitParameter("AccessControlAllowOrigin"));
        // 表明在xxx秒内,不需要再发送预检验请求,可以缓存该结果
        httpResponse.setHeader("Access-Control-Allow-Methods",
                config.getInitParameter("AccessControlAllowMethods"));
        // 表明它允许xxx的外域请求
        httpResponse.setHeader("Access-Control-Max-Age",
                config.getInitParameter("AccessControlMaxAge"));
        // 表明它允许跨域请求包含xxx头
        httpResponse.setHeader("Access-Control-Allow-Headers",
                config.getInitParameter("AccessControlAllowHeaders"));
        chain.doFilter(request, response);
    }
}

web.xml的配置中

<!--  CORS过滤器-->
  <filter>
    <filter-name>CrossOrigin</filter-name>
    <filter-class>cn.mashirodever.blog.filter.CrossOriginFilter</filter-class>
    <init-param>
      <param-name>AccessControlAllowOrigin</param-name>
      <param-value>*</param-value>
    </init-param>
    <init-param>
      <param-name>AccessControlAllowMethods</param-name>
      <param-value>HEAD,POST,GET,DELETE,PUT</param-value>
    </init-param>
    <init-param>
      <param-name>AccessControlMaxAge</param-name>
      <param-value>3628800</param-value>
    </init-param>
    <init-param>
      <param-name>AccessControlAllowHeaders</param-name>
      <param-value>x-requested-with</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CrossOrigin</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

二.SpringMVC中配置开启

这种方法在spring项目中支持性会比filter好些,有时用filter不行的可尝试切换到这种。有一次就是filter中配置了允许的请求方法,但是只有get能跨域,post请求就一直报cors错误。换到这种就好了😂

<mvc:cors>
        <mvc:mapping path="/**"
                     allowed-origins="*"
                     allowed-methods="POST, GET, OPTIONS, DELETE, PUT"
                     allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
                     allow-credentials="true"
                     max-age="3600" />
</mvc:cors>

origins中设为*就是全部域都能共享(开启跨域),这样还是不是很安全的,可以指定域:

<!-- path 是指定的地址,要多可有多个mapping -->
<!-- allowed-origins 是开启的域 -->
path="/api/**"
allowed-origins="http:xx1.com,https:xx2.com"

三.添加配置类开启

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/api/**")
			.allowedOrigins("http://domain2.com")
			.allowedMethods("PUT", "DELETE")
			.allowedHeaders("header1", "header2", "header3")
			.exposedHeaders("header1", "header2")
			.allowCredentials(false).maxAge(3600);
	}
}
posted @ 2021-04-24 22:14  会飞的一棵树  阅读(848)  评论(0编辑  收藏  举报