【Spring】后端解决跨域问题

来源:互联网 发布:淘宝饰品店铺名 编辑:程序博客网 时间:2024/06/12 22:04

什么是跨域?
跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript施加的安全限制。

举个栗子:
http://www.123.com/index.html 的同源检测结果
URL-结果-原因
http://www.123.com/server.PHP 成功
http://www.456.com/server.php 失败 主域名不同
http://def.123.com/server.php 失败 子域名不同
http://www.123.com:8081/server.php 失败 端口不同
https://www.123.com/server.php 失败 协议不同

解决办法

JSONP 配合前端
JSONP的最基本的原理是:动态添加一个script标签,而script标签的src属性是没有跨域的限制的。

后端配合可以新建一个类:

package com.company.api.controller;import org.springframework.http.MediaType;import org.springframework.http.server.ServerHttpRequest;import org.springframework.http.server.ServerHttpResponse;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;import java.nio.charset.Charset;@ControllerAdvice(basePackages = "com.company.api.controller")public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {    @Override    protected MediaType getContentType(MediaType contentType, ServerHttpRequest request, ServerHttpResponse response) {        return new MediaType("application", "javascript", Charset.forName("utf-8"));    }    public JsonpAdvice() {        super("callback");    }}

添加这个类后,baseController中配置路径中的controller都支持跨域请求,缺点是仅支持Get请求。

Spring 注解

Controller增加@CrossOrigin,被注解的Controller具备接受跨域请求的功能。默认情况下,它使方法具备接受所有域,所有请求消息头的请求。当然也可以自己配置接受的域、请求头、方法和是否允许cookie,下面的例子中,我们仅接受百度发送来的跨域请求。

@RestController@CrossOrigin(origins = "http://www.baidu.com,https://www.baidu.com")public class CrossController {    ...}

Spring WebMvcConfigurerAdapter

用WebMvcConfigurerAdapter增加配置,同样可以自定义接受的域、请求头、方法、是否允许cookie,
下面的栗子中,我们接受一切。

package com.haonanren.example.config;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;/** * Created by zjief on 17-3-27. */@Configurationpublic class WebMvcConfiguration extends WebMvcConfigurerAdapter {    @Override    public void addCorsMappings(CorsRegistry registry) {        registry.addMapping("/**")                .allowedOrigins("*")                .allowedMethods("*")                .allowedHeaders("*");    }}