Struts2 整合jQuery实现Ajax功能(2)
1.1.1???Action利用struts2-json-plugin-X.X.X.jar響應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( "您確認運行刪除操作么?")){??
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代碼(做了簡化)
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數據 ?
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.?? ?????*?刪除相應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.?? ????/** ? ?獲得分頁數 ? ???*/ ??
59.?? ????public?String?getPageSize()? throws ?Exception{??
60.?? ????????page?=?recordService.getPage();??
61.?? ????????return?SUCCESS;??
62.?? ????}??
63.?? }
上面代碼中,使用了 @JSON(serialize=false),
除此之外,@JSON還支持例如以下幾個域:
name:指定Action屬性被序列化成JSON對象的屬性名。
serialize:設置是否序列化該屬性
deserialize:設置是否反序列化該屬性。
format:設置用于格式化輸出、解析日期表單域的格式。比如"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包,而不再繼承默認的default包,這是由于僅僅有在該包下才有json類型的Result。
Result能夠使用 <param name="excludeProperties">page,index</param>排除Action 中這些都不返回的屬性.
我們僅僅要輸出person對象的name屬性值,配置例如以下
1.?????<result?type="json">??
2.?????????<param?name="root">person.name</param>??
3.?????</result>??
?
excludeNullProperties參數:表示是否去掉空值,?默認值是false
4.?????<result?type="json">??
5.?????????<param?name="excludeNullProperties">true</param>??
6.??????</result>?
?
ignoreHierarchy參數:表示是否忽略等級,也就是繼承關系,比方:TestAction繼承于BaseAction,那么TestAction中返回的json字符串默認是不會包括父類BaseAction的屬性值,ignoreHierarchy值默覺得true
7.????? <result?type="json">??
8.????? ????<param?name="ignoreHierarchy">false</param>??
9.????? </result>??
?
includeProperties參數:輸出結果中須要包括的屬性值,這里正則表達式和屬性名匹配,能夠用“,”切割填充多個正則表達式。?如:輸出person的全部屬性
10.?? <result?type="json">??
11.?? ????<param?name="includeProperties">person.*,?person/.name</param>??
12.?? </result>??
?
?
比如:
??? <!-- 購房合同管理 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>
?
二級聯動標簽
在struts2 標簽s:doubleselect二級聯動標簽的基礎上實現事件:第二級onchange時調用struts2 action,在action中查詢一個名稱,然后返回回來,此信息顯示在頁面上(這僅僅是給用戶一個提示信息,不影響表單是否能提交)
?
須要加事件的二級聯動jsp代碼
1.?????????<td?class="alignLeft"?width="22%">???所屬業務/項目名稱:???</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>??
????我們須要在“項目名稱”被改變的事件下調用函數,在生成的靜態頁面中查得它的id是cbApplySubmit_changeApplyFormBO_productId
說明一下,這里生成的id有一點規律,貌似。cbApplySubmit是本頁面form表單的action,而changeApplyFormBO.productId是“項目名稱”的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對象??????
9.????????????????var?prodStr=JSON.stringify(jsonProd);????//將JSON對象轉變成JSON格式的字符串??
10.?? ???????????$.post(url,{json:prodStr},callback,"json");???
11.?? ??????????}??
12.?? ????????function?callback(json){?????
13.?? ????????????$("#company").html(json.msg);??
14.?? ?????????}???
15.?? ?????});???
16.?? ??????
17.?? </script>??
?這里,無論是從瀏覽器端(JS,Ajax,Jquery等)發送給server端,還是從server端(Struts的Action,Servlet等)發送回client,發送的都是JSON格式的字符串
?
解釋例如以下:
1.?????var?jsonProd={productId:prodId};??
?這句是組裝JSON對象,這里非常easy,key是productId,value是頁面選擇的項目名稱的id
??
1.?????//將JSON對象轉變成JSON格式的字符串??
2.?????var?prodStr=JSON.stringify(jsonProd);???
?通過JavaScript內置對象JSON的stringify方法,將JSON對象轉換成字符串。由于,我們傳送給server端的要是JSON格式的字符串。
?
1.?????$.post(url,{json:prodStr},callback,"json");???
?這一句,jquery用POST方法向server端發送數據,url是我們要調用的action全路徑,而{json:prodStr}是我們要發送的數據(data),{json:prodStr},事實上也是一個JSON對象,Key:value的形式,注意,我們把prodStr這個json串發過去,在Action那里接收時,要接收“json”這個變量,這個變量的值就是我們發送的prodStr字符串。
回調函數(callback)是指server端成功返回時,在JS端運行的函數。最后一個參數“json”是返回數據類型的一種,另外,還有”text”、“xml”等
?function?callback(json){?????
1.?????????????$("#company").html(json.msg);??
2.??????????}???
3.??????});??
?company是span的id,請看最上面二級聯動標簽處。這個函數用來顯示action中組裝的json對象的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.??????????*?通過選擇的項目名稱,給出提示事業部名稱的提示信息?
8.??????????*??
9.??????????*?@return?
10.?? ?????*?@throws?Exception?
11.?? ?????*/??
12.?? ????public?void?ajaxGetCompany()?throws?Exception?{??
13.?? ????????JSONObject?jsonObj?=?new?JSONObject(json);?//?將JSON格式的字符串構造成JSON對象??
14.?? ??????????
15.?? ????????String?productId?=?jsonObj.getString("productId");?//?獲取JSON對象中的productId屬性的值??
16.?? ??????????
17.?? ????????ProductBO?prod?=?productMng.loadProduct(Integer.parseInt(productId));??
18.?? ????????Integer?companyId?=?prod.getCompanyId();??
19.?? ????????CompanyBO?comp?=?productMng.loadCompany(companyId);??
20.?? ????????String?companyName?=?"事業部為:"?+?comp.getName();??
21.?? ????????json?=?"{msg:'"?+?companyName?+?"'}";????//構造JSON格式的字符串?????
22.?? ????????sendMsg(json);????//發送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的站點http://www.json.org/java/index.html上下載了一些java文件,然后將這些.java文件打成一個jar包json.jar,放在項目lib里面 ajaxGetCompany方法沒有像struts2 別的方法那樣有返回值String,這里設的是void,因我們不須要不論什么跳轉.
???這里有個須要注意的,json= "{msg:'" + companyName + "'}"; companyName外面應該有引號括起來
?
?struts2 配置文件
1.?????<action?name="ajaxGetCompany"?class="CBApplyAction"??
2.?????????method="ajaxGetCompany">??
3.?????</action>??
?沒有result?
總結
以上是生活随笔為你收集整理的Struts2 整合jQuery实现Ajax功能(2)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IBM copy service--fl
- 下一篇: Android_神奇的android:c