崛起于Springboot2.X + 全方位解决Cors跨域(49)

《SpringBoot2.X心法总纲》php

1、概念理解Cors

1.一、什么是Cors?html

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

1.二、什么是跨域?web

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

非跨域: 
      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项目接口,算是跨域访问,我会把全部用到的代码都放到上面,省的你们评论为啥我这不行...spring

      A项目:springboot+freemakerjson

 2.一、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>

2.二、application.propertiesspringboot

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.三、controllermvc

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

2.四、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项目建立

3.一、pom.xml

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

3.二、application.properties

server.port=8082

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

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

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;
    }
}

    

      成功截图和上面是同样的,可是实现方式是不同的。固然,若是你的注解只写成

@CrossOrigin(maxAge = 3600)

     那么它是能够容许任何网站均可以访问的,已经测试了,你们能够把origins去掉就能够了origins

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

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

@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,喜欢的话能够关注我,嘻嘻。

相关文章
相关标签/搜索