SpringMVC解决跨域问题及CROS
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的更多相关文章
- SpringMVC解决跨域问题
有个朋友在写扇贝插件的时候遇到了跨域问题. 于是我对解决跨域问题的方式进行了一番探讨. 问题 API:查询单词 URL: https://api.shanbay.com/bdc/search/?wor ...
- [转载]SpringMVC解决跨域问题
本文转载自 https://www.cnblogs.com/morethink/p/6525216.html SpringMVC解决跨域问题, 感谢作者! 有个朋友在写扇贝插件的时候遇到了跨域问题. ...
- SpringMVC解决跨域的两种方案
1. 什么是跨域 2. 跨域的应用情景 3. 通过注解的方式允许跨域 4. 通过配置文件的方式允许跨域 1. 什么是跨域 跨域,即跨站HTTP请求(Cross-site HTTP request),指 ...
- springMVC解决跨域
原文:https://www.cnblogs.com/shihaiming/p/9544060.html 介绍: 跨站 HTTP 请求(Cross-site HTTP request)是指发起请求 ...
- springmvc 解决跨域CORS
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import ja ...
- 前端通过Nginx反向代理解决跨域问题
在前面写的一篇文章SpringMVC 跨域,我们探讨了什么是跨域问题以及SpringMVC怎么解决跨域问题,解决方式主要有如下三种方式: JSONP CORS WebSocket 可是这几种方式都是基 ...
- java springmvc 前端 跨域问题
有个朋友在写扇贝插件的时候遇到了跨域问题.于是我对解决跨域问题的方式进行了一番探讨. 问题 API:查询单词URL: https://api.shanbay.com/bdc/search/?word= ...
- 使用SpringMVC的@CrossOrigin注解解决跨域请求问题
跨域问题,通俗说就是用ajax请求其他站点的接口,浏览器默认是不允许的.同源策略(Same-orgin policy)限制了一个源(orgin)中加载脚本或脚本与来自其他源(orgin)中资源的交互方 ...
- html5中的postMessage解决跨域问题
解决跨域问题的方法有很多,如:图像ping(简单).jsonp(缺点是不能实现跨域post).CROS(CORS的本质让服务器通过新增响应头Access-Control-Allow-Origin,通过 ...
随机推荐
- throws和throw的用法例子以及检测和非检查异常
throws E1,E2,E3 只是告诉程序这个方法可能会抛出这些个异常,方法的调用者可能要处理这些异常.而这些异常E1,E2,E3可能是该函数体产生的. 而throw是明确之处这个地方要抛出这个异常 ...
- File工具类
package cn.itcast.bos.utils; import java.io.IOException; import java.net.URLEncoder; import sun.misc ...
- AWR报告分析解读
http://blog.csdn.net/weiwangsisoftstone/article/details/7614430 1.AWR报告头信息 DB Name :数据库名字 DBid: 数据库i ...
- html03表单
<!DOCTYPE HTML> <html> <head> <title>用户登录的表单</title> </head> < ...
- LeetCode OJ:Next Permutation(下一排列)
Implement next permutation, which rearranges numbers into the lexicographically next greater permuta ...
- 初识Linux(二)--命令行基本操作
安装完Ubuntu后,进入系统,呈现在眼前的是Ubuntu的界面,跟windows的差不太多.一般操作系统包含GUI和CLI.GUI就是我们现在看到的,也是windows常用的直接用拖拽,点击等操作对 ...
- PostgreSQL full_page_write记录
PostgreSQL 在 checkpoint 之后在对数据页面的第一次写的时候会将整个数据页面写到 xlog 里面. 当出现主机断电或者OS崩溃时,redo操作时通过checksum发现“部分写”的 ...
- setInterval(callback(),time)
最近在写一个需求的时候,出了点小小的问题,在这做个记录. 对于定时函数setInterval()大家应该都不陌生,setInterval(callback(),time)就是说设置一个定时器,每隔ti ...
- HAWQ取代传统数仓实践(十四)——事实表技术之累积快照
一.累积快照简介 累积快照事实表用于定义业务过程开始.结束以及期间的可区分的里程碑事件.通常在此类事实表中针对过程中的关键步骤都包含日期外键,并包含每个步骤的度量,这些度量的产生一般都会滞后于数据行的 ...
- canvas 创建渐变图形
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...