前台js代码
//数据源store var store=new Ext.create('Ext.data.TreeStore',{ proxy:{ type:'ajax', url:'ThemeServlet?type=query' }, //如果不添加fields,只能识别text及id字段 fields:['id','code','name','pid'] }); //创建树 var tree= new Ext.create('Ext.tree.Panel',{ id:'themeTreePanel', store:store, rootVisible:false,//隐藏根节点 userArrows:true,//在树节点中使用箭头 frame:true, title:'专题分类', width:250, height:'100%', columns:[{ xtype:'treecolumn',//树状表格列 text:'名称',//显示的列名 dataIndex:'name'//显示的名称 },{ text:'代码',//显示的列名 dataIndex:'code',//显示的名称 flex: 1 }] });
后台Java代码
/**
* 获取分类代码的json数据
* @return
*/
public String getJsonStandard(){
//jsonArray
JSONArray ja=new JSONArray();
//HashMap临时存放jsonobject
Map<String,JSONObject> hash=new HashMap<String,JSONObject>();
StandardDao dao;
ArrayList<StandardBean> list;
try {
//实例化查询对象
dao = new StandardDao();
//获取全部数据
list=dao.queryALL();
//循环
for(int i=0;i<list.size();i++){
//标准bean
StandardBean bean=list.get(i);
//为bean赋值
String id=bean.getId();
String name=bean.getName();
String typeCode=bean.getTypeCode();
String parendId=bean.getParentId();
//声明jsonobject
JSONObject obj=new JSONObject();
//赋值object
obj.put("id", id);
obj.put("text", name);
obj.put("children", new JSONArray());
obj.put("typeCode", typeCode);
JSONObject parent=hash.get(parendId);
//判断是否是根节点
if(parent==null){
obj.put("leaf", false);
obj.put("expanded", true);
ja.element(obj);
}else{
//子节点递归添加到jsonArray
obj.put("leaf", true);
JSONArray children=parent.getJSONArray("children");
children.element(obj);
}
//hash临时变量
hash.put(id, obj);
}
}catch(Exception e){
e.printStackTrace();
}
//返回json字符串
return ja.toString();
}