用JSONP实现的跨域访问的解决方案2014-02-20跨域访问一直是困扰很多开发者的问题之一。因为涉及到安全性问题,所以跨域访问默认是不可以进行的,否则假设今天我写了一段js去更改google的图标,明天他写了一段代码去吧google首页的文字全部变成梵文,那还得了?首先,讲下什么是相同的域。域是这样定义的,协议名+host名+端口号,只有这3个都一样,才能说是同样的域,同样的域里面的访问不受到同源策略限制,你可以用你的js代码任意的去操作资源,但是不同域你就不能这样做了。解决跨域访问有很多方法,最常见的一种“单向”跨域访问方式是用JSONP(Json with Padding),它解决思路就是如果域A (充当客户端)上的js 要操作域B(充当服务器端)上的资源,那么只要吧域A上的js函数名传递给域B,然后在域B进行封装,它解析来自域A的函数名,并且将域B上的资源转为json对象,并且两者进行组合,组合后的字符串就是 域A函数名(域B json对象) 这种函数调用的形式,然后当域A上用script src="#"">域A函数名(域B json对象)的形式,于是就达到了域A函数处理域B资源的效果。为了更有说服力,我们这里做一个非常简单的实验,假定域A(客户端)有个应用部署在http://localhost:8180上,域B(服务器端)有个应用部署在http://localhost:8080上,显然这2个域由于端口不同,所以域A如果要访问域B必定是跨域访问的。域A 有一段js函数,域B提供了一个json对象,我们想要域A的js函数操作域B的json对象。会怎样呢?服务端(我们部署在http://localhost:8080上):先贴上域B(服务器端的代码),它用一个java servlet,负责接收来自客户端的带回调函数名参数的请求,并且与自己端提供的json对象包装,包装为一个jsonp后然后放入响应输出流。
package com.charles.jsonp;import java.io.IOException; import java.io.PrintWriter;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import org.json.simple.JSONObject;/*** Servlet implementation class JSONPServlet*/public class JSONPServlet extends HttpServlet { private static final long serialVersionUID = 1L; /*** @see HttpServlet#HttpServlet()*/public JSONPServlet() { super(); // TODO Auto-generated constructor stub }/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub//get the callback function which comes from client String callbackFuncFromClient= request.getParameter("callbackFunc"); //create a json object JSONObject jsonInfo = new JSONObject(); jsonInfo.put("name","charles"); jsonInfo.put("title", "technical lead"); jsonInfo.put("info","talent man"); //create a string which stands for a javascript with the format func(jsonobject) StringBuffer jsonpString = new StringBuffer(); jsonpString.append(callbackFuncFromClient).append("(").append(jsonInfo.toJSONString()).append(")"); //construct the output jsonp and output to the client response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); out.println(jsonpString); out.flush(); }/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub }}然后我们把这个servlet映射到某个url上,见web.xml:
<servlet> <description>This servlet will create a jsonp object,it wraps the js function and the json object</description> <display-name>JSONPServlet</display-name> <servlet-name>JSONPServlet</servlet-name> <servlet-class>com.charles.jsonp.JSONPServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>JSONPServlet</servlet-name> <url-pattern>/JSONPServlet</url-pattern> </servlet-mapping>