微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用Spring CROS解决项目中的跨域问题详解

这篇文章主要介绍了使用Spring CROS解决项目中的跨域问题详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

CROS(Cross-Origin Resource Sharing) 用于解决浏览器中跨域请求的问题。简单的Get请求可以使用JSONP来解决,而对于其它复杂的请求则需要后端应用的支持CROS。Spring在4.2版本之后提供了@CrossOrigin 注解来实现对Cross的支持

在Controller方法上配置

@CrossOrigin(origins = {"http://loaclhost:8088"}) @RequestMapping(value = "/crosstest",method = RequestMethod.GET) public String greeting() { return "coRSS test"; }

在Controller上配置,那么这个Controller中的所有方法都会支持CORS

import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @CrossOrigin(origins = "http://localhost:8088",maxAge = 3600) @Controller @RequestMapping("/api") public class AppController { @RequestMapping(value = "/crosstest",method = RequestMethod.GET) public String greeting() { return "coRSS test"; } }

Java Config全局配置

import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @EnableWebMvc public class SpringWebConfig extends WebMvcConfigurerAdapter { /** * {@inheritDoc} * This implementation is empty. * * @param registry */ @Override public void addCorsMappings(CorsRegistry registry) { super.addCorsMappings(registry); // 对所有的URL配置 registry.addMapping("/**"); // 针对某些URL配置 registry.addMapping("/api/**").allowedOrigins("http:///localhost:8088") .allowedMethods("PUT","DELETE") .allowedHeaders("header1","header2","header3") .exposedHeaders("header1","header2") .allowCredentials(false).maxAge(3600); } }

XML全局配置

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐