標籤:des blog http java 使用 os
一、使用情境
當我們請求非本伺服器的資源的時候,瀏覽器會禁止訪問,並提示不允許跨域訪問。此時我們可以使用jsonp這種請求方式,從其他伺服器擷取資源。在用戶端調用提供jsonp支援的介面,擷取jsonp格式的資料。
二、用戶端的實現
用戶端使用jsp,用js發送ajax請求,代碼如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>jsonp</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><script type="text/javascript" src="./js/jquery-1.9.1.min.js"></script></head><body><script type="text/javascript">jQuery(document).ready(function() {$.ajax( {type : "get",async : false,url : "http://127.0.0.1:8089/test2/TestServlet?id=1",dataType : "jsonp",jsonp : "callback",//傳遞給請求處理常式或頁面的,用以獲得jsonp回呼函數名的參數名(一般預設為:callback)jsonpCallback : "Tcallback",//自訂的jsonp回呼函數名稱,預設為jQuery自動產生的隨機函數名,也可以寫"?",jQuery會自動為你處理資料success : function(json) {alert(‘name: ‘ + json.name + ‘,age: ‘ + json.age);},error : function() {alert(‘fail‘);}});});</script></body></html>
此段代碼相當於get請求http://127.0.0.1:8089/test2/TestServlet?id=1&callback=Tcallback .
三、伺服器實現
伺服器端使用servlet實現,代碼如下:
public class TestServlet extends HttpServlet{public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{String id = request.getParameter("id");String callback = request.getParameter("callback");//值為Tcallback String name = "zhangsan";int age = 20;String json = String.format("%s({\"name\":\"%s\", \"age\":%s})",callback, name, age);//返回的資料PrintWriter out = response.getWriter();out.print(json);out.flush();out.close();}}