首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

struts2 回来json数据(结合Extjs)

2012-09-21 
struts2 返回json数据(结合Extjs)本例使用struts2版本?struts-2.1.8.1?首先导入必要的jar包:?配置web.xml:

struts2 返回json数据(结合Extjs)

本例使用struts2版本?struts-2.1.8.1

?

首先导入必要的jar包:


struts2 回来json数据(结合Extjs)

?

配置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>*.action</url-pattern></filter-mapping>

?

?
?接着书写Action类:

?

?

import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import com.opensymphony.xwork2.Action;public class Test {public Map responseJson;public Map getResponseJson() {return responseJson;}public void setResponseJson(Map responseJson) {this.responseJson = responseJson;}public String getList(){Map<String, Object> map = new HashMap<String, Object>();List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();for(int i=0;i<3;i++){Map<String, Object> m = new HashMap<String, Object>();m.put("id", i);m.put("name", "Mic"+i);list.add(m);}map.put("rows", list);map.put("totalCont", 3);this.setResponseJson(map);return Action.SUCCESS;}}

?

?

最后配置struts.xml文件:

?

?

<package name="jsonTest" extends="json-default"><action name="test" method="getList"><result type="json"><param name="root">responseJson</param></result></action></package>

?

struts.xml配置说明:

1,<result type="json"> 这句说明返回类型为json,所以extends设置为"json-default"。

2,<param name="root">responseJson</param>?responseJson对应返回数据的根,如果省略这行返回的结果如下:

?

{"list":"success","responseJson":{"rows":[{"name":"Mic0","id":0},{"name":"Mic1","id":1},{"name":"Mic2","id":2}],"totalCont":3}}

?

?如果设置了root,结果如下:

?

{"rows":[{"name":"Mic0","id":0},{"name":"Mic1","id":1},{"name":"Mic2","id":2}],"totalCont":3}
?

以上步骤做好后,我们就可以调用该action了:

?

Ext.onReady(function(){  new Mic.GridPanel({title : 'test',width : 500,height : 410,        dataUrl : 'test.action',        dwrStore : false,        colMapping : ['id','name'],headers : [{ header: "Id", width: 60, dataIndex:'id'},        { header: "名称", width: 150, dataIndex:'name'}]}).render(Ext.getBody());  });

?调用说明: dataUrl : 'test.action' ?test就是action中的name属性。

?

返回数据:


struts2 回来json数据(结合Extjs)

?

效果图:


struts2 回来json数据(结合Extjs)

?

?

热点排行
Bad Request.