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上添 ...
随机推荐
- sed 命令替换字符串
sed -i 's/13/15/g' `grep 13 -rl 目录` -i 表示替换 -r 表示搜索子目录 -l 显示替换名
- bzoj 2302: [HAOI2011]Problem c
Description 给n个人安排座位,先给每个人一个1~n的编号,设第i个人的编号为ai(不同人的编号可以相同),接着从第一个人开始,大家依次入座,第i个人来了以后尝试坐到ai,如果ai被占据了, ...
- bzoj 5016: [Snoi2017]一个简单的询问
Description 给你一个长度为N的序列ai,1≤i≤N和q组询问,每组询问读入l1,r1,l2,r2,需输出 get(l,r,x)表示计算区间[l,r]中,数字x出现了多少次. Input 第 ...
- 学习Object.assign()
Object.assign()用于将所有可枚举的值从一个或多个源对象复制到目标对象.它将返回目标对象. 语法 Object.assign(target, ...source); var obj = { ...
- Xamarin安卓开发:去掉Activity的头部标题栏及全屏显示
http://blog.csdn.net/u012234115/article/details/35814209 以下是用修改布局文件的方法,其实还有用C#代码的方法. 打开AndroidManife ...
- 微信小程序之页面路由
路由方式 简介 对于路由的触发方式以及页面生命周期函数如下: 路由方式 触发时机 路由前页面 路由后页面 初始化 小程序打开的第一个页面 onLoad, onSHow 打开新页面 调用 API w ...
- JavaBean入门笔记
看了JavaBean感觉很困惑,不知道什么意思,直到查看了资料发现自己理解错误,把JavaBean误当成一种技术,其实Java Bean只是符合一定规范的Java类,便于封装重用.符合这种规范的Jav ...
- jmeter测试
时间过得飞快,转眼间就到了公司半个月了,这是第三周上班,从上班到现在感觉自己什么都没有做,只是写了一些前台的验证,况且我的前台并不是很熟,js学了很久也快忘记了,看了看插件也不咋会用,但是自己也写了点 ...
- linux下vsftpd的安装及配置使用详细步骤
vsftpd 是“very secure FTP daemon”的缩写,安全性是它的一个最大的特点. vsftpd 是一个 UNIX 类操作系统上运行的服务器的名字,它可以运行在诸如 Linux.BS ...
- Javascript一句代码实现JS字符串去除重复字符
需求: 原字符串:abcdabecd 去重后字符串:abcde JS字符串去重,一个简单需求,网上找案例发现都是一大堆代码,对于强迫症的我 实再无法忍受,于是自己手动写出一段代码,完美解决该问题. 代 ...