一、什么是跨域

1.1、为什么会出现跨域问题

出于浏览器的同源策略限制。同源策略(sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互。所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)

简单说a应用只能访问a应用后台传来数据,b应用只能访问b应用后台传来的数据,如果a应用用ajax获取数据时的url地址中的协议、端口、域名其中有一个和b应用对应的话,则是a应用跨域了想获取b应用数据,是不允许的

1.2、什么是跨域

当一个请求url的 协议、域名、端口 三者之间任意一个与当前页面url不同即为跨域

当前页面url 被请求页面url 是否跨域 原因
http://www.test.com/ http://www.test.com/index.html 同源(协议、域名、端口号相同)
http://www.test.com/ https://www.test.com/index.html 跨域 协议不同(http/https)
http://www.test.com/ http://www.baidu.com/ 跨域 主域名不同(test/baidu)
http://www.test.com/ http://blog.test.com/ 跨域 子域名不同(www/blog)
http://www.test.com:8080/ http://www.test.com:7001/ 跨域 端口号不同(8080/7001)

1.3、非同源限制

浏览器为了安全性,限制了一些请求无法访问非同源url

【1】无法读取非同源网页的 cookie、localstorage 和 indexeddb
【2】无法接触非同源网页的 dom
【3】无法向非同源地址发送 ajax 请求

1.4、如何解决跨域问题

服务端使用纯代码的方式逻辑解决跨域问题,如果使用springboot的话请看下章

【腾讯文档】jsonp跨域解决 https://docs.qq.com/doc/dvevtemdrcvvjsfle

二、springboot解决跨域问题

①:返回新的corsfilter

②:重写webmvcconfigurer

③:使用注解@crossorigin

注意:corfilter / webmvconfigurer / @crossorigin 需要 springmvc 4.2以上版本才支持,对应springboot 1.3版本以上上面前两种方式属于全局 cors 配置,后两种属于局部 cors配置。如果使用了局部跨域是会覆盖全局跨域的规则,
所以可以通过 @crossorigin 注解来进行细粒度更高的跨域资源控制。其实无论哪种方案,最终目的都是修改响应头,向响应头中添加浏览器所要求的数据,进而实现跨域

2.1、配置corsfilter(全局跨域)

import org.springframework.boot.springbootconfiguration;
import org.springframework.context.annotation.bean;
import org.springframework.web.cors.corsconfiguration;
import org.springframework.web.cors.urlbasedcorsconfigurationsource;
import org.springframework.web.filter.corsfilter;

@springbootconfiguration
public class webglobalconfig {

    @bean
    public corsfilter corsfilter() {

        //创建corsconfiguration对象后添加配置
        corsconfiguration config = new corsconfiguration();
        //设置放行哪些原始域
        config.addallowedorigin("*");
        //放行哪些原始请求头部信息
        config.addallowedheader("*");
        //暴露哪些头部信息
        config.addexposedheader("*");
        //放行哪些请求方式
        config.addallowedmethod("get");     //get
        config.addallowedmethod("put");     //put
        config.addallowedmethod("post");    //post
        config.addallowedmethod("delete");  //delete
        //corsconfig.addallowedmethod("*");     //放行全部请求

        //是否发送cookie
        config.setallowcredentials(true);

        //2. 添加映射路径
        urlbasedcorsconfigurationsource corsconfigurationsource =
                new urlbasedcorsconfigurationsource();
        corsconfigurationsource.registercorsconfiguration("/**", config);
        //返回corsfilter
        return new corsfilter(corsconfigurationsource);
    }
}

如果你使用的是高版本springboot2.4.4则需要改动一下,否则后台报错

java.lang.illegalargumentexception: when allowcredentials is true, allowedorigins cannot contain the special value “*” since that cannot be set on the “access-control-allow-origin” response header. to allow credentials to a set of origins, list them explicitly or consider using “allowedoriginpatterns” instead.
at org.springframework.web.cors.corsconfiguration.validateallowcredentials(corsconfiguration.java:453) ~[spring-web-5.3.6.jar:5.3.6]

当allowcredentials为true时,alloedorigins不能包含特殊值“*”,因为该值不能在“access-control-allow-origin”响应头部中设置。要允许凭据访问一组来源,请显式列出它们或考虑改用“allowedoriginpatterns”。

解决:把config.addallowedorigin(“*”); 替换成config.addallowedoriginpattern(“*”);

2.2、重写webmvcconfigurer(全局跨域)

import org.springframework.boot.springbootconfiguration;
import org.springframework.web.servlet.config.annotation.corsregistry;
import org.springframework.web.servlet.config.annotation.webmvcconfigurer;

@springbootconfiguration
public class corsconfig implements webmvcconfigurer {
    @override
    public void addcorsmappings(corsregistry registry) {
        //添加映射路径
        registry.addmapping("/**")
                //是否发送cookie
                .allowcredentials(true)
                //设置放行哪些原始域   springboot2.4.4下低版本使用.allowedorigins("*")    
                .allowedoriginpatterns("*")
                //放行哪些请求方式
                .allowedmethods(new string[]{"get", "post", "put", "delete"})
                //.allowedmethods("*") //或者放行全部
                //放行哪些原始请求头部信息
                .allowedheaders("*")
                //暴露哪些原始请求头部信息
                .exposedheaders("*");
    }
}

2.3、使用注解@crossorigin(局部跨域)

@target({elementtype.type, elementtype.method})
@retention(retentionpolicy.runtime)
@documented
public @interface crossorigin {
    //这origins和value是一样的
    //允许来源域名的列表,例如 'www.jd.com',匹配的域名是跨域预请求 response 头中的'access-control-aloow_origin' 
    //字段值。不设置确切值时默认支持所有域名跨域访问。
    @aliasfor("origins")
    string[] value() default {};
    @aliasfor("value")
    string[] origins() default {};
    //高版本下spring2.4.4使用originpatterns 而不是value 和 origins
    string[] originpatterns() default {};

    //跨域请求中允许的请求头中的字段类型, 该值对应跨域预请求 response 头中的 'access-control-allow-headers' 字段值。
    //不设置确切值默认支持所有的header字段(cache-controller、content-language、content-type、
    //expires、last-modified、pragma)跨域访问
    string[] allowedheaders() default {};

    //跨域请求请求头中允许携带的除cache-controller、content-language、content-type、expires、last-modified、
    //pragma这六个基本字段之外的其他字段信息,对应的是跨域请求 response 头中的 'access-control-expose-headers'字段值
    string[] exposedheaders() default {};

    //跨域http请求中支持的http请求类型(get、post...),不指定确切值时默认与 controller 方法中的 methods 字段保持一致。
    requestmethod[] methods() default {};

    //该值对应的是是跨域请求 response 头中的 'access-control-allow-credentials' 字段值。
    //浏览器是否将本域名下的 cookie 信息携带至跨域服务器中。默认携带至跨域服务器中,但要实现 cookie 
    //共享还需要前端在 ajax 请求中打开 withcredentials 属性。
    string allowcredentials() default "";

    //该值对应的是是跨域请求 response 头中的 'access-control-max-age' 字段值,表示预检请求响应的缓存持续的最大时间,
    //目的是减少浏览器预检请求/响应交互的数量。默认值1800s。设置了该值后,浏览器将在设置值的时间段内对该跨域请求不再发起预请求
    long maxage() default -1;
}

①:在控制器(类上)使用@crossorigin注解,表示该类的所有方法允许跨域

@controller
@requestmapping("/shop")
@crossorigin(originpatterns = "*", methods = {requestmethod.get, requestmethod.post})
public class shopcontroller {
    
    @getmapping("/")
    @responsebody
    public map<string, object> findall() {
        //返回数据
        return dataschool.getstudents();
    }
}

②:我们也可以设置更小的粒度,在方法上设置跨域

@controller
@requestmapping("/shop")
public class shopcontroller {

    @getmapping("/")
    @responsebody
    //更小的解决跨域 设置只能某些地址访问
    @crossorigin(originpatterns = "http://localhost:8080")
    public map<string, object> findall() {
        //返回数据
        return dataschool.getstudents();
    }
}

以上就是解决springboot跨域的三种方式的详细内容,更多关于springboot跨域的资料请关注www.887551.com其它相关文章!