Spring解决跨域问题方案

项目中需要前后端分离部署,所以需要解决跨域的问题。
跨域可以在前端通过 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

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值