然后我們把這個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>
現在我們測試服務器端是否已經正確部署:
我們打開瀏覽器,輸入訪問服務器端這個servlet的url,注意帶上請求參數,參數名為callbackFunc,參數值為任意函數名:則我們可以看到封裝后的JSONP效果,的確是“函數名(json對象)”的字符串形式。比如我們例子中,我們傳入的函數名是 someFunc ,而服務器端自身提供的json對象是{"title":"technical lead","name":"charles","info":"talent man"},則后服務器端返回的JSONP 字符串是someFunc{json}
客戶端:
服務器端部署正確后,我們讓客戶端部署在另外一個域:http://localhost:8180上,要實現跨域訪問,客戶端必須有2部分,1是定義一個回調函數(這個函數用于將來處理服務器json數據),二是一個頁面,這個頁面要用<script src來指向服務器端能 提供JSONP的url),我們一步步來:
先定義一個回調函數:
這個回調函數能在控制臺和alert窗口打印出服務器端的json對象提供的信息
//這段代碼用于定義回調函數
function clientMethodWhichOperateServerResource(result){
console.log("Begin to execute the call function named clientMethodWhichOperateServerResource(result)");
//獲取服務器端傳遞過來的json字符串,轉為json對象
var jsonObject=result;
//從json對象中分離出一些相關信息
var name=jsonObject.name;
var title=jsonObject.title;
var info=jsonObject.info;
console.log("name: "+name);
console.log("title: "+title);
console.log("info: "+info);
var serverInfoString="姓名: "+name+",";
serverInfoString+="頭銜: "+title+",";
serverInfoString+="信息: "+info;
alert(serverInfoString);
}