温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Springboot2.X如何全方位解决Cors跨域

发布时间:2021-10-20 16:58:46 来源:亿速云 阅读:141 作者:柒染 栏目:大数据

Springboot2.X如何全方位解决Cors跨域,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

一、概念理解Cors

1.1、什么是Cors?

      直接解释为跨域,是一个比jsonp更优秀的存在,JSONP只支持Get请求,CORS支持所有类型的HTTP请求。

1.2、什么是跨域?

      同源是指,域名、协议、端口均为相同,如果三者有其一不同,都算作跨域,A网站的ajax访问B网站的接口就是跨域,如下解释

非跨域: 
      http://www.osc.com/index.html      调用 http://www.osc.com/index.php   非跨域跨 域:      http://www.osc.com/index.html      调用 http://www.qq.com/index.php    跨域,主域不同 
      http://abc.osc.com/index.html      调用 http://def.osc.com/server.php  跨域,子域名不同 
      http://www.osc.com:8080/index.html 调用 http://www.osc.com/server.php  跨域,端口不同 
      https://www.osc.com/index.html     调用 http://www.osc.com/server.php  跨域,协议不同(https和http的区别)
二、准备A项目

      准备2个Springboot项目,不同端口号,A项目ajax访问B项目接口,算是跨域访问,我会把所有用到的代码都放到上面,省的大家评论为啥我这不行...

      A项目:springboot+freemaker

 2.1、pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.2、application.properties

server.port=8089
server.servlet.context-path=/tssd

#thymeleaf
spring.mvc.view.prefix=classpath:/templates/
spring.mvc.view.suffix=.html
spring.thymeleaf.cache=false
spring.mvc.static-path-pattern=/**
spring.resources.static-locations =classpath:/static/
spring.thymeleaf.mode=LEGACYHTML5

2.3、controller

@Controller
public class EveryController {
    @RequestMapping(value = "/every/{url}")
    public String toEveryUrl(@PathVariable("url") String url){
        return url;
    }
}

2.4、templates文件夹下index.html,现在此ajax访问的是8082,所以B项目端口号必须是8082

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>xixi</title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
    i love you,my beast love girl aoxin
<script>
    $(function() {
        $.ajax({
            url : "http://localhost:8082/test",
            type : "POST",
            dataType: "json",
            success : function(data) {
                alert(data.data);
            },
            error: function () {
                alert("错误");
            }
        });
    })
</script>
</body>
</html>

一会我们就直接通过接口 http://localhost:8089/tssd/every/index 就直接到了index.html,然后页面加载函数ajax请求B项目接口。

三、B项目创建

3.1、pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

3.2、application.properties

server.port=8082

3.3、实体类

@Data
@AllArgsConstructor
public class Result {
    private boolean success;
    private String code;
    private String message;
    private Object data;
    public Result() {
        this.success = true;
        this.code = "200";
    }
}

然后其他的就先不需要配置了,到此为止,B项目结束。

四、方法一:method局部解决跨域

      是针对某一个接口解决跨越问题。

      在B项目中,使用注解在方法上,这样我们这个方法就可以被跨域了。

@CrossOrigin(origins = "http://localhost:8089",maxAge = 3600)
@RequestMapping(value = "/test",method = RequestMethod.POST)
@ResponseBody
public Result testOne(){
    Result result = new Result();
    result.setData("fjsd");
    return result;
}

      http://localhost:8089/tssd/every/index

Springboot2.X如何全方位解决Cors跨域

五、方法二:局部解决跨域之类

      把方法一作用在方法上的注解CrossOrigin作用到类上,这样,该类的所有方法都可以被跨域。

@Controller
@CrossOrigin(origins = "http://localhost:8089",maxAge = 3600)
public class FirstController {

    @RequestMapping(value = "/test",method = RequestMethod.POST)
    @ResponseBody
    public Result testOne(){
        Result result = new Result();
        result.setData("fjsd");
       return result;
    }
}

    Springboot2.X如何全方位解决Cors跨域

      成功截图和上面是一样的,但是实现方式是不一样的。当然,如果你的注解只写成

@CrossOrigin(maxAge = 3600)

     那么它是可以允许任何网站都可以访问的,已经测试了,大家可以把origins去掉就可以了origins

六、方法三:全局配置解决跨域

      把方法一、方法二的注解去掉,添加全局配置,配置可以跨域的接口路径等等。

@Configuration
public class MyCrosConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/test")
                .allowedOrigins("http://localhost:8089")
                .allowedMethods("PUT", "DELETE","POST","GET")
                .allowedHeaders("*")
                .maxAge(3600);
    }
}
七、方法四:过滤器解决跨域

      可以把之前的三个方法的注解或者@Configuration都去掉,接下里我们用第四种方法测试。

@Configuration
public class CrosFilter {
    @Bean
    CorsFilter getCorsFilter(){
        CorsConfiguration cors = new CorsConfiguration();
        cors.setAllowCredentials(true);
        cors.addAllowedMethod("*");
        cors.addAllowedOrigin("*");
        cors.setMaxAge(3600L);
        cors.addAllowedHeader("*");
        cors.applyPermitDefaultValues();

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",cors);

        CorsFilter corsFilter = new CorsFilter(source);
        return corsFilter;
    }
}

      结果:成功。

八、总结

      其实不仅仅有局部方法、局部类、全局配置以及过滤器方法,还有xml方式,只不过个人不喜欢,所以就不介绍给大家,毕竟Springboot不提倡用xml,喜欢的话可以关注我,嘻嘻。

关于Springboot2.X如何全方位解决Cors跨域问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI