SPRING BOOT跨域访问处理
尊重原创:http://blog.csdn.net/ruiguang21/article/details/77878933
- 问题场景:由于项目中使用到跨域访问,今天也得到高人指点,所以写出来分享给大家可能是考虑到前后端分离,前端后端服务器不在一台机器上,出现这种跨域访问的情况。正常情况下本地访问是没有问题,但是遇到这种非同一台服务器的情况下,就会报错Access-Control-Allow-Origin。具体报错内容不记得了。
- 问题解决方案一:采用添加拦截器的方式对请求添加跨域访问的头,允许跨域访问。
包com.meicloud.interceptor; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 公共 类 CommonInterceptor 扩展HandlerInterceptorAdapter { 私人 最终 静态 记录器记录器= Logger.getLogger(CommonInterceptor。类); @覆盖
公共 布尔 preHandle(HttpServletRequest请求,HttpServletResponse响应,对象处理程序)抛出异常{
logger.info( “添加跨域访问头配置,Access-Control-Allow-Origin:*” );
// 跨域访问CORS
response.addHeader(“Access-Control-Allow-Origin”,“*” );
response.addHeader( “Access-Control-Allow-Methods”,“POST,GET,OPTIONS,PUT,DELETE,HEAD” );
response.addHeader( “Access-Control-Allow-Headers”,“S_ID,content-type” );
response.addHeader( “Access-Control-Max-Age”,“3600000” );
response.addHeader( “Access-Control-Allow-Credentials”,“true” ); // 让请求,不被缓存,
response.setHeader(“Cache-Control”,“no-cache” );
response.setHeader( “Cache-Control”,“no-store” );
response.setHeader( “Pragma”,“no-cache” );
response.setDateHeader( “Expires”,0 );
logger.debug
( “================================== preHandle” );
返回 true ;
} @覆盖
公共 无效postHandle(HttpServletRequest请求,
HttpServletResponse响应,对象处理程序,
ModelAndView modelAndView)抛出Exception {logger.debug
( “================================== postHandle” );
} @覆盖
public void afterCompletion(HttpServletRequest request,
HttpServletResponse响应,对象处理程序,Exception ex)
抛出Exception {
logger.debug( “================================== afterCompletion” );
}
}- 上面是拦截器内容,下面是对拦截器的配置。
包com.meicloud.config; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.meicloud.interceptor.CommonInterceptor; @ComponentScan
@组态
公共 类 WebMvcConfig 扩展WebMvcConfigurerAdapter { @覆盖
public void addInterceptors(InterceptorRegistry registry){
// TODO自动生成的方法存根
registry.addInterceptor(new CommonInterceptor())。addPathPatterns(“/ getDOC” );
} }
然后就可以在控制器中使用他了,下面是我的控制器
我们可以通过调用
这个方法来实现一个简单的方法来实现这个方法,这个方法可以
用来实现一个简单的方法来实现这个方法
。
BaseReturn baseReturn = new BaseReturn(); 字符串名称= mailEntity.getName();
String company = mailEntity.getCompany();
字符串部门= mailEntity.getDepartments();
String job = mailEntity.getJob();
String email = mailEntity.getEmail();
String phone = mailEntity.getPhone();
String doc = mailEntity.getDoc(); 尝试{
if(name == null || name.equals(“”)){
throw new CommenException(“姓名不能为空!
}
if(email == null || email.equals(“”)){
throw new CommenException(“Email不能为空!”);
}
if(phone == null || phone.equals(“”)){
throw new CommenException(“电话号码不能为空!”);
}
if(doc == null || doc.equals(“”)){
throw new CommenException(“文档不能为空!”);
}
}赶上(例外E1){
baseReturn.setCode(ReturnType.FAIL);
baseReturn.setMsg(e1.getMessage());
log.error(e1.getMessage());
返回基地返回;
} try {
// iMailClent.sendMail(mailEntity);
iMailClent.sendHtmlMail(mailEntity);
baseReturn.setCode(ReturnType.SUCCESS);
catch(Exception e){
e.printStackTrace();
baseReturn.setCode(ReturnType.FAIL);
baseReturn.setMsg( “发送邮件失败!”);
log.error(e.getMessage());
} return baseReturn;
}
接下来是前端的调用,前端采用ajax post请求
var params = {
名称:名称,
公司:公司,
部门:部门,
工作:工作,
电子邮件:电子邮件,
电话:电话,
doc: '/ doc/ api.doc'
}; var type ='POST' ;
var url = Config.host + url; $就({
url:url,
数据:JSON.stringify(params),
键入:type,
contentType: “application / json” ,
async:false ,
成功:函数(数据){
// TODO成功
},
错误:函数(数据){
// TODO失败
}
});
问题解决方案二:使用JSONP来实现跨域访问,直接上代码,前端代码为:
url ='http:// localhost:9999 / getDOC'+'?name ='+ params.name
+'&company ='+ params.company
+'&departments ='+ params.departments +'&job ='+ params.job
+'&email ='+ params.email +'&phone ='+ params.phone +'&doc ='
+ params.doc; $就({
url:url,
键入: 'get' ,
async:false ,
dataType: “jsonp” ,
jsonpCallback: “回调” ,
成功:功能(数据){
// TODO成功
},
错误:函数(数据){
// TODO失败
}
});
限制调用方式为get,数据类型为jsonp。后端也必须响应JSONPObject对象。
@ResponseBody
@RequestMapping(value =“/ getDOC”,method = RequestMethod.GET)
公共JSONPObject getDOC(HttpServletRequest请求,字符串回调){ BaseReturn baseReturn = new BaseReturn(); String name = request.getParameter(“name” );
String company = request.getParameter(“company” );
String departments = request.getParameter(“departments” );
String job = request.getParameter(“job” );
String email = request.getParameter(“email” );
String phone = request.getParameter(“phone” );
String doc = request.getParameter(“doc” ); 尝试{
if(name == null || name.equals(“” )){
throw new CommenException(“姓名不能为空!” );
}
if(email == null || email.equals(“” )){
throw new CommenException(“Email不能为空!” );
}
if(phone == null || phone.equals(“” )){
throw new CommenException(“电话号码不能为空!” );
}
if(doc == null || doc.equals(“” )){
throw new CommenException(“文档不能为空!” );
}
} 捕获(例外E1){
baseReturn.setCode(ReturnType.FAIL);
baseReturn.setMsg(e1.getMessage());
log.error(e1.getMessage());
返回 新的JSONPObject(callback,baseReturn);
} MailEntity mailEntity = new MailEntity();
mailEntity.setCompany(公司);
mailEntity.setDepartments(部门);
mailEntity.setDoc(DOC);
mailEntity.setEmail(电子邮件);
mailEntity.setJob(工作);
mailEntity.setName(名称);
mailEntity.setPhone(电话); 尝试{
iMailClent.sendHtmlMail(mailEntity);
baseReturn.setCode(ReturnType.SUCCESS);
} 捕获(例外五){
e.printStackTrace();
baseReturn.setCode(ReturnType.FAIL);
baseReturn.setMsg( “发送邮件失败!” );
log.error(e.getMessage());
} 返回 新的JSONPObject(callback,baseReturn);
}
今天得到高人指点,原来有一种更加简便的方法,可以实现。不过原理肯定都是一样的,通过给请求添加消息头来设置跨域访问,这点是无疑的。新的解决办法就是给控制器或方法添加@CrossOrigin注解,具体详情请参考:http://spring.io/blog/2015/06/08/cors-support-in-spring-framework
@ResponseBody
@RequestMapping(value =“/ getDOC”,method = RequestMethod.POST)公共BaseReturn getDOC(@RequestBody MailEntity mailEntity,HttpServletRequest请求,HttpServletResponse响应,HttpSession httpSession){
@CrossOrigin // 使用注解方式添加跨域访问消息头 log.info( “执行控制器HomeController.getDOC”);
SPRING BOOT跨域访问处理的更多相关文章
- Spring Boot 跨域访问
如何在 Spring Boot 中配置跨域访问呢? Spring Boot 提供了对 CORS 的支持,您可以实现WebMvcConfigurer 接口,重写addCorsMappings 方法来添加 ...
- spring boot 跨域访问处理
问题场景:由于项目中使用到跨域访问,今天也得到高人指点,所以写出来分享给大家.可能是考虑到前后端分离,前端后端服务器不在一台机器上,出现这种跨域访问的情况.正常情况下本地访问是没有问题,但是遇到这种非 ...
- spring boot跨域请求访问配置以及spring security中配置失效的原理解析
一.同源策略 同源策略[same origin policy]是浏览器的一个安全功能,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源. 同源策略是浏览器安全的基石. 什么是源 源[orig ...
- spring boot跨域设置
定义 跨域是指从一个域名的网页去请求另一个域名的资源 跨域背景 限制原因 如果一个网页可以随意地访问另外一个网站的资源,那么就有可能在客户完全不知情的情况下出现安全问题 为什么要跨域 公司内部有多个不 ...
- spring boot跨域问题
跨域是指不同域名之间相互访问.跨域,指的是浏览器不能执行其他网站的脚本.它是浏览器的同源策略造成的,是浏览器对JavaScript施加的安全限制.也就是如果在A网站中,我们希望使用Ajax来获得B网站 ...
- spring boot 跨域请求
场景 网站localhost:56338要访问网站localhost:3001的服务 在网站localhost:3001中增加CORS相关Java Config @Configuration @Ord ...
- SpringBoot 优雅配置跨域多种方式及Spring Security跨域访问配置的坑
前言 最近在做项目的时候,基于前后端分离的权限管理系统,后台使用 Spring Security 作为权限控制管理, 然后在前端接口访问时候涉及到跨域,但我怎么配置跨域也没有生效,这里有一个坑,在使用 ...
- Spring Boot跨域解决方案
一.什么是跨域 为保证浏览器的安全,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源,这称之为同源策略,如果一个请求地址里的协议.域名.端口号都相同,就属于同源.依据浏览器同源策略,非同源脚 ...
- spring boot跨域问题的简便解决方案
刚学spring boot的时候被跨域问题拦住好久,最终好不容易从网上抄了别人的极端代码才解决. 但是前些天看一同事的代码时,发现spring boot中用注解就可以解决. 在controller上添 ...
随机推荐
- Windows下RabbitMQ安装及入门
1.Windows下安装RabbitMQ需要以下几个步骤 (1):下载erlang,原因在于RabbitMQ服务端代码是使用并发式语言erlang编写的,下载地址:http://www.erlang. ...
- 关于html,css,js三者的加载顺序问题
<head lang="en"> <meta charset="utf-8"> <title></title> ...
- Nodejs真.多线程处理
前言 Threads à gogo 是nodejs 的原生模块,使用这个模块可以让nodejs 具备多线程处理功能 安装方法 npm install threads_a_gogo 下载测试源码 git ...
- mysql 数据表字段修改sql 语句
1 新增字段 alter table bulletin add citycode varchar(6) not null default 0 [after `id`]; # 城市代码 2 修改字段 a ...
- Django__WSGI
WEB应用的本质 : 1. 浏览器发送一个http请求 2. 服务器收到请求,生成一个html文档 3. 服务器把HTML文档作为HTTP响应的body发送给浏览器 4. 浏览器收到http响应,从h ...
- Linux 定时任务不生效的问题
Linux 中定时任务不生效的问题屡见不鲜, 本质原因是: 登录式 shell & 非登录式 shell. 登录式 shell & 非登录式 shell 登录式 shell 有: su ...
- 基础环境之Docker入门
随着Docker技术的不断成熟,越来越多的企业开始考虑使用Docker.Docker有很多的优势,本文主要讲述了Docker的五个最重要优势,即持续集成.版本控制.可移植性.隔离性和安全性. 有了Do ...
- angular4.0配置同时使用localhost和本机IP访问项目
之前写过<angular4.0配置本机IP访问项目>的文章,今天再次更新一个,谢谢大家的指正. 今天的目的是:使用本机IP地址,或者localhost都可以访问项目. 第一步:找到此文件& ...
- 使用git工具将项目上传到github
注册github账号 https://github.com/ 安装git工具: https://git-for-windows.github.io/ 上面的准备工作完成后,现在开始操作. 一.进入gi ...
- angular4.0常用依赖汇总
Routes 路由配置 Router 路由跳转 ActivatedRoute 路由参数 FormsModule 表单配置(在app.module.ts中注入在imports下) EventEmitte ...