为了方便ajax调用传输数据,在struts2中加入的json插件用来做对象的序列化和反序列化,json插件可以在Struts2压缩包中的lib目录下找到。
?
2.json插件执行原理时序图
点击查看原图
?
3.将struts.xml里面的
- < package ? name = "default" ? extends = "struts-default" > ??
<package name="default" extends="struts-default">
? 改为
- < package ? name = "default" ? extends = "json-default" > ??
<package name="default" extends="json-default">
?
4.Action中的配置
- < action ? name = "testAction" ? class = "com.json.action.TestAction" ? method = "testMethod" > ??
- ????< interceptor-ref ? name = "json" ? /> <!--处理以JSON文本提交的请求--> ??
- ????< result ? type = "json" ? /> ? <!--将action的bean属性以json字符串返回浏览器--> ??
- </ action > ??
<action name="testAction" class="com.json.action.TestAction" method="testMethod"> <interceptor-ref name="json" /><!--处理以JSON文本提交的请求--> <result type="json" /> <!--将action的bean属性以json字符串返回浏览器--> </action>
?? 注:根据需要选择interceptor和result配置
?
5. 你会发现前台返回的json字符串,是把action中的所有属性全部转化为json字符串返回给浏览器了,但是我有时候需要根据实际情况返回部分结果,如何对json的结果进行定制输出呢?result提供了一些参数替你解决这个问题
? 5.1. root参数:从返回结果中根据ognl表达式取出你需要输出的结果
???????? 如:
??? action类
- public ? class ?BaseAction? extends ?ActionSupport? implements ??{??
- ????private ?Person?person?=? null ;??
- ????????????????...??
- }??
public class BaseAction extends ActionSupport implements { private Person person = null; ... }
??? bean类??
- public ? class ?Person?{??
- ????private ?String?name;??
- ????private ? int ?age;??
- ????...??
- }??
public class Person { private String name; private int age; ... }
??? 我们只要输出person对象的name属性值,配置如下
- < result ? type = "json" > ??
- ????< param ? name = "root" > person.name </ param > ??
- </ result > ??
<result type="json"> <param name="root">person.name</param> </result>
?
? 5.2. excludeNullProperties 参数:表示是否去掉空值,?默认值是false,如果设置为true会自动将为空的值过滤,只输出不为空的值。
- < result ? type = "json" > ??
- ????< param ? name = "excludeNullProperties" > true </ param > ??
- </ result > ??
<result type="json"> <param name="excludeNullProperties">true</param> </result>
?
? 5.3. ignoreHierarchy 参数:表示是否忽略等级,也就是继承关系,比如:TestAction继承于BaseAction,那么TestAction中返回的json字符串默认 是不会包含父类BaseAction的属性值,ignoreHierarchy值默认为true,设置为false后会将父类和子类的属性一起返回。
- < result ? type = "json" > ??
- ????< param ? name = "ignoreHierarchy" > false </ param > ??
- </ result > ??
<result type="json"> <param name="ignoreHierarchy">false</param> </result>
?
? 5.4. includeProperties 参数:输出结果中需要包含的属性值,这里正则表达式和属性名匹配,可以用“,”分割填充多个正则表达式。
?? 如:输出person的所有属性?
- < result ? type = "json" > ??
- ????< param ? name = "includeProperties" > person.*,?person\.name </ param > ??
- </ result > ??
<result type="json"> <param name="includeProperties">person.*, person\.name</param> </result>
?
? 5.5. excludeProperties 参数:输出结果需要剔除的属性值,也支持正则表达式匹配属性名,可以用“,”分割填充多个正则表达式,类同5.4.