溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Struts2如何處理AJAX請(qǐng)求

發(fā)布時(shí)間:2022-03-19 16:24:55 來源:億速云 閱讀:241 作者:iii 欄目:web開發(fā)

本文小編為大家詳細(xì)介紹“Struts2如何處理AJAX請(qǐng)求”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“Struts2如何處理AJAX請(qǐng)求”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。

Struts2 處理AJAX請(qǐng)求

Struts2整合AJAX有2種方式:

  • 使用type="stream"類型的<result>

  • 使用JSON插件

使用type="stream"類型的<result>  獲取text

前端
  <body>
  <form>
    學(xué)號(hào):<input type="text" id="no"><br />
    姓名:<input type="text" id="name"><br />
    <button type="button" id="btn">查詢成績</button>
  </form>
  <p id="score"></p>

  <script src="js/jquery-3.4.1.min.js"></script>
  <script>
    $("#btn").click(function () {
      $.ajax({
        url:"HandlerAction",   
        type:"get",   
        data:{"no":$("#no").val(),"name":$("#name").val()},
        dataType:"text",
        error:function () {
          console.log("ajax請(qǐng)求失敗!")
        },
        success:function (data) {
          $("#score").text(data);
        }
      })
    });
  </script>
  </body>

url要和struts.xml中action的name、包的namespace對(duì)應(yīng)。

action

public class HandlerAction extends ActionSupport {
    private int no;
    private String name;
    private InputStream inputStream;

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    @Override
    public String execute() throws Exception {
        //此處缺省連接數(shù)據(jù)庫查詢總分
        String result = name + "同學(xué),你的總分是:680";
        //設(shè)置要返回的數(shù)據(jù)。我們傳給瀏覽器的數(shù)據(jù)含有中文,需要設(shè)置utf-8編碼,來解決中文亂碼
        inputStream=new ByteArrayInputStream(result.getBytes("utf-8"));
        return SUCCESS;
    }
}

前端向后臺(tái)發(fā)送了2個(gè)字段:no、name

action需要設(shè)置2個(gè)同名的成員變量,并提供對(duì)應(yīng)的getter、setter方法,才能接收到前端傳來的數(shù)據(jù)。

需要一個(gè)InputStream類型的成員變量,并提供對(duì)應(yīng)的getter、setter,用于向?yàn)g覽器返回?cái)?shù)據(jù)。

需要一個(gè)處理請(qǐng)求的方法(execute),設(shè)置返回給瀏覽器的數(shù)據(jù)。

struts.xml

<struts>
    <package name="action" namespace="/" extends="struts-default">
        <action name="HandlerAction" class="action.HandlerAction">
            <result name="success" type="stream">
                <!-- 設(shè)置返回給瀏覽器的數(shù)據(jù)類型 -->
                <param name="contentType">text/html</param>
                <!--指定獲取InputStream的方法,getInputStream(),約定:去掉get,后面部分使用camel寫法 -->
                <param name="inputName">inputStream</param>
            </result>
        </action>
    </package>
</struts>
流程分析
  • 前端向后臺(tái)發(fā)送ajax請(qǐng)求,傳遞no、name2個(gè)字段

  • JVM創(chuàng)建action實(shí)例,調(diào)用no、name對(duì)應(yīng)的setter方法把前端傳過來的值賦給成員變量(會(huì)自動(dòng)轉(zhuǎn)換為目標(biāo)類型),完成action的初始化

  • JVM調(diào)用action處理業(yè)務(wù)的方法execute,設(shè)置向?yàn)g覽器返回的數(shù)據(jù)

  • JVM根據(jù)struts.xml中<result>指定的方法(getInputStream),獲取InputSteam,將里面的數(shù)據(jù)傳給瀏覽器。

使用type="stream"類型的<result>  獲取json

前端
 <body>
  <form>
    學(xué)號(hào):<input type="text" id="no"><br />
    <button type="button" id="btn">查詢學(xué)生信息</button>
  </form>
  <div id="show"></div>

  <script src="js/jquery-3.4.1.min.js"></script>
  <script>
    $("#btn").click(function () {
      $.ajax({
        url:"HandlerAction",
        type:"post",
        data:{"no":$("#no").val()},
        dataType:"json",
        error:function () {
          console.log("ajax請(qǐng)求失?。?quot;)
        },
        success:function (data) {
          $("#show").append("姓名:" + data.name+",");
          $("#show").append("年齡:" + data.age+",");
          $("#show").append("成績:" + data.score+"。");
        }
      })
    });
  </script>
  </body>
action
public class HandlerAction extends ActionSupport {
    private int no;
    private InputStream inputStream;

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    @Override
    public String execute() throws Exception {
        //此處缺省連接數(shù)據(jù)庫查詢得到學(xué)生信息
        Student student = new Student(1, "張三", 20, 100);
        String jsonStr = JSON.toJSONString(student);

        //設(shè)置要返回的數(shù)據(jù)
        inputStream=new ByteArrayInputStream(jsonStr.getBytes("utf-8"));
        return SUCCESS;
    }
}

使用了阿里的fastjson.jar,需要自己下載引入。

struts.xml

配置同上

使用JSON插件實(shí)現(xiàn)AJAX

前端
<body>
  <form>
    學(xué)號(hào):<input type="text" id="no"><br />
    <button type="button" id="btn">查詢學(xué)生信息</button>
  </form>
  <div id="show"></div>

  <script src="js/jquery-3.4.1.min.js"></script>
  <script>
    $("#btn").click(function () {
      $.ajax({
        url:"HandlerAction",
        type:"post",
        data:{"no":$("#no").val()},
        dataType:"json",
        error:function () {
          console.log("ajax請(qǐng)求失敗!")
        },
        success:function (data) {
          $("#show").append("姓名:" + data.student.name+",");
          $("#show").append("年齡:" + data.student.age+",");
          $("#show").append("成績:" + data.student.score+"。");
        }
      })
    });
  </script>
  </body>
action
public class HandlerAction extends ActionSupport {
    private int no;
    private Student student;

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public Student getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    @Override
    public String execute() throws Exception {
        //此處缺省連接數(shù)據(jù)庫查詢得到學(xué)生信息
        student = new Student(1, "張三", 20, 100);
        return SUCCESS;
    }
}

需要設(shè)置同名的成員變量,并提供getter、setter方法,來接收前端傳來的數(shù)據(jù)。

此種方式是由JSON插件把a(bǔ)ction對(duì)象序列化為一個(gè)JSON格式的字符串,傳給瀏覽器。瀏覽器可以直接訪問action的所有成員變量(實(shí)質(zhì)是調(diào)用對(duì)應(yīng)的getter方法)。

我們只需要把a(bǔ)jax要請(qǐng)求的數(shù)據(jù)封裝為action的成員變量,并提供對(duì)應(yīng)的getter、setter方法。需要在主調(diào)方法(execute)的return語句之前對(duì)請(qǐng)求的數(shù)據(jù)賦值。

success:function (data) {
          $("#show").append("姓名:" + data.student.name+",");
          $("#show").append("年齡:" + data.student.age+",");
          $("#show").append("成績:" + data.student.score+"。");
}

瀏覽器接受到的數(shù)據(jù)data本身就是action實(shí)例,可通過.訪問成員變量。

struts.xml
<struts>
    <package name="example" namespace="/" extends="json-default">
        <action name="HandlerAction" class="action.HandlerAction">
            <!--type="json"的result,可以缺省name屬性,當(dāng)然寫上也行-->
            <result type="json">
                <param name="noCache">true</param>
                <!-- 設(shè)置返回給瀏覽器的數(shù)據(jù)類型 -->
                <param name="contentType">text/html</param>
            </result>
        </action>
    </package>
</struts>
說明

需要手動(dòng)添加JSON插件 struts2-json-plugin.jar 。

Struts2如何處理AJAX請(qǐng)求

上面的壓縮包含有struts的所有jar包,其中就包括了struts2-json-plugin.jar。

下面的壓縮包只有struts核心的8個(gè)jar包。

讀到這里,這篇“Struts2如何處理AJAX請(qǐng)求”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI