日期:2014-05-16 浏览次数:20349 次
1、引入包(本文中的包全部引自struts-2.1.8.1\lib):
这7个包是返回json形式的数据必须的。因为json大量引用了Apache commons的包,所以要加入4个,commons包,除了commons的包外,还需要引入一个 ezmorph的包。最后加入struts2必须的6个包:
2、后台:
public class UserInfo implements Serializable { private int userId; private String userName; private String password; get set方法略 } |
public class TestAction extends ActionSupport { private String message; //使用json返回单个值 private UserInfo userInfo; //使用json返回对象 private List userInfosList; //使用josn返回List对象 get set方法略 /*返回单个值*/ public String returnMsg(){ this.message = "成功返回单个值"; return SUCCESS; } /*返回UserInfo对象*/ public String returnUser(){ userInfo = new UserInfo(); userInfo.setUserId(10000); userInfo.setUserName("刘栋"); userInfo.setPassword("123456"); return SUCCESS; } /*返回List对象*/ public String returnList(){ userInfosList = new ArrayList<UserInfo>(); UserInfo u1 = new UserInfo(); u1.setUserId(10000); u1.setUserName("张三"); u1.setPassword("111111"); UserInfo u2 = new UserInfo(); u2.setUserId(10001); u2.setUserName("李四"); u2.setPassword("222222"); userInfosList.add(u1); userInfosList.add(u2); return SUCCESS; } } |
<package name="default" namespace="/json" extends="json-default"> <action name="returnMsg" class="com.testAction " method="returnMsg"> <result name="success" type="json"> <param name="root">validate</param> </result> </action> <action name="returnUser " class="com.testAction " method="returnUser "> <result name="success" type="json"> <param name="includeProperties"> userInfo\.userId,userInfo\.userName,userInfo\.password </param> </result> </action> <action name="returnList" class="com.testAction " method="returnList"> <result name="success" type="json"> <param name="includeProperties"> userInfosList\[\d+\]\.userName,userInfosList\[\d+\]\.password </param> </result> </action> </package> |
3、前台:
<script language="javascript"> function getMsg(){ $.ajax({ url:'json/returnMsg.action', type:'post', dataType:'json', success:function(data){ $("#result").html(data.message); } }); } function getUser(){ $("# result ").html(""); $.ajax({ url:'json/returnUser.action', type:'post', dataType:'json', success:function(data){ $("#result").append("用户ID:"+data.userInfo.userId+"") .append("用户名:"+data.userInfo.userName+"") .append("密码:"+data.userInfo.password+""); } }); } function getUserList(){ $("# result ").html(""); $.ajax({ url:'json/returnList.action', type:'post', dataType:'json', success:function(data){ $.each(data.userInfosList,function(i,value){ |