您的位置:首页 > Web前端 > JQuery

Struts2 整合jQuery实现Ajax功能(2)

2015-01-31 18:48 579 查看
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.onchange=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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: