日期:2014-05-16  浏览次数:20329 次

mybatis3.0+spring3.0+struts2整合(json介绍)

关于json的介绍

由于项目中使用到了jqgrid组建以及ajax的异步提交等,有时候可能会需要后台往前台返回的是一个json格式的结果。因此我引入了jsonplugin-0.32的jar包。

?

json插件提供了一个“json”结果类型来把action序列化成json.如果使用了json拦截器,action将可通过请求中的json内容组装出来,该拦截器需要遵循以下几条规则:

  1. "content-type" 必须为 "application/json"
  2. JSON 内容必须是格式良好的, 参考?json.org?中的语法.
  3. Action 里必须有欲获取值的属性的相应?public 的?"setter" 方法.
  4. 所支持的类型有:?原始类型 (int,long...String), Date, List, Map, 原始类型数组,?其他的类 (将会支持更多), 和其他类型的数组.
  5. JSON 中的任何将要被填入到 list 或 map 中的对象会是 Map?类型(属性映射到值), 任何整数都是 Long 类型,?任何小数会是 Double 类型,?任何数组会是 List 类型.

排除属性
逗号分隔的正则表达式列表可传递给 JSON Result 和 Interceptor(拦截器), 被任何 一个正则表达式匹配的属性将会在序列化过程时忽略掉:
<!-- Result fragment -->
<result type="json">
  <param name="excludeProperties">
    login.password,
    studentList.*\.sin
  </param>
</result>
 
<!-- Interceptor fragment -->
<interceptor-ref name="json">
  <param name="enableSMD">true</param>
  <param name="excludeProperties">
    login.password,
    studentList.*\.sin
  </param>
</interceptor-ref>
?
包含属性
逗号分隔的正则表达式列表可被传递给 JSON Result, 用于限制哪些属性可用于序列化. 只有当能够匹配任何一个正则表达式的属性才会包含在序列化输出中.

排除属性表达式优先于包含属性的表达式. ?那就是说, 如果包含和排除表达式应用于同一个结果, 包含表达式对于被排除表达式匹配到的属性是不起作用的.
<result type="json">
  <param name="includeProperties">
    ^entries\[\d+\]\.clientNumber,
    ^entries\[\d+\]\.scheduleNumber,
    ^entries\[\d+\]\.createUserId
  </param>
</result>
?
根对象
使用 "root" 属性(OGNL 表达式) 指定被用于序列化的根对象.
<result type="json">
  <param name="root">
    person.job
  </param>
</result>
?
举个例子
import java.util.HashMap;
import java.util.Map;
 
import com.opensymphony.xwork2.Action;
 
public class JSONExample {
    private String field1 = "str";
    private int[] ints = {10, 20};
    private Map map = new HashMap();
    private String customName = "custom";
 
    //'transient' fields are not serialized
    private transient String field2;
 
    //fields without getter method are not serialized
    private String field3;
 
    public String execute() {
        map.put("John", "Galt");
        return Action.SUCCESS;
    }
 
    public String getField1() {
        return field1;
    }
 
    public void setField1(String field1) {
        this.field1 = field1;
    }
 
    public int[] getInts() {
        return ints;
    }
 
    public void setInts(int[] ints) {
        this.ints = ints;
    }
 
    public Map getMap() {
        return map;
    }
 
    public void setMap(Map map) {
        this.map = map;
    }
 
    @JSON(name="newName")
    public String getCustomName() {
        return this.customName;
    }
}
?
struts的配置文件如下
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
 
  <package name="example"  extends="json-default">
     <action name="JSONExample">
        <result type="json"/>
     </action>
  </package>
 
</struts>
?<