springmvc springboot 跨域问题(CORS)
官方文档:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cors.html
springmvc springboot 跨域问题(CORS)
控制器方法CORS设定
你可以添加到你的@RequestMapping注解处理方法@CrossOrigin,以便能够在其上CORS注释(默认情况下@CrossOrigin允许所有的起源和在指定的HTTP方法@RequestMapping注释):
@RestController
@RequestMapping("/account")
public class AccountController { @CrossOrigin
@GetMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
} @DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
也可以使CORS整个控制器:
@CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController { @GetMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
} @DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
在这个例子中CORS的支持,是你在启用retrieve()和remove()处理方法,你还可以看到如何使用自定义CORS配置@CrossOrigin属性。
你甚至可以使用两个控制器和方法级CORS配置,Spring会再结合这两个注释属性来创建一个合并CORS配置。
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController { @CrossOrigin(origins = "http://domain2.com")
@GetMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
} @DeleteMapping("/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
如果你正在使用Spring Security,确保enable CORS at Spring Security level 以及允许其利用在Spring MVC的级别定义的配置。
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()...
}
}
全局CORS配置
除了细粒度的,基于注解的配置,你可能会想定义一些全局CORS配置为好。这是类似于使用过滤器,但可以声明withing Spring MVC和细粒度组合@CrossOrigin配置。默认情况下,所有的起源和GET,HEAD和POST方法都是允许的。
JavaConfig
启用CORS为整个应用程序是非常简单:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter { @Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
如果你在使用Spring boot,建议声明WebMvcConfigurer bean如下:
@Configuration
public class MyConfiguration { @Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
}
你可以轻松地更改任何属性,以及仅适用此CORS配置到特定的路径模式:
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(3600);
}
如果你正在使用Spring Security,确保enable CORS at Spring Security level 以及允许其利用在Spring MVC的级别定义的配置。
XML命名空间
也可以与配置CORS MVC XML命名空间。
这个最小的XML配置启用CORS /**具有比JavaConfig一个相同的默认属性路径图案:
<mvc:cors>
<mvc:mapping path="/**" />
</mvc:cors>
也可以用自定义的属性来声明几个CORS映射:
<mvc:cors>
<mvc:mapping path="/api/**"
allowed-origins="http://domain1.com, http://domain2.com"
allowed-methods="GET, PUT"
allowed-headers="header1, header2, header3"
exposed-headers="header1, header2" allow-credentials="false"
max-age="123" />
<mvc:mapping path="/resources/**"
allowed-origins="http://domain1.com" />
</mvc:cors>
如果你正在使用Spring Security的,不要忘了enable CORS at Spring Security level 还有:
<http>
<!-- Default to Spring MVC's CORS configuration -->
<cors />
...
</http>
它是如何工作的?
CORS请求(包括那些预检与OPTIONS方法)被自动分发到各个HandlerMapping注册秒。他们处理CORS预检要求和拦截CORS简单而实际的请求得益于CorsProcessor实现(DefaultCorsProcessor以添加相关CORS响应头(如默认情况下)Access-Control-Allow-Origin)。CorsConfiguration允许你指定CORS请求应如何处理:允许起源,头,方法等,可以以各种方式提供:
AbstractHandlerMapping#setCorsConfiguration()允许指定Map几个CorsConfiguration映射路径模式,如/api/**- 子类可以提供自己
CorsConfiguration的首要AbstractHandlerMapping#getCorsConfiguration(Object, HttpServletRequest)方法 - 处理程序可以实现
CorsConfigurationSource接口(像ResourceHttpRequestHandler现在一样),以提供一个CorsConfiguration为每个请求。
基于过滤器CORS支持
至于其它方法替代以上呈现,Spring框架还提供了一个CorsFilter。在这种情况下,而不是使用@CrossOrigin或WebMvcConfigurer#addCorsMappings(CorsRegistry),例如,你可以声明过滤器在Spring boot应用程序如下:
@Configuration
public class MyConfiguration { @Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://domain1.com");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
}
springmvc springboot 跨域问题(CORS)的更多相关文章
- springboot 项目跨域问题 CORS
package com.example.demo.cors; import org.springframework.context.annotation.Bean; import org.spring ...
- java springmvc 前端 跨域问题
有个朋友在写扇贝插件的时候遇到了跨域问题.于是我对解决跨域问题的方式进行了一番探讨. 问题 API:查询单词URL: https://api.shanbay.com/bdc/search/?word= ...
- SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域
SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域 >>>>>>>>>>>> ...
- SpringMVC解决跨域问题
有个朋友在写扇贝插件的时候遇到了跨域问题. 于是我对解决跨域问题的方式进行了一番探讨. 问题 API:查询单词 URL: https://api.shanbay.com/bdc/search/?wor ...
- 前后端分离框架前端react,后端springboot跨域问题分析
前后端分离框架前端react,后端springboot跨域问题分析 为啥跨域了 前端react的设置 springboot后端设置 为啥跨域了 由于前后端不在一个端口上,也是属于跨域问题的一种,所以必 ...
- [转载]SpringMVC解决跨域问题
本文转载自 https://www.cnblogs.com/morethink/p/6525216.html SpringMVC解决跨域问题, 感谢作者! 有个朋友在写扇贝插件的时候遇到了跨域问题. ...
- SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域[转]
SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域 原文地址:https://www.cnblogs.com/fanshuyao/p/716847 ...
- springboot跨域请求
首页 所有文章 资讯 Web 架构 基础技术 书籍 教程 Java小组 工具资源 SpringBoot | 番外:使用小技巧合集 2018/09/17 | 分类: 基础技术 | 0 条评论 | 标 ...
- 跨域问题-cors
什么是跨域如大家所知,出于安全考虑,浏览器会限制脚本中发起的跨站请求.比如,使用 XMLHttpRequest 对象发起 HTTP 请求就必须遵守同源策略(same-origin policy). 具 ...
随机推荐
- bind 详解
请看我的有道云笔记: http://note.youdao.com/noteshare?id=eaf4194473cf4294776fbc263ffe6b89&sub=5CB214C594E0 ...
- pl/sql 存储过程执行execute immediate 卡住
在存储过程中,执行了create table.update table.insert into table 但是在使用pl/sql的存储过程调试的时候,一有问题就直接卡住(标识:执行中.....) 后 ...
- Orchard Core 使用工作流处理审批和创建内容项
译自:http://www.ideliverable.com/blog/orchard-core-workflows-walkthrough-content-approval 转载请注明出处, 原文地 ...
- 【转载】#446 - Deciding Between an Abstract Class and an Interface
An abstract class is a base class that may have some members not implemented in the base class, but ...
- [转]查找问题的利器 - Git Bisect
转自:http://gitbook.liuhui998.com/5_4.html 假设你在项目的'2.6.18'版上面工作, 但是你当前的代码(master)崩溃(crash)了. 有时解决这种问题的 ...
- note01-计算机网络
1.基础概述 三网: 电信网络.有线电视网络.计算机网络(连通&共享) 终端->z本地ISP->x地区IXP->y主干ISP 通信方式: C/S .P2P(即是client也 ...
- POSIX多线程—线程基本概念
http://blog.csdn.net/livelylittlefish/article/details/7957007 作者:阿波链接:http://blog.csdn.net/livelylit ...
- Wannafly模拟赛
题目描述 给出一个n * m的矩阵.让你从中发现一个最大的正方形.使得这样子的正方形在矩阵中出现了至少两次.输出最大正方形的边长. 输入描述: 第一行两个整数n, m代表矩阵的长和宽: 接下来n行,每 ...
- 自定义Powershell提示符
实现效果: 实现原理: Powershell将个人配置脚本文件的地址存放在$profile变量中, 通过修改该变量达到想要的目的. 实现过程: 1>创建一个新的配置脚本: 2>编辑脚本内容 ...
- VK Cup 2012 Round 1 D. Distance in Tree (树形dp)
题目:http://codeforces.com/problemset/problem/161/D 题意:给你一棵树,问你两点之间的距离正好等于k的有多少个 思路:这个题目的内存限制首先大一倍,他有5 ...