【spring boot】SpringBoot初学(9.1)– 简单配置corsFilter对跨域请求支持
前言
只是简单的配置实现了cors,并没有讲任何东西。(有兴趣的可看: CORS 跨域 实现思路及相关解决方案)
github: https://github.com/vergilyn/SpringBootDemo
代码位置:
origin:表示服务端程序(默认为:127.0.0.1:8080)。其中有CorsFilter,且allow-origina配置为http://127.0.0.1:8081。
client_a/client_b:分别是客户端。其中client_a的端口号是8081,client_b的端口号是8082.
@SpringBootApplication
public class CorsOriginApplication {
public final static String CORS_ADDRESS = "127.0.0.1"; public static void main(String[] args) {
SpringApplication.run(CorsOriginApplication.class,args);
}
}
CorsOriginApplication.java
@Controller
@RequestMapping("/cors")
public class CorsOriginController { /**
* 如果CrosFilter中配置有Access-Control-Allow-Origin, 则CrossOrigin无效。
* 否则, 以@CrossOrigin为准。
* @return
*/
@CrossOrigin(origins = "http://127.0.0.1:8082")
@RequestMapping("/get")
@ResponseBody
public Map<String,Object> get(){
return Constant.map;
}
}
@Configuration
@WebFilter(urlPatterns = "/cors")
public class CorsFilter extends OncePerRequestFilter {
private final static String ALLOWORIGIN_CORS_A = "http://127.0.0.1:8081";
private final static String ALLOWORIGIN_CORS_b = "http://127.0.0.1:8082"; @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// Access-Control-Allow-Origin: 指定授权访问的域
response.addHeader("Access-Control-Allow-Origin", ALLOWORIGIN_CORS_A); //此优先级高于@CrossOrigin配置 // Access-Control-Allow-Methods: 授权请求的方法(GET, POST, PUT, DELETE,OPTIONS等)
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); response.addHeader("Access-Control-Allow-Headers", "Content-Type"); response.addHeader("Access-Control-Max-Age", "1800");//30 min
filterChain.doFilter(request, response);
}
}
注意:
如果在CorsFilter中配置有"Access-Control-Allow-Origin", 则controller中方法注解@CrossOrigin失效。(即filter的优先级高于@CrossOrigin方法注解)
Cors A:
@SpringBootApplication
@Controller
public class CorsAApplication implements EmbeddedServletContainerCustomizer {
private static int CORS_A_PORT = 8081; public static void main(String[] args) {
SpringApplication app = new SpringApplication(CorsAApplication.class);
app.run(args);
} @Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(CORS_A_PORT);
} @RequestMapping("corsA")
public String index(Model model){
model.addAttribute("port",CORS_A_PORT);
model.addAttribute("address", CorsOriginApplication.CORS_ADDRESS);
return "cors/corsA_index";
}
}
corsA_index.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="./static/common/jquery-2.1.4.js"></script>
<title>cors client_a</title>
<script type="text/javascript"> /*<![CDATA[*/
function corsFilter() {
var url = "http://localhost:8080/cors/get";
$.ajax({
type: 'get',
url: url,
data: {},
success: function (r) {
$("#result").text(JSON.stringify(r));
},
error: function (err) {
console.info(err);
alert('error!');
}
});
}
/*]]>*/
</script>
</head>
<body>
<h4>cors client_a</h4>
<p th:text="'server.address: ' + ${address}"/>
<p th:text="'server.port: ' + ${port}"/>
<p>cors配置: allowOrigin = "http://127.0.0.1:8081", 所以此页面可以得到结果!</p> <input type="button" value="request" onclick="corsFilter()"/><br/>
<h5>结果:</h5>
<p id="result"></p>
</body>
</html>
Cors B:
@SpringBootApplication
@Controller
public class CorsBApplication implements EmbeddedServletContainerCustomizer {
private static int CORS_B_PORT = 8082; public static void main(String[] args) {
SpringApplication app = new SpringApplication(CorsBApplication.class);
app.run(args);
} @Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(CORS_B_PORT);
} @RequestMapping("corsB")
public String index(Model model){
model.addAttribute("port",CORS_B_PORT);
model.addAttribute("address", CorsOriginApplication.CORS_ADDRESS);
return "cors/corsB_index";
}
}
corsB_index.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="./static/common/jquery-2.1.4.js"></script>
<title>cors client_b</title>
<script type="text/javascript"> /*<![CDATA[*/
function corsFilter() {
var url = "http://localhost:8080/cors/get";
$.ajax({
type: 'get',
url: url,
data: {},
success: function (r) {
$("#result").text(JSON.stringify(r));
},
error: function (err) {
console.info(err);
$("#errMsg").css("display","block");
alert('error!'); }
});
}
/*]]>*/
</script>
</head>
<body>
<h4>cors client_b</h4>
<p th:text="'server.address: ' + ${address}"/>
<p th:text="'server.port: ' + ${port}"/>
<p>cors配置: allowOrigin = "http://127.0.0.1:8081", 所以此页面<font color="red">无法得到结果!</font></p> <input type="button" value="request" onclick="corsFilter()"/><br/>
<h5>结果:</h5>
<p id="result"></p> <h5>错误描述:</h5>
<p id="errMsg" style="display: none">
已拦截跨源请求:同源策略禁止读取位于 http://localhost:8080/cors/get 的远程资源。(原因:CORS 头 'Access-Control-Allow-Origin' 不匹配 'http://127.0.0.1:8081')。
</p>
</body>
</html>
结果演示:
1. 127.0.0.1:8081/corsA可以正确的请求"http://localhost:8080/cors/get"并正确得到返回的结果。

2. 127.0.0.1:8082/corsB可以正确的请求"http://localhost:8080/cors/get"但无法正确得到请求结果。


【spring boot】SpringBoot初学(9.1)– 简单配置corsFilter对跨域请求支持的更多相关文章
- Spring Boot Web应用开发 CORS 跨域请求支持:
Spring Boot Web应用开发 CORS 跨域请求支持: 一.Web开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS等等CORS与JSONP相比 1. JSONP只能实现 ...
- 009-Spring Boot全局配置跨域请求支持
1.Spring Boot 2.0以前全局配置跨域主要是继承WebMvcConfigurerAdapter @Configuration public class CorsConfig extends ...
- WebService跨域配置、Ajax跨域请求、附开发过程源码
项目开发过程中需要和其他公司的数据对接,当时我们公司提供的是WebService,本地测试,都是好的,Ajax跨域请求,就报错,配置WebService过程中,花了不少功夫,入不少坑,不过最终问题还是 ...
- SpringBoot配置Cors解决跨域请求问题
一.同源策略简介 同源策略[same origin policy]是浏览器的一个安全功能,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源. 同源策略是浏览器安全的基石. 什么是源 源[or ...
- Spring Boot Web应用开发 CORS 跨域请求支持
一.Web开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS等等 CORS与JSONP相比 1. JSONP只能实现GET请求,而CORS支持所有类型的HTTP请求. 2. 使用C ...
- 跨域访问支持(Spring Boot、Nginx、浏览器)
原文:http://www.itmuch.com/work/cors/ 最近家中事多,好久没有写点啥了.一时间竟然不知从何说起.先说下最近家里发生的事情吧: 老爸肺气肿住院: 老妈甲状腺囊肿 儿子喘息 ...
- spring mvc \ spring boot 允许跨域请求 配置类
用@Component 注释下,随便放个地方就可以了 package com.chinaws.wsarchivesserver.core.config; import org.springframew ...
- 让Spring Boot项目启动时可以根据自定义配置决定初始化哪些Bean
让Spring Boot项目启动时可以根据自定义配置决定初始化哪些Bean 问题描述 实现思路 思路一 [不符合要求] 思路二[满足要求] 思路三[未试验] 问题描述 目前我工作环境下,后端主要的框架 ...
- 51. spring boot属性文件之多环境配置【从零开始学Spring Boot】
原本这个章节是要介绍<log4j多环境不同日志级别的控制的>但是没有这篇文章做基础的话,学习起来还是有点难度的,所以我们先一起了解下spring boot属性文件之多环境配置,当然文章中也 ...
随机推荐
- Fst指数说明
群体遗传学--Fst指数,即群体间分化指数,用于群体间分化分析. 群体遗传学中衡量群体间分化程度的指标有很多种,最常用的就是Fst指数.Fst指数,由F统计量演变而来.F统计量(FIS,FIT,FST ...
- DOCKER 学习笔记7 Docker Machine 建立虚拟机实战,以及错误总结
前言 通过以上6小节的学习,已经可以使用DOCKER 熟练的部署应用程序了.大家都可以发现使用 DOCKER 带来的方便之处,因为现在的话,只是在一台服务器上部署,这样部署,我们只需要一条命令,需要的 ...
- javabst1an
(单选题)下列概念中不包括任何实现,与存储空间没有任何关系的是() A)类 B)接口 C)抽象类 D)对象 正确答案为:B解析:接口是一种只含有抽象方法或常量的一种特殊的抽象类,因为接口不包括任何实现 ...
- python学习记录(二)
0824--https://www.cnblogs.com/fnng/archive/2013/02/24/2924283.html 如果需要写一个非常非常长的字符串,它需要跨多行,那么,可以使用三个 ...
- 90万条数据玩转RFM用户分析模型
RFM,是一种经典的用户分类.价值分析模型: R,Rencency,即每个客户有多少天没回购了,可以理解为最近一次购买到现在隔了多少天. F,Frequency,是每个客户购买了多少次. M,Mone ...
- shell命令之一天一见
一.在统计行数时常要用的到命令包括 w.c.l, 在这里做个简单的介绍. 语法:wc [选项] 文件… 说明:该命令统计给定文件中的字节数.字数.行数.如果没有给出文件名,则从标准输入读取.wc同时也 ...
- WeChall_Training: Crypto - Caesar I (Crypto, Training)
As on most challenge sites, there are some beginner cryptos, and often you get started with the good ...
- layui表格增删改查与上传图片+Api
API 控制器1 主要用于增删改查已经反填数据查询 using System; using System.Collections.Generic; using System.Data.SqlClie ...
- Go语言实现:【剑指offer】链表中环的入口结点
该题目来源于牛客网<剑指offer>专题. 给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null. Go语言实现: /** * Definition for sing ...
- 珠峰-buffer-流事件
#### Buffer // 字符串的二进制转10进制 let r = parseInt('11111111', 2); console.log(r); // 打印 255 // Number类型转为 ...