浅谈struts2和json的集成
该例子以非常简单的形式描述了struts2和json的集成开发。。和大家共同学习。。
我用到的是struts2.2.3的jar包。
除了导入struts2的jar包外,还引入struts2-json-plugin.jar
JSONExample.javapackage com.lysf.json;
import java.util.HashMap;
import java.util.Map;
import org.apache.struts2.json.annotations.JSON;
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<package name="example" extends="json-default">
<action name="JSONExample" class="com.lysf.json.JSONExample">
<result type="json"/>
</action>
</package>
web.xml<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
最后得到的结果为:
{"newName":"custom","field1":"str","ints":[10,20],"map":{"John":"Galt"}}