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). 具 ...
随机推荐
- Visual Studio 发布 Windows Service小记
第一步:新建一个Window服务 第二步:添加安装程序 第三步,配置属性信息(Account选择LocalService) 第四步,在 OnStart和OnStop方法中写上你要干的事情吧.我这里用Q ...
- c++ 单继承派生类的构造函数
1.派生类的构造函数: #include <iostream> #include<string> using namespace std; class Student//声明基 ...
- java递归菜单树转换成pojo对象
package com.cjonline.foundation.authority.pojo; import java.util.ArrayList; import java.util.Collect ...
- 使用dva框架的总结
最近的项目是react+dva+atd+webpack的一个后台项目,刚接触dva就感觉很喜欢,很简洁用着很爽. 关于使用redux中的一些问题 1.文件切换问题. redux的项目通常哟啊分为red ...
- springboot缓存的使用
spring针对各种缓存实现,抽象出了CacheManager接口,用户使用该接口处理缓存,而无需关心底层实现.并且也可以方便的更改缓存的具体实现,而不用修改业务代码.下面对于在springboot中 ...
- Beginning DirectX11 Game Programming
DirectX11 or 10 made a big change comparing to DirectX9 The fixed-function pipeline was removed in D ...
- 基于 UIImagePickerController 的拓展封装 - iOS
基于 UIImagePickerController 的拓展,分别支持调用相机.相册的功能,其中相机可以设置默认调用前后摄像头; 简单对此进行了封装和实现,其中还有很多点可以继续挖掘和优化,该版本具体 ...
- Struts2知识点小结(二)
一.结果视图的配置 <result name="success">/success.jsp</result> 1.局部结果视图 ...
- 模块socket使用
什么是socket:socket是应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口.我们无需再去深入理解tcp/udp协议,按照socket的规定去使用就行了. 首先一个c/s架构:分为两 ...
- 不再手写import - VSCode自动引入Vue组件和Js模块
:first-child{margin-top:0!important}.markdown-body>:last-child{margin-bottom:0!important}.markdow ...