struts2中json应用

1.导包struts2-json-plugin-2.1.8.1.jar
2.(1)struts.xml

<package name="dang-default" extends="json-default" namespace="/">
    <include file="config/struts/struts-user.xml" />
</package>
(2)struts-user.xml
<package name="user" extends="dang-default" namespace="/user">
<action name="userAction_*" class="com.tarena.dang.web.action.UserAction" method="{1}">
.............
</action>
</package>
3.具体的语法在代码中体会,说再多也不如实践
(1)

<result name="displayVerifyCode" type="json">
    <param name="includeProperties">user\.verifyCode</param>
</result>

结果
{"user":{"verifyCode":"6de5fe9c67c140469310ee1f54e56a14-79"}}


在js中用jquery ajax处理返回来的json字符串  data.user.verifyCode (前提是dataType是json,data为success()函数的参数)


如果要访问user的全部属性,在struts.xml中

<result name="displayVerifyCode" type="json">
    <param name="includeProperties">user.*</param>
</result>

结果
{"user":{"email":" [email protected]","emailVerify":0,"id":0,"lastIP":null,"lastLogin":0,"nickname":null,"password":null,"verifyCode":"6de5fe9c67c140469310ee1f54e56a14-79"}}


如果访问的的是一个List类型的.List<User> userList = new ArrayList<User>();
要返回userList中所有信息

<result name="displayVerifyCode" type="json">
    <param name="includeProperties">userList.*</param>
</result>

结果

{"userList":[{"email":"[email protected]","emailVerify":0,"id":1,"lastIP":null,"lastLogin":0,"nickname":"李勇","password":"1234","verifyCode":null},{"email":"[email protected]","emailVerify":0,"id":2,"lastIP":null,"lastLogin":0,"nickname":"张超","password":"1234","verifyCode":null}]}

 如果要返回userList中所有user对象的所有email

<result name="displayVerifyCode" type="json">
   <param name="includeProperties">userList\[\d+\]\.email</param>
</result>

结果

{"userList":[{"email":"[email protected]"},{"email":"[email protected]"}]}

(2)根对象只包含user

<result name="displayVerifyCode" type="json">
    <param name="root">user</param>
   </result>

结果
{"email":"[email protected]","emailVerify":0,"id":0,"lastIP":null,"lastLogin":0,"nickname":null,"password":null,"verifyCode":"6de5fe9c67c140469310ee1f54e56a14-79"}

在js中 data.verifyCode 就可以得到,前面不需要加user

你可能感兴趣的:(struts2中json应用)