Spring Boot实现跨域(转)
一、方法:
- 服务端设置Respone Header头中Access-Control-Allow-Origin
- 配合前台使用jsonp
- 继承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实现跨域(转)的更多相关文章
- Spring Boot 允许跨域设置失败的问题深究
在公司开发过程中,一个前后端分离的项目遇见了跨域的问题. 前端控制台报错:No 'Access-Control-Allow-Origin' header is present on the reque ...
- 玩转spring boot——ajax跨域
前言 java语言在多数时,会作为一个后端语言,为前端的php,node.js等提供API接口.前端通过ajax请求去调用java的API服务.今天以node.js为例,介绍两种跨域方式:Cross ...
- Spring/Spring MVC/Spring Boot实现跨域
说明:Spring MVC和Spring Boot其实用的都是同一套. CORS介绍请看这里:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Acc ...
- Spring Boot + Vue 跨域请求问题
使用Spring Boot + Vue 做前后端分离项目搭建,实现登录时,出现跨域请求 Access to XMLHttpRequest at 'http://localhost/open/login ...
- spring boot 解决 跨域 的两种方法 -- 前后端分离
1.前言 以前做项目 ,基本上是使用 MVC 模式 ,使得视图与模型绑定 ,前后端地址与端口都一样 , 但是现在有些需求 ,需要暴露给外网访问 ,那么这就出现了个跨域问题 ,与同源原则冲突, 造成访问 ...
- 【Spring Boot】Spring Boot之跨域解决方案
一.什么是跨域 跨域,指的是从一个域名去请求另外一个域名的资源.即跨域名请求!跨域时,浏览器不能执行其他域名网站的脚本,是由浏览器的同源策略造成的,是浏览器施加的安全限制. 跨域的严格一点来讲就是只要 ...
- spring boot 解决跨域访问
package com.newings.disaster.shelters.configuration; import org.springframework.context.annotation.B ...
- spring mvc \ spring boot 允许跨域请求 配置类
用@Component 注释下,随便放个地方就可以了 package com.chinaws.wsarchivesserver.core.config; import org.springframew ...
- 踩坑录- Spring Boot - CORS 跨域 - 浏览器同源策略
1.解决办法,创建一个过滤器,处理所有response响应头 import java.io.IOException; import javax.servlet.Filter; import javax ...
随机推荐
- Farseer.net轻量级ORM开源框架 V1.x 入门篇:表的数据操作
导航 目 录:Farseer.net轻量级ORM开源框架 目录 上一篇:Farseer.net轻量级ORM开源框架 V1.x 入门篇:表实体类映射 下一篇:Farseer.net轻量级ORM开源框 ...
- win+r 快速命令
control keymgr.dll 打开凭据管理器 secpol.msc 本地安全策略 mstsc 远程 msconfig 启动选项 %temp% 临时文件夹 \\192.168 ...
- codeforces_C. Maximum Subrectangle
http://codeforces.com/contest/1060/problem/C 题意: a.b数组长度分别为n.m.矩阵C,Cij=ai*bj.在C中找到一个子矩阵,该子矩阵所有元素和不大于 ...
- swift 使用计算属性+结构管理内存
class GooClass { deinit { print("aaaaaaaa") } var str = "gooClass" } struct GooS ...
- CSS3 四边形 凹角写法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 火狐加载用户配置文件 "C:\XXX\Mozilla Firefox\firefox.exe" http://192.168.1.1:8080 -profile ../kkk
"C:\XXX\Mozilla Firefox\firefox.exe" http://192.168.1.1:8080 -profile ../kkk $("#clic ...
- 【转】UpdateData()函数
一.总结UpdateData()函数 UpdateData(true);//用于将屏幕上控件中的数据交换到变量中. UpdateData(false);//用于将数据在屏幕中对应控件中显示出来. 当你 ...
- 深入React技术栈之setState详解
抛出问题 class Example extends Component { contructor () { super() this.state = { value: 0, index: 0 } } ...
- C51 动态数码管 个人笔记
8段led管构成一个数字. 开发板上共有8个数字. 每个数字有一个使能端(段选引脚) 每个数字的位选端(选择8段led管哪些亮,即构成什么图案)并联在一起 轮流点亮不同数字,速度很快,视觉暂留,从而形 ...
- Android BottomSheet:List列表或Grid网格展示(3)
Android BottomSheet:List列表或Grid网格展示(3) BottomSheet可以显示多种样式的底部弹出面板风格,比如常见的List列表样式或者Grid网格样式,以一个例子 ...