Spring MVC 从4.2版本开始增加了对CORS的支持,可以全局配置,也可以对类或方法配置;可以通过Java代码,也可以通过xml配置方式。

对于低版本的Spring MVC 可以通过Filter 往response写http header来实现

还有一种更省事的办法是在Nginx上加入支持。

Java配置

新建一个类,做跨域的配置

@Configuration
@EnableWebMvc
public class CorsConfigureAdapter extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
super.addCorsMappings(registry);
registry.addMapping("/**");
}
}

在Controller上或方法上使用@CrossOrigin注解

@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController { @CrossOrigin("http://domain2.com")
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
} @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}

基于XML的配置

<mvc:cors>
<mvc:mapping path="/**" />
</mvc:cors>

这个配置和上面JAVA方式的第一种作用一样。

同样,你可以做更复杂的配置:

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

SpringMVC 3 支持跨域

SpringMVC 3不支持以上方法,通过Filter的方式实现。

@Component
public class SimpleCORSFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
} public void init(FilterConfig filterConfig) {}
public void destroy() {}
}

web.xml里配置

<filter>
<filter-name>cors</filter-name>
<filter-class>test.cors.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Nginx支持跨域请求

需要在配置里添加add_header Access-Control*指令,如:

location /{
add_header 'Access-Control-Allow-Origin' 'http://other.subdomain.com';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET';
...
the rest of your configuration here
...
}

作者:happeace

链接:https://www.jianshu.com/p/453afeef49c1

Spring MVC 后端接口支持跨域CORS调用的更多相关文章

  1. springboot webapi 支持跨域 CORS

    1.创建corsConfig 配置文件 @Configuration public class corsConfig { @Autowired varModel varModel_; @Bean pu ...

  2. [JAVA]SpringBoot中让接口支持跨域

    官方原文:https://spring.io/blog/2015/06/08/cors-support-in-spring-framework ===抽空翻译 最简单办法:在方法上增加注解: @Cro ...

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

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

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

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

  5. spring boot + spring security +前后端分离【跨域】配置 + ajax的json传输数据

    1.前言 网上各个社区的博客参差不齐 ,给初学者很大的困扰 , 我琢磨了一天一夜,到各个社区找资料,然后不断测试,遇到各种坑,一言难尽啊,要么源码只有一部分,要么直接报错... 最后实在不行,直接去看 ...

  6. python 全栈开发,Day100(restful 接口,DRF组件,DRF跨域(cors组件))

    昨日内容回顾 1. 为什么要做前后端分离? - 前后端交给不同的人来编写,职责划分明确.方便快速开发 - 针对pc,手机,ipad,微信,支付宝... 使用同一个接口 2. 简述http协议? - 基 ...

  7. .Net WebApi 支持跨域访问使用 Microsoft.AspNet.WebApi.Cors

    首先导入Cors库,通过程序包管理控制台导入 Install-Package Microsoft.AspNet.WebApi.Cors 引用库之后,我们需要进行简单的配置. 现在WebApiConfi ...

  8. 使Web Api 支持跨域资源共享(CORS)

    Reference:http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api Imp ...

  9. Asp.Net Web Api 接口,拥抱支持跨域访问。

    如何让你的 Asp.Net Web Api 接口,拥抱支持跨域访问. 由于 web api 项目通常是被做成了一个独立站点,来提供数据,在做web api 项目的时候,不免前端会遇到跨域访问接口的问题 ...

随机推荐

  1. day5 io模型

    五种概览:http://www.cnblogs.com/xiehongfeng100/p/4763225.html http://sukai.me/linux-five-io-models/  内有多 ...

  2. CentOS 6.5 部署 Horizon

    以root用户进行部署,python源也可以使用 http://mirrors.aliyun.com/pypi/simple/ 修改系统 更改SElinux的配置文件 /etc/selinux/con ...

  3. BZOJ3894:文理分科(最大流)(同BZoj3438)

    文理分科是一件很纠结的事情!(虽然看到这个题目的人肯定都没有纠 结过) 小P所在的班级要进行文理分科.他的班级可以用一个n*m的矩阵进行 描述,每个格子代表一个同学的座位.每位同学必须从文科和理科中选 ...

  4. iPhone4s 9.2.1安装cydia(越狱)

    依据网上资料而来 主要就是上图视频中的6步骤选项,不要选错. 1.prepare for jailbreak 2.选择Accept 3. proceed with jailbreak 4.begin ...

  5. ubuntu 新手帖

    作为菜鸟,接触ubuntu的时间不长,遇到一些问题,在这总结一下,可能不全不完善,但是希望能有用: 1,ubuntu 12.04的gedit打开中文记事本全是乱码的处理 参考:http://bbs.c ...

  6. Django基于Form之登录和注册

    1.创建Forms文件,内容略多,大家将就着看,不懂请留言 #!/usr/bin/env python # -*- coding: utf8 -*- #__Author: "Skiler H ...

  7. flex 伸缩布局

    伸缩布局 布局的传统解决方案,基于盒状模型,依赖 display属性 + position属性 + float属性.它对于那些特殊布局非常不方便.CSS3在布局方面做了非常大的改进,使得我们对块级元素 ...

  8. 相对导入中Attempted relative import in non-package问题

    这一篇应该是解释的比较清楚: http://stackoverflow.com/questions/14664313/attempted-relative-import-in-non-package- ...

  9. Ubuntu 破解密码及用户管理

    Ubuntu 破解密码及用户管理 ubuntu 16.04 破解密码 useradd 实现以下要求 1.ubuntu16.04破解密码 2.创建下面的用户.组和组成员关系 名字为xipudata 的组 ...

  10. c++里面有没有什么办法做到 判断某个给定的未知数是double类型还是int类型 呢?

    c++里面有没有什么办法做到 判断某个给定的未知数是double类型还是int类型 呢? 如果只是double和int, 可以用sizeof 1 2 3 4 5 6 7 8 9 10 11 12 13 ...