struts2学习笔记——struts2-json-plugin

来源:互联网 发布:六级英语听力软件 编辑:程序博客网 时间:2024/06/16 19:33

介绍

使用Struts2-Json插件可以不用更改action中的任何代码,只需要在配置文件中进行配置即可。默认情况下它会将action中的所有对象序列化,这个序列化过程是递归的。

配置使用

以下面的studentAction为例进行演示:

public class StudentAction extends ActionSupport {    private StudentService studentService;    private Student student;    private List<Student> students;    private String ajaxResult;        public String list(){        students = studentService.getStudents();        ajaxResult = "success";        return "list_success";    }        .....set、get方法}

配置文件内容:

<package name="student" namespace="/" extends="json-default">    <action name="list" method="list" class="json.studentAction">        <result type="json" name="list_success">        </result>    </action></package>

需要注意的是要将package中的extends的值改为json-default,result中的type要设为json,这样struts2-json才能够正常工作。

使用上面配置,会将action中所有有get方法的对象进行序列化。显然,大部分情况下我们不会这么做,会选择一些需要的对象进行序列化,这需要在配置文件中添加一些参数来完成。

参数说明

<param name="root">ajaxResult</param>

root参数用来指定要序列化的对象。按照上面配置,返回的json字符串将只包含ajaxResult而不包含其它属性。


<param name="includeProperties">    student\.id,    student\.name,    students\[\d+\]\.id,    students\[\d+\]\.name,    students\[\d+\]\.teacher\.name</param>

includeProperties参数用来指定要序列化的属性,该参数支持正则表达式,用,来分割多个表达式。按照上面的配置,返回的json字符串将只包含student的id、name属性,而返回的students集合中,每一个student只包含id和name以及该student对象中teacher的name属性。


<param name="excludeProperties">    students\[\d+\]\.age    students\[\d+\]\.teacher</param>

excludeProperties参数指定了要排除不进行序列化的属性。按照上面的配置,返回的json字符串中将不会包含student的age和teacher两个属性。

注意:
excludeProperties优先于includeProperties,也就是说如果你同时使用了这两个参数,并且配置了相同的表达式,将只会应用excludeProperties中的表达式。


<param name="excludeNullProperties">true</param>

excludeNullProperties参数默认为false,意味着值为null的属性也会被序列化,将其设置为true即可排除所有值为null的属性。


<param name="ignoreHierarchy">false</param>

ignoreHierarchy参数表示是否忽略等级,也就是继承关系。默认值为true,设置为false后会序列化所有基类 的属性(直到Object...)。


<param name="wrapPrefix">/*</param><param name="wrapSuffix">*/</param>

出于某些原因,你可能想为json字符串包裹一些文本,比如注释之类的。wrapPrefix参数将在json字符串之前添加文本,wrapSuffix参数将在json字符串之后添加文本。


<param name="enableGZIP">true</param>

enableGZIP参数设置为true将会对输出的json结果进行压缩。请求头部的Accept-Encoding包含gzip才可以使其工作。


<param name="noCache">true</param>

noCache参数默认为false,设置为true后将会禁止浏览器缓存响应。


<param name="statusCode">304</param><param name="errorCode">404</param>

statusCode参数用来设置响应的状态,errorCode会发送一个错误。


<param name="encoding">UTF-8</param>

encoding参数用来指定每一次请求的编码。