spring mvc 跨域请求处理——spring 4.2 以上
Controller method CORS configuration
You can add to your @RequestMapping annotated handler method a @CrossOrigin annotation in order to enable CORS on it (by default @CrossOrigin allows all origins and the HTTP methods specified in the @RequestMapping annotation):
@RestController
@RequestMapping("/account")
public class AccountController {
@CrossOrigin
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
It is also possible to enable CORS for the whole controller:
@CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
In this example CORS support is enabled for both retrieve() and remove() handler methods, and you can also see how you can customize the CORS configuration using@CrossOrigin attributes.
You can even use both controller and method level CORS configurations, Spring will then combine both annotation attributes to create a merged CORS configuration.
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {
@CrossOrigin(origins = "http://domain2.com")
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
@RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
Global CORS configuration
In addition to fine-grained, annotation-based configuration you’ll probably want to define some global CORS configuration as well. This is similar to using filters but can be declared withing Spring MVC and combined with fine-grained @CrossOrigin configuration. By default all origins and GET, HEAD and POST methods are allowed.
JavaConfig
Enabling CORS for the whole application is as simple as:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
You can easily change any properties, as well as only apply this CORS configuration to a specific path pattern:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@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);
}
}
XML namespace
It is also possible to configure CORS with the mvc XML namespace.
This minimal XML configuration enable CORS on /** path pattern with the same default properties than the JavaConfig one:
<mvc:cors>
<mvc:mapping path="/**" />
</mvc:cors>
It is also possible to declare several CORS mappings with customized properties:
<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>
How does it work?
CORS requests (including preflight ones with an OPTIONS method) are automatically dispatched to the various HandlerMappings registered. They handle CORS preflight requests and intercept CORS simple and actual requests thanks to a CorsProcessor implementation (DefaultCorsProcessor by default) in order to add the relevant CORS response headers (likeAccess-Control-Allow-Origin). CorsConfiguration allows you to specify how the CORS requests should be processed: allowed origins, headers, methods, etc. It can be provided in various ways:
AbstractHandlerMapping#setCorsConfiguration()allows to specify aMapwith severalCorsConfiguration mapped on path patterns like/api/**- Subclasses can provide their own
CorsConfigurationby overridingAbstractHandlerMapping#getCorsConfiguration(Object, HttpServletRequest)method - Handlers can implement
CorsConfigurationSourceinterface (likeResourceHttpRequestHandlernow does) in order to provide a CorsConfiguration for each request.
spring mvc 跨域请求处理——spring 4.2 以上的更多相关文章
- 关于Spring MVC跨域
1.Sping MVC 3.X跨域 关于跨域问题,主要用的比较多的是cros跨域. 详细介绍请看https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Ac ...
- spring mvc 跨域问题。。。解决
官方推荐方式: http://spring.io/blog/2015/06/08/cors-support-in-spring-framework 方式1: $.ajax({ //前台:常规写法.注意 ...
- spring mvc跨域设置(全局)
//--------------第一步//spring 5版本全局配置方式 @Configuration @EnableWebMvc public class SpringMvcBeans imple ...
- spring mvc跨域(ajax post json)--filter方案
@RequestMapping(value = "/login.do",method = RequestMethod.POST) public Message login(Http ...
- spring mvc跨域(post)--filter方案
import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.Http ...
- spring boot跨域请求访问配置以及spring security中配置失效的原理解析
一.同源策略 同源策略[same origin policy]是浏览器的一个安全功能,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源. 同源策略是浏览器安全的基石. 什么是源 源[orig ...
- spring boot 跨域请求
场景 网站localhost:56338要访问网站localhost:3001的服务 在网站localhost:3001中增加CORS相关Java Config @Configuration @Ord ...
- SpringBoot 优雅配置跨域多种方式及Spring Security跨域访问配置的坑
前言 最近在做项目的时候,基于前后端分离的权限管理系统,后台使用 Spring Security 作为权限控制管理, 然后在前端接口访问时候涉及到跨域,但我怎么配置跨域也没有生效,这里有一个坑,在使用 ...
- Spring MVC 3.0.5+Spring 3.0.5+MyBatis3.0.4全注解实例详解(二)
在上一篇文章中我详细的介绍了如何搭建maven环境以及生成一个maven骨架的web项目,那么这章中我将讲述Spring MVC的流程结构,Spring MVC与Struts2的区别,以及例子中的一些 ...
随机推荐
- ZooKeeper系列
Zookeeper系列(一) ZooKeeper系列(二) ZooKeeper系列(三) ZooKeeper系列(四)
- 启动其他APK的Activity方法 (转至http://www.cnblogs.com/lijunamneg/archive/2013/02/26/2934060.html)
有两个app,分别叫做App1和App2.App1包含两个Activity,分别叫做App1_A和App1_B.其中App1_A是入口Activity.也就是App1_A设置intent-filter ...
- C# 导出资源文件到硬盘
我把一个exe应用程序添加了资源里面, 我想,程序运行之后,点击按钮之后,就把这个资源文件导出到硬盘, 代码如下: private void button1_Click(object sender, ...
- Hibernate的七种映射关系之基本映射
说到关系,在这个世界无处不在,我们必须以某个关系的节点存在在这个世界网中.比如父子关系,师生关系,上下属关系甚至是危险关系.数据也是一样的,它的存在必为某其他节点做准备. Hibernate有七种映射 ...
- 038改变状态栏的颜色(扩展知识:关于iOS不同版本的消息通知知识)
效果如下: ViewController.h #import <UIKit/UIKit.h> @interface ViewController : UIViewController @e ...
- Linq 查询某个字段为null的数据
如tb_flag 数据结构如下:flag int null 不能使用:flag==null 生成的SQL语句为 where flag=null 建议使用:可空类型 用Nullable<T&g ...
- 将nosetests的echo结果保存到本地文件
nose是很好用的python 测试框架. 但是一直很纠结如何将结果保存到本地.采用nosetests -h查看相关的options,找到一个xunit的东西,似乎可以实现功能. 测试结果: 可见,已 ...
- spring aop的配置
http://www.cnblogs.com/oumyye/p/4480196.html http://blog.csdn.net/hjm4702192/article/details/1727766 ...
- python中是否有单独的字符类型,通过下标的方式表示字符串中的字符
说明: 在python中,没有单独的字符类型,一个字符呢就是一个大小为1的字符串. 并且可以通过下标的方式,表示字符串中的字符. 操作过程: 1.通过[ ]的方式表示字符串中的第几个字符 >&g ...
- 让maven使用国内镜像和archetypeCatalog
https://blog.csdn.net/zhang_red/article/details/54603530