Struts2 整合jQuery实现Ajax功能(2)
1.1.1???Action利用struts2-json-plugin-X.X.X.jar響應(yīng)Json格式信息:
1.????? function?removerecordbyid(recordid){???
2.????? ????????$("#showallrecord?table?tr").each(??
3.????? ????????function(){??
4.????? ??????????var?seq=parseInt($( this ).children( "td" ).html());??
5.????? ??????????var?thisrecord?=? this ;??
6.????? ??????????if(seq==recordid)??
7.????? ????????????if(confirm( "您確認(rèn)運(yùn)行刪除操作么?")){??
8.????? ????????????????$.ajax({??
9.????? ????????????????????type:?"POST",??
10.?? ????????????????????url:"removeRecordById.action",??
11.?? ????????????????????dataType:"json",??
12.?? ????????????????????data:{"msg.id":recordid},??
13.?? ????????????????????success:function(json){??
14.?? ????????????????????????if(json.status==4){??
15.?? ????????????????????????????alert("刪除失敗,僅僅有提交留言的ip才干刪除" );??
16.?? ????????????????????????}else{??
17.?? ????????????????????????????$(thisrecord).remove();??
18.?? //??????????????????????????alert("刪除成功");?? ??
19.?? ????????????????????????}??
20.?? ????????????????????},??
21.?? ????????????????????error:function(){??
22.?? ????????????????????????alert("del?error");??
23.?? ????????????????????}??
24.?? ????????????????});??
25.?? ????????????}??
26.?? ????????});??
27.?? ????}??
?Action代碼(做了簡(jiǎn)化)
1.????? public ? class ?CrudMsgAction? extends?ActionSupport{??
2.????? ????private?Record?msg;??
3.????? ????private ? int?index;??
4.????? ????private?RecordService?recordService;??
5.????? ????private?List<Record>?records;??
6.????? ????private ? int ?status?=?0 ;??
7.????? ????private ? int?page?=? 0 ;??
8.????? ??????
9.????? ????@JSON (serialize= false)??
10.?? ????public?RecordService?getRecordService()?{??
11.?? ????????return?recordService;??
12.?? ????}??
13.?? ??????
14.?? ????/** ?
15.?? ?????*?返回全部記錄的JSON數(shù)據(jù) ?
16.?? ?????*?@return?list?.?All?of?the?record.?
17.?? ?????*?@throws?Exception?
18.?? ?????*/ ???
19.?? ????public?String?listAllRecord()? throws ?Exception{??
20.?? ????????List<Record>?list?=?recordService.listAllRecord();??
21.?? ????????records?=?list;??
22.?? ????????return?SUCCESS;??
23.?? ????}??
24.?? ??????
25.?? ????public?String?listAllRecordByPage()? throws?Exception{??
26.?? ????????List<Record>?list?=?recordService.listAllRecord(page);??
27.?? ????????records?=?list;??
28.?? ????????return?SUCCESS;??
29.?? ????}??
30.?? ??
31.?? ????/** ?
32.?? ?????*?插入記錄 ?
33.?? ?????*?@return?update?the?view?with?AJAX?when?struts2?action?return?
34.?? ?????*?@throws?Exception?
35.?? ?????*/ ?
36.?? ????public?String?listRecordByIndex()? throws ?Exception{??
37.?? ????????List<Record>?list?=?recordService.listAllRecord();??
38.?? ????????this.msg?=?list.get( this .getIndex());??
39.?? ??????????
40.?? ????????return?SUCCESS;??
41.?? ????}??
42.?? ????/** ?
43.?? ?????*?刪除相應(yīng)id記錄 ?
44.?? ?????*?@return?field?status.?in?order?to?update?view?with?AJAX ?
45.?? ?????*?@throws?Exception?
46.?? ?????*/ ??
47.?? ????public?String?removeRecordById()? throws ?Exception{??
48.?? ????????String?clientIpAddr?=?ServletActionContext.getRequest().getRemoteAddr();??
49.?? ????????Record?r?=?recordService.listRecordById(msg.getId());??
50.?? ????????if(clientIpAddr.equals(r.getIpaddr())){??
51.?? ????????????recordService.removeRecordById(msg.getId());??
52.?? ????????????return?SUCCESS;??
53.?? ????????}??
54.?? ????????status?=?4;??
55.?? ????????return?SUCCESS;??
56.?? ????}??
57.?? ??????
58.?? ????/** ? ?獲得分頁(yè)數(shù) ? ???*/ ??
59.?? ????public?String?getPageSize()? throws ?Exception{??
60.?? ????????page?=?recordService.getPage();??
61.?? ????????return?SUCCESS;??
62.?? ????}??
63.?? }
上面代碼中,使用了 @JSON(serialize=false),
除此之外,@JSON還支持例如以下幾個(gè)域:
name:指定Action屬性被序列化成JSON對(duì)象的屬性名。
serialize:設(shè)置是否序列化該屬性
deserialize:設(shè)置是否反序列化該屬性。
format:設(shè)置用于格式化輸出、解析日期表單域的格式。比如"yyyy-MM-dd'T'HH:mm:ss"
?
1.????? ?< package ? name = "json" ?extends = "json-default" > ??
2.????? ????????<action ? name = "ajaxRequest" ? class ="com.jun.demos.struts2json.HelloWorld" > ??
3.????? ????????????<result ? type = "json" ? /> ??
4.????? ????????</action > ??
5.????? ????????<action ? name = "listIndexRecord" ? class ="com.jun.demos.book.action.CrudMsgAction" > ??
6.????? ????????????<result ? type = "json" ? /> ??
7.????? ????????</action > ??
8.????? ????????<action ? name = "listAllRecord" ? class ="com.jun.demos.book.action.CrudMsgAction" ? method ="listAllRecord" > ??
9.????? ????????????<result ? type = "json" ? /> ??
10.?? ????????</action > ???
11.?? ????????<action ? name = "removeRecordById" ? class ="CrudMsgAction" ? method = "removeRecordById" >??
12.?? ????????????<result ? type = "json" ? /> ??
13.?? ????????</action > ??
14.?? ????????<action ? name = "getPageIndex" ? class = " CrudMsgAction"? method = "getPageSize" > ??
15.?? ????????????<result ? type = "json" ? /> ??
16.?? ????????</action > ??
17.??????</package > ??
配置該Action與配置普通Action存在小小的差別。
包繼承了json-default包,而不再繼承默認(rèn)的default包,這是由于僅僅有在該包下才有json類型的Result。
Result能夠使用 <param name="excludeProperties">page,index</param>排除Action 中這些都不返回的屬性.
我們僅僅要輸出person對(duì)象的name屬性值,配置例如以下
1.?????<result?type="json">??
2.?????????<param?name="root">person.name</param>??
3.?????</result>??
?
excludeNullProperties參數(shù):表示是否去掉空值,?默認(rèn)值是false
4.?????<result?type="json">??
5.?????????<param?name="excludeNullProperties">true</param>??
6.??????</result>?
?
ignoreHierarchy參數(shù):表示是否忽略等級(jí),也就是繼承關(guān)系,比方:TestAction繼承于BaseAction,那么TestAction中返回的json字符串默認(rèn)是不會(huì)包括父類BaseAction的屬性值,ignoreHierarchy值默覺(jué)得true
7.????? <result?type="json">??
8.????? ????<param?name="ignoreHierarchy">false</param>??
9.????? </result>??
?
includeProperties參數(shù):輸出結(jié)果中須要包括的屬性值,這里正則表達(dá)式和屬性名匹配,能夠用“,”切割填充多個(gè)正則表達(dá)式。?如:輸出person的全部屬性
10.?? <result?type="json">??
11.?? ????<param?name="includeProperties">person.*,?person/.name</param>??
12.?? </result>??
?
?
比如:
??? <!-- 購(gòu)房合同管理 namespace保證action的路徑與jQuery兼容-->
??? <package name="yushou_hetong" extends="json-default"namespace="/pages/hetong">
??? ??? <actionname="hetongAdd"class="hetongAddAction">
??? ??? ??? <result name="list">/pages/hetong/qylist.jsp</result>
??? ??? ??? <!-- <resultname="add">/pages/hetong/add.jsp</result> 改用純Html+jQuery-->
??? ??? ??? <result name="add">/pages/hetong/add.html</result>
??? ??? ??? <result name="Query">/pages/hetong/query.html</result>
??? ??? ??? <result name="xiangmu">/pages/hetong/add/xiangmu.jsp</result>
??? ??? ??? <result name="loupan">/pages/hetong/add/loupan.jsp</result>
??? ??? ??? <result name="house">/pages/hetong/add/house.jsp</result>
??? ??? ??? <result name="houseList">/pages/hetong/add/houseList.jsp</result>
??? ??? ??? <result name="fukuan">/pages/hetong/add/fukuan.jsp</result>
??? ??? ??? <result name= "success"? type="json" >
??? ??? ??? ??? ??? <param name="ignoreHierarchy">false</param>
??? ??? ??? ??? ??? <param name="includeProperties">errmsg</param>
??? ??? ??? </result>
??? ??? </action>
??? </package>
?
二級(jí)聯(lián)動(dòng)標(biāo)簽
在struts2 標(biāo)簽s:doubleselect二級(jí)聯(lián)動(dòng)標(biāo)簽的基礎(chǔ)上實(shí)現(xiàn)事件:第二級(jí)onchange時(shí)調(diào)用struts2 action,在action中查詢一個(gè)名稱,然后返回回來(lái),此信息顯示在頁(yè)面上(這僅僅是給用戶一個(gè)提示信息,不影響表單是否能提交)
?
須要加事件的二級(jí)聯(lián)動(dòng)jsp代碼
1.?????????<td?class="alignLeft"?width="22%">???所屬業(yè)務(wù)/項(xiàng)目名稱:???</td>??
2.?????????<td?valign="top"?class="alignLeft"?width="20%">??
3.?????????????<s:doubleselect?name="changeApplyFormBO.operationId"?list="operationList"?listKey="id"??
4.?????????????listValue="operationName"?doubleList="operationSubProductList"???
5.?????????????doubleListKey="id"?doubleListValue="prudName"??doubleName="changeApplyFormBO.productId"??
6.?????????????headerKey=""??headerValue="---?Please?Select?---"?/>????
7.????????????? <span?id="company"?style="color:red"></span>??
8.?????????</td>??
????我們須要在“項(xiàng)目名稱”被改變的事件下調(diào)用函數(shù),在生成的靜態(tài)頁(yè)面中查得它的id是cbApplySubmit_changeApplyFormBO_productId
說(shuō)明一下,這里生成的id有一點(diǎn)規(guī)律,貌似。cbApplySubmit是本頁(yè)面form表單的action,而changeApplyFormBO.productId是“項(xiàng)目名稱”的name
?
以下給出定制下拉菜單事件的js?
1.?????<script>??
2.???????????
3.???????????$(function(){??
4.???????????????var?obj=document.getElementById("cbApplySubmit_changeApplyFormBO_productId");??
5.???????????????obj.οnchange=function(){??????
6.????????????????var?prodId=obj.value;??
7.????????????????var?url="${contextPath}/assets/businessChange/ajaxGetCompany.do";??
8.????????????????var?jsonProd={productId:prodId};????//JSON對(duì)象??????
9.????????????????var?prodStr=JSON.stringify(jsonProd);????//將JSON對(duì)象轉(zhuǎn)變成JSON格式的字符串??
10.?? ???????????$.post(url,{json:prodStr},callback,"json");???
11.?? ??????????}??
12.?? ????????function?callback(json){?????
13.?? ????????????$("#company").html(json.msg);??
14.?? ?????????}???
15.?? ?????});???
16.?? ??????
17.?? </script>??
?這里,無(wú)論是從瀏覽器端(JS,Ajax,Jquery等)發(fā)送給server端,還是從server端(Struts的Action,Servlet等)發(fā)送回client,發(fā)送的都是JSON格式的字符串
?
解釋例如以下:
1.?????var?jsonProd={productId:prodId};??
?這句是組裝JSON對(duì)象,這里非常easy,key是productId,value是頁(yè)面選擇的項(xiàng)目名稱的id
??
1.?????//將JSON對(duì)象轉(zhuǎn)變成JSON格式的字符串??
2.?????var?prodStr=JSON.stringify(jsonProd);???
?通過(guò)JavaScript內(nèi)置對(duì)象JSON的stringify方法,將JSON對(duì)象轉(zhuǎn)換成字符串。由于,我們傳送給server端的要是JSON格式的字符串。
?
1.?????$.post(url,{json:prodStr},callback,"json");???
?這一句,jquery用POST方法向server端發(fā)送數(shù)據(jù),url是我們要調(diào)用的action全路徑,而{json:prodStr}是我們要發(fā)送的數(shù)據(jù)(data),{json:prodStr},事實(shí)上也是一個(gè)JSON對(duì)象,Key:value的形式,注意,我們把prodStr這個(gè)json串發(fā)過(guò)去,在Action那里接收時(shí),要接收“json”這個(gè)變量,這個(gè)變量的值就是我們發(fā)送的prodStr字符串。
回調(diào)函數(shù)(callback)是指server端成功返回時(shí),在JS端運(yùn)行的函數(shù)。最后一個(gè)參數(shù)“json”是返回?cái)?shù)據(jù)類型的一種,另外,還有”text”、“xml”等
?function?callback(json){?????
1.?????????????$("#company").html(json.msg);??
2.??????????}???
3.??????});??
?company是span的id,請(qǐng)看最上面二級(jí)聯(lián)動(dòng)標(biāo)簽處。這個(gè)函數(shù)用來(lái)顯示action中組裝的json對(duì)象的value值
?
struts2 action類?
1.?????import?org.json.JSONObject;??
2.???????
3.?????public?class?CBApplyAction?extends?ActionSupport?{??
4.?????????private?IProductMng?productMng;??
5.?????????private?String?json;??
6.?????????/**?
7.??????????*?通過(guò)選擇的項(xiàng)目名稱,給出提示事業(yè)部名稱的提示信息?
8.??????????*??
9.??????????*?@return?
10.?? ?????*?@throws?Exception?
11.?? ?????*/??
12.?? ????public?void?ajaxGetCompany()?throws?Exception?{??
13.?? ????????JSONObject?jsonObj?=?new?JSONObject(json);?//?將JSON格式的字符串構(gòu)造成JSON對(duì)象??
14.?? ??????????
15.?? ????????String?productId?=?jsonObj.getString("productId");?//?獲取JSON對(duì)象中的productId屬性的值??
16.?? ??????????
17.?? ????????ProductBO?prod?=?productMng.loadProduct(Integer.parseInt(productId));??
18.?? ????????Integer?companyId?=?prod.getCompanyId();??
19.?? ????????CompanyBO?comp?=?productMng.loadCompany(companyId);??
20.?? ????????String?companyName?=?"事業(yè)部為:"?+?comp.getName();??
21.?? ????????json?=?"{msg:'"?+?companyName?+?"'}";????//構(gòu)造JSON格式的字符串?????
22.?? ????????sendMsg(json);????//發(fā)送JSON格式的字符串回JS端??????
23.?? ????}??
24.?? ??????
25.?? ????public?void?sendMsg(String?content)?throws?IOException{??????
26.?? ????????HttpServletResponse?response?=?ServletActionContext.getResponse();??????
27.?? ????????response.setCharacterEncoding("UTF-8");??????
28.?? ????????response.getWriter().write(content);??????
29.?? ????}????
30.?? ??
31.?? ????public?String?getJson()?{??
32.?? ????????return?json;??
33.?? ????}??
34.?? ??
35.?? ????public?void?setJson(String?json)?{??
36.?? ????????this.json?=?json;??
37.?? ????}??
38.?? ??
39.?? ????public?void?setProductMng(IProductMng?productMng)?{??
40.?? ????????this.productMng?=?productMng;??
41.?? ????}????
42.?? }??
???? JSONObject是我從json的站點(diǎn)http://www.json.org/java/index.html上下載了一些java文件,然后將這些.java文件打成一個(gè)jar包json.jar,放在項(xiàng)目lib里面 ajaxGetCompany方法沒(méi)有像struts2 別的方法那樣有返回值String,這里設(shè)的是void,因我們不須要不論什么跳轉(zhuǎn).
???這里有個(gè)須要注意的,json= "{msg:'" + companyName + "'}"; companyName外面應(yīng)該有引號(hào)括起來(lái)
?
?struts2 配置文件
1.?????<action?name="ajaxGetCompany"?class="CBApplyAction"??
2.?????????method="ajaxGetCompany">??
3.?????</action>??
?沒(méi)有result?
總結(jié)
以上是生活随笔為你收集整理的Struts2 整合jQuery实现Ajax功能(2)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: IBM copy service--fl
- 下一篇: Android_神奇的android:c