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. tyvj 1055 沙子合并 区间dp经典模型,石子合并

    P1055 沙子合并 时间: 1000ms / 空间: 131072KiB / Java类名: Main 描述     设有N堆沙子排成一排,其编号为1,2,3,…,N(N<=300).每堆沙子 ...

  2. 报错HTTP Status 500 - Unable to instantiate Action

    报错如下: HTTP Status 500 - Unable to instantiate Action, visitAction, defined for 'visit_toAddPage' in ...

  3. srm开发(基于ssh)(3)

    联系人管理 (1)客户和联系人一对多配置(重点) (2)新增联系人 -新增功能实现 -Struts2实现文件上传 (3)联系人列表 -no session问题 (4)客户和联系人级联删除 联系人管理模 ...

  4. java中的char类型所占空间

    java中统一使用unicode编码,所以每个字符都是2个字节16位.unicode包括中文,所以对String类计算长度的时候,一个中文和一个英文都是一个长度.String voice = &quo ...

  5. 用 LoadLibraryExW 函数测试加载 dll (CSharp、Windows)

    效果如下: $ llbtest "E:\Developer\emgucv-windesktop 3.3.0.2824\libs\x64" LoadLibraryExW PATH: ...

  6. Springboot项目打成war包,部署到tomcat上,正常启动访问报错404

    前言: 项目介绍,此项目是一个Maven多模块项目,模块项目:all(父模块):util (公用的工具类):dao(实体类.业务类.mapper.mapper.xml):business(业务serv ...

  7. AI实现五子棋机器人(一)

    前言: 前几天在 csdn 下载资源的时候才发现自己 csdn 有近 200 的下载积分,看了看共享的资源,哈哈 ... 7年前写的五子棋游戏很受欢迎. 下载地址:新手入门五子棋游戏     刚入行的 ...

  8. urllib2打开URL(含中文)的问题

    import urllib2 url = u"http://www.baidu.com/wd=测试" urllib2.urlopen(url.encode('utf-8')).re ...

  9. mysql查询结果带上序号

    select (@i:=@i+1) as rownum,t1.id ","from mega_user t1,(select @i:=0) t2 order by t1.gold ...

  10. react bootstrap-loader

    1.install npm install bootstrap-loader jquery resolve-url-loader 2.webpack.config.js entry: ['bootst ...