Spring 跨域问题CORS (Cross Origin Resources Share)

Posted 小白ii

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring 跨域问题CORS (Cross Origin Resources Share)相关的知识,希望对你有一定的参考价值。

1、Spring给我们提供了三种跨域方法

  1. CorsFilter 过滤器
  2. CorsConfiguration Bean
  3. @CrossOrigin 注解

2、CorsFilter 过滤器

CorsFilter代码如下:

package com.xiaobai.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "MyFilter")
public class MyFilter implements Filter {

    public void destroy() {
    }
    String allowList [] = null;

    @Override
    public void init(FilterConfig config) throws ServletException {
        String origins = config.getInitParameter("allowList");
        if(origins != null){
            if(origins.equals("*")){
                allowList = new String[]{"*"};
            }else {
                allowList = origins.split(",");
            }
        }
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String origin = request.getHeader("Origin");
        if (origin != null && !origin.isEmpty()) {
            for (String s : allowList) {
                if (s.equals(origin) || s.equals("*")) {
                    response.setHeader("Access-Control-Allow-Origin", origin);
                }
            }
        }
        chain.doFilter(request, response);
    }
}

web.xml代码如下:

    <filter>
        <filter-name>MyFilter</filter-name>
        <filter-class>com.xiaobai.filter.MyFilter</filter-class>

        <init-param>
            <param-name>allowList</param-name>
            <param-value>http://127.0.0.1:8081, http://192.168.2.24:8081</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>MyFilter</filter-name>
        <url-pattern>/aa</url-pattern>
    </filter-mapping>

3、CorsConfiguration Bean

<mvc:cors>:

<mvc:cors>
  <mvc:mapping path="/xxx"
               allowed-origins="http://localhost:7070"
               allowed-methods="GET, POST"
               allowed-headers="Accept-Charset, Accept, Content-Type"
               allow-credentials="true" />
  <mvc:mapping path="/yyy/*"
               allowed-origins="*"
               allowed-methods="*"
               allowed-headers="*" />
</mvc:cors>

4、@CrossOrigin 注解

@CrossOrigin 注解本质上也是用来配置 CorsConfiguration。

@CrossOrigin代码如下:

@CrossOrigin
public class CORSController {
    public String cors(@RequestParam(defaultValue = "callback") String callback, HttpServletResponse response) {
        // 最原始的方式,手动写请求头
        response.setHeader("Access-Control-Allow-Origin", "http://192.168.163.1:8081");
        return callback + "(‘hello‘)";
    }


    // 将跨域设置在方法上
    @RequestMapping("/cors")
    @CrossOrigin(origins = {"http://localhost:8080", "http://remotehost:82323"},
                 methods = {RequestMethod.GET, RequestMethod.POST},
                 allowedHeaders = {"Content-Type", "skfjksdjfk"},
                 allowCredentials = "true",
                 maxAge = 1898978
                 )
    @RequestMapping("/rrr")
    public String rrr(@RequestParam(defaultValue = "callback") String callback) {
        return callback + "(‘rrr‘)";
    }
}

5、其实也可以采用全注解的方式

结合 @ControllerAdvice 使用,进行全局化:

@Component
@ControllerAdvice
@CrossOrigin
public class CorsAdvice {
}

  

 

以上是关于Spring 跨域问题CORS (Cross Origin Resources Share)的主要内容,如果未能解决你的问题,请参考以下文章

CORS跨域请求规则以及在Spring中的实现

Spring Security (CORS)跨域资源访问配置

SpringBoot CORS 跨域 @CrossOrigin

spring MVC cors跨域实现源码解析 CorsConfiguration UrlBasedCorsConfigurationSource

Spring Boot 最简单的解决跨域问题

Spring Boot 最简单的解决跨域问题