Http访问跨域解决

2018-3-23    seo达人

如果您想订阅本博客内容,每天自动发到您的邮箱中, 请点这里

一、跨域科普

跨域,即跨站HTTP请求(Cross-site HTTP request),指发起请求的资源所在域不同于请求指向资源所在域的HTTP请求。

二、如何产生跨域

当使用前后端分离,后端主导的开发方式进行前后端协作开发时,常常有如下情景:

    a、后端开发完毕在服务器上进行部署并给前端API文档。
    b、前端在本地进行开发并向远程服务器上部署的后端发送请求。
    c、在这种开发过程中,如果前端想要一边开发一边测试接口,就需要使用跨域的方式。

三、解决方案

1、JQuery+ajax+jsonp 跨域访问

Jsonp(JSON with Padding)是资料格式 json 的一种“使用模式”,可以让网页从别的网域获取资料。

下面给出例子:

html 前端代码:

[html] view plain copy
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">    
  2. <html>    
  3. <head>    
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    
  5. <title>Insert title here</title>    
  6. <script type="text/javascript" src="resource/js/jquery-1.7.2.js"></script>    
  7. </head>    
  8. <script type="text/javascript">    
  9. $(function(){       
  10.  /*    
  11.  //简写形式,效果相同    
  12.  $.getJSON("http://app.example.com/base/json.do?sid=1494&busiId=101&jsonpCallback=?",    
  13.          function(data){    
  14.              $("#showcontent").text("Result:"+data.result)    
  15.  });    
  16.  */    
  17.  $.ajax({    
  18.      type : "get",    
  19.      async:false,    
  20.      url : "http://app.example.com/base/json.do?sid=1494&busiId=101",    
  21.      dataType : "jsonp",//数据类型为jsonp    
  22.      jsonp: "jsonpCallback",//服务端用于接收callback调用的function名的参数    
  23.      success : function(data){    
  24.          $("#showcontent").text("Result:"+data.result)    
  25.      },    
  26.      error:function(){    
  27.          alert('fail');    
  28.      }    
  29.  });     
  30. });    
  31. </script>    
  32. <body>    
  33. <div id="showcontent">Result:</div>    
  34. </body>    
  35. </html>    

服务器端:

[java] view plain copy
  1. import java.io.IOException;    
  2. import java.io.PrintWriter;    
  3. import java.util.HashMap;    
  4. import java.util.Map;    
  5. import javax.servlet.http.HttpServletRequest;    
  6. import javax.servlet.http.HttpServletResponse;    
  7. import net.sf.json.JSONObject;    
  8. import org.springframework.stereotype.Controller;    
  9. import org.springframework.web.bind.annotation.RequestMapping;    
  10.      
  11. @Controller    
  12. public class ExchangeJsonController {    
  13.  @RequestMapping("/base/json.do")    
  14.  public void exchangeJson(HttpServletRequest request,HttpServletResponse response) {    
  15.     try {    
  16.      response.setContentType("text/plain");    
  17.      response.setHeader("Pragma""No-cache");    
  18.      response.setHeader("Cache-Control""no-cache");    
  19.      response.setDateHeader("Expires"0);    
  20.      Map<String,String> map = new HashMap<String,String>();     
  21.      map.put("result""content");    
  22.      PrintWriter out = response.getWriter();         
  23.      JSONObject resultJSON = JSONObject.fromObject(map); //根据需要拼装json    
  24.      String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数    
  25.      out.println(jsonpCallback+"("+resultJSON.toString(1,1)+")");//返回jsonp格式数据    
  26.      out.flush();    
  27.      out.close();    
  28.    } catch (IOException e) {    
  29.     e.printStackTrace();    
  30.    }    
  31.  }    
  32. }    

2、通过注解的方式允许跨域

在Controller类或其方法上加@CrossOrigin注解,来使之支持跨域。

举例:
[java] view plain copy
  1. @CrossOrigin(origins = "*", maxAge = 3600)  
  2. @RestController  
  3. @RequestMapping("/User")  
  4. public class UserController {  
  5. }  

其中origins为CrossOrigin的默认参数,即跨域来源,*即任何来源,也可以是其他域名。即可以以以下形式:

[java] view plain copy
  1. @CrossOrigin("http://test.com")  
  2. @CrossOrigin(origins="http://test.com",maxAge=3600)  

该注解用于方法上,写法相同,处理时,SpringMVC会对类上标签和方法上标签进行合并。

3、通过配置文件的方式允许跨域

在web.xml中添加如下配置:

[html] view plain copy
  1. <filter-mapping>   
  2.     <filter-name>CorsFilter</filter-name>   
  3.     <url-pattern>/*</url-pattern>   
  4. </filter-mapping>  
使用这个Filter即可让整个服务器全局允许跨域。

蓝蓝设计www.lanlanwork.com )是一家专注而深入的界面设计公司,为期望卓越的国内外企业提供卓越的UI界面设计、BS界面设计 、 cs界面设计 、 ipad界面设计 、 包装设计 、 图标定制 、 用户体验 、交互设计、 网站建设 平面设计服务


分享本文至:

日历

链接

blogger

蓝蓝 http://www.lanlanwork.com

存档