前言

只是简单的配置实现了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对跨域请求支持的更多相关文章

  1. Spring Boot Web应用开发 CORS 跨域请求支持:

    Spring Boot Web应用开发 CORS 跨域请求支持: 一.Web开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS等等CORS与JSONP相比 1. JSONP只能实现 ...

  2. 009-Spring Boot全局配置跨域请求支持

    1.Spring Boot 2.0以前全局配置跨域主要是继承WebMvcConfigurerAdapter @Configuration public class CorsConfig extends ...

  3. WebService跨域配置、Ajax跨域请求、附开发过程源码

    项目开发过程中需要和其他公司的数据对接,当时我们公司提供的是WebService,本地测试,都是好的,Ajax跨域请求,就报错,配置WebService过程中,花了不少功夫,入不少坑,不过最终问题还是 ...

  4. SpringBoot配置Cors解决跨域请求问题

    一.同源策略简介 同源策略[same origin policy]是浏览器的一个安全功能,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源. 同源策略是浏览器安全的基石. 什么是源 源[or ...

  5. Spring Boot Web应用开发 CORS 跨域请求支持

    一.Web开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS等等 CORS与JSONP相比 1. JSONP只能实现GET请求,而CORS支持所有类型的HTTP请求. 2. 使用C ...

  6. 跨域访问支持(Spring Boot、Nginx、浏览器)

    原文:http://www.itmuch.com/work/cors/ 最近家中事多,好久没有写点啥了.一时间竟然不知从何说起.先说下最近家里发生的事情吧: 老爸肺气肿住院: 老妈甲状腺囊肿 儿子喘息 ...

  7. spring mvc \ spring boot 允许跨域请求 配置类

    用@Component 注释下,随便放个地方就可以了 package com.chinaws.wsarchivesserver.core.config; import org.springframew ...

  8. 让Spring Boot项目启动时可以根据自定义配置决定初始化哪些Bean

    让Spring Boot项目启动时可以根据自定义配置决定初始化哪些Bean 问题描述 实现思路 思路一 [不符合要求] 思路二[满足要求] 思路三[未试验] 问题描述 目前我工作环境下,后端主要的框架 ...

  9. 51. spring boot属性文件之多环境配置【从零开始学Spring Boot】

    原本这个章节是要介绍<log4j多环境不同日志级别的控制的>但是没有这篇文章做基础的话,学习起来还是有点难度的,所以我们先一起了解下spring boot属性文件之多环境配置,当然文章中也 ...

随机推荐

  1. Linux后门的几种姿势

    转载自 https://evilanne.github.io/2017/08/26/Linux%E5%90%8E%E9%97%A8-%E6%8C%81%E7%BB%AD%E5%85%B3%E6%B3% ...

  2. 加快Chrome网页开启速度

    谷歌浏览器一直是众多大神心中的最爱,但是对于启动速度还是有一些纠结,这里找到一个好方法可以加快一些启动的速度,亲测有效. 1.地址栏输入chrome://flags: 2.启用"覆盖软件渲染 ...

  3. jsp简单实现交互

    test.html <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type&quo ...

  4. JS代码格式化时间戳

    一.[24小时制]yyyy-MM-dd HH:mm:ss new Date().toJSON() // 2019-12-13T13:12:32.265Z 通过上面的方法,基本就可以将日期格式化,然后稍 ...

  5. Qt 条件编译 arm windows linux 判断 跨平台

    如果代码里面有些判断需要不同的参数做判断: 办法:在pro文件里面做定义 方法1:直接定义一个宏:用的时候可以直接判断,这样做不好的地方是编译前需要重新切换一下宏 1)定义宏 DEFINES += _ ...

  6. apache 负载均衡

    此次使用mod_proxy的方式来实现的,因为在Apache2以上的版本中已经集成了,因此不需要再另行安装和配置了. 只需要把注释去掉即可,去掉以下模块的注释: LoadModule proxy_mo ...

  7. Apache 容器 Directory Location Files 及htaccess文件

    配置段容器的类型 相关模块 core mod_proxy 相关指令 <Directory> <DirectoryMatch> <Files> <FilesMa ...

  8. Unable to update index for nexus-publish | http://ip:port/repository/maven-public/

    问题描述:Unable to update index for nexus-publish | http://ip:port/repository/maven-public/ 解决方案:进入工作空间. ...

  9. PHP关于mb_substr不能起作用的问题

    mb_substr不能起作用最大的原因是因为没有在php.ini文件没有把 ;extension=mbstring 前面的 :号去掉

  10. 解决shiro自定义filter后,ajax登录无法登录,并且无法显示静态资源的问题

    这个问题困扰了我一天,看了下面两个文章,豁然开朗: https://www.cnblogs.com/gj1990/p/8057348.html https://412887952-qq-com.ite ...