CORS

首先因为最近在做一个前后端分离的项目,分开就意味着可能不在一个域中,所以不可避免的遇到CORS的问题。试过几个方法:

  • Spring MVC 4.2.5以后新增的支持跨域的注解@CrossOrigin,如果是老项目的话升级spring库可能会有些兼容的问题,不知为什么这个注解没有升效;
  • 用反向代理,这个一定好使的;
  • 还有就是我现在使用的,手动增加一个Filter,在Response中增加对跨域的支持,这种方式对老浏览器可能会有问题。

public class CORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}

web.xml

<filter>
<filter-name>cors</filter-name>
<filter-class>xxxx.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

如此即可解决跨域问题。

另外这是一个加了CROS之后的Controller类:

package com.smt.controller;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile; import com.iflytek.voicecloud.model.Message;
import com.smt.pojo.FlyEvent;
import com.smt.pojo.Txjp;
import com.smt.service.IIflyService;
import com.smt.service.ITxjpService; @CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/ifly")
public class IflyController {
private static final Logger LOGGER = Logger.getLogger(IflyController.class); @Autowired
private IIflyService iflyService; @RequestMapping(path="/goFly")
public @ResponseBody String showUserInfos(@RequestParam("file") CommonsMultipartFile file,String empid,HttpServletRequest request){
String path = request.getSession().getServletContext().getRealPath("upload");
String filename = "";
LOGGER.info(path);
InputStream fis = null;
try {
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
fis = file.getInputStream();
filename = empid+sdf.format(d)+".mp3";
iflyService.saveFile(fis, filename, path);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally{
if(fis != null){
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} FlyEvent model = new FlyEvent();
model.setiId(UUID.randomUUID().toString());
model.setiDate(new Date());
model.setiUrl("/upload/"+filename);
model.setiUserId(empid);
iflyService.saveEvent(model); String json = "暂无";
try {
Message mes = iflyService.upload(path+"\\"+filename);
LOGGER.info("上传状态码:"+mes.getOk());
if(mes.getOk() == 0){
model.setiWorkId(mes.getData());
iflyService.updateEvent(model);
// LOGGER.info("开始等待...");
// Thread.sleep(10000);
// LOGGER.info("结束等待...");
// Message res = iflyService.result(mes.getData());
// if(res.getOk() == 0){
// json = res.getData();
// LOGGER.info("翻译结果:"+json);
// model.setiContent(json);
// iflyService.updateEvent(model);
// }else{
// LOGGER.error("返回报错:"+res.getFailed());
// }
}else{
LOGGER.error("上传报错:"+mes.getFailed());
}
} catch (Exception e) {
LOGGER.error("抛出异常:"+e.getMessage());
} return json;
}
}

其中@CrossOrigin(origins = "*", maxAge = 3600)注解是支持所有域,但是很显然不好使。

@RestController是REST模式,也就是类似于.NET里面的WebApi。

SpringMVC解决跨域问题及CROS的更多相关文章

  1. SpringMVC解决跨域问题

    有个朋友在写扇贝插件的时候遇到了跨域问题. 于是我对解决跨域问题的方式进行了一番探讨. 问题 API:查询单词 URL: https://api.shanbay.com/bdc/search/?wor ...

  2. [转载]SpringMVC解决跨域问题

    本文转载自  https://www.cnblogs.com/morethink/p/6525216.html SpringMVC解决跨域问题, 感谢作者! 有个朋友在写扇贝插件的时候遇到了跨域问题. ...

  3. SpringMVC解决跨域的两种方案

    1. 什么是跨域 2. 跨域的应用情景 3. 通过注解的方式允许跨域 4. 通过配置文件的方式允许跨域 1. 什么是跨域 跨域,即跨站HTTP请求(Cross-site HTTP request),指 ...

  4. springMVC解决跨域

    原文:https://www.cnblogs.com/shihaiming/p/9544060.html 介绍:   跨站 HTTP 请求(Cross-site HTTP request)是指发起请求 ...

  5. springmvc 解决跨域CORS

    import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import ja ...

  6. 前端通过Nginx反向代理解决跨域问题

    在前面写的一篇文章SpringMVC 跨域,我们探讨了什么是跨域问题以及SpringMVC怎么解决跨域问题,解决方式主要有如下三种方式: JSONP CORS WebSocket 可是这几种方式都是基 ...

  7. java springmvc 前端 跨域问题

    有个朋友在写扇贝插件的时候遇到了跨域问题.于是我对解决跨域问题的方式进行了一番探讨. 问题 API:查询单词URL: https://api.shanbay.com/bdc/search/?word= ...

  8. 使用SpringMVC的@CrossOrigin注解解决跨域请求问题

    跨域问题,通俗说就是用ajax请求其他站点的接口,浏览器默认是不允许的.同源策略(Same-orgin policy)限制了一个源(orgin)中加载脚本或脚本与来自其他源(orgin)中资源的交互方 ...

  9. html5中的postMessage解决跨域问题

    解决跨域问题的方法有很多,如:图像ping(简单).jsonp(缺点是不能实现跨域post).CROS(CORS的本质让服务器通过新增响应头Access-Control-Allow-Origin,通过 ...

随机推荐

  1. Node.js 项目的配置文件

    在 Node.js 中可以通过process.env来访问当前的环境变量信息,比如: { PATH: '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', T ...

  2. linux下安装配置apache+nagios

    1.安装依赖包 yum install -y gcc glibc glibc-common gd gd-devel xinetd openssl-devel 2.创建nagios用户和用户组 # us ...

  3. JDK_环境变量

    1. 在系统环境变量中设置: ClASSPATH中输入: ".;C:\Program Files\Java\jdk1.7.0_07\jre\lib\rt.jar;"//java的安 ...

  4. 单网卡安装neutron

    devstack中机器只有一个物理网卡,如何设置neutron中的external网络? 方式是: 创建一个linux bridge和veth,把eth0和veth1加入到brige,用veth的另一 ...

  5. Origin软件作图留白过多问题解决

    解决空白过大方法:1.Tools——>Options2.Page——>Copy page setting——>Margin默认是Page,下拉菜单选Border,Clip Borde ...

  6. SpringBoot下的Dubbo和Zookeeper整合

    最近一直在学各种分布式的内容,学到了dubbo分布式服务框架就想写个小demo使用一下,但是由于我要整合在SpringBoot框架中,SpringBoot框架毕竟提倡的是java注解配置,XML文件不 ...

  7. Javascript鼠标和滚轮事件

    (转自:http://www.cnblogs.com/MrBackKom/archive/2012/06/25/2562920.html) a)鼠标事件 鼠标事件也许是web页面当中最常用到的事件,因 ...

  8. hdu4185

    题解:每两个联通的油井建边 然后二分图最大匹配 最后答案除以2 代码: #include<cstdio> #include<cmath> #include<cstring ...

  9. canvas压缩图片成base64,传到后台解码需要注意的问题

    去除压缩完后的头部标志,data:imge一直到,位置,然后看看有没有空格,有的就替换成+号,传送的时候+号被http协议去掉了

  10. HTTPPost/AFNetWorking/JSONModel/NSPredicate

    一.HTTPPost================================================ 1. POST方式发送请求 HTTP协议下默认数据发送请求方法是GET方式,若需要 ...