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 ...
随机推荐
- [BZOJ1798][AHOI2009]Seq维护序列 线段树
题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1798 一眼看过去线段树,事实上就是线段树.对于乘和加的两个标记,我们可以规定一个顺序,比如 ...
- R Programming week1-Reading Data
Reading Data There are a few principal functions reading data into R. read.table, read.csv, for read ...
- Maven error in eclipse (pom.xml) : Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4
i wanna make web project using the Maven to import automatically all libraries that i need, so i cho ...
- tf.app.run() got unexpected keyword argument 'argv'
运行的代码是mnist_with_summaries.py.出现的问题是 tf.app.run() got unexpected keyword argument 'argv' 昨天一直以为是我自己不 ...
- oracle 表之间的连接
排序 - - 合并连接(Sort Merge Join, SMJ): a) 对于非等值连接,这种连接方式的效率是比较高的. b) 如果在关联的列上都有索引,效果更好. c) 对于将2个较大的row s ...
- vc++实现控制USB设备启用与否
#include <WINDOWS.H> #include <TCHAR.H> #include <SETUPAPI.H> //#in ...
- 用字符串对列表赋值,一个字符串对应一个列表元素,eg: my @escaped = "asteriskasterisk hash access unpack_func";
my @escaped = "asteriskasterisk hash access unpack_func"; # 是一个元素的赋值 25 unless( $escap ...
- 11-3 re模块
目录 r 的作用 re模块的常用功能 findall search match split sub 将数字替换成'H' subn 将数字替换成'H',返回元组(替换的结果,替换了多少次) compil ...
- SQLServer锁的概述
SQLServer锁的概述 锁的概述 一. 为什么要引入锁 多个用户同时对数据库的并发操作时会带来以下数据不一致的问题: 丢失更新 A,B两个用户读同一数据并进行修改,其中一个用户的修改结果破坏了 ...
- OBJECTPROPERTY用法整理
OBJECTPROPERTY用法整理 分类: 系统表与表结构 数据库管理维护2010-06-03 16:37 2783人阅读 评论(1) 收藏 举报 数据库sql serverinsertobject ...