【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.setPasswordquot222222quot 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类型的属性userInfosList d. userName表示userInfosList中存储的对象0..end的userName属性list中存储的对象必须有userName属性。
8、为什么要用includeProperties或excludeProperties 参数主要是为了过滤掉接口pojo的set、list、其它对象等不需要的数据防止循环取其它关联对象或找不到接口。
如果不配置默认是处理 action中的所有属性如果action中有接口注入json拦截器可能找不到接口而返回不了结果还有如果action中有一个对象这个对象与好多对象都有关联json拦截器会将相关联的所有对象的属性全部转换成json格式如果其它对象有list、set其返回结果相当庞大有可能是死循环而无法返回 。
如果不用ltparam namequotincludePropertiesquotgt或其他方式进行json数据过滤通过debug你会发现前台返回的json字符串是把 action中的所有属性全部转化成json字符串返回给客户端包括service接口、pojo所有属性及有关联的pojo。
有时候根本返回不了结果也不报错后台执行了但前台执行不到callback function这主要是因为找不到接口或者关联的pojo太多造成死循环一般情况下用的最多的就是root、 includeProperties 和excludeNullProperties参数。
当然还有其他的方法如给pojo的属性加json注解。
9、总结 action中避免使用get开头的action方法去掉action中的接口的get方法 为json类型的result配置includeProperties excludeProperties等参数. 另一篇资料 本例程分为二步来写第一步实现返回一个结果对象第二步实现返回一个结果列表首先来看下返回结果对象的实现. 我们需要先建立一个JavaBean 为值对象用来将用户的基本数据封装进去该实体在结果对象和结果列表中都会使用到 Users.java 代码如下: Java代码 1. package com.jsontostruts2.vo 2. 3. / 4. ltpgt 5. 创 建 人ChenTao 6. ltpgt 7. 创建日期2009-5-18 下午05:24:48 8. ltpgt 9. / 10. public class Users 11. 12. private Integer userId 13. 14. private String userName 15. 16. private String sex 17. 18. public Users 19. 20. 21. // get... set.... 略...... 22. 实现 UserAction.java
源码如下: Java代码 1. package com.jsontostruts2.action 2. 3. import com.googlecode.jsonplugin.annotations.JSON 4. import com.jsontostruts2.vo.Users 5. import com.opensymphony.xwork2.ActionSupport 6. 7. / 8. ltpgt 9. 创 建 人ChenTao 10. ltpgt 11. 创建日期2009-5-18 下午05:22:50 12. ltpgt 13. / 14. SuppressWarningsquotserialquot 15. public class UserAction extends ActionSupport 16. 17. private Users users 18. 19. JSONnamequotUSERquot 20. public Users getUsers 21. return users 22. 23. 24. public void setUsersUsers users 25. this.users users 26. 27. 28. Override 29. public String execute throws Exception 30. users new Users 31. users.setUserId1 32. users.setUserNamequotctojxzsycztaoquot 33. users.setSexquot男人quot 34. return SUCCESS 35. 36. 37. 接下来我们需要配置 struts.xml 文件为了在现下面不再重复写该文件这里我将结果对象和列表的请求控制一并贴上来文件内容: Xml代码 1. ltxml versionquot1.0quot encodingquotUTF-8quotgt 2. ltDOCTYPE struts PUBLIC 3. quot-//Apache Software Foundation//DTD Struts Configuration 2.0//ENquot 4. quothttp://struts.apache.org/dtds/struts-2.0.dtdquotgt 5. 6. ltstrutsgt 7. lt-- 注意这里扩展不再是 struts-default而是 json-default --gt 8. ltpackage namequotjsonManagerquot extendsquotjson-defaultquotgt 9. lt-- 返回结果类型为 json --gt 10. ltaction namequotuserJsonquot classquotcom.jsontostruts2.action.UserActionquotgt 11. ltresult typequotjsonquot/gt 12. lt/actiongt 13. lt-- 该action在返回列表时添加进来的 --gt 14. ltaction namequotjsonlistquot classquotcom.jsontostruts2.action.UserListActionquotgt 15. ltresult typequotjsonquot/gt 16. lt/actiongt 17. 18. lt/packagegt 19. lt/strutsgt 能后创建web.xml 和 userjson.
jsp: Xml代码 1. web.xml 2. ltxml versionquot1.0quot encodingquotUTF-8quotgt 3. ltweb-app versionquot2.5quot xmlnsquothttp://java.sun.com/xml/ns/javaeequot 4. xmlns:xsiquothttp://www.w3.org/2001/XMLSchema-instancequot 5. xsi:schemaLocationquothttp://java.sun.com/xml/ns/javaee 6. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsdquotgt 7. 8. ltfiltergt 9. ltfilter-namegtStruts2lt/filter-namegt 10. ltfilter-classgt 11. org.apache.struts2.dispatcher.FilterDispatcher 12. lt/filter-classgt 13. lt/filtergt 14. ltfilter-mappinggt 15. ltfilter-namegtStruts2lt/filter-namegt 16. lturl-patterngt.actionlt/url-patterngt 17. lt/filter-mappinggt 18. ltfilter-mappinggt 19. ltfilter-namegtStruts2lt/filter-namegt 20. lturl-patterngt.jsplt/url-patterngt 21. lt/filter-mappinggt 22. 23. ltwelcome-file-listgt 24. ltwelcome-filegtindex.jsplt/welcome-filegt 25. lt/welcome-file-listgt 26. lt/web-appgt userjson.
jsp : Html代码 1. lt page languagequotjavaquot contentTypequottext/htmlcharsetUTF-8quotgt 2. ltDOCTYPE HTML PUBLIC quot-//W3C//DTD HTML 4.01 Transitional//ENquotgt 3. lthtmlgt 4. ltheadgt 5. lttitlegtjson 返回对象处理lt/titlegt 6. ltscript languagequotjavascriptquotgt 7. var xmlHttp false 8. try 9. xmlHttp new ActiveXObjectquotmsxml2.XMLHTTPquot 10. catche1 11. try 12. xmlHttp new ActiveXObjectquotmicrosoft.XMLHTTPquot 13. catche2 14. try 15. xmlHttp new XMLHttpRequest 16. catche3 17. xmlHttp false 18. 19. 20. 21. ifxmlHttp 22. alertquotcreate xmlHttpRequest failquot 23. 24. function jsonResult 25. xmlHttp.onreadystatechange function 26. ifxmlHttp.readyState 4 27. // 将 JSON 对象转换为JSON字符串需要注意调用eval函数时必须使用quotquot和quotquot将JSON字符串括起来否 28. 29. 则会出错 30. var userObj eval xmlHttp.responseText 31. var userStr quotlttable border0gtquot 32. userStr lttrgtlttdgtltbgtuserIdlt/bgtlt/tdgtlttdgt userObj.USER.userId lt/tdgtlt/trgt 33. userStr lttrgtlttdgtltbgtuserNamelt/bgtlt/tdgtlttdgt userObj.USER.userName lt/tdgtlt/trgt 34. userStr lttrgtlttdgtltbgtsexlt/bgtlt/tdgtlttdgt userObj.USER.sex lt/tdgtlt/trgt 35. userStr quotlt/tablegtquot 36. document.getElementByIdjsonDiv.innerHTML userStr 37. 38. 39. xmlHttp.openquotPOSTquotquotuserJson.actionquottrue 40. xmlHttp.sendnull 41. 42. lt/scriptgt 43. lt/headgt 44. ltbodygt 45. ltdiv idquotjsonDivquotgtlt/divgt 46. ltinput typequotbuttonquot valuequotshowquot onclickquotjsonResultquotgt 47. lt/bodygt 48. lt/htmlgt 现在你可以将应用发布到你的容器当中输入 http://localhost:8080/struts2ToJson/userjson.
jsp 点show这个时候你可以看到你想要的结 果接来实现下返回列表的做法当然与返回对象会有所不同我们需要将一个List对象转换为一个JSON规范的字符串能后发送给客户端的JS 首先建立一个将List 转换为指定字符串的工具类该工具是在一个无意间从网上看到就拿来用了经过少许修改为了减少代码行数我将只贴 出适用于本示例的代码: JsonUtil.java : Java代码 1. package com.jsontostruts2.util 2. 3. import java.beans.IntrospectionException 4. import java.beans.Introspector 5. import java.beans.PropertyDescriptor 6. import java.util.List 7. 8. / 9. ltpgt 10. author ChenTao 11. ltpgt 12. Date 2009-5-18 下午05:47:27 13. ltpgt 14. / 15. public class JsonUtil 16. 17. / 18. param object 19. 任意对象 20. return java.lang.String 21. / 22. public static String objectToJsonObject object 23. StringBuilder json new StringBuilder 24. if object null 25. json.appendquot/quot/quotquot 26. else if object instanceof String object instanceof Integer 27. json.appendquot/quotquot.appendStringobject.appendquot/quotquot 28. else 29. json.appendbeanToJsonobject 30. 31. return json.toString 32. 33. 34. / 35. 功能描述:传入任意一个 javabean 对象生成一个指定规格的字符串 36. 37. param bean 38. bean对象 39. return String 40. / 41. public static String beanToJsonObject bean 42. StringBuilder json new StringBuilder 43. json.appendquotquot 44. PropertyDescriptor props null 45. try 46. props Introspector.getBeanInfobean.getClass Object.class 47. .getPropertyDescriptors 48. catch IntrospectionException e 49. 50. if props null 51. for int i 0 i lt props.length i 52. try 53. String name objectToJsonpropsi.getName 54. String value objectToJsonpropsi.getReadMethod.invokebean 55. json.appendname 56. json.appendquot:quot 57. json.appendvalue 58. json.appendquotquot 59. catch Exception e 60. 61. 62. json.setCharAtjson.length - 1 63. else 64. json.appendquotquot 65. 66. return json.toString 67. 68. 69. / 70. 功能描述:通过传入一个列表对象调用指定方法将列表中的数据生成一个JSON规格指定字符串 71. 72. param list 73. 列表对象 74. return java.lang.String 75. / 76. public static String listToJsonListltgt list 77. StringBuilder json new StringBuilder 78. json.appendquotquot 79. if list null ampamp list.size gt 0 80. for Object obj : list 81. json.appendobjectToJsonobj 82. json.appendquotquot 83. 84. json.setCharAtjson.length - 1 85. else 86. json.appendquotquot 87. 88. return json.toString 89. 90. UserListAction.java: Java代码 1. package com.jsontostruts2.action 2. 3. import java.util.ArrayList 4. import java.util.List 5. 6. import com.googlecode.jsonplugin.annotations.JSON 7. import com.jsontostruts2.util.JsonUtil 8. import com.jsontostruts2.vo.Users 9. import com.opensymphony.xwork2.ActionSupport 10. 11. / 12. ltpgt 13. 创 建 人ChenTao 14. ltpgt 15. 创建日期2009-5-18 下午05:45:42 16. ltpgt 17. / 18. SuppressWarningsquotserialquot 19. public class UserListAction extends ActionSupport 20. 21. / 用于存放JSON生成后的字符串结果 / 22. private String jsonResult 23. 24. JSONnamequotJSONRESULTquot 25. public String getJsonResult 26. return jsonResult 27. 28. 29. public void setJsonResultString jsonResult 30. this.jsonResult jsonResult 31. 32. 33. Override 34. public String execute throws Exception 35. ListltUsersgt userList new ArrayListltUsersgt 36. Users users new Users 37. users.setUserId1 38. users.setUserNamequotctojxzsycztaoquot 39. users.setSexquot男人quot 40. userList.addusers 41. users null 42. users new Users 43. users.setUserId2 44. users.setUserNamequotrainquot 45. users.setSexquot女人quot 46. userList.addusers 47. users null 48. users new Users 49. users.setUserId3 50. users.setUserNamequotmimiquot 51. users.setSexquot女人quot 52. userList.addusers 53. jsonResult JsonUtil.listToJsonuserList 54. System.out.printlnjsonResult 55. return SUCCESS 56. 57. 接下来将要写一个jsonList.
JSP页面来将结果承现给用户 Html代码 1. lt page languagequotjavaquot contentTypequottext/htmlcharsetUTF-8quotgt 2. ltDOCTYPE HTML PUBLIC quot-//W3C//DTD HTML 4.01 Transitional//ENquotgt 3. lthtmlgt 4. ltheadgt 5. lttitlegtjson 返回列表处理lt/titlegt 6. ltscript languagequotjavascriptquotgt 7. var xmlHttp false 8. try 9. xmlHttp new ActiveXObjectquotmsxml2.XMLHTTPquot 10. catche1 11. try 12. xmlHttp new ActiveXObjectquotmicrosoft.XMLHTT.
上一篇:
跟我一步一步开发自己的Openfire插件
下一篇:
还记得,那年的风车吗?