1.什么是跨域?
跨域请求,就是说浏览器在执行脚本文件的ajax请求时,脚本文件所在的服务地址和请求的服务地址不一样。说白了就是ip、网络协议、端口都一样的时候,就是同一个域,否则就是跨域。这是由于Netscape提出一个著名的安全策略——同源策略造成的,这是浏览器对JavaScript施加的安全限制。是防止外网的脚本恶意攻击服务器的一种措施。
2.代码工程
实验目标
让Spring Boot应用支持跨域
pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>springboot-demo</artifactId><groupId>com.et</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>cors</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies></project>
第一种跨域解决方法
使用 @CrossOrigin 注解可以轻松的实现跨域,此注解既可以修饰类,也可以修饰方法。当修饰类时,表示此类中的所有接口都可以跨域;当修饰方法时,表示此方法可以跨域,它的实现如下
package com.et.cors.controller;import org.springframework.web.bind.annotation.*;import java.util.HashMap;import java.util.Map;@RestControllerpublic class HelloWorldController {//@CrossOrigin@GetMapping("/hello")public String hello() {System.out.println("get hello");return "get hello";}@CrossOrigin@PostMapping("/hello")public String hello2() {System.out.println("post hello");return "post hello";}}
第二种跨域解决方法
通过 CorsFilter 跨域,“*”代表全部。”**”代表适配所有接口。 其中addAllowedOrigin(String origin)方法是追加访问源地址。如果不使用”*”(即允许全部访问源),则可以配置多条访问源来做控制。 例如:
config.addAllowedOrigin("http://www.liuhaihua.cn/");config.addAllowedOrigin("http://test.liuhaihua.cn/");
package com.et.cors.filter;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;import org.springframework.web.filter.CorsFilter;@Configurationpublic class MyCorsFilter {@Beanpublic CorsFilter corsFilter() {CorsConfiguration config = new CorsConfiguration();config.addAllowedOrigin("*");config.setAllowCredentials(true);config.addAllowedMethod("*");config.addAllowedHeader("*");UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();corsConfigurationSource.registerCorsConfiguration("/**", config);return new CorsFilter(corsConfigurationSource);}}
第三种跨域解决方法
重写 WebMvcConfigurer
package com.et.cors.config;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configurationpublic class WebConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowCredentials(true).allowedOrigins("*").allowedMethods("GET", "POST", "PUT", "DELETE").allowedHeaders("*");}}
index.html
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title></head><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script><script>function btnClick() {$.get('http://localhost:8088/hello', function (msg) {$("#app").html(msg);});}function btnClick2() {$.post('http://localhost:8088/hello', function (msg) {$("#app").html(msg);});}</script><body><div id="app"></div><input type="button" onclick="btnClick()" value="get_button"><input type="button" onclick="btnClick2()" value="post_button"></body></html>
以上只是一些关键代码,所有代码请参见下面代码仓库
代码仓库
-
https://github.com/Harries/springboot-demo(cors)
3.测试
请注意:localhost和127.0.0.1虽然都指向本机,但也属于跨域。
-
启动Spring Boot应用
-
访问http://127.0.0.1:8088/index.html
-
点击第一个按钮,出现跨域问题
Access to XMLHttpRequest at 'http://localhost:8088/hello' from origin 'http://127.0.0.1:8088' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
-
点击第二个按钮,添加注解@CrossOrigin,未出现跨域
4.引用
-
https://docs.spring.io/spring-framework/docs/4.2.x/javadoc-api/org/springframework/web/cors/CorsConfiguration.html#addAllowedOrigin-java.lang.String-
-
http://www.liuhaihua.cn/archives/711225.html
948

被折叠的 条评论
为什么被折叠?



