日期:2014-05-16 浏览次数:20463 次
由于项目中使用到了jqgrid组建以及ajax的异步提交等,有时候可能会需要后台往前台返回的是一个json格式的结果。因此我引入了jsonplugin-0.32的jar包。
?
json插件提供了一个“json”结果类型来把action序列化成json.如果使用了json拦截器,action将可通过请求中的json内容组装出来,该拦截器需要遵循以下几条规则:
<!-- 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>
?<result type="json">
<param name="includeProperties">
^entries\[\d+\]\.clientNumber,
^entries\[\d+\]\.scheduleNumber,
^entries\[\d+\]\.createUserId
</param>
</result>
<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;
}
}
<?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>
?<