尊重原创:http://blog.csdn.net/ruiguang21/article/details/77878933

  1. 问题场景:由于项目中使用到跨域访问,今天也得到高人指点,所以写出来分享给大家可能是考虑到前后端分离,前端后端服务器不在一台机器上,出现这种跨域访问的情况。正常情况下本地访问是没有问题,但是遇到这种非同一台服务器的情况下,就会报错Access-Control-Allow-Origin。具体报错内容不记得了。
  2. 问题解决方案一:采用添加拦截器的方式对请求添加跨域访问的头,允许跨域访问。
  3. 包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” );
    }
    }

      

  4. 上面是拦截器内容,下面是对拦截器的配置。
包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跨域访问处理的更多相关文章

  1. Spring Boot 跨域访问

    如何在 Spring Boot 中配置跨域访问呢? Spring Boot 提供了对 CORS 的支持,您可以实现WebMvcConfigurer 接口,重写addCorsMappings 方法来添加 ...

  2. spring boot 跨域访问处理

    问题场景:由于项目中使用到跨域访问,今天也得到高人指点,所以写出来分享给大家.可能是考虑到前后端分离,前端后端服务器不在一台机器上,出现这种跨域访问的情况.正常情况下本地访问是没有问题,但是遇到这种非 ...

  3. spring boot跨域请求访问配置以及spring security中配置失效的原理解析

    一.同源策略 同源策略[same origin policy]是浏览器的一个安全功能,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源. 同源策略是浏览器安全的基石. 什么是源 源[orig ...

  4. spring boot跨域设置

    定义 跨域是指从一个域名的网页去请求另一个域名的资源 跨域背景 限制原因 如果一个网页可以随意地访问另外一个网站的资源,那么就有可能在客户完全不知情的情况下出现安全问题 为什么要跨域 公司内部有多个不 ...

  5. spring boot跨域问题

    跨域是指不同域名之间相互访问.跨域,指的是浏览器不能执行其他网站的脚本.它是浏览器的同源策略造成的,是浏览器对JavaScript施加的安全限制.也就是如果在A网站中,我们希望使用Ajax来获得B网站 ...

  6. spring boot 跨域请求

    场景 网站localhost:56338要访问网站localhost:3001的服务 在网站localhost:3001中增加CORS相关Java Config @Configuration @Ord ...

  7. SpringBoot 优雅配置跨域多种方式及Spring Security跨域访问配置的坑

    前言 最近在做项目的时候,基于前后端分离的权限管理系统,后台使用 Spring Security 作为权限控制管理, 然后在前端接口访问时候涉及到跨域,但我怎么配置跨域也没有生效,这里有一个坑,在使用 ...

  8. Spring Boot跨域解决方案

    一.什么是跨域 为保证浏览器的安全,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源,这称之为同源策略,如果一个请求地址里的协议.域名.端口号都相同,就属于同源.依据浏览器同源策略,非同源脚 ...

  9. spring boot跨域问题的简便解决方案

    刚学spring boot的时候被跨域问题拦住好久,最终好不容易从网上抄了别人的极端代码才解决. 但是前些天看一同事的代码时,发现spring boot中用注解就可以解决. 在controller上添 ...

随机推荐

  1. KVM 初探

    KVM 是业界最为流行的 Hypervisor,全称是 Kernel-based Virtual Machine.它是作为 Linux kernel 中的一个内核模块而存在,模块名为 kvm.ko,也 ...

  2. bzoj 2427: [HAOI2010]软件安装

    Description 现在我们的手头有N个软件,对于一个软件i,它要占用Wi的磁盘空间,它的价值为Vi.我们希望从中选择一些软件安装到一台磁盘容量为M计算机上,使得这些软件的价值尽可能大(即Vi的和 ...

  3. JavaScript构造函数、继承的理解

    前两天稍微深入一点点理解了原型和原型链,然后就开始有挺多疑问的: function dog() { this.name = "huahua"; } var cat = new do ...

  4. String源码图

    String StringBuffer StringBuilder 均为对字符数组的操作. 实现了不同的接口,导致不同的覆写. 实现了同样的接口,适应不同的场景.

  5. crontabs linux定时任务功能安装

    crontab命令常见于Unix和Linux的操作系统之中,用于设置周期性被执行的指令.该命令从标准输入设备读取指令,并将其存放于"crontab"文件中,以供之后读取和执行.通常 ...

  6. 如何实现虚拟机(VirtualBox)中的Ubuntu与Windows XP间的数据共享

    环境: 主机是Windows XP系统 虚拟机与Ubuntu的版本分别为: VirtualBox-3.2.12-68302-Win ubuntu-10.10-desktop-i386 前提:已安装Vi ...

  7. JS中typeof和instanceof用法区别

    typeof和instanceof都可以用来判断变量 1.typeof用以获取一个变量或者表达式的类型,typeof一般只能返回如下几个结果: number,boolean,string,functi ...

  8. Python爬取视频(其实是一篇福利)

    窗外下着小雨,作为单身程序员的我逛着逛着发现一篇好东西,来自知乎 你都用 Python 来做什么?的第一个高亮答案. 到上面去看了看,地址都是明文的,得,赶紧开始吧. 下载流式文件,requests库 ...

  9. SpringCloud学习笔记(7)——Sleuth

    Part VII. Spring Cloud Sleuth 46. Introduction Spring Cloud Sleuth为Spring Cloud实现了分布式的跟踪解决方案 46.1 Te ...

  10. ionic2 安装(一)

    1.安装java JDK 2.安装nodejs 3.安装最新版ionic 指令:npm install ionic@latest 4.安装cordova 指令:npm install -g cordo ...