日期:2014-05-16 浏览次数:20359 次
public class Usr { private java.lang.String userId; private java.lang.String fullName; private java.lang.String email; //getters and setters }然后我们可以在Action里面通过Spring和Hibernate来获取List<Usr>,当然也可以由其他方式取得,和前台是无关的,因此这里省略,只是简单地赋值。
public class TestJson extends ActionSupport{ private List<Usr> usrs; private boolean success=true; //在EXT JS中的store对象需要用到的判断属性 public boolean isSuccess() { return success; } public void setUsrs(List<Usr> usrs) { this.usrs= usrs; } public List<Usr> getUsrs() { return usrs; } @Override public String execute() throws Exception { Usr a = new Usr (); a.setUsrId("id1"); a.setFullName("mg"); a.setEmail("scutmg@gmail.com"); ids.add(a); return "success"; } }以下是配置文件struts.xml:
<struts> <!-- Configuration for the default package. --> <package name="default" extends="json-default"> <action name="testJson" method="execute" class="TestJson"> <result type="json"/> </action> </package> </struts>需要注意的是package里面的属性extends必须使用json-default来获得json的支持,另外action的result type也要是json。
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> <link rel="stylesheet" type="text/css" href="ExtJs/resources/css/ext-all.css" /> <script type="text/javascript" src="ExtJs/adapter/ext/ext-base.js"></script> <script type="text/javascript" src="ExtJs/ext-all.js"></script> <script> function showUrl(value){ return "<a href='mailto:"+value+"'>value</a>"; } Ext.onReady(function(){ var ds = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url:'testJson.action'}),//调用的动作 reader: new Ext.data.JsonReader({ root: 'usrs', //从struts2里面传递过来的参数 successProperty :'success' }, [ //JSON数据的映射 {name: 'usrId',mapping:'usrId',type:'string'}, {name: 'fullName',mapping:'fullName',type:'string'}, {name: 'email',mapping:'email',type:'string'}, ]) }); var grid = new Ext.grid.GridPanel({ id:"grid", el:"example-grid", ds : ds, store: ds, columns: [ {header: "id", width: 120, dataIndex: 'usrId', sortable: true}, {header: "usrName", width: 120, dataIndex: 'fullName', sortable: true}, {header: "email", width: 120, dataIndex: 'email', renderer:showUrl} //显示超链接 ], width:360, height:600 }); grid.render(); ds.load(); }); </script> </head> <body> <table align="center" width="80%"> <tr><td align="center"><div id="example-grid"></div></td></tr> </table> </body> </html>这样,数据就可以很方便地从Struts2的action里面传递到ExtJS的GridPanel数据表格中了。