CORS(Cross-origin resource sharing)是由W3C定制的一种跨域资源共享技术,其目的就是为例解决前端的跨域请求。在javaEE开发中,最常见的前端跨域请求解决方案时JSONP,但是JSONP只支持GET请求;
什么是JavaEE请求:
它的原理是借助script
标签不受浏览器同源策略限制,允许跨域请求资源,因此可以通过script
标签的src
属性,进行跨域访问。
代码如下:
// 1. 前端定义一个 回调函数 handleResponse 用来接收后端返回的数据
function handleResponse(data) {console.log(data);
};// 2. 动态创建一个 script 标签,并且告诉后端回调函数名叫 handleResponse
var body = document.getElementsByTagName('body')[0];
var script = document.gerElement('script');
script.src = 'http://www.laixiangran.cn/json?callback=handleResponse';
body.appendChild(script);// 3. 通过 script.src 请求 `http://www.laixiangran.cn/json?callback=handleResponse`,
// 4. 后端能够识别这样的 URL 格式并处理该请求,然后返回 handleResponse({"name": "laixiangran"}) 给浏览器
// 5. 浏览器在接收到 handleResponse({"name": "laixiangran"}) 之后立即执行 ,也就是执行 handleResponse 方法,获得后端返回的数据,这样就完成一次跨域请求了。
CORS 支持多种 HTTP 请求,它其实就是定义了一套跨域资源请求时,浏览器与服务器之间的交互方式。基本的原理就是通过自定义的 HTTP 请求头来传递信息,进行验证。
方法一:使用**@CrossOrigin
**
该注解可用于方法和类上,注解在方法上,表示对该方法的请求进行 CORS 校验,注解在类上(即Controller
上),表示该类内的方法都遵循该 CORS 校验。如下所示:
@Slf4j
@RestController
@RequestMapping("cors")
@CrossOrigin(value = "http://127.0.0.1:5500", maxAge = 1800,allowedHeaders = "*")
public class CorsController {@PostMapping("/")public String add(@RequestParam("name") String name,@RequestHeader("Origin") String origin) {log.info("Request Header ==> Origin: " + origin);return "add successfully: " + name;}@DeleteMapping("/{id}")public String delete(@PathVariable("id") Long id) {return String.valueOf(id) + " deleted!";}
}
@CrossOrigin
注解可选参数如下:
方法 | 作用 |
---|---|
value | 表示支持的域,即Access-Control-Allow-Origin 的值 |
origins | 表示支持的域数组 |
methods | 表示支持的 CORS 请求方法,即Access-Control-Allow-Methods 的值。 其默认值与绑定的控制器方法一致 |
maxAge | 表示探测请求缓存时间(单位:秒),即Access-Control-Max-Age 的值。 其默认值为1800 ,也即 30 分钟 |
allowedHeaders | 表示允许的请求头,即Access-Control-Allow-Headers 的值 默认情况下,支持所有请求头 |
exposedHeaders | 表示下发其他响应头字段给浏览器,即Access-Control-Expose-Headers 的值。 默认不下发暴露字段 |
allowCredentials | 表示是否支持浏览器发送认证信息(比如 Cookie),即Access-Control-Allow-Credentials 的值。 默认不支持接收认证信息 |
方式二:配置类
增加一个配置类,CrossOriginConfig.java。继承WebMvcConfigurerAdapter或者实现WebMvcConfigurer接口,其他都不用管,项目启动时,会自动读取配置。
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**") //设置允许跨域的路径.allowedOrigins("*").allowedMethods("*").allowedHeaders("*").maxAge(1800).allowCredentials(true);}
}
只需创建一个配置类实现接口WebMvcConfigurer
,然后覆写方法addCorsMappings
即可。
addCorsMappings
方法中,registry.addMapping
用于设置可以进行跨域请求的路径,比如/cors/**
表示路径/cors/
下的所有路由都支持 CORS 请求。其他的设置与注解@CrossOrigin
一样,无需介绍。
方法三:采用过滤器(filter)的方式
@Component
public class CORSFilter implements Filter {@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {HttpServletResponse res = (HttpServletResponse) response;res.addHeader("Access-Control-Allow-Credentials", "true");res.addHeader("Access-Control-Allow-Origin", "*");res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {response.getWriter().println("ok");return;}chain.doFilter(request, response);}@Overridepublic void destroy() {}@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}
}
Spring Security 配置跨域:如果项目中使用了 Spring Security 框架,那么也可以直接配置 Spring Security 支持跨域即可:
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {// 允许跨域资源请求// by default uses a Bean by the name of corsConfigurationSourcehttp.cors(Customizer.withDefaults());}@BeanCorsConfigurationSource corsConfigurationSource() {CorsConfiguration configuration = new CorsConfiguration();configuration.setAllowedOrigins(Arrays.asList("*"));configuration.setAllowedMethods(Arrays.asList("GET","POST","OPTIONS"));UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();// 所有 url 都使用 configuration 定制的跨域规则source.registerCorsConfiguration("/**", configuration);return source;}
}