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 ...
随机推荐
- 有关HTML版本
先说说HTML的简史:从HTML1.0~2.0(1989~1991)>HTML3(1995)>HTML4(1998)>HTML4.01(1999)>XHTML1.0(2001) ...
- HTML中的那些bug
1.语法检测时提示有多余的结束标签 <!doctype html> <html> <head> <meta charset="utf-8" ...
- OC中文件读取类(NSFileHandle)介绍和常用使用方法
NSFileHandle 1.NSFileManager类主要对于文件的操作(删除,修改,移动,赋值等等) //判断是否有 tagetPath 文件路径,没有就创建 NSFileManager *fi ...
- 【PostgreSQL-9.6.3】启动,登录,退出,关闭
当我们费尽千辛万苦安装完数据库后,一定会迫不及待的想使用它.骚年,不要着急,且看我为您解析PostgreSQL的启动,登录,退出,关闭过程. 一 启动数据库服务器 1. 没有设置环境变量的情况下 po ...
- this常用的用法
1.函数作为对象的方法时,this指的是该对象: var obj ={ name:"bob", age:25, getName:function(){ console.log(th ...
- js基础盲点
var myarray= new Array(8); //创建数组,存储8个数据. 注意:1.创建的新数组是空数组,没有值,如输出,则显示undefined.2.虽然创建数组时,指定了长度,但实际上数 ...
- Swift3命名空间的实现
最近在看一些Swift开源库的时候,发现了一些优秀的开源库都使用了命名空间,例如Kingfisher这个开源库中,就针对UIImage,UIImageView,UIButton做了命名空间的扩展.通过 ...
- 【VScode】使用VScode 来写markdown时序图
准备工作 在VScode中下载插件Markdown Preview Enhanced插件 创建一个.md文件 在VScode中打开文件,界面内点击右键可以看到Open preview to the s ...
- JVM内存管理及垃圾回收机制
一.JVM内存组成结构 JVM栈由堆.栈.本地方法栈.方法区等部分组成,结构图如下所示: 二.JVM内存回收 Sun的JVMGenerationalCollecting(垃圾回收)原理是这样的:把对 ...
- vue hash模式和404页面的配置
1.设置我们的路由配置文件(/src/router/index.js): { path:'*', component:Error } 这里的path:’*’就是找不到页面时的配置,component是 ...