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 GETHEAD 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:

spring mvc 跨域请求处理——spring 4.2 以上的更多相关文章

  1. 关于Spring MVC跨域

    1.Sping MVC 3.X跨域 关于跨域问题,主要用的比较多的是cros跨域. 详细介绍请看https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Ac ...

  2. spring mvc 跨域问题。。。解决

    官方推荐方式: http://spring.io/blog/2015/06/08/cors-support-in-spring-framework 方式1: $.ajax({ //前台:常规写法.注意 ...

  3. spring mvc跨域设置(全局)

    //--------------第一步//spring 5版本全局配置方式 @Configuration @EnableWebMvc public class SpringMvcBeans imple ...

  4. spring mvc跨域(ajax post json)--filter方案

    @RequestMapping(value = "/login.do",method = RequestMethod.POST) public Message login(Http ...

  5. spring mvc跨域(post)--filter方案

    import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.Http ...

  6. spring boot跨域请求访问配置以及spring security中配置失效的原理解析

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

  7. spring boot 跨域请求

    场景 网站localhost:56338要访问网站localhost:3001的服务 在网站localhost:3001中增加CORS相关Java Config @Configuration @Ord ...

  8. SpringBoot 优雅配置跨域多种方式及Spring Security跨域访问配置的坑

    前言 最近在做项目的时候,基于前后端分离的权限管理系统,后台使用 Spring Security 作为权限控制管理, 然后在前端接口访问时候涉及到跨域,但我怎么配置跨域也没有生效,这里有一个坑,在使用 ...

  9. Spring MVC 3.0.5+Spring 3.0.5+MyBatis3.0.4全注解实例详解(二)

    在上一篇文章中我详细的介绍了如何搭建maven环境以及生成一个maven骨架的web项目,那么这章中我将讲述Spring MVC的流程结构,Spring MVC与Struts2的区别,以及例子中的一些 ...

随机推荐

  1. FusionCancer-人类癌症相关的融合基因的数据库

    RNA-seq 测序可以用于融合基因的发现,在过去的十几年里,RNA-seq 测序数据不断增加,发现的融合基因的数据也不断增加: FusionCancer 是一个人类癌症相关的融合基因的数据库,利用N ...

  2. 仿网易nec首页动画效果

    仿网页nec首页动画效果nec链接:http://nec.netease.com/ 首先,介绍animationanimation检索或设置对象所应用的动画特效.animation由“keyframe ...

  3. 如何在Sql Server中读取最近一段时间的记录,比如取最近3天的或最近3个月的记录。

    如何在Sql Server中读取最近一段时间的记录,比如取最近3天的或最近3个月的记录. 主要用到DATEADD函数,下面是详细语句 取最近3天 select * from 表名where rq> ...

  4. CorelDRAW中如何分布对象

    分布对象功能主要用来控制选择对象之间的距离,可以满足用户对均匀间距的要求,通常用于选择三个或三个以上的物体,将他们之间的距离平均分布.本教程将详解CorelDRAW中关于分布对象的操作. CorelD ...

  5. tomcat设置debug模式

    1.设置 编辑catalina.bat,在 rem Guess CATALINA_HOME if not definedset "CURRENT_DIR=%cd%"if not & ...

  6. Java正则表达式的使用和详解(上)

    1.匹配验证-验证Email是否正确 public static void main(String[] args) { // 要验证的字符串 String str = "service@xs ...

  7. 转:Hibernate query.list()之卡住问题

    某个函数里面有调用Query的list()方法,然后它有时会出现这种症状: 忽然停住不动,但是也没报异常,就是界面死了. 我的查询差不多是这样: Query q=sessionFactory.open ...

  8. HTML5标签embed详解

    摘要: <embed> 标签是 HTML 5 中的新标签,用来定义嵌入的内容,比如插件.类似于HTML 4.01 中的object和applet标签.我们要在网页中正常显示flash内容, ...

  9. [Object Tracking] Identify and Track Specific Object

    Abstract—Augmented Reality (AR) has become increasingly popular in recent years and it has a widespr ...

  10. mac版本cornerstone的无限期破解方法(转)

    CornerStone是个人非常喜欢的mac上的一款SVN客户端工具,官方提供了14天的免费试用(trail)版本.我们可以在此基础上提供无限期试用版本. 方法一:如果你从来没有安装过这个trail版 ...