struts2中jQuery的异步交互有两种方式:
1)是利用构造字符串的方式来实现;
使用该方法主要是在服务器端根据前端的请求,返回一个字符串信息,然后前端的jQuery通过解析该字符串信息得到对应的请求内容。该方法优点是使用比较灵活,缺点是使用比较复杂。
2)是利用struts自带的jQuery插件来实现。
使用插件方法时,其过程比较简单,和配置普通action信息一样。需要构造XXXset和XXXget方法以及execute方法。然后在struts.xml文件中配置action。该方法优点是使用简单,缺点是:需要在action中定义出前端页面中可能要获取的所有属性信息,使用起来不够灵活。
下面通过代码看一下:
Person属性映射表
1 packagecom.action.xml;2
3 public classPerson {4
5 private intid;6 privateString name;7 private intage;8 privateString address;9 public intgetId() {10 returnid;11 }12 public void setId(intid) {13 this.id =id;14 }15 publicString getName() {16 returnname;17 }18 public voidsetName(String name) {19 this.name =name;20 }21 public intgetAge() {22 returnage;23 }24 public void setAge(intage) {25 this.age =age;26 }27 publicString getAddress() {28 returnaddress;29 }30 public voidsetAddress(String address) {31 this.address =address;32 }33
34 }
客户端页面getJson.jsp代码:
1
2
3 Stringpath=request.getContextPath();4 StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";5 %>
6
7
8
9
10 ">
11
12
My JSP 'getJson.jsp' starting page13
14
15
16
17
18
19
22
23
24
25 $(function(){26 $("#button1").click(function(){27 $.post("getJsonAction2.action",{name:$("#name").val()},function(returnedData,status){28 varhtml= "
id | name | age | address |
---|
30
31 varpeople=returnedData;32 varid=people.id;33 varname=people.name;34 varage=people.age;35 varaddress=people.address;36
37 varhtml= "
id | name | age | address |
---|---|---|---|
"+id+" | "+name+" | "+age+" | "+address+" |
39 $("#theBody table:eq(0)").remove();//找到id为theBody的body中的第0个table(即第一个table表)将其的内容删除掉,防止出现累加
40 $("#theBody").append(html);//将构建的HTML加入到id为theBody的body中
41
42 });43 });44 })45
46
47
48
49
50
51
52 zhangsan
53 lisi
54
55
56
57