该帖已经被评为隐藏帖
|
|
---|---|
作者 | 正文 |
发表时间:2008-02-15
不敢独享收获 ,借javaeye这一平台将我的成果和大家分享。不足和错误之处敬请批评指正。有疑问欢迎联系我。qq:446702119 msn: wh_aq@hotmail.com 在此要感谢javaeye、感谢ext官方论坛和大峡 ,感谢CCTV、CHANNEL V 。。。。。呵呵。 废话少说,还是从生成树开始吧。 一、树的对象模型。 package com.ssgly.model; import java.util.List; import java.util.Set; public class Region { private Long id; private String name; private String code; private Region parent; private Set<Region> children = new java.util.HashSet<Region>(); public Region() {} public Region(String name, String code, Region parent) { this.name = name; this.code = code; if(parent!=null) parent.addChild(this); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Region getParent() { return parent; } public void setParent(Region parent) { this.parent = parent; } public Set<Region> getChildren() { return children; } public void setChildren(Set<Region> children) { this.children = children; } } 二、树结构的数据库(mySql)DDL CREATE TABLE `region` ( `id` bigint(20) NOT NULL, `name` varchar(100) default NULL, `code` varchar(100) default NULL, `parent_id` bigint(20) default NULL, PRIMARY KEY (`id`), KEY `FK91AD1314568C1D72` (`parent_id`), CONSTRAINT `FK91AD1314568C1D72` FOREIGN KEY (`parent_id`) REFERENCES `region` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 三、对象模型到数据库的Hibernate映射关系 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.ssgly.model.Region" table="region" > <id name="id" column="id" type="java.lang.Long"> <generator class="assigned" /> </id> <property name="code" column="code" type="java.lang.String" /> <property name="name" column="name" type="java.lang.String" /> <many-to-one name="parent" column="parent_id" cascade="save-update" /> <set name="children" inverse="true" cascade="save-update" lazy="false"> <key column="parent_id" ></key> <one-to-many class="com.ssgly.model.Region"></one-to-many> </set> </class> </hibernate-mapping> 四、用Spring框架来管理和支撑持久层、业务逻辑层和展示层 【一】持久层采用了DAO模式 。具体设计了一个类型安全的泛型DAO。由于这不是我要讲的重点部分,感兴趣的朋友可以 查阅有关文档。要生成一个树,必须要从后台数据库中按一定类型(我用了适配器模式)取出java对象--TreeNode 对象 。及要实现方法 public List<Region> listRegionByParent(Region parent)。 TreeNode类型为: package com.ssgly.model; public class TreeNode { private String id; private String Text; private boolean leaf; private String cls=""; private Region region; public TreeNode(Region region) { this.region=region; } public String getId() { return region.getId().toString(); } public boolean getLeaf() { return region.getChildren().size()<1; } public String getText() { return region.getName(); } public String getCls() { return region.getChildren().size()<1?"file":"folder"; } } 具体生成树的泛型DAO实现是: package com.ssgly.dao; import java.io.IOException; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.List; import com.ssgly.model.Region; import com.ssgly.model.Page; public class RegionDAOImpl extends GenericHibernateDAOCrud<Region> implements IRegionDAO { public RegionDAOImpl(){ super(Region.class); } public void deleteRegion(Region region) { hibernateTemplate.delete(region); } public void deleteRegion(Long id) { hibernateTemplate.delete(hibernateTemplate.get(Region.class, id)); } public Region getRegion(Long id) { return (Region)hibernateTemplate.get(Region.class, id); } public Long saveRegion(Region region) { hibernateTemplate.save(region); return region.getId(); } public void updateRegion(Region region) { hibernateTemplate.saveOrUpdate(region); } /** * 查询父节点的所有子节点 * @param parent 父节点 * @return 该父节点对应的子节点 * * **/ public List<Region> listRegionByParent(Region parent) { if (parent==null){ return (List<Region>)hibernateTemplate.find("from Region as r where r.parent is null"); }else{ return (List<Region>)queryForLists("from Region as r where r.parent=?" ,new Object[]{parent}); } } } 从上面java代码中可以看到:DWR需要解析的是 List<Region> 类型的对象。 【二】业务逻辑层主要采用一个实现类BusinessServiceImp 。将所有的业务逻辑放在一个类中,一是便于spring中bean好管理,二是方便权限控制。BusinessServiceImp 中的一个很重要的属性是: private IRegionDAO regionDAO; regionDAO的生命周期依赖于spring容器,在spring中管理和维护。逻辑层的代码如下: package com.ssgly.business.impl; import java.io.IOException; import java.io.Serializable; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.ssgly.model.*; import com.ssgly.util.Hzxs; import com.ssgly.business.BusinessService; import com.ssgly.dao.*; public class BusinessServiceImpl implements BusinessService { private IRegionDAO regionDAO; public void setRegionDAO(IRegionDAO regionDAO) { this.regionDAO = regionDAO; } public List<TreeNode> getAllChildren(Long parentId) throws IOException, SQLException { List<Region> listRegion=regionDAO.listRegionByParent(regionDAO.getRegion(parentId)); List<TreeNode> listTreeNode=new ArrayList<TreeNode>(); for(Region region:listRegion){ System.out.println(">>"+region.getName()); listTreeNode.add(new TreeNode(region)); } //System.out.println("List<TreeNode> getAllChildren 方法已执行!"); return listTreeNode; } } 【三】Spring容器的配置主要是通过xml方式体现。 一是:web.xml的配置如下: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/dispatcherServlet-servlet.xml, /WEB-INF/model-config.xml </param-value> </context-param> <!-- log4j config --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/log4j.properties</param-value> </context-param> <!--======================================================================== Filters =========================================================================--> <filter> <filter-name>encodingFilter</filter-name> <filter-class>com.ssgly.web.filter.EncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>*</url-pattern> </filter-mapping> <!--======================================================================== Listeners =========================================================================--> <listener> <listener-class> org.springframework.web.util.Log4jConfigListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <!--======================================================================== Servlets =========================================================================--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!--======================================================================== DWR 配置 =========================================================================--> <!--配置DWR拦截器--> <servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>classes</param-name> <param-value>java.lang.Object</param-value> </init-param> <load-on-startup>100</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping> <!--======================================================================== Session =========================================================================--> <session-config> <session-timeout>30</session-timeout> </session-config> </web-app> 二是:bean生成的配置。model-config.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>/WEB-INF/jdbc.properties</value> </list> </property> </bean> <bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" destroy-method="close"> <property name="dataSource"> <ref local="myDataSource" /> </property> <property name="mappingResources"> <list> <value> com/ssgly/model/Region.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="connection.characterEncoding">utf-8</prop> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.jdbc.batch_size">50</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <bean id="regionDao" class="com.ssgly.dao.RegionDAOImpl"> <property name="hibernateTemplate"> <ref bean="hibernateTemplate"/> </property> </bean> <bean id="businessService" class="com.ssgly.business.impl.BusinessServiceImpl"> <property name="regionDAO"><ref bean="regionDao" /></property> </bean> <bean id="todoSsglyService" class="com.ssgly.ext.ToDoImpl"> <property name="businessServiceImpl"> <ref bean="businessService"/> </property> </bean> </beans> 三是:servlet配置 dispatcherServlet-servlet.xml <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <!--============================================================================ URL Mapping configuration =============================================================================--> <bean id="beanNameUrlMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"> <property name="alwaysUseFullPath" value="true" /> </bean> <!--============================================================================ Velocity configuration =============================================================================--> <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"> <property name="contentType"><value>text/html;charset=GBK</value></property> </bean> <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"> <property name="configLocation" value="/WEB-INF/velocity.properties" /> <property name="resourceLoaderPath" value="/" /> </bean> <bean id="treeRegionServlet" name="/treeRegionServlet.do" class="com.ssgly.web.TreeRegionServlet"> <property name="businessService"> <ref bean="businessService"/> </property> </bean> </beans> 有了这些xml的配置。Spring能将三层很好地组合起来。以上是java部分。还没有讲到extJs。extJs可以接受asp、php、java等服务器端生成的json格式的对象。就java来说 ,extJs能接受三种方式的json对象,一是servlet中拼接json对象;其次是引用json lib 包;三是DWR方式,绕过Controller(就Spring来说)或servlet,在javascript中 直接调用java业务逻辑层中的方法(通过DWR引擎),利用dwr代理或者javascript 回调函数返回json对象并在页面展示。 本人采用了第三种DWR方式实现ExtJs生成树。要使用dwr 就的要在以上几个配置文件中配置DWR(已配)。具体的下次再说吧。 今天就写到这里吧。不知写的怎么样?有朋友关注这一块?若支持,请鼓励一下;写的不好、不对或不懂的地方,请拍砖。(续) 抱歉啊,这几天忙着考驾照,把这事给耽搁啊。书接上回吧。 【四】基于Spring方式的DWR配置说明。 一、首先在WEB.xml中配置dwr拦截器 代码如下(节选): <!--配置DWR拦截器--> <servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> <init-param> <param-name>debug</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>classes</param-name> <param-value>java.lang.Object</param-value> </init-param> <load-on-startup>100</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping> 二、dwr.xml的配置。这里将Spring管理的bean映射成javascipt操作的对象。更直观的说法就是使得页面中javascript能直接使用java中对象的方法。代码如下: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://getahead.ltd.uk/dwr/dwr20.dtd"> <dwr> <allow> <convert converter="bean" match="com.ssgly.model.*"/> <convert converter="map" match="org.directwebremoting.convert.MapConverter"/> <create creator="spring" javascript="treeBusinessService"> <param name="beanName" value="businessService"/> <include method="getAllChildren" /> </create> </allow> </dwr> 从上面的代码可以看出,javascript使用treeBusinessService.getAllChildren 方法就能够直接取出 Spring维持的业务逻辑层定义的bean----- businessService。从而完成了DWR的功能。这里当然存在安全问题,在这里暂时没有讨论,关于如何在DWR中进行安全控制,大家可以参考有关文档。本文暂不考虑。 【五】ext和服务器端交互的机制和具体实现 一般说来,按照上面DWR的配置,就已经实现了在页面中使用java的方法。但java方法执行后生成的List 传回到页面还需要靠回调函数实现。例如下面代码就是包含了回调函数的测试页。 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>ExtJS-树示例</title> <link rel="stylesheet" type="text/css" href="ext2/resources/css/ext-all.css" /> <script type="text/javascript" src="ext2/adapter/ext/ext-base.js"></script> <script type="text/javascript" src="ext2/ext-all.js"></script><script type="text/javascript" src="dwr/interface/treeBusinessService.js "></script> <script type="text/javascript" src="dwr/engine.js "></script> <script type="text/javascript" src="dwr/util.js "></script> 现在分析一下上面页面主要代码: <script type="text/javascript" src="dwr/interface/treeBusinessService.js "></script> 这句中的treeBusinessService就是DWR.xml中定义的 <create creator="spring" javascript="treeBusinessService"> 下面两句是使用DWR所必需的,原样加上即可。 <script type="text/javascript" src="dwr/engine.js "></script> <script type="text/javascript" src="dwr/util.js "></script> 有了上面的这些DWR配置,就能够以DWR的方式使用java的方法啦: <script type="text/javascript"> treeBusinessService.getAllChildren(1,function(ret){ alert("一共有"+ret.length+"个子节点"); }); </script> function(ret)就是回调函数。因为treeBusinessService.getAllChildren执行的结果是List类型,DWR解析List到页面应该是javascript的对象数组,所以ret应该是个数组,ret.length是这个数组的长度。 上面的例子只不过是原理性的介绍,帮助我们理解javascript如何和后台进行的交互。真正要实现DWRTree 还需要专门的DWRTreeLoader代理。下面这段代码很是重要,参考了ext官方bbs上的代码,并做了修改。先提供如下: Ext.tree.DWRTreeLoader = function(config) { Ext.tree.DWRTreeLoader.superclass.constructor.call(this, config); }; Ext.extend(Ext.tree.DWRTreeLoader, Ext.tree.TreeLoader, { args:[], requestData : function(node, callback) { if (this.fireEvent("beforeload", this, node, callback) !== false) { var callParams = new Array(); var success = this.handleResponse.createDelegate(this, [node, callback], 1); var error = this.handleFailure.createDelegate(this, [node, callback], 1); callParams.push(node.id); callParams.push({callback:success, errorHandler:error}); //todo: do we need to set this to something else? this.transId=true; this.dataUrl.apply(this, callParams); } else { // if the load is cancelled, make sure we notify // the node that we are done if (typeof callback == "function") { //alert(callback); callback(); } } }, processResponse : function(response, node, callback){ try { for(var i = 0; i < response.length; i++){ var n = this.createNode(response[i]); if(n){ node.appendChild(n); } } if(typeof callback == "function"){ callback(this, node); } }catch(e){ this.handleFailure(response); } }, handleResponse : function(response, node, callback){ this.transId = false; this.processResponse(response, node, callback); this.fireEvent("load", this, node, response); }, handleFailure : function(response, node, callback){ this.transId = false; this.fireEvent("loadexception", this, node, response); if(typeof callback == "function"){ callback(this, node); } } }); 上面的代码可以直接在项目中使用,无需修改。 【六】最终DWRTree的实现包括 tree.js和 tree.html tree.js完整代码如下: Ext.onReady(function(){ Ext.tree.DWRTreeLoader = function(config) { Ext.tree.DWRTreeLoader.superclass.constructor.call(this, config); }; Ext.extend(Ext.tree.DWRTreeLoader, Ext.tree.TreeLoader, { args:[], requestData : function(node, callback) { if (this.fireEvent("beforeload", this, node, callback) !== false) { var callParams = new Array(); var success = this.handleResponse.createDelegate(this, [node, callback], 1); var error = this.handleFailure.createDelegate(this, [node, callback], 1); callParams.push(node.id); callParams.push({callback:success, errorHandler:error}); //todo: do we need to set this to something else? this.transId=true; this.dataUrl.apply(this, callParams); } else { // if the load is cancelled, make sure we notify // the node that we are done if (typeof callback == "function") { //alert(callback); callback(); } } }, processResponse : function(response, node, callback){ try { for(var i = 0; i < response.length; i++){ var n = this.createNode(response[i]); if(n){ node.appendChild(n); } } if(typeof callback == "function"){ callback(this, node); } }catch(e){ this.handleFailure(response); } }, handleResponse : function(response, node, callback){ this.transId = false; this.processResponse(response, node, callback); this.fireEvent("load", this, node, response); }, handleFailure : function(response, node, callback){ this.transId = false; this.fireEvent("loadexception", this, node, response); if(typeof callback == "function"){ callback(this, node); } } }); var myTree = new Ext.tree.TreePanel({ el:Ext.getBody(), autoScroll:true, animate:true, width:'300px', height:'800px', enableDD:true, containerScroll: true, root:new Ext.tree.AsyncTreeNode({ text: '单位', draggable:false, id:'1' }), loader:new Ext.tree.DWRTreeLoader({ dataUrl:treeBusinessService.getAllChildren, listeners : { 'beforeload' : function( node) { myTree.getLoader().args[0]=(node.id!='root'?node.id:"1"); } } }) }); myTree.render(); }); 提个醒:这句 myTree.getLoader().args[0]=(node.id!='root'?node.id:"1");不能错哦,它是和 DWRTreeLoader耦合的。 tree.html是这样的: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>ExtJS-树示例</title> <link rel="stylesheet" type="text/css" href="ext2/resources/css/ext-all.css" /> <script type="text/javascript" src="ext2/adapter/ext/ext-base.js"></script> <script type="text/javascript" src="ext2/ext-all.js"></script> <script type="text/javascript" src="dwr/interface/treeBusinessService.js "></script> <script type="text/javascript" src="dwr/engine.js "></script> <script type="text/javascript" src="dwr/util.js "></script> <script type="text/javascript" src="js/tree.js"></script> </head> <body> </body> </html> 好了,基于Spring+hibernate+dwr+EXTJs的DWRTreeLoader的实现就是这样。本想提供完整代码下载。但想来想去还是让读者自己结合我的文章边做边体会比较好。说不定还能优化我的代码呢。你说是吗? 还有comBoboxTree的实现没有写。也不知大家感兴趣没?还是欢迎大家多提意见吧。 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2008-02-16
呵呵,知道楼上是谁了?
谢谢。 |
|
返回顶楼 | |
发表时间:2008-02-16
我后来使用action做的,也贴出来。
public List getsubdept(String roleid) { /* * 1、输入一个节点代码,获得该节点及下级成员。 2、将这个结点拼装成一个基本的串。 3、通过递归,寻找全部节点 * */ // 也可以先找到该节点,拼好,添加字串。 // List deptlist = new ArrayList(); Iterator iter = getchild(roleid); // Map tree = new HashMap(); List childList = new ArrayList(); while (iter.hasNext()) { Mktree getdata = (Mktree) iter.next(); // String dm=getdata.getDm(); if (getdata.getBzw().equals("0") || getdata.getBzw().equals("1")) { Map child = new HashMap(); child.put("id", getdata.getDm()); child.put("text", getdata.getMkmc()); child.put("cls", "package"); child.put("iconCls", "icon-pkg"); child.put("singleClickExpand", "true"); child.put("children", getsubdept(getdata.getDm())); childList.add(child); log.debug("上级"); } else { Map child = new HashMap(); child.put("id", getdata.getDm()); child.put("text", getdata.getMkmc()); child.put("hrefTarget", getdata.getWz() + getdata.getDm()); child.put("leaf", getdata.getBzw().equals("2") ? "true" : "false"); // 0基本、1节点、2叶子 childList.add(child); } } return childList; } |
|
返回顶楼 | |
发表时间:2008-02-16
楼主...继续写...我关注的是后面那一块
|
|
返回顶楼 | |
发表时间:2008-02-16
kaki 写道 呵呵,知道楼上是谁了?
谢谢。 也感谢你的沙发啊 。 也明白你啦。 |
|
返回顶楼 | |
发表时间:2008-02-18
投良好帖赞一下!
|
|
返回顶楼 | |
发表时间:2008-02-19
都是一个战壕的兄弟啊。最近在忙着考驾照,没有时间写啊。等忙完这一阵子,将后续的一部分完成。
|
|
返回顶楼 | |
发表时间:2008-02-20
N天都不更新 我都等哭了,做好发个DEMO嘛
|
|
返回顶楼 | |
发表时间:2008-02-21
import com.ssgly.util.Hzxs;
import com.ssgly.business.BusinessService; import com.ssgly.model.Page; 好像都没有,代码不全呀!希望楼主提供完整的代码下载,谢谢! |
|
返回顶楼 | |
发表时间:2008-02-22
wxc2100 写道 import com.ssgly.util.Hzxs;
import com.ssgly.business.BusinessService; import com.ssgly.model.Page; 好像都没有,代码不全呀!希望楼主提供完整的代码下载,谢谢! 解释一下: import com.ssgly.util.Hzxs 是汉字显示类。用于那些数据库是非gb的汉字字段的显示。可以忽略不管。 import com.ssgly.business.BusinessService 是业务逻辑层的接口。 import com.ssgly.model.Page 是分页类。 这三个类对异步加载树来说,都可以忽略的,不影响这篇文章。 |
|
返回顶楼 | |