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。