一、方法:

  1. 服务端设置Respone Header头中Access-Control-Allow-Origin
  2. 配合前台使用jsonp
  3. 继承WebMvcConfigurerAdapter 添加配置类

二、实例:

后台(spring boot 1.3.7.RELEASE):

1、用一个Filter进行了身份验证同时进行了跨域处理,具体代码:

public class AuthFilter implements Filter {
// @Autowired
//这个不能自动注入servlet和filter是被tomcat管理的
private BaseUserService baseUserService;
private String[] excludePaths; @Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("initFilter");
//不能在初始化中通过Appliaction Context获取因为这时候还没初始化Application Context
//baseUserService = SpringUtils.getBean("baseUserService", BaseUserService.class);
excludePaths = new String[]{"/api/user/noLogin", "/api/user/tokenError", "/api/user/loginForeground",
"/api/user/loginBackground", "/api/user/inCorrectUserId"};
} @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
//这里填写你允许进行跨域的主机ip
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
//允许的访问方法
httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
//Access-Control-Max-Age 用于 CORS 相关配置的缓存
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
String userId = request.getParameter("userId");
String token = request.getParameter("token");
//有token的 `
if (userId != null && token != null) {
try {
Integer id = Integer.parseInt(userId);
if (baseUserService == null)
baseUserService = SpringUtils.getBean("baseUserService", BaseUserService.class);
int status = baseUserService.checkLogin(id, token);
if (status == 1) {
chain.doFilter(request, response);
} else if (status == 0) {
httpServletResponse.sendRedirect("/api/user/tokenError");
} else if (status == -2) {
httpServletResponse.sendRedirect("/api/user/inCorrectUserId");
} else {
httpServletResponse.sendRedirect("/api/user/noLogin");
}
} catch (NumberFormatException exception) {
httpServletResponse.sendRedirect("/api/user/inCorrectUserId");
}
} else {
String path = httpServletRequest.getServletPath();
if (excludePath(path)) {
chain.doFilter(request, response);
} else {
httpServletRequest.getRequestDispatcher("/api/user/noLogin").forward(request, response);
}
}
// ((HttpServletResponse) response).addHeader("Access-Control-Allow-Origin", "*");
// CorsFilter corsFilter=new CorsFilter(); } private boolean excludePath(String path) {
for (int i = 0; i < excludePaths.length; i++) {
if (path.equals(excludePaths[i]))
return true;
}
return false;
} @Override
public void destroy() {
System.out.println("destroy method");
} }

这种方法还适用于Servlet中,特别注意的是一定要在Filter动作之前加上这句话,也就是在代码的最前面加上这个话。

2、基于WebMvcConfigurerAdapter配置加入Cors的跨域

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration
public class CorsConfig extends WebMvcConfigurerAdapter { @Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600);
} }

这里有个坑,Spring Boot以前的版本这样设置可以用Filter,但是在1.3.7.RELEASE不能用,所以用第二种方式是万能的。

参考:

http://blog.csdn.net/hanghangde/article/details/53946366(以上内容转自此篇文章)

Spring Boot实现跨域(转)的更多相关文章

  1. Spring Boot 允许跨域设置失败的问题深究

    在公司开发过程中,一个前后端分离的项目遇见了跨域的问题. 前端控制台报错:No 'Access-Control-Allow-Origin' header is present on the reque ...

  2. 玩转spring boot——ajax跨域

    前言  java语言在多数时,会作为一个后端语言,为前端的php,node.js等提供API接口.前端通过ajax请求去调用java的API服务.今天以node.js为例,介绍两种跨域方式:Cross ...

  3. Spring/Spring MVC/Spring Boot实现跨域

    说明:Spring MVC和Spring Boot其实用的都是同一套. CORS介绍请看这里:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Acc ...

  4. Spring Boot + Vue 跨域请求问题

    使用Spring Boot + Vue 做前后端分离项目搭建,实现登录时,出现跨域请求 Access to XMLHttpRequest at 'http://localhost/open/login ...

  5. spring boot 解决 跨域 的两种方法 -- 前后端分离

    1.前言 以前做项目 ,基本上是使用 MVC 模式 ,使得视图与模型绑定 ,前后端地址与端口都一样 , 但是现在有些需求 ,需要暴露给外网访问 ,那么这就出现了个跨域问题 ,与同源原则冲突, 造成访问 ...

  6. 【Spring Boot】Spring Boot之跨域解决方案

    一.什么是跨域 跨域,指的是从一个域名去请求另外一个域名的资源.即跨域名请求!跨域时,浏览器不能执行其他域名网站的脚本,是由浏览器的同源策略造成的,是浏览器施加的安全限制. 跨域的严格一点来讲就是只要 ...

  7. spring boot 解决跨域访问

    package com.newings.disaster.shelters.configuration; import org.springframework.context.annotation.B ...

  8. spring mvc \ spring boot 允许跨域请求 配置类

    用@Component 注释下,随便放个地方就可以了 package com.chinaws.wsarchivesserver.core.config; import org.springframew ...

  9. 踩坑录- Spring Boot - CORS 跨域 - 浏览器同源策略

    1.解决办法,创建一个过滤器,处理所有response响应头 import java.io.IOException; import javax.servlet.Filter; import javax ...

随机推荐

  1. Vue.js学习笔记--2.基础v-指令

    整理自官网教程 -- https://cn.vuejs.org/ 1. v-bind绑定Class与Style a. 绑定Class 语法:v-bind:class="{classname: ...

  2. redis 在windows 集群

    前言:为什么自己要花时间写一篇redis集群文章,网上众多的文章大都是思路正确,但是细节不足,这里写一篇文章记录自己部署时候遇到的问题,当下次再部署的时候避免跳入重复的坑. 上篇文章(http://w ...

  3. Linux下支持mysql支持远程ip访问

    示例代码: use mysql; SELECT `Host`,`User` FROM user; UPDATE user SET `Host` = '%' WHERE `User` = 'use**' ...

  4. JS 中的 JSON

    JSON是JavaScript Object Notation的缩写,它是一种数据交换格式. 在JSON出现之前,大家一直用XML来传递数据.因为XML是一种纯文本格式,所以它适合在网络上交换数据.X ...

  5. Vuex/Vue 练手项目 在线汇率转换器

    详情请点击: https://zhuanlan.zhihu.com/p/33362758

  6. 解决【npm ERR! Unexpected end of JSON input while parsing near '...sh_time":141072930277'】方案

    问题描述执行npm install的时候报错npm ERR! Unexpected end of JSON input while parsing near '...sh_time":141 ...

  7. 关闭警告&关闭eslint

    1.main.js中添加 vue.config.productiontip = false  这样即可去除警告!  第一个除了那个配置意外,还需要将 NODE_ENV 设置为 production 参 ...

  8. hdfs深入:06、hdfs的写入过程

    7.HDFS的文件写入过程 详细步骤解析: 1. client发起文件上传请求,通过RPC与NameNode建立通讯,NameNode检查目标文件是否已存在,父目录是否存在,返回是否可以上传: 2. ...

  9. 51nod 1021 石子归并 - 区间dp(经典)

    题目地址:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1021 经典区间dp,dp[i][j] 表示将从 i 到 j 堆 ...

  10. Luogu P4299 首都 LCT

    既然是中文题目,这里便不给题意. 分析: 这个题的做法据说是启发式合并? 但是我不会啊…… 进入正题,LCT是怎样做掉这道题的.记得在前面的一篇<大融合>的题解中,介绍过LCT维护子树信息 ...