Struts2和Ajax數(shù)據(jù)交互示例詳解
前言
我們從Web 2.0的隨波逐流,Ajax的大放異彩說起,Struts2框架自己整合了對Ajax的原生支持(struts 2.1.7+,之前的版本可以通過插件實(shí)現(xiàn)),框架的整合只是使得JSON的創(chuàng)建變得異常簡單,并且可以簡單的融入到Struts2框架中,當(dāng)然這只是在我們需要JSON的時(shí)候才會顯得流光溢彩。
ajax請求在項(xiàng)目中常常使用,今天就平時(shí)掌握的總結(jié)一下,關(guān)于使用ajax請求到Struts2中的action時(shí),前臺頁面與后臺action之間的數(shù)據(jù)傳遞交互問題。
這里我主要記錄下自己所掌握的幾種方式??梢愿鶕?jù)自己平時(shí)項(xiàng)目的需求來進(jìn)行選擇。
1.使用stream類型的result
此種類型可以直接讓Struts2中的action向客戶端瀏覽器生成文本響應(yīng)。
示例:
jsp頁面:
<%@ taglib prefix="s" uri="/struts-tags" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>ajax提交登錄信息</title> <%--導(dǎo)入js插件--%> <script src="${PageContext.request.contextPath}/demo/js/jquery-1.4.4.min.js" type="text/javascript"></script> </head> <body> <h3>異步登錄</h3> <s:form id="loginForm" method="POST"> <s:textfield name="username"/> <s:textfield name="psw"/> <input id="loginBtn" type="button" value="提交"> </s:form> <div id="show" style="display:none;"></div> </body> <script type="text/javascript"> $("#loginBtn").click(function(){ $("#show").hide(); //發(fā)送請求login 以各表單里歌空間作為請求參數(shù) $.get("login",$("#loginForm").serializeArray(), function(data,statusText){ $("#show").height(80) .width(240) .css("border","1px solid black") .css("border-radius","15px") .css("backgroud-color","#efef99") .css("color","#ff0000") .css("padding","20px") .empty(); $("#show").append("登錄結(jié)果:"+data+"<br/>"); $("#show").show(600); },"html");//指定服務(wù)器響應(yīng)為html }); </script> </html>
處理邏輯的action:
/** * Description:eleven.action * Author: Eleven * Date: 2018/1/26 18:09 */ public class LoginAction extends ActionSupport{ private String username; private String psw; //輸出結(jié)果的二進(jìn)制流 private InputStream inputStream; public String login() throws Exception{ if(username.equals("tom")&& psw.equals("123")){ inputStream = new ByteArrayInputStream("恭喜您,登錄成功".getBytes("UTF-8")); }else{ inputStream = new ByteArrayInputStream("對不起,登錄失敗".getBytes("UTF-8")); } return SUCCESS; } //提供get方法 public InputStream getInputStream() { return inputStream; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPsw() { return psw; } public void setPsw(String psw) { this.psw = psw; } }
action中除了接收頁面?zhèn)鬟f的用戶名、密碼外,還有一個(gè)InputStream類型的成員變量,并為它提供了對應(yīng)的get方法。get方法中返回的二進(jìn)制流將會直接輸出給客戶端瀏覽器。
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> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <action name="login" class="eleven.action.LoginAction" method="login"> <result type="stream"> <!--指定stream流生成響應(yīng)的數(shù)據(jù)類型--> <param name="contentType">text/html</param> <!--指定action中由哪個(gè)方法去輸出InputStream類型的變量--> <param name="inputName">inputStream</param> </result> </action> </package> </struts>
在瀏覽器中瀏覽該頁面,并輸入相關(guān)信息,然后提交,可以看到后臺action直接將消息數(shù)據(jù)返回給頁面,而同時(shí)頁面也不需要進(jìn)行刷新,而是直接在局部進(jìn)行顯示,這是利用了ajax的異步發(fā)送請求。注意,此種方式需要在struts.xml文件中要配置類型為stream的流,并設(shè)置inputName屬性,并在action中提供InputStream對應(yīng)的get方法。
運(yùn)行截圖:
2.使用json類型的result
有個(gè)jar包struts2-json-plugin-2.3.16.3.jar,可以為Struts2增加JSON插件,即當(dāng)action中的result的類型設(shè)為json時(shí),也可以在客戶端js中異步調(diào)用action,并且action中返回的數(shù)據(jù),可以直接被JSON插件序列化成json格式的字符串,并將該字符串返回給客戶端瀏覽器。
示例:
jsp頁面:
<%@ taglib prefix="s" uri="/struts-tags" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>ajax提交登錄信息</title> <%--導(dǎo)入js插件--%> <script src="${PageContext.request.contextPath}/demo/js/jquery-1.4.4.min.js" type="text/javascript"></script> </head> <body> <h3>異步登錄</h3> <s:form id="loginForm" method="POST"> <s:textfield name="username"/> <s:textfield name="psw"/> <input id="loginBtn" type="button" value="提交"> </s:form> <div id="show" style="display:none;"></div> </body> <script type="text/javascript"> $("#loginBtn").click(function(){ $("#show").hide(); //發(fā)送請求login 以各表單里歌空間作為請求參數(shù) $.get("login",$("#loginForm").serializeArray(), function(data,statusText){ //此時(shí)的data中包含username,psw,age $("#show").height(80) .width(300) .css("border","1px solid black") .css("border-radius","15px") .css("backgroud-color","#efef99") .css("color","#ff0000") .css("padding","20px") .empty(); alert(data); $("#show").append(data+"<br/>"); $("#show").show(600); },"html"); }); </script> </html>
action代碼:
public class LoginAction extends ActionSupport{ private String username; private String psw; private int age; public String login() throws Exception{ age = 18; return SUCCESS; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPsw() { return psw; } public void setPsw(String psw) { this.psw = psw; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
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> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default,json-default"> <action name="login" class="eleven.action.LoginAction" method="login"> <result type="json"> <param name="noCache">true</param> <param name="contentType">text/html</param> </result> </action> </package> </struts>
在瀏覽器中瀏覽該頁面,并輸入相關(guān)信息,然后提交,可以看到后臺action直接將消息數(shù)據(jù)返回給頁面,而同時(shí)頁面也不需要進(jìn)行刷新,而是直接在局部進(jìn)行顯示,這是利用了ajax的異步發(fā)送請求。注意,此種方式需要在struts.xml文件中要配置package繼承json-default,且配置result類型為json,并在action中提供需要傳遞數(shù)據(jù)的對應(yīng)的get方法。當(dāng)然了前提是添加了struts2-json-plugin-2.3.16.3.jar,不然struts2是不會自動將數(shù)據(jù)轉(zhuǎn)為json格式的數(shù)據(jù)的。
效果截圖:
故我們可以總結(jié)一下result類型為json的步驟:
1.導(dǎo)入jar包:struts2-json-plugin-2.3.7.jar
2.配置struts返回的結(jié)果集視圖 設(shè)置type=json
3.設(shè)置對應(yīng)action所在的package繼承自json-default
4.將要返回的數(shù)據(jù)提供get方法
5.在struts.xml中設(shè)置返回?cái)?shù)據(jù)的格式
對于第5步設(shè)置返回?cái)?shù)據(jù)的格式,可以根據(jù)自己項(xiàng)目的需要,去具體設(shè)置,這里只是簡單舉例,并沒有拿復(fù)雜的數(shù)據(jù),如果是返回一個(gè)List集合,那么對于數(shù)據(jù)的格式可以進(jìn)行如下設(shè)置:
<result name="test" type="json"> <!-- 設(shè)置數(shù)據(jù)的來源從某個(gè)數(shù)據(jù)得到 --> <!-- 過濾數(shù)據(jù)從gtmList集合中得到,且只獲取集合中對象的name,跟uuid屬性 --> <param name="root">gtmList</param> <param name="includeProperties"> \[\d+\]\.name, \[\d+\]\.uuid </param> </result>
上面這種方式外,還有下面這種方式
<result name="ajaxGetBySm" type="json"> <!-- 一般使用這種方式 先用來源過濾action默認(rèn)從整個(gè)action中獲取所有的(前提是此action中沒有g(shù)etAction()方法) 但是為了方便 一般不寫root:action這個(gè) 然后再用包含設(shè)置進(jìn)行過濾設(shè)置 --> <param name="root">action</param> <param name="includeProperties"> gtmList\[\d+\]\.name, gtmList\[\d+\]\.uuid </param> </result>
上面兩種方式都是設(shè)置數(shù)據(jù)從gtmList集合中獲取且,只獲取對象的屬性為name與uuid的。這里只做簡單的舉例,具體可自己下去深入研究。
附上json類型的Result允許指定的常用參數(shù):
另外,除了以上兩種是struts2支持的ajax外,其實(shí)如果單純的只是可以讓服務(wù)器端可以跟客戶端瀏覽器進(jìn)行數(shù)據(jù)交互,可以使用response.getWrite()這種方式。
PrintWriter printWriter =response.getWriter(); printWriter.print("success");
選擇哪種方式?
對于我,如果只是對增刪改功能是否成功的一個(gè)flag判斷的數(shù)據(jù),則可優(yōu)先選擇response.getWriter().print("xxx")與設(shè)置result類型為stream的方式,但是如果是需要返回大量對象數(shù)據(jù),在頁面接收然后進(jìn)行數(shù)據(jù)展示,例如頁面通過ajax請求,需要后臺action返回一個(gè)list集合,則就要選擇配置result類型為json的方式了。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
本人ajax留言板的源程序 不錯(cuò)的應(yīng)用js
本人ajax留言板的源程序 不錯(cuò)的應(yīng)用js...2007-09-09關(guān)于多個(gè)Ajax請求執(zhí)行返回先后的問題示例探討
這篇文章主要與大家探討下關(guān)于多個(gè)Ajax請求執(zhí)行返回先后的問題,需要的朋友可以參考下2014-07-07Ajax實(shí)現(xiàn)異步加載數(shù)據(jù)
這篇文章主要為大家詳細(xì)介紹了Ajax實(shí)現(xiàn)異步加載數(shù)據(jù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11