崛起于Springboot2.0.X之最全方法解决Cors跨域(49)

1、概念理解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的区别)   
2、准备A项目

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

      A项目:springboot+freemaker

      pom.xml

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

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

      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

      controller

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

      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项目接口。

3、B项目创建

      pom.xml

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

      application.properties

server.port=8082

      实体类

@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项目结束。

4、方法一:局部解决跨域之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

f0c34c9c99f146622a8505baf8fefd7d782.jpg

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

      把方法一作用在方法上的注解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;
    }
}

    cb030f51d8dfd6ef6a997057656320cd2d6.jpg

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

@CrossOrigin(maxAge = 3600)

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

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

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

@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);
    }
}
7、方法四:过滤器解决跨域

      可以把之前的三个方法的注解或者@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;
    }
}

      结果:成功。

8、总结

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

转载于:https://my.oschina.net/mdxlcj/blog/3099178

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值