官方文档: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配置。默认情况下,所有的起源和GETHEADPOST方法都是允许的。

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请求应如何处理:允许起源,头,方法等,可以以各种方式提供:

基于过滤器CORS支持

至于其它方法替代以上呈现,Spring框架还提供了一个CorsFilter。在这种情况下,而不是使用@CrossOriginWebMvcConfigurer#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)的更多相关文章

  1. springboot 项目跨域问题 CORS

    package com.example.demo.cors; import org.springframework.context.annotation.Bean; import org.spring ...

  2. java springmvc 前端 跨域问题

    有个朋友在写扇贝插件的时候遇到了跨域问题.于是我对解决跨域问题的方式进行了一番探讨. 问题 API:查询单词URL: https://api.shanbay.com/bdc/search/?word= ...

  3. SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域

    SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域 >>>>>>>>>>>> ...

  4. SpringMVC解决跨域问题

    有个朋友在写扇贝插件的时候遇到了跨域问题. 于是我对解决跨域问题的方式进行了一番探讨. 问题 API:查询单词 URL: https://api.shanbay.com/bdc/search/?wor ...

  5. 前后端分离框架前端react,后端springboot跨域问题分析

    前后端分离框架前端react,后端springboot跨域问题分析 为啥跨域了 前端react的设置 springboot后端设置 为啥跨域了 由于前后端不在一个端口上,也是属于跨域问题的一种,所以必 ...

  6. [转载]SpringMVC解决跨域问题

    本文转载自  https://www.cnblogs.com/morethink/p/6525216.html SpringMVC解决跨域问题, 感谢作者! 有个朋友在写扇贝插件的时候遇到了跨域问题. ...

  7. SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域[转]

    SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域 原文地址:https://www.cnblogs.com/fanshuyao/p/716847 ...

  8. springboot跨域请求

      首页 所有文章 资讯 Web 架构 基础技术 书籍 教程 Java小组 工具资源 SpringBoot | 番外:使用小技巧合集 2018/09/17 | 分类: 基础技术 | 0 条评论 | 标 ...

  9. 跨域问题-cors

    什么是跨域如大家所知,出于安全考虑,浏览器会限制脚本中发起的跨站请求.比如,使用 XMLHttpRequest 对象发起 HTTP 请求就必须遵守同源策略(same-origin policy). 具 ...

随机推荐

  1. Orchard Core 中文文档翻译(一)关于Orchard Core

    原文连接:https://www.cnblogs.com/Qbit/p/9746363.html 转载请注明出处 翻译说明:本系列为直译,按照官方的计划现在这个版本(2018年10月5日)已经接近最终 ...

  2. 【转载】#457 Converting Between enums and their Underlying Type

    When you declare an enum, by default each enumerated value is represented internally with an int. (S ...

  3. ul li一行两个显示

  4. 【洛谷5280】[ZJOI2019] 线段树(线段树大力分类讨论)

    点此看题面 大致题意: 给你一棵线段树,两种操作.一种操作将每棵线段树复制成两个,然后在这两个线段树中的一个上面进行\(Modify(l,r)\).另一种操作询问所有线段树的\(tag\)总和. 大力 ...

  5. POJ 2976 Dropping tests 【01分数规划+二分】

    题目链接:http://poj.org/problem?id=2976 Dropping tests Time Limit: 1000MS   Memory Limit: 65536K Total S ...

  6. (转)理解YOLOv2训练过程中输出参数含义

    最近有人问起在YOLOv2训练过程中输出在终端的不同的参数分别代表什么含义,如何去理解这些参数?本篇文章中我将尝试着去回答这个有趣的问题. 刚好现在我正在训练一个YOLOv2模型,拿这个真实的例子来讨 ...

  7. 初入AngularJS基础门

    作为mvvm 框架过重 不适用于性能比较高的移动端的web栈, ui组建性对复杂,不利于重用 AngularJS 构建一个CRUD ( create retrieve update delete )的 ...

  8. 数据库——MySQL——完整性约束

    约束,就是用来保证数据完整性和一致性的. 常见的约束分为: PRIMARY KEY (PK) 标识该字段为该表的主键,可以唯一的标识记录 FOREIGN KEY (FK) 标识该字段为该表的外键 NO ...

  9. Oracle客户端与Toad、plsql developer安装

    (一)oracle client与oracle instant client比较 当我们要使用Toad.plsql developer等工具连接数据库时,首先需要在自己的电脑上安装oracle cli ...

  10. SpringBoot学习16:springboot整合junit单元测试

    1.创建maven项目,修改pom.xml文件 <!--springboot项目依赖的父项目--> <parent> <groupId>org.springfram ...