Ajax+Servlet、jsonp+Servlet、 jsonp+Struts2 實現跨域

因爲公司項目需求,要實現兩個系統的單點登錄(SSO)聯動。例如,在A系統登錄,再從A系統跳轉至B系統時無需再次登錄。

在完成SSO登錄之前,需要先實現跨域的數據傳輸,在網上找了半天,全是半拉子工程,參差不齊,寫的一點兒也全。摸索了一天才弄出來一個小成品。所以趕在下班之前分享出來。

先建立兩個web項目(取名A項目和B項目。A和B的tomcat端口號要不一致,模擬跨域)。

1.首先是Ajax+Servlet

A爲請求端,請求從B項目獲取數據。請求方式爲Ajax。代碼如下:

function test(){
        $.ajax({
     //接收端使用Servlet
     url:"http://localhost:8089/testServlet",
          type:"get",
          dataType:"text",
          success:function(data){
            alert(data);
          }
        })
      }

B爲接收端,獲取A的請求,並返回數據,方式爲Servlet。代碼如下:

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException,IOException{

        //添加響應頭,讓其允許跨域

   response.addHeader("Access-Control-Allow-Origin","*");

   //返回數據"Hello World"

  response.getWriter().write("Hello World");

}

這樣A系統執行test()方法後就會收到B系統的 迴應,並alert“Hello World”。

2.然後是jsonp+Servlet

jsonp和Ajax的區別是 把   dataType   改爲 ‘jsonp’。 也有可選的兩個其他參數jsonp,和jsonCallback。

  function test2(){
        alert("2");
        $.ajax({
          url:"http://localhost:8089/testServlet",
          type:"get",
          dataType:"jsonp",
     //(1)
     //jsonp:"call",
     //(2)
     //jsonpCallback:"otherMethod",
          success:function(data){
            alert(data);
          }
        })
      }
 function otherMethod(){
  alert("otherMethod");
 }

當執行test2()方法時,瀏覽器會向http://localhost:8089/testServlet 發送一個請求,請求爲

發現後面帶了一個叫  ‘callback’的參數 ,這個參數名稱可以修改,上面代碼中(1)的jsonp:‘ call’,這個'call'就是請求參數的名稱,當不寫也是可以的,系統會默認添加一個‘callback’。代碼中(2)的jsonpCallback‘otherMethod’是指當服務器收到請求並且相應完成後,執行名稱爲‘otherMethod’方法,而且要比success方法要先執行。

Serlvet 的代碼爲

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String str= "123";
   //前端會默認生成一個callback參數,當然你也可以自己指定參數名稱
   //當前端的jsonp設定爲‘call’時,下面需修改爲request.getParameter("call")
   String method = request.getParameter("callback");
        str= method + "(" + str+ ")";
        response.getWriter().write(str);
 }

3.然後是jsonp+Struts2

前端代碼不變

 function test3(){
        $.ajax({
          url:"http://localhost:8081/testJsonp",
          data:{param1:"1"},
          type:"get",
          dataType:"jsonp",
          jsonp:"call",
          //jsonpCallback:"otherMethod",
          success:function(data){
            alert(data);
          }
        })
      }

Action 代碼

package com.keerqin;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

public class login extends ActionSupport{
   HttpServletRequest request = ServletActionContext.getRequest();
   HttpServletResponse response = ServletActionContext.getResponse();
   private String result;

   public String getResult() {
      return result;
   }
   public void setResult(String result) {
      this.result = result;
   }

   public String sout(){
      String param1 = request.getParameter("param1");
      System.out.println(param1);

      result = "Hello World";
      /*String callback = request.getParameter("call");
      result = callback + "(" + result + ")";*/
      return SUCCESS;
   }
}
這裏註釋的部分即使註釋,跨域請求依舊好用。打開的話,前端的success函數alert時會將‘callback’的值和result值一併輸出。


struts.xml代碼
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <package name="default" namespace="/" extends="struts-default,json-default">

        <action name="testJsonp" class="com.keerqin.login" method="sout">
            <result type="json" name="success">
                <param name="root">result</param>
                <param name="callbackParameter">call</param>
            </result>
        </action>
    </package>
</struts>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章