【Jsp精品源码栏目提醒】:以下是网学会员为您推荐的Jsp精品源码-【精品】:Struts2返回JSON对象-1 - 培训教程,希望本篇文章对您学习有所帮助。
1、引入包本文中的包全部引自struts-2.1.8.1lib 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 quot成功返回单个值quot return SUCCESS /返回UserInfo对象/ public String returnUser userInfo new UserInfo userInfo.setUserId10000 userInfo.setUserNamequot刘栋quot userInfo.setPasswordquot123456quot return SUCCESS /返回List对象/ public String returnList userInfosList new ArrayListltUserInfogt UserInfo u1 new UserInfo u1.setUserId10000 u1.setUserNamequot张三quot u1.setPasswordquot111111quot UserInfo u2 new UserInfo u2.setUserId10001 u2.setUserNamequot李四quot u2.setPass
wordquot222222quot userInfosList.addu1 userInfosList.addu2 return SUCCESS 3 struts.xml必须继承json-default、json-default继承自struts-default ltpackage namequotdefaultquot namespacequot/jsonquot extendsquotjson-defaultquotgt ltaction namequotreturnMsgquot classquotcom.testAction quot methodquotreturnMsgquotgt ltresult namequotsuccessquot typequotjsonquotgt ltparam namequotrootquotgtvalidatelt/paramgt lt/resultgt lt/actiongt ltaction namequotreturnUser quot classquotcom.testAction quot methodquotreturnUser quotgt ltresult namequotsuccessquot typequotjsonquotgt ltparam namequotincludePropertiesquotgt userInfo.userIduserInfo.userNameuserInfo.password lt/paramgt lt/resultgt lt/actiongt ltaction namequotreturnListquot classquotcom.testAction quot methodquotreturnListquotgt ltresult namequotsuccessquot typequotjsonquotgt ltparam namequotincludePropertiesquotgt userInfosListd.userNameuserInfosListd.password lt/paramgt lt/resultgt lt/actiongt lt/packagegt 4、只要继承extendsquotjson-defaultquotresult type设置成json之后容器会把action的属性自动封装到一个json对象中json拦截器来做 5、includeProperties 参数输出结果中需要包含的属性值这里正则表达式和属性名匹配可以用“”分割填充多个正则表达式。
如输出UserInfo的所有属性及UserInfo的userName属性 ltresult typequotjsonquotgt ltparam namequotincludePropertiesquotgt userInfo. userInfo . userName lt/paramgt lt/resultgt 6、excludeProperties 参数输出结果需要剔除的属性值也支持正则表达式匹配属性名可以用“”分割填充多个正则表达式类同includeProperties 7、输出一个JSON List列表 ltresult namequotsuccessquot typequotjsonquotgt ltparam namequotincludePropertiesquotgt userInfosListd.userNameuserInfosListd.password lt/paramgt lt/resultgt 其中userInfosList是action中的一个List类型的属性userInfosL