一、跨域科普跨域,即跨站HTTP请求(Cross-site HTTP request),指发起请求的资源所在域不同于请求指向资源所在域的HTTP请求。二、如何产生跨域当使用前后端分离,后端主导的开发方式进行前后端协作开发时,常常有如下情景: a、后端开发完毕在服务器上进行部署并给前端API文档。 b、前端在本地进行开发并向远程服务器上部署的后端发送请求。 c、在这种开发过程中,如果前端想要一边开发一边测试接口,就需要使用跨域的方式。三、解决方案1、JQuery+ajax+jsonp 跨域访问Jsonp(JSON with Padding)是资料格式 json 的一种“使用模式”,可以让网页从别的网域获取资料。下面给出例子:html 前端代码: [html] view plain copy
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- <script type="text/javascript" src="resource/js/jquery-1.7.2.js"></script>
- </head>
- <script type="text/javascript">
- $(function(){
- /*
- //简写形式,效果相同
- $.getJSON("http://app.example.com/base/json.do?sid=1494&busiId=101&jsonpCallback=?",
- function(data){
- $("#showcontent").text("Result:"+data.result)
- });
- */
- $.ajax({
- type : "get",
- async:false,
- url : "http://app.example.com/base/json.do?sid=1494&busiId=101",
- dataType : "jsonp",//数据类型为jsonp
- jsonp: "jsonpCallback",//服务端用于接收callback调用的function名的参数
- success : function(data){
- $("#showcontent").text("Result:"+data.result)
- },
- error:function(){
- alert('fail');
- }
- });
- });
- </script>
- <body>
- <div id="showcontent">Result:</div>
- </body>
- </html>
服务器端: [java] view plain copy
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.HashMap;
- import java.util.Map;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import net.sf.json.JSONObject;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- @Controller
- public class ExchangeJsonController {
- @RequestMapping("/base/json.do")
- public void exchangeJson(HttpServletRequest request,HttpServletResponse response) {
- try {
- response.setContentType("text/plain");
- response.setHeader("Pragma", "No-cache");
- response.setHeader("Cache-Control", "no-cache");
- response.setDateHeader("Expires", 0);
- Map<String,String> map = new HashMap<String,String>();
- map.put("result", "content");
- PrintWriter out = response.getWriter();
- JSONObject resultJSON = JSONObject.fromObject(map); //根据需要拼装json
- String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数
- out.println(jsonpCallback+"("+resultJSON.toString(1,1)+")");//返回jsonp格式数据
- out.flush();
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
2、通过注解的方式允许跨域在Controller类或其方法上加@CrossOrigin注解,来使之支持跨域。举例: [java] view plain copy
- @CrossOrigin(origins = "*", maxAge = 3600)
- @RestController
- @RequestMapping("/User")
- public class UserController {
- }
其中origins为CrossOrigin的默认参数,即跨域来源,*即任何来源,也可以是其他域名。即可以以以下形式: [java] view plain copy
- @CrossOrigin("http://test.com")
- @CrossOrigin(origins="http://test.com",maxAge=3600)
该注解用于方法上,写法相同,处理时,SpringMVC会对类上标签和方法上标签进行合并。3、通过配置文件的方式允许跨域在web.xml中添加如下配置: [html] view plain copy
- <filter-mapping>
- <filter-name>CorsFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
使用这个Filter即可让整个服务器全局允许跨域。
阅读全文
|