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 ...
随机推荐
- 将call/apply方法应用于其他对象上的几种方法
在处理类数组中,发现了两种将数组方法应用于类数组的方法,现将call/apply的常用方式总结一下. 一.当做函数调用 function print_vars(var1,var2){ console. ...
- Java数据类型和MySql数据类型对应一览 [转]
类型名称 显示长度 数据库类型 JAVA类型 JDBC类型索引(int) 描述 VARCHAR L+N VARCHAR java.lang.String 12 CHAR N ...
- SDK manager.exe 运行时报错:系统找不到指定的文件 android.bat
android studio 2.3.1的 SDK Manager工具 突然没有 Launcher XXX 那个按钮,只好到SDK目录中去启动,无奈发生以下错误. 解决办法:运行android.bat ...
- Android(java)学习笔记191:ContentProvider使用之利用ContentProvider备份和还原手机短信(掌握)
1. 通过阅读系统源码我们知道: 短信的内容提供者: content://sms/ 系统短信的内容提供者的路径 2. 利用ContentProvider备份和还原手机短信: (1 ...
- C# 支持多线程
C# 支持多线程并行执行程序 .一个程序由一个单线程开始,该单线程由CLR和操作系统创建而成,并具有多线程创建额外线程的功能. .创建线程的方法 2.1 通过Thread类来创建线程. ThreadS ...
- hibernate 5.x版本中中schemaexport的使用
public static void main(String[] args) { /*//创建hibernate配置对象 Configuration cfg = new Configuration() ...
- idea vue提示
我在idea中,装了,vue.js插件,可就是死活,没有提示,我的html 文件是 .html扩展名,我想是不是因为这个原因,我就新建了个,test.vue,哈哈,提示出来了,我又在其它.html文件 ...
- 通过JS判断联网类型和连接状态的实现代码
<!DOCTYPE HTML><html xmlns="http://www.w3.org/1999/xhtml" lang="en"> ...
- BZOJ 4464 旅行时的困惑 最小流
题面: Waldives 有 N 个小岛.目前的交通系统中包含 N-1 条快艇专线,每条快艇 专线连接两个岛.这 N-1条快艇专线恰好形成了一棵树. 由于特殊的原因,所有N-1条快艇专线都是单向的.这 ...
- AC手动机 [原创]
题目背景 Monster_Qi 又双叒叕拿到了rank1! 在开心之余他决定帮助蒟蒻floatiy拿到合适的排名. 题目描述 已知考试有n道题,每道题有num个测试点,有m个人 b[x,i,j](01 ...