struts2返回json数据
1、引入包(本文中的包全部引自struts-2.1.8.1\lib):
struts2-json-plugin-2.1.8.1.jar
json-lib-2.1.jar
commons-collections-3.2.jar
commons-beanutils-1.7.0.jar
commons-lang-2.3.jar
commons-logging-1.0.4.jar
ezmorph-1.0.3.jar
这7个包是返回json形式的数据必须的。因为json大量引用了Apache commons的包,所以要加入4个,commons包,除了commons的包外,还需要引入一个 ezmorph的包。最后加入struts2必须的6个包:
struts2-core-2.1.8.1.jar
xwork-core-2.1.6.jar
ognl-2.7.3.jar
freemarker-2.3.15.jar
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
2、后台:
1) Userinfo实体类代码
public class UserInfo implements Serializable {
private int userId;
private String userName;
private String password;
get set方法略
}
2) Action类
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;
}
}
3) struts.xml(必须继承json-default、json-default继承自struts-default)
<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