资料:http://clayz.iteye.com/blog/422125
配置中的参数含义:
root参数用于指定要序列化的根对象,如果省去这一配置,表示要序列化action中的所有属性
ignoreHierarchy 为false时表示要序列化根对象的所有基类
excludeProperties表示排除的序列化的属性
includeProperties表示哪些属性被序列化
Action配置:
<!-- jsonplugin的使用配置 -->
<!-- package要继承json-default 以加载json插件 -->
<action name="jsonAct" class="cn.enjoylife.prac.action.JsonAction">
<result type="json">
<!-- root参数用于指定要序列化的根对象,如果省去这一配置,表示要序列化action中的所有属性 -->
<param name="root">map</param>
<!-- ignoreHierarchy 为false时表示要序列化根对象的所有基类 -->
<param name="ignoreHierarchy">false</param>
<!-- 排除hello属性,使其不被序列化 -->
<param name="excludeProperties">hello</param>
</result>
</action>
JsonAction.java:
/**
* @author Evan
*
*/
public class JsonAction extends ActionSupport {
private static final long serialVersionUID = 3870310687165227565L;
private int[] ints = { 100, 200 };
private Map<String, Object> map = new HashMap<String, Object>();
private String hello = "helloWorld";
private String username = "evan";//没有getter方法,不会被序列化
private String password = "pwd";
private String validateCode = "123456";
public int[] getInts() {
return ints;
}
public void setInts(int[] ints) {
this.ints = ints;
}
@JSON(name="newMap")//重新命名
public Map<String, Object> getMap() {
return map;
}
public void setMap(Map<String, Object> map) {
this.map = map;
}
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
public void setUsername(String username) {
this.username = username;
}
@JSON(serialize=true)//这是默认值,可以省去
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@JSON(serialize=false)//serialize参数为false,不会被序列化
public String getValidateCode() {
return validateCode;
}
public void setValidateCode(String validateCode) {
this.validateCode = validateCode;
}
@Override
public String execute() throws Exception {
map.put("info", "今天的雨真大啊!");
return SUCCESS;
}
}
使用jquery操作返回的json串:
$(document).ready(function(){
$.getJSON(
"./jsonAct.action",
function(data){
alert(data.info);
}
);
});
Annotation:
***********************************************************************************
JSON插件提供了一种名为json的ResultType,一旦为某个Action指定了一个类型为json的Result,则该Result无需映射到任何视图资源。将下载到的jsonplugin-0.7.jar文件复制到Web应用的WEB-INF路径下,即可完成JSON插件的安装。
JSON插件提供了一种名为json的ResultType,一旦为某个Action指定了一个类型为json的Result,则该Result无需映射到任何视图资源。因为JSON插件会负责将Action里的状态信息序列化成JSON格式的数据,并将该数据返回给客户端页面的JavaScript。
简单地说,JSON插件允许我们在JavaScript中异步调用Action,而且Action不再需要使用视图资源来显示该Action里的状态信息,而是由JSON插件负责将Action里的状态信息返回给调用页面——通过这种方式,就可以完成Ajax交互。
Struts2提供了一种可插拔方式来管理插件,安装Struts2的JSON插件与安装普通插件并没有太大的区别,一样只需要将Struts2插件的JAR文件复制到Web应用的WEB-INF/lib路径下即可。
安装JSON插件按如下步骤进行:
(1)登陆http://code.google.com/p/jsonplugin/downloads/list站点,下载Struts2的JSON插件的最新版本,当前最新版本是0.7,我们可以下载该版本的JSON插件。
(2)将下载到的jsonplugin-0.7.jar文件复制到Web应用的WEB-INF路径下,即可完成JSON插件的安装。
实现Actio逻辑
假设wo,en输入页面中包含了三个表单域,这三个表单域对于三个请求参数,因此应该使用Action来封装这三个请求参数。三个表单域的name分别为field1、field2和field3。
处理该请求的Action类代码如下:
public class JSONExample |
在上面代码中,使用了JSON注释,注释时指定了name域,name域指定Action属性被序列化成JSON对象的属性名。除此之外,JSON注释还支持如下几个域:
serialize:设置是否序列化该属性
deserialize:设置是否反序列化该属性。
format:设置用于格式化输出、解析日期表单域的格式。例如"yyyy-MM-dd'T'HH:mm:ss"。
配置该Action与配置普通Action存在小小的区别,应该为该Action配置类型为json的Result。而这个Result无需配置任何视图资源。
配置该Action的struts.xml文件代码如下:
<?xml version="1.0" encoding="GBK"?> |
在上面配置文件中有两个值得注意的地方:
第一个地方是配置struts.i18n.encoding常量时,不再是使用GBK编码,而是UTF-8编码,这是因为Ajax的POST请求都是以UTF-8的方式进行编码的。
第二个地方是配置包时,自己的包继承了json-default包,而不再继承默认的default包,这是因为只有在该包下才有json类型的Result。
Apache提供的一个插件包,可以把 Action中的数据以 JSON做个封装然后返回。
它会将整个 action中的变量转化为 JSON数据 (根对象在 JSON中数据添加一个 ”root”标识 )。如果要使用它, Action必须遵循以下几点:
· 返回的页面类型中 ”content-type”必须是 ”application/json”.(这个已经 Internet Community采用 ).
· JSON内容必须是符合格式要求的 .
· Action中 field必须有 public的 get方法 .(是不是没有 set方法就不会将 field添加到 JSON数据中,有待验证 ).,可以没有set方法
· 它支持的类型有 : 基本类型 (int,long...String), Date, List, Map, Primitive Arrays, 其它 class, 对象数组 .
· 在 JSON中任何的 Object会被封装在 list或 map中,数据会被封装程 Long,如果是含有的数据则会被封装程 Double,数组会被封装程 List.
下面给出 JSON的数据格式:
Json代码
1. <span style="font-family: arial,helvetica,sans-serif;">{
2. "doubleValue": 10.10,
3. "nestedBean": { "name": "Mr Bean" },
4. "list": ["A", 10, 20.20, { "firstName": "El Zorro" }],
5. "array": [10, 20]
6. }</span>
这个插件支持以下几个注释 :
注释名 |
简介 |
默认值 |
序列化 |
反序列化 |
name |
配置 JSON 中 name |
empty |
yes |
no |
serialize |
在 serialization 中 |
true |
yes |
no |
deserialize |
在 deserialization 中 |
true |
no |
yes |
format |
格式化 Date 字段 |
"yyyy-MM-dd'T'HH:mm:ss" |
yes |
yes |
可以通过配置来显示指出要放在 JSON中 field,其中有个自己的验证规则需要研究 .
Xml代码
1. <!-- Result fragment -->
2. <result type="json">
3. <param name="excludeProperties">
4. login.password,
5. studentList.*".sin
6. </param>
7. </result>
8.
9. <!-- Interceptor fragment -->
10. <interceptor-ref name="json">
11. <param name="enableSMD">true</param>
12. <param name="excludeProperties">
13. login.password,
14. studentList.*".sin
15. </param>
16. </interceptor-ref>
根对象
Xml代码
1. <result type="json">
2. <param name="root">
3. person.job
4. </param>
5. </result>
也可以使用拦截器配置操作父对象
Xml代码
1. <interceptor-ref name="json">
2. <param name="root">bean1.bean2</param>
3. </interceptor-ref>
将 JSON数据用注释封装
如果 wrapWithComments 设置为 true( 默认值为 false) ,则生成的 JSON 数据会变成这样
Json代码
1. /* {
2. "doubleVal": 10.10,
3. "nestedBean": { "name": "Mr Bean" },
4. "list": ["A", 10, 20.20, { "firstName": "El Zorro" }],
5. "array": [10, 20]
6. } */
这样做可以避免 js中一些潜在的风险,使用时需要 :Var responseObject = eval("("+data.substring(data.indexOf(""/"*")+2, data.lastIndexOf(""*"/"))+")");
父类
“root”对象中父类的 field不会(会?) 默认存放到 JSON数据中,如果不想这样做,需要在配置时指定 ignoreHierarchy 为 false:
Xml代码
1. <result type="json">
2. <param name="ignoreHierarchy">false</param>
3. </result>
枚举类型
默认处理枚举类型时,会被处理成 JSON数据中 name等于枚举中 value而 value等于枚举中 name.
Java代码
1. public enum AnEnum {
2. ValueA,
3. ValueB
4. }
JSON: "myEnum":"ValueA"
如果在处理枚举类型时,在 xml中配置了 enumAsBean,则会被当作一个 Bean处理,在 JSON数据中会有一个特别的属性 ”_name”值为 name().这个枚举中的所有属性都会被处理 .
Java代码
1. public enum AnEnum {
2. ValueA("A"),
3. ValueB("B");
4.
5. private String val;
6.
7. public AnEnum(val) {
8. this.val = val;
9. }
10.
11. public getVal() {
12. return val;
13. }
14. }
JSON: myEnum: { "_name": "ValueA", "val": "A" }
Xml中配置 :
Xml代码
1. <result type="json">
2. <param name="enumAsBean">true</param>
3. </result>