SpringBoot跨域访问解决方案

1、编写类:随便放在哪个目录下即可。至少与Chapter25Application.java的目录同级

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;

/**
* 跨域访问配置
*/
@Configuration
public class CorsConfig
{
private CorsConfiguration buildConfig()
{
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}

@Bean
public CorsFilter corsFilter()
{
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}


2、随便放在哪个目录下即可。至少与Chapter25Application.java的目录同级
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
* 跨域访问配置
*/
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter
{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**")
.allowedMethods("*")
.allowedOrigins("*")
.allowedHeaders("*");
}
}


测试方法:增加一个html:它的核心目的是到目标地址访问该地址,获取字符串,并且打印出来
html直接拖入浏览器运行即可
内容如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
<title>测试CORS</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#cors").click(function () {
$.ajax({
url: " http://localhost:8080/cors",
success: function (data) {
alert(data);
}
})
});
});
</script>
</head>
<body>
<input type="button" id="cors" value="CORS跨域测试"/>
</body>
</html>

新建一个controller内容如下:核心目的是返回Json字符串,给html打印出来。
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CoreController
{
@RequestMapping(value = "/cors")
public String testCors()
{
return "This is cors test";
}

}

猜你喜欢

转载自blog.csdn.net/zhou199252/article/details/80733012