struts2 集成 json
2011-05-28 15:02:45| 分类:
json
| 标签:
|举报
|字号大中小 订阅
1、首先需要struts2的json 插件struts2-json-plugin-xxx.jar ,放到项目的lib下。
2、package 的 extends 设置为 json-default,否则没有 json 的 result type:<result type="json" />
3、在刚才设置 extends="json-default" 的package 下定义一个 Action,和别的action没什么区别,唯一不同的是result,不需要其他result,为其定义<result type="json"/> 即可。
这样访问这个action,得到的就是一串文本,现假设Action定义如下:
public class MyAction extends ActionSupport implements ModelDriven{
private MyActionFrom form = new MyActionForm();
@Override public Object getModel(){return form;}
public String name="name";
public String getName(){...}
public void setName(String name){...}
public String execute(){...}
}
public class MyActionForm{ public String formName="aaa"; //getter and stter ...}
struts xml config:
<package name="sss" namespace="/" extends="json-default">
<action name="json" class="com.kangzye.MyAction">
<result type="json"/>
</action>
</package>
访问 localhost:8080/projdct/json.action 后得到的将会是: {"model":{"formName":"aaa"},"name":"name"}
如果只想要 name 这个属性被json 序列化,不要 model ,那么修改result达到目的:
<result type="json">
<param name="root">name</param> // name 则是你要被序列化的属性名
</result>
评论这张
转发至微博
转发至微博
评论