项目中需要前后端分离部署,所以需要解决跨域的问题。
跨域可以在前端通过 JSONP 来解决,但是 JSONP 只可以发送 GET 请求,无法发送其他类型的请求,在 RESTful 风格的应用中,就显得非常鸡肋。
比如在前端ajax请求资源
$.ajax({
url : 'http://dev.***.***.com/rest/insight/1.0/iql/objects?objectSchemaId=2&iql=Name=ACI',
type : "get",
dataType:"jsonp",
crossDomain: true,
username:'60055859',
password:'169533!A',
success : function (result) {
}
})
跨越请求,需要将dataType设置为“jsonp”格式。
因此,从代码规范性,安全性,复杂度来讲,我们推荐在后端通过 (CORS,Cross-origin resource sharing) 来解决跨域问题。
一、同源策略
所谓同源,是指协议、域名以及端口均相同。
二、解决方案
方案(1): @Configuration启动容器+@Bean
这种方法在容器初始化,也就是在项目启动的时候,就会去加载这个类,实现规则的register
package org.spring.springboot.controller;
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;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class CorsConfig{
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}
方案(2):@CrossOrigin注解
默认允许所有访问源和访问方法。可以指定具体的访问地址,比如@CrossOrigin(origins = "http://localhost:8088", maxAge = 3600)
第一种:加在controller方法/类上
@RestController
@RequestMapping("/testBoot")
public class UserController {
@Autowired
private UserService userService;
// 查询
@CrossOrigin(origins = "*",maxAge = 3600)
@GetMapping("/getUser")
@ResponseBody
public String GetUsers(@RequestParam(value="id") int id ) {
return userService.Sel(id).toString();
}
第二种: 加在controller类上,指定访问源
@CrossOrigin(origins = "*",maxAge = 3600)
@RestController
@RequestMapping("/testBoot")
public class UserController {
@Autowired
private UserService userService;
// 查询
@GetMapping("/getUser")
@ResponseBody
public String GetUsers(@RequestParam(value="id") int id ) {
return userService.Sel(id).toString();
}
}
三、项目结构
1.将前端模拟前后端分离html页面,放到本地桌面,然后双击打开运行
测试1.html
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<input type="button" value="跨域问题测试" onclick="ajaxloding()" />
<div id="usermessage"></div>
<script>
var getdata=0;
function ajaxloding(){
$.ajax({
async:false,
type:"get",
url:"http://10.0.20.200:8086/testBoot/getUser?id=1",
contentType: "application/x-www-form-urlencoded",
dataType: "json",
data: {},
success:function(result){
alert("结果"+result)
},
error: function (errorMsg) {
//请求失败时执行该函数
alert("请求数据失败!"+errorMsg);
}
});
$("#usermessage").text(getdata)
}
</script>
</body>
</html>
2.本地浏览器访问,正常显示
3.未设置跨域措施前执行,存在跨域
4.设置跨域方案,正常访问
5.项目整体结构,基于Springboot+Mybatis+Mysql
参考文章
https://blog.csdn.net/qq_15351167/article/details/89284397
https://xulinjie.blog.csdn.net/article/details/81142413
https://www.jianshu.com/p/c6ea21b64f6e
https://blog.csdn.net/weixin_44259720/article/details/104900530