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. Springboot- Spring缓存抽象学习笔记

    Spring缓存作用准备: 1.准备数据(准备一个有数据的库和表/导入数据库文件,准备好表和表里面的数据) 2.创建javaBean封装数据 3.整合MyBatis操作数据库( 这里用MyBatis) ...

  2. SurfaceView基本使用--动态画正弦函数

    package com.zzw.TestSurfaceView; import android.content.Context; import android.graphics.Canvas; imp ...

  3. 广义线性模型(GLM)

    一.广义线性模型概念 在讨论广义线性模型之前,先回顾一下基本线性模型,也就是线性回归. 在线性回归模型中的假设中,有两点需要提出: (1)假设因变量服从高斯分布:$Y={{\theta }^{T}}x ...

  4. js最基础的作用域问题

    1.什么是作用域? 每个变量和函数,都有其作用的范围,超出这个范围,就不能使用了,这个范围就叫做“作用域”,我们举个例子,一个文件中的变,在另一个文件中直接访问,是访问不到的,两个文件是两个“域”,两 ...

  5. laravel5表单验证

    学习laravel框架有一段时间了,觉得它自带的表单验证特别好用,和大家分享分享 对于一些验证规则手册上都有,相信大家看了就会,我简单的说下怎么使用自定义正则验证: 验证手机号:'tel' => ...

  6. 【PL/SQL编程】注释说明

    1. 单行注释 由两个连接字符“--”开始,后面紧跟着注释内容. 2. 多行注释 由/*开头, 由*/结尾.

  7. jsp转发和重定向

    response应答 a) Response.sendRedirect(路径); //重定向 b) Response.getRequestDispatcher(路径).forward(request, ...

  8. Android的方法和属性(1)

    1.Activity常用的方法 View findViewById(int id) //根据组件的ID取得组件对象 setContentView(int layoutResID) //设置布局文件,设 ...

  9. ubuntu 添加新硬盘

    查看硬盘: # fdisk -l ... Disk /dev/sdb: 274.9 GB, 274877906944 bytes 255 heads, 63 sectors/track, 33418 ...

  10. (十八)js控制台方法

    console.log 以日志的形式打印 console.warn 输出警示信息 console.info 输出提示信息 console.error 输出错误信息 console.debug 输出调试 ...