在各种论坛上看了很久,没见到完整extJs树的生成代码。研究了很久终于实现了Spring+Hibernate+DWR+extJs的生成树及下拉comBoboxTree。
不敢独享收获 ,借javaeye这一平台将我的成果和大家分享。不足和错误之处敬请批评指正。有疑问欢迎联系我。qq:446702119 msn: wh_aq@hotmail.com
废话少说,还是从生成树开始吧。
一、树的对象模型。
Java代码
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;
}
}
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
Java代码
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;
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映射关系
Java代码
<?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>
<?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类型为:
Java代码
package com.ssgly.model;
ublic 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";
}
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实现是:
Java代码
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});
}
}
}
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中管理和维护。逻辑层的代码如下:
Java代码
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;
}
}
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的配置如下:
Java代码
<?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>
<?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
Java代码
<?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>
<?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
Java代码
<?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 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拦截器 代码如下(节选):
Java代码
<!--配置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拦截器-->
<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中对象的方法。代码如下:
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>
<?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 传回到页面还需要靠回调函数实现。例如下面代码就是包含了回调函数的测试页。
Java代码
<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>
<PRE class=java name="code"><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></PRE>
<BR><script type="text/javascript">
<BR>
<BR> treeBusinessService.getAllChildren(1,function(ret){
<BR> alert("一共有"+ret.length+"个子节点");
<BR> });
<BR>
<BR></script>
<BR></head>
<BR>
<BR><body>
<BR><div id="tree-div"></div>
<BR></body>
<BR></html>
<BR>
<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>
Java代码 <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>
<script type="text/javascript" src="dwr/engine.js "></script>
<script type="text/javascript" src="dwr/util.js "></script>
<script type="text/javascript">
treeBusinessService.getAllChildren(1,function(ret){
alert("一共有"+ret.length+"个子节点");
});
</script>
</head>
<body>
<div id="tree-div"></div>
</body>
</html>
现在分析一下上面页面主要代码:
Java代码
<script type="text/javascript" src="dwr/interface/treeBusinessService.js "></script>
<script type="text/javascript" src="dwr/interface/treeBusinessService.js "></script>
这句中的treeBusinessService就是DWR.xml中定义的Java代码
<create creator="spring" javascript="treeBusinessService">
<create creator="spring" javascript="treeBusinessService">
下面两句是使用DWR所必需的,原样加上即可。
Java代码
<script type="text/javascript" src="dwr/engine.js "></script>
<script type="text/javascript" src="dwr/util.js "></script>
<script type="text/javascript" src="dwr/engine.js "></script>
<script type="text/javascript" src="dwr/util.js "></script>
有了上面的这些DWR配置,就能够以DWR的方式使用java的方法啦:
Java代码
<script type="text/javascript">
treeBusinessService.getAllChildren(1,function(ret){
alert("一共有"+ret.length+"个子节点");
});
</script>
<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上的代码,并做了修改。先提供如下:
Java代码
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);
}
}
});
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完整代码如下:
Java代码
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();
});
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();
});
提个醒:这句Java代码
myTree.getLoader().args[0]=(node.id!='root'?node.id:"1");
myTree.getLoader().args[0]=(node.id!='root'?node.id:"1");
不能错哦,它是和 DWRTreeLoader耦合的。
tree.html是这样的:
Java代码
<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>
<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的实现没有写。也不知大家感兴趣没?还是欢迎大家多提意见吧。
jbpm的持久层能使用JPA吗? | 完整的Spring+Hibernate+DWR+extJs的生成树 ... 14:06 浏览 (1299) 论坛浏览 (6929) 评论 (11) 收藏 相关推荐 评论
11 楼 flash8627 2008-12-31 引用
import com.ssgly.model.Page;
不在
GenericHibernateDAOCrud
没有
希望能给个完全的下载,谢谢
10 楼 joeyhacker 2008-12-04 引用
代码好像不全吧
9 楼 mniz 2008-10-14 引用
看了楼上的代码,我也把我整合别人代码拿出来分享下
就是那个下拉树。。。
ComboTree
Java代码
Ext.QuickTips.init();
var Artform = new Ext.form.FormPanel({
labelAlign: 'right',
labelWidth: 150,
width: 600,
frame: true,
items: [{
layout: 'column',
items: [{
width:580,
xtype:'fieldset',
title: '输入标题',
autoHeight:true,
defaults: {width: 300},
defaultType: 'textfield',
items: [{
fieldLabel: '标题',
name: 'title',
id:'title',
allowBlank:false,
blankText:'标题不能为空'
// value:'adfadsfasd'
},{
xtype:"combo",
fieldLabel: '选择',
name: 'combo',
id:'combotree',
store: new Ext.data.SimpleStore({fields:[],data:[[]]}),
editable:false,//是否可编辑的表格
selectClass:'',//适用于所有样式
mode: 'local', //本地数据
triggerAction:'all', //是否自动匹配
autoHeight: true,
tpl: "<tpl for='.'><div style='height:200px'><div id='tree'></div></div></tpl>", //模板 循环
emptyText:'请选择'
}]
}]
},{
layout: 'form',
labelAlign: 'top',
items: [{
xtype: 'htmleditor',
fieldLabel: '请输入文章内容',
id: 'context',
height:400,
allowBlank:false,
blankText:'内容不能为空',
anchor: '98%'
// value:'adfadfasd'
}]
}] ,
buttons: [{text: '保存',handler:add},
{text: '取消'}]
});
var treedata = new Ext.tree.TreeLoader({
url:'http://localhost:8080/pkm/register!queryChild.action'
});
var tree = new Ext.tree.TreePanel({
loader:treedata,
border:false,
root:new Ext.tree.AsyncTreeNode({text:'目录结构',id:'1'})
});
tree.on('click',function(node){
Artform.findById('combotree').value=node.id;//设置combo的键值
Artform.findById('combotree').setRawValue(node.text); //给combo设置显示的值
Artform.findById('combotree').collapse(); //隐藏下拉列表中,如果它展开,这个属性将会完成数据的加载
});
Artform.findById('combotree').on('expand',function(){
tree.render('tree');//ComboBox的tpl里的<div id='tree'>这个ID可以改成别的, 但必须要在'expand'事件里, 将树显示在这个div上
});
function add(){
if(Artform.form.isValid()){
//btn.disabled=true;//确认按钮有效默认为false
Ext.MessageBox.show({
msg: '正在请求数据, 请稍侯',
progressText: '正在请求数据',
width:300,
wait:true,
waitConfig: {interval:200}
});//进度条显示
Ext.Ajax.request({
url:'http://localhost:8080/pkm/article!saveOrupdate.action',
params:{
title:Ext.getCmp('title').getValue(),
context:Ext.getCmp('context').getValue(),
type:Artform.findById('combotree').value
},
failure:function(){
Ext.MessageBox.alert('友情提示',"异步通讯失败,请与管理员联系!");
},
success:function(request){
Ext.MessageBox.hide();
Ext.MessageBox.alert("友情提示","信息保存成功");
}
});
}else{
Ext.MessageBox.alert("信息","请填写完整");
}
}
Artform.render("form");
});
Ext.QuickTips.init();
var Artform = new Ext.form.FormPanel({
labelAlign: 'right',
labelWidth: 150,
width: 600,
frame: true,
items: [{
layout: 'column',
items: [{
width:580,
xtype:'fieldset',
title: '输入标题',
autoHeight:true,
defaults: {width: 300},
defaultType: 'textfield',
items: [{
fieldLabel: '标题',
name: 'title',
id:'title',
allowBlank:false,
blankText:'标题不能为空'
// value:'adfadsfasd'
},{
xtype:"combo",
fieldLabel: '选择',
name: 'combo',
id:'combotree',
store: new Ext.data.SimpleStore({fields:[],data:[[]]}),
editable:false,//是否可编辑的表格
selectClass:'',//适用于所有样式
mode: 'local', //本地数据
triggerAction:'all', //是否自动匹配
autoHeight: true,
tpl: "<tpl for='.'><div style='height:200px'><div id='tree'></div></div></tpl>", //模板 循环
emptyText:'请选择'
}]
}]
},{
layout: 'form',
labelAlign: 'top',
items: [{
xtype: 'htmleditor',
fieldLabel: '请输入文章内容',
id: 'context',
height:400,
allowBlank:false,
blankText:'内容不能为空',
anchor: '98%'
// value:'adfadfasd'
}]
}] ,
buttons: [{text: '保存',handler:add},
{text: '取消'}]
});
var treedata = new Ext.tree.TreeLoader({
url:'http://localhost:8080/pkm/register!queryChild.action'
});
var tree = new Ext.tree.TreePanel({
loader:treedata,
border:false,
root:new Ext.tree.AsyncTreeNode({text:'目录结构',id:'1'})
});
tree.on('click',function(node){
Artform.findById('combotree').value=node.id;//设置combo的键值
Artform.findById('combotree').setRawValue(node.text); //给combo设置显示的值
Artform.findById('combotree').collapse(); //隐藏下拉列表中,如果它展开,这个属性将会完成数据的加载
});
Artform.findById('combotree').on('expand',function(){
tree.render('tree');//ComboBox的tpl里的<div id='tree'>这个ID可以改成别的, 但必须要在'expand'事件里, 将树显示在这个div上
});
function add(){
if(Artform.form.isValid()){
//btn.disabled=true;//确认按钮有效默认为false
Ext.MessageBox.show({
msg: '正在请求数据, 请稍侯',
progressText: '正在请求数据',
width:300,
wait:true,
waitConfig: {interval:200}
});//进度条显示
Ext.Ajax.request({
url:'http://localhost:8080/pkm/article!saveOrupdate.action',
params:{
title:Ext.getCmp('title').getValue(),
context:Ext.getCmp('context').getValue(),
type:Artform.findById('combotree').value
},
failure:function(){
Ext.MessageBox.alert('友情提示',"异步通讯失败,请与管理员联系!");
},
success:function(request){
Ext.MessageBox.hide();
Ext.MessageBox.alert("友情提示","信息保存成功");
}
});
}else{
Ext.MessageBox.alert("信息","请填写完整");
}
}
Artform.render("form");
});
我这是一个form 里面生成的下拉树,单独测试的时候 其实可以用一个简单的comboBox 做的,我这里为了方便就直接把我的代码拿过来和大家分享下
其实上面的代码 最重要的就只有一个部分,下拉树写出来很简单,问题就是怎么能取到值给form 让它提交到后台,
Java代码
tree.on('click',function(node){
Artform.findById('combotree').value=node.id;设置combo的键值
Artform.findById('combotree').setRawValue(node.text); //给combo设置显示的值
Artform.findById('combotree').collapse(); //隐藏下拉列表中,如果它展开,这个属性将会完成数据的加载
});
tree.on('click',function(node){
Artform.findById('combotree').value=node.id;设置combo的键值
Artform.findById('combotree').setRawValue(node.text); //给combo设置显示的值
Artform.findById('combotree').collapse(); //隐藏下拉列表中,如果它展开,这个属性将会完成数据的加载
});
秘诀就在这里,这里能给你提交到后台什么的 ,什么父节点不能选择,根节点不能选择什么的,那个简单,你直接把你的树写好,就OK 在哪里判断 如有不对,请拍砖—-—!!
不敢独享收获 ,借javaeye这一平台将我的成果和大家分享。不足和错误之处敬请批评指正。有疑问欢迎联系我。qq:446702119 msn: wh_aq@hotmail.com
废话少说,还是从生成树开始吧。
一、树的对象模型。
Java代码
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;
}
}
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
Java代码
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;
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映射关系
Java代码
<?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>
<?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类型为:
Java代码
package com.ssgly.model;
ublic 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";
}
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实现是:
Java代码
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});
}
}
}
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中管理和维护。逻辑层的代码如下:
Java代码
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;
}
}
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的配置如下:
Java代码
<?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>
<?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
Java代码
<?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>
<?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
Java代码
<?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 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拦截器 代码如下(节选):
Java代码
<!--配置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拦截器-->
<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中对象的方法。代码如下:
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>
<?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 传回到页面还需要靠回调函数实现。例如下面代码就是包含了回调函数的测试页。
Java代码
<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>
<PRE class=java name="code"><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></PRE>
<BR><script type="text/javascript">
<BR>
<BR> treeBusinessService.getAllChildren(1,function(ret){
<BR> alert("一共有"+ret.length+"个子节点");
<BR> });
<BR>
<BR></script>
<BR></head>
<BR>
<BR><body>
<BR><div id="tree-div"></div>
<BR></body>
<BR></html>
<BR>
<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>
Java代码 <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>
<script type="text/javascript" src="dwr/engine.js "></script>
<script type="text/javascript" src="dwr/util.js "></script>
<script type="text/javascript">
treeBusinessService.getAllChildren(1,function(ret){
alert("一共有"+ret.length+"个子节点");
});
</script>
</head>
<body>
<div id="tree-div"></div>
</body>
</html>
现在分析一下上面页面主要代码:
Java代码
<script type="text/javascript" src="dwr/interface/treeBusinessService.js "></script>
<script type="text/javascript" src="dwr/interface/treeBusinessService.js "></script>
这句中的treeBusinessService就是DWR.xml中定义的Java代码
<create creator="spring" javascript="treeBusinessService">
<create creator="spring" javascript="treeBusinessService">
下面两句是使用DWR所必需的,原样加上即可。
Java代码
<script type="text/javascript" src="dwr/engine.js "></script>
<script type="text/javascript" src="dwr/util.js "></script>
<script type="text/javascript" src="dwr/engine.js "></script>
<script type="text/javascript" src="dwr/util.js "></script>
有了上面的这些DWR配置,就能够以DWR的方式使用java的方法啦:
Java代码
<script type="text/javascript">
treeBusinessService.getAllChildren(1,function(ret){
alert("一共有"+ret.length+"个子节点");
});
</script>
<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上的代码,并做了修改。先提供如下:
Java代码
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);
}
}
});
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完整代码如下:
Java代码
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();
});
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();
});
提个醒:这句Java代码
myTree.getLoader().args[0]=(node.id!='root'?node.id:"1");
myTree.getLoader().args[0]=(node.id!='root'?node.id:"1");
不能错哦,它是和 DWRTreeLoader耦合的。
tree.html是这样的:
Java代码
<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>
<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的实现没有写。也不知大家感兴趣没?还是欢迎大家多提意见吧。
jbpm的持久层能使用JPA吗? | 完整的Spring+Hibernate+DWR+extJs的生成树 ... 14:06 浏览 (1299) 论坛浏览 (6929) 评论 (11) 收藏 相关推荐 评论
11 楼 flash8627 2008-12-31 引用
import com.ssgly.model.Page;
不在
GenericHibernateDAOCrud
没有
希望能给个完全的下载,谢谢
10 楼 joeyhacker 2008-12-04 引用
代码好像不全吧
9 楼 mniz 2008-10-14 引用
看了楼上的代码,我也把我整合别人代码拿出来分享下
就是那个下拉树。。。
ComboTree
Java代码
Ext.QuickTips.init();
var Artform = new Ext.form.FormPanel({
labelAlign: 'right',
labelWidth: 150,
width: 600,
frame: true,
items: [{
layout: 'column',
items: [{
width:580,
xtype:'fieldset',
title: '输入标题',
autoHeight:true,
defaults: {width: 300},
defaultType: 'textfield',
items: [{
fieldLabel: '标题',
name: 'title',
id:'title',
allowBlank:false,
blankText:'标题不能为空'
// value:'adfadsfasd'
},{
xtype:"combo",
fieldLabel: '选择',
name: 'combo',
id:'combotree',
store: new Ext.data.SimpleStore({fields:[],data:[[]]}),
editable:false,//是否可编辑的表格
selectClass:'',//适用于所有样式
mode: 'local', //本地数据
triggerAction:'all', //是否自动匹配
autoHeight: true,
tpl: "<tpl for='.'><div style='height:200px'><div id='tree'></div></div></tpl>", //模板 循环
emptyText:'请选择'
}]
}]
},{
layout: 'form',
labelAlign: 'top',
items: [{
xtype: 'htmleditor',
fieldLabel: '请输入文章内容',
id: 'context',
height:400,
allowBlank:false,
blankText:'内容不能为空',
anchor: '98%'
// value:'adfadfasd'
}]
}] ,
buttons: [{text: '保存',handler:add},
{text: '取消'}]
});
var treedata = new Ext.tree.TreeLoader({
url:'http://localhost:8080/pkm/register!queryChild.action'
});
var tree = new Ext.tree.TreePanel({
loader:treedata,
border:false,
root:new Ext.tree.AsyncTreeNode({text:'目录结构',id:'1'})
});
tree.on('click',function(node){
Artform.findById('combotree').value=node.id;//设置combo的键值
Artform.findById('combotree').setRawValue(node.text); //给combo设置显示的值
Artform.findById('combotree').collapse(); //隐藏下拉列表中,如果它展开,这个属性将会完成数据的加载
});
Artform.findById('combotree').on('expand',function(){
tree.render('tree');//ComboBox的tpl里的<div id='tree'>这个ID可以改成别的, 但必须要在'expand'事件里, 将树显示在这个div上
});
function add(){
if(Artform.form.isValid()){
//btn.disabled=true;//确认按钮有效默认为false
Ext.MessageBox.show({
msg: '正在请求数据, 请稍侯',
progressText: '正在请求数据',
width:300,
wait:true,
waitConfig: {interval:200}
});//进度条显示
Ext.Ajax.request({
url:'http://localhost:8080/pkm/article!saveOrupdate.action',
params:{
title:Ext.getCmp('title').getValue(),
context:Ext.getCmp('context').getValue(),
type:Artform.findById('combotree').value
},
failure:function(){
Ext.MessageBox.alert('友情提示',"异步通讯失败,请与管理员联系!");
},
success:function(request){
Ext.MessageBox.hide();
Ext.MessageBox.alert("友情提示","信息保存成功");
}
});
}else{
Ext.MessageBox.alert("信息","请填写完整");
}
}
Artform.render("form");
});
Ext.QuickTips.init();
var Artform = new Ext.form.FormPanel({
labelAlign: 'right',
labelWidth: 150,
width: 600,
frame: true,
items: [{
layout: 'column',
items: [{
width:580,
xtype:'fieldset',
title: '输入标题',
autoHeight:true,
defaults: {width: 300},
defaultType: 'textfield',
items: [{
fieldLabel: '标题',
name: 'title',
id:'title',
allowBlank:false,
blankText:'标题不能为空'
// value:'adfadsfasd'
},{
xtype:"combo",
fieldLabel: '选择',
name: 'combo',
id:'combotree',
store: new Ext.data.SimpleStore({fields:[],data:[[]]}),
editable:false,//是否可编辑的表格
selectClass:'',//适用于所有样式
mode: 'local', //本地数据
triggerAction:'all', //是否自动匹配
autoHeight: true,
tpl: "<tpl for='.'><div style='height:200px'><div id='tree'></div></div></tpl>", //模板 循环
emptyText:'请选择'
}]
}]
},{
layout: 'form',
labelAlign: 'top',
items: [{
xtype: 'htmleditor',
fieldLabel: '请输入文章内容',
id: 'context',
height:400,
allowBlank:false,
blankText:'内容不能为空',
anchor: '98%'
// value:'adfadfasd'
}]
}] ,
buttons: [{text: '保存',handler:add},
{text: '取消'}]
});
var treedata = new Ext.tree.TreeLoader({
url:'http://localhost:8080/pkm/register!queryChild.action'
});
var tree = new Ext.tree.TreePanel({
loader:treedata,
border:false,
root:new Ext.tree.AsyncTreeNode({text:'目录结构',id:'1'})
});
tree.on('click',function(node){
Artform.findById('combotree').value=node.id;//设置combo的键值
Artform.findById('combotree').setRawValue(node.text); //给combo设置显示的值
Artform.findById('combotree').collapse(); //隐藏下拉列表中,如果它展开,这个属性将会完成数据的加载
});
Artform.findById('combotree').on('expand',function(){
tree.render('tree');//ComboBox的tpl里的<div id='tree'>这个ID可以改成别的, 但必须要在'expand'事件里, 将树显示在这个div上
});
function add(){
if(Artform.form.isValid()){
//btn.disabled=true;//确认按钮有效默认为false
Ext.MessageBox.show({
msg: '正在请求数据, 请稍侯',
progressText: '正在请求数据',
width:300,
wait:true,
waitConfig: {interval:200}
});//进度条显示
Ext.Ajax.request({
url:'http://localhost:8080/pkm/article!saveOrupdate.action',
params:{
title:Ext.getCmp('title').getValue(),
context:Ext.getCmp('context').getValue(),
type:Artform.findById('combotree').value
},
failure:function(){
Ext.MessageBox.alert('友情提示',"异步通讯失败,请与管理员联系!");
},
success:function(request){
Ext.MessageBox.hide();
Ext.MessageBox.alert("友情提示","信息保存成功");
}
});
}else{
Ext.MessageBox.alert("信息","请填写完整");
}
}
Artform.render("form");
});
我这是一个form 里面生成的下拉树,单独测试的时候 其实可以用一个简单的comboBox 做的,我这里为了方便就直接把我的代码拿过来和大家分享下
其实上面的代码 最重要的就只有一个部分,下拉树写出来很简单,问题就是怎么能取到值给form 让它提交到后台,
Java代码
tree.on('click',function(node){
Artform.findById('combotree').value=node.id;设置combo的键值
Artform.findById('combotree').setRawValue(node.text); //给combo设置显示的值
Artform.findById('combotree').collapse(); //隐藏下拉列表中,如果它展开,这个属性将会完成数据的加载
});
tree.on('click',function(node){
Artform.findById('combotree').value=node.id;设置combo的键值
Artform.findById('combotree').setRawValue(node.text); //给combo设置显示的值
Artform.findById('combotree').collapse(); //隐藏下拉列表中,如果它展开,这个属性将会完成数据的加载
});
秘诀就在这里,这里能给你提交到后台什么的 ,什么父节点不能选择,根节点不能选择什么的,那个简单,你直接把你的树写好,就OK 在哪里判断 如有不对,请拍砖—-—!!