从Spring-Boot开始深入理解Spring系列(八)——Spring-Boot处理web开发的跨域问题

本文深入解析跨域请求的概念,探讨浏览器同源策略下为何需要跨域,并提供多种跨域解决方案,包括JSONP、CORS、WebSocket等技术实现,以及spring-boot应用中CORS配置实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是跨域?

  • 定义:浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制

为什么需要跨域?

这个问题的始作俑者,请点击浏览器的同源策略
具体分析,请参考文章:https://segmentfault.com/a/1190000015597029

如何跨域?

解决方案参考:

  • 解决方案一:JSONP
  • 解决方案二:CORS
  • 解决方案三:WebSocket
  • 解决方案四:iframe
  • 解决方案五:代理

示例:spring-boot开发web应用通过CORS跨域

跨域访问方,client端的js代码

			$.ajax({
                    url: "http://localhost:8081/api/get",
                    type: "POST",
                    data: {
                        name: "测试"
                    },
                    success: function(data, status, xhr) {
                        console.log(data);
                        alert(data.name);
                    }
                });

服务提供方核心代码配置

方式一:注解式控制,粒度细,更灵活

关键代码展示

	@CrossOrigin(origins = "http://localhost:8080")
	@RequestMapping(value = "/get")
	public HashMap<String, Object> get(@RequestParam String name) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("title", "hello world");
		map.put("name", name);
		return map;
	}

方式二:全局控制,简单省事

关键代码展示

package com.roncoo.education.util.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
* 全局设置
* @author wujing
*/
@Configuration
public class CustomCorsConfiguration {

	@Bean
	public WebMvcConfigurer corsConfigurer() {
		return new WebMvcConfigurerAdapter() {
			@Override
			public void addCorsMappings(CorsRegistry registry) {
				// 限制了路径和域名的访问
				registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
			}
		};
	}
}

  • 跨域成功和失败的效果展示

成功:
在这里插入图片描述
在这里插入图片描述在这里插入图片描述
失败:
在这里插入图片描述

小结:

本文设计的跨域,是端口不一致下的跨域访问。其他类型的跨域同理可证

附:代码下载
https://github.com/bill4j/spring-boot-course/tree/develop/spring-boot-cors
参考文章:

http://www.ruanyifeng.com/blog/2016/04/cors.html
http://www.ruanyifeng.com/blog/2016/04/same-origin-policy.html
https://segmentfault.com/a/1190000015597029

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值