Spring Boot 2.X 如何优雅的解决跨域问题?
一、什么是源和跨域
源(origin)就是协议、域名和端口号。
URL由协议、域名、端口和路径组成,如果两个URL的协议、域名和端口全部相同,则表示他们同源。否则,只要协议、域名、端口有任何一个不同,就是跨域。
对https://www.baidu.com/index.html进行跨域比较:
| URL | 是否跨域 | 原因 |
|---|---|---|
| https://www.baidu.com/more/index.html | 不跨域 | 三要素相同 |
| https://map.baidu.com/ | 跨域 | 域名不同 |
| http://www.baidu.com/index.html | 跨域 | 协议不同 |
| https://www.baidu.com:81/index.html | 跨域 | 端口号不同 |
二、什么是同源策略?
同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。
同源策略又分为以下两种:
- DOM同源策略:禁止对不同源页面DOM 进行操作。这里主要场景是iframe跨域的情况,不同域名的iframe是限制互相访问的。
- XMLHttpRequest同源策略:禁止使用XHR对象向不同源的服务器地址发起HTTP请求。
三、Spring Boot跨域解决方案
本例使用Spring Boot 2.1.2.RELEASE演示,分别用8080和8081端口启动,部分代码如下:
跨域页面:testOtherDomain.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>不同域名-Java碎碎念</title>
</head>
<body>
<button id="b1">点我测试</button>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
$("#b1").click(function () {
$.ajax({
url: "http://localhost:8081/hello",
type: "post",
success:function (res) {
console.log(res);
}
})
});
</script>
</body>
</html>
接口类:HelloController
package com.example.helloSpringBoot.controller; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class HelloController {
@RequestMapping("/hello")
public String HelloSpring (){
return "hello Java碎碎念!";
}
}
未解决跨域前运行截图:

在Spring Boot 2.X应用程序中可以使用注解@CrossOrigin,也可以通过使用WebMvcConfigurer对象来定义全局CORS配置。
- @CrossOrigin注解示例代码
package com.example.helloSpringBoot.controller; import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class HelloController { @CrossOrigin
@RequestMapping("/hello")
public String HelloSpring (){
return "hello Java碎碎念!";
}
}
2. WebMvcConfigurer对象示例代码
package com.example.helloSpringBoot.config; 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; @Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/*")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
.maxAge(3600);
}
};
}
}
按照上面两种方式的一种配置完成后,即可实现对跨域的支持,运行成功截图如下:

完整源码地址:https://github.com/suisui2019/helloSpringBoot
推荐阅读
1.Redis Cluster搭建高可用Redis服务器集群
2.为什么单线程的Redis这么快?
3.Spring Boot集成spring session实现session共享
4.Spring Boot入门-快速搭建web项目
5.Spring Boot2.0整合Redis
6.一篇文章搞定SpringMVC参数绑定
限时领取免费Java相关资料,涵盖了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo/Kafka、Hadoop、Hbase、Flink等高并发分布式、大数据、机器学习等技术。
关注下方公众号即可免费领取:

Spring Boot 2.X 如何优雅的解决跨域问题?的更多相关文章
- Spring Boot2 系列教程(十四)CORS 解决跨域问题
今天和小伙伴们来聊一聊通过CORS解决跨域问题. 同源策略 很多人对跨域有一种误解,以为这是前端的事,和后端没关系,其实不是这样的,说到跨域,就不得不说说浏览器的同源策略. 同源策略是由 Netsca ...
- Spring Boot中通过CORS解决跨域问题
今天和小伙伴们来聊一聊通过CORS解决跨域问题. 同源策略 很多人对跨域有一种误解,以为这是前端的事,和后端没关系,其实不是这样的,说到跨域,就不得不说说浏览器的同源策略. 同源策略是由Netscap ...
- eclipse spring boot 项目出现java.lang.ClassCastException 解决方法
问题 eclipse spring boot 项目出现java.lang.ClassCastException 解决方法: 重新生成项目
- spring boot 解决跨域访问
package com.newings.disaster.shelters.configuration; import org.springframework.context.annotation.B ...
- Spring boot 解决跨域问题
import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.we ...
- spring @CrossOrigin解决跨域问题
阅读目录: 一.跨域(CORS)支持: 二.使用方法: 1.controller配置CORS 2.全局CORS配置 3.XML命名空间 4.How does it work? 5.基于过滤器的CORS ...
- Spring @CrossOrigin 通配符 解决跨域问题
@CrossOrigin 通配符 解决跨域问题 痛点: 对很多api接口需要 开放H5 Ajax跨域请求支持 由于环境多套域名不同,而CrossOrigin 原生只支持* 或者具体域名的跨域支持 所以 ...
- spring mvc 图片上传,图片压缩、跨域解决、 按天生成文件夹 ,删除,限制为图片代码等相关配置
spring mvc 图片上传,跨域解决 按天生成文件夹 ,删除,限制为图片代码,等相关配置 fs.root=data/ #fs.root=/home/dev/fs/ #fs.root=D:/fs/ ...
- 提示"No 'Access-Control-Allow-Origin' header"及Spring 中解决跨域问题
问题描述 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://12 ...
随机推荐
- OKHttp源码学习同步请求和异步请求(二)
OKHttp get private void doGet(String method, String s) throws IOException { String url = urlAddress ...
- ArrayList的add(E e)方法与扩容
ArrayList是Java开发中经常用到的集合类,它是List接口的实现类,具有很高的查询性能,但不是线程安全的.本文主要讲述了ArrayList的add(E e)方法及该方法中涉及到的容量扩容技术 ...
- Dynamics 365 CE中使用FetchXML进行聚合运算
微软动态CRM专家罗勇 ,回复328或者20190429可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me! Dynamics 365 Customer Engagement ...
- 一起学Android之Sqlite
概述 Android对Sqlite提供了完全友好的支持,在应用程序内部,都可以通过名称访问任何的数据库.建议通过SQLiteOpenHelpe的子类并通过重写onCreate() 方法进行创建数据表. ...
- 一个能快速写出实体类的Api文档管理工具
今天各种MVC框架满天飞,大大降低了编码的难度,写实体类就没有办法回避的一件事了,花大把的时间去做一些重复而且繁琐的工作,实在不是一个优秀程序员的作风,所以多次查找和尝试后,找到一个工具类网站——Ap ...
- 第一次JVM分析记录:Out of Memory Error (workgroup.cpp:96), pid=6196, tid=139999645685504
tomcat的catalina.out日志报错如下: Exception in thread "http-bio-8081-Acceptor-0" java.lang.OutOfM ...
- 使用Git将项目托管到码云及从码云导入项目到本地
前言 码云+Git+IntellJ IDEA 欢迎转载,请注明作者和出处哦☺ Git 的安装及使用的教程 最好不要在官网下载,官网下载要vpn而且速度还很慢 . 推荐在 https://gi ...
- git使用笔记1:结合Github远程仓库管理项目
git是一个十分好用的版本控制工具,我们经常在本地使用git进行项目开发,Git 并不像 SVN 那样有个中心服务器,如果想要通过 Git 分享你的代码或者与其他开发人员合作,就需要将数据放到一台其他 ...
- 4. [mmc subsystem] mmc core(第四章)——host模块说明
零.说明 对应代码drivers/mmc/core/host.c,drivers/mmc/core/host.h. 为底层host controller driver实现mmc host的申请以及注册 ...
- Cocos Creator 资源加载流程剖析【二】——Download部分
Download流程的处理由Downloader这个pipe负责(downloader.js),Downloader提供了各种资源的"下载"方式--即如何获取文件内容,有从网络获取 ...