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. 一个简单的perl程序

    和朋友聊天,说perl的神奇,最主要的是一行代码搞定所有. 想想用python3写的测试脚本,觉得还是有点多的,真的用几行代码写一个测试脚本,可以节约不少时间. 当然,网上黑perl的还是很多,不过自 ...

  2. Java获取正在执行的函数名

    利用StackTrace堆栈轨迹获取某个时间的调用堆栈状态. package com.dsp.demo; public class TechDemo { public static void main ...

  3. IO多路复用的机制:select、poll、epoll

    select.poll.epoll之间的区别总结[整理] IO多路复用之epoll总结 我读过的最好的epoll讲解--转自”知乎“

  4. Linux Shell nohup命令用法

    linux的nohup命令的用法.   在应用Unix/Linux时,我们一般想让某个程序在后台运行,于是我们将常会用 & 在程序结尾来让程序自动运行.比如我们要运行mysql在后台: /us ...

  5. JsonObject和Gson详解

    参考文件:http://www.cnblogs.com/xwdreamer/archive/2011/12/16/2296904.html一.JsonObject 1.JAR包简介 要使程序可以运行必 ...

  6. Xianfeng轻量级Java中间件平台:属性管理、字典管理

    属性管理:主要功能是维护一些系统定义的.业务定义的属性数据,至于属性是什么,简单的说就是由键key和值value组成的数据,属性查询列表页面如下: 表格实现了直接编辑的功能 字典管理:主要功能是维护一 ...

  7. windows 找不到文件'igfxHK.exe'

    现象:开机时windows报:windows 找不到文件'igfxHK.exe' 解决办法:win+r  输入services.msc  进入服务管理, 找到服务名称为: Intel(R) HD Gr ...

  8. lakala反欺诈建模实际应用代码GBDT监督学习

    /** * Created by lkl on 2018/1/16. */ import org.apache.spark.mllib.evaluation.BinaryClassificationM ...

  9. 简单理解AOP(面向切面编程)

    AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术. AOP与OOP是面向不同领域的两种设计思想. ...

  10. 【NLP】simhash判断文档相似度

    http://blog.csdn.net/heiyeshuwu/article/details/44117473