- 浏览: 12507 次
- 性别:
- 来自: 天津
文章分类
最新评论
-
TJYCHYANGCHENHUI:
<div class="quote_title ...
jQuery+s2sh 实现无限级tree -
jackyrong:
最好提供代码下载参考吧,另外强烈推荐一个国产的ZTREE,树的 ...
jQuery+s2sh 实现无限级tree
1:成果预览图
[img]
[/img]
2:实现过程
a: 框架的搭建:效果图(因为本文章的重点是对treeView的实现,所以框架的搭建就不在多说)
b:创建t_category 表格
c:创建实体模型Category
d:创建CategoryDAO接口
e:创建CategoryDAOImpl
f:配置映射文件
g:添加一些需要的文件
h: 创建一个servlet进行返回json格式的数据(这篇文章使用的是servlet由于时间原因下次会更改为action)
h:创建index.html
i:在jquery.treeview.async.js 中添加代码,只有这样才能够完成树的异步构建
j:新建category.js处理节点的添加与编辑函数的编写
k:编写action类
M:applicationContext.xml的配置
N: 结束:
M:源码:
谢谢你的提供,因为jar包大于10m所以就没有上传,但是源码我上传在了csdn上面 url[url]
http://download.csdn.net/detail/tjychyangchenhui/4245836
[/url]
[img]
[/img]
2:实现过程
a: 框架的搭建:效果图(因为本文章的重点是对treeView的实现,所以框架的搭建就不在多说)
b:创建t_category 表格
c:创建实体模型Category
package com.yangchenhui.model; import java.util.HashSet; import java.util.Set; public class Category implements java.io.Serializable { private static final long serialVersionUID = -8759167738763128025L; private Integer categoryId; private Category category; private String categoryName; private Integer depth; private Set<Category> categories = new HashSet<Category>(0); // Constructors /** default constructor */ public Category() { } /** minimal constructor */ public Category(String categoryName) { this.categoryName = categoryName; } /** full constructor */ public Category(Category category, String categoryName, Integer depth, Set<Category> categories) { this.category = category; this.categoryName = categoryName; this.depth = depth; this.categories = categories; } // Property accessors public Integer getCategoryId() { return this.categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public Category getCategory() { return this.category; } public void setCategory(Category category) { this.category = category; } public String getCategoryName() { return this.categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public Integer getDepth() { return this.depth; } public void setDepth(Integer depth) { this.depth = depth; } public Set<Category> getCategories() { return this.categories; } public void setCategories(Set<Category> categories) { this.categories = categories; } }
d:创建CategoryDAO接口
package com.yangchenhui.dao; import java.util.List; import com.yangchenhui.model.Category; public interface CategoryDAO { public abstract void save(Category transientInstance); public abstract void delete(Category persistentInstance); public abstract Category findById(java.lang.Integer id); public abstract List findByExample(Category instance); public abstract List findByProperty(String propertyName, Object value); public abstract List findByCategoryName(Object categoryName); public abstract List findByDepth(Object depth); public abstract List findAll(); public abstract Category merge(Category detachedInstance); public abstract void attachDirty(Category instance); public abstract void attachClean(Category instance); void deleteCategoryByParentId(Integer categoryId); }
e:创建CategoryDAOImpl
package com.yangchenhui.dao; import java.util.List; import java.util.Set; import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate.criterion.Example; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.yangchenhui.model.Category; /** * A data access object (DAO) providing persistence and search support for * Category entities. Transaction control of the save(), update() and delete() * operations can directly support Spring container-managed transactions or they * can be augmented to handle user-managed Spring transactions. Each of these * methods provides additional information for how to configure it for the * desired type of transaction control. * * @see com.yangchenhui.model.Category * @author MyEclipse Persistence Tools */ public class CategoryDAOImpl extends HibernateDaoSupport implements CategoryDAO { private static final Logger log = LoggerFactory .getLogger(CategoryDAOImpl.class); // property constants public static final String CATEGORY_NAME = "categoryName"; public static final String DEPTH = "depth"; /* (non-Javadoc) * @see com.yangchenhui.dao.CategoryDAO#save(com.yangchenhui.model.Category) */ @Override public void save(Category transientInstance) { log.debug("saving Category instance"); try { getSession().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } /* (non-Javadoc) * @see com.yangchenhui.dao.CategoryDAO#delete(com.yangchenhui.model.Category) */ @Override public void delete(Category persistentInstance) { log.debug("deleting Category instance"); try { getSession().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } /* (non-Javadoc) * @see com.yangchenhui.dao.CategoryDAO#findById(java.lang.Integer) */ @Override public Category findById(java.lang.Integer id) { log.debug("getting Category instance with id: " + id); try { Category instance = (Category) getSession().get( "com.yangchenhui.model.Category", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } /* (non-Javadoc) * @see com.yangchenhui.dao.CategoryDAO#findByExample(com.yangchenhui.model.Category) */ @Override public List findByExample(Category instance) { log.debug("finding Category instance by example"); try { List results = getSession() .createCriteria("com.yangchenhui.model.Category") .add(Example.create(instance)).list(); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } /* (non-Javadoc) * @see com.yangchenhui.dao.CategoryDAO#findByProperty(java.lang.String, java.lang.Object) */ @Override public List findByProperty(String propertyName, Object value) { log.debug("finding Category instance with property: " + propertyName + ", value: " + value); try { String queryString = "from Category as model where model." + propertyName + "= ?"; Query queryObject = getSession().createQuery(queryString); queryObject.setParameter(0, value); return queryObject.list(); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } /* (non-Javadoc) * @see com.yangchenhui.dao.CategoryDAO#findByCategoryName(java.lang.Object) */ @Override public List findByCategoryName(Object categoryName) { return findByProperty(CATEGORY_NAME, categoryName); } /* (non-Javadoc) * @see com.yangchenhui.dao.CategoryDAO#findByDepth(java.lang.Object) */ @Override public List findByDepth(Object depth) { return findByProperty(DEPTH, depth); } /* (non-Javadoc) * @see com.yangchenhui.dao.CategoryDAO#findAll() */ @Override public List findAll() { log.debug("finding all Category instances"); try { String queryString = "from Category"; Query queryObject = getSession().createQuery(queryString); return queryObject.list(); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } /* (non-Javadoc) * @see com.yangchenhui.dao.CategoryDAO#merge(com.yangchenhui.model.Category) */ @Override public Category merge(Category detachedInstance) { log.debug("merging Category instance"); try { Category result = (Category) getSession().merge(detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } /* (non-Javadoc) * @see com.yangchenhui.dao.CategoryDAO#attachDirty(com.yangchenhui.model.Category) */ @Override public void attachDirty(Category instance) { log.debug("attaching dirty Category instance"); try { getSession().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } /* (non-Javadoc) * @see com.yangchenhui.dao.CategoryDAO#attachClean(com.yangchenhui.model.Category) */ @Override public void attachClean(Category instance) { log.debug("attaching clean Category instance"); try { getSession().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } @Override public void deleteCategoryByParentId(Integer categoryId){ log.debug("deleting Category instance"); try { Query query = getSession().createQuery("delete from Category c where c.category.categoryId = " + categoryId); query.executeUpdate(); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } }
f:配置映射文件
<?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"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="com.yangchenhui.model.Category" table="t_category" catalog="ambow"> <id name="categoryId" type="java.lang.Integer"> <column name="categoryId" /> <generator class="increment"></generator> </id> <many-to-one name="category" class="com.yangchenhui.model.Category" fetch="select"> <column name="parentId" /> </many-to-one> <property name="categoryName" type="java.lang.String"> <column name="categoryName" length="20" not-null="true" /> </property> <property name="depth" type="java.lang.Integer"> <column name="depth" /> </property> <set name="categories" inverse="true"> <key> <column name="parentId" /> </key> <one-to-many class="com.yangchenhui.model.Category" /> </set> </class> </hibernate-mapping>
g:添加一些需要的文件
h: 创建一个servlet进行返回json格式的数据(这篇文章使用的是servlet由于时间原因下次会更改为action)
package com.yagnchenhui.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.yangchenhui.model.Category; import com.yangchenhui.service.CategoryService; public class CategoryFindAllServlet extends HttpServlet { private CategoryService categoryService; /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/json;charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); response.setContentType("text/json;charset=UTF-8"); PrintWriter out = response.getWriter(); String sb = getRootNode(); System.out.println(sb); out.print(sb.toString()); out.flush(); out.close(); } public String getRootNode() { StringBuffer sb = new StringBuffer(); sb.append("["); sb.append("{"); sb.append("\"text\":\"分类\""); sb.append(",\"classes\":\"categoryRoot\""); sb.append(",\"expanded\":true"); sb.append(",\"children\":"+getOneNode(categoryService.queryOneLevelParentsCategory()) +""); sb.append("}"); sb.append("]"); return sb.toString(); } public String getOneNode(List<Category> categoryList){ StringBuffer sb = new StringBuffer(); sb.append("["); for(int i = 0; i < categoryList.size(); i++){ if(categoryList.get(i).getCategory() == null){ if(i == 0){ sb.append("{"); sb.append("\"text\":\"" + categoryList.get(i).getCategoryName() + "\""); sb.append(",\"id\":\""+ categoryList.get(i).getCategoryId()+"\""); sb.append(",\"classes\":\"categoryOneLevel\""); sb.append(",\"expanded\":true"); sb.append(",\"children\":" + getTwoNode(categoryList.get(i).getCategoryId()) + ""); sb.append("}"); }else{ sb.append(",{"); sb.append("\"text\":\"" + categoryList.get(i).getCategoryName() + "\""); sb.append(",\"id\":\""+ categoryList.get(i).getCategoryId()+"\""); sb.append(",\"classes\":\"categoryOneLevel\""); sb.append(",\"expanded\":true"); sb.append(",\"children\":" + getTwoNode(categoryList.get(i).getCategoryId()) + ""); sb.append("}"); } } } sb.append("]"); return sb.toString(); } public String getTwoNode(Integer parentId){ List<Category> children = categoryService.queryChildrenCategoryByParentId(parentId); StringBuffer sb = new StringBuffer(); sb.append("["); for(int i = 0; i < children.size(); i++){ if(i == 0){ sb.append("{"); sb.append("\"text\":\"" + children.get(i).getCategoryName() + "\""); sb.append(",\"classes\":\"categoryOneLevel\""); sb.append(",\"id\":\""+ children.get(i).getCategoryId()+"\""); if(categoryService.hasChildren(children.get(i).getCategoryId())){ sb.append(",\"children\":"+getTwoNode(children.get(i).getCategoryId())+ ""); sb.append("}"); }else{ sb.append("}"); } }else{ sb.append(",{"); sb.append("\"text\":\"" + children.get(i).getCategoryName() + "\""); sb.append(",\"classes\":\"categoryOneLevel\""); sb.append(",\"id\":\""+ children.get(i).getCategoryId()+"\""); if(categoryService.hasChildren(children.get(i).getCategoryId())){ sb.append(",\"children\":"+getTwoNode(children.get(i).getCategoryId())+ ""); sb.append("}"); }else{ sb.append("}"); } } } sb.append("]"); return sb.toString(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { WebApplicationContext wpc = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); categoryService = (CategoryService) wpc.getBean("categoryService"); } }
h:创建index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>index.html</title> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <link rel="stylesheet" href="css/jquery.treeview.css" /> <link rel="stylesheet" href="css/screen.css" /> <script type="text/javascript" src="js/jquery-1.7.2.js"> </script> <script type="text/javascript" src="js/jquery.treeview.js"> </script> <script type="text/javascript" src="js/jquery.cookie.js"> </script> <script type="text/javascript" src="js/jquery.treeview.async.js"> </script> <script type="text/javascript" src="js/jquery.contextmenu.r2.js"></script> <script type="text/javascript" src="js/category.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#navigation").treeview({ animated: "fast", collapsed: true, unique: true, persist: "location", url: "categoryFindAllServlet" }); }); </script> </head> <body> <ul id="navigation" class="treeview-red"></ul> <div class="contextMenu" id="rootMenu"> [list] <li id="addOneLevelCategory">新增一级分类</li> <li id="deleteAllOneLevelCategory">删除所有一级分类</li> [/list] </div> <div class="contextMenu" id="OneMenu"> [list] <li id="editOneLevelCategory">编辑</li> <li id="deleteOneLevelCategory">删除</li> <li id="addChildCategory">新增子分类</li> [/list] </div> </body> </html>
i:在jquery.treeview.async.js 中添加代码,只有这样才能够完成树的异步构建
/* * Async Treeview 0.1 - Lazy-loading extension for Treeview * * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/ * * Copyright (c) 2007 Jörn Zaefferer * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id$ * */ ;(function($) { function load(settings, root, child, container) { function createNode(parent) { var current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>").appendTo(parent); if (this.classes) { current.children("span").addClass(this.classes); } if (this.expanded) { current.addClass("open"); } if (this.hasChildren || this.children && this.children.length) { var branch = $("<ul/>").appendTo(current); if (this.hasChildren) { current.addClass("hasChildren"); createNode.call({ classes: "placeholder", text: " ", children:[] }, branch); } if (this.children && this.children.length) { $.each(this.children, createNode, [branch]); } } } $.ajax($.extend(true, { url: settings.url, dataType: "json", data: { root: root }, success: function(response) { child.empty(); $.each(response, createNode, [child]); $(container).treeview({add: child}); //代码添加的开始 $("span.categoryRoot").contextMenu("rootMenu",{ bindings:{ addOneLevelCategory:addOneLevelCategory, deleteAllOneLevelCategory:deleteAllOneLevelCategory } }); $("span.categoryOneLevel").contextMenu("OneMenu",{ bindings:{ editOneLevelCategory:editOneLevelCategory, deleteOneLevelCategory:deleteOneLevelCategory, addChildCategory:addChildCategory } }); //代码添加的结束 } }, settings.ajax)); /* $.getJSON(settings.url, {root: root}, function(response) { function createNode(parent) { var current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>").appendTo(parent); if (this.classes) { current.children("span").addClass(this.classes); } if (this.expanded) { current.addClass("open"); } if (this.hasChildren || this.children && this.children.length) { var branch = $("<ul/>").appendTo(current); if (this.hasChildren) { current.addClass("hasChildren"); createNode.call({ classes: "placeholder", text: " ", children:[] }, branch); } if (this.children && this.children.length) { $.each(this.children, createNode, [branch]) } } } child.empty(); $.each(response, createNode, [child]); $(container).treeview({add: child}); }); */ } var proxied = $.fn.treeview; $.fn.treeview = function(settings) { if (!settings.url) { return proxied.apply(this, arguments); } var container = this; if (!container.children().size()) load(settings, "source", this, container); var userToggle = settings.toggle; return proxied.call(this, $.extend({}, settings, { collapsed: true, toggle: function() { var $this = $(this); if ($this.hasClass("hasChildren")) { var childList = $this.removeClass("hasChildren").find("ul"); load(settings, this.id, childList, container); } if (userToggle) { userToggle.apply(this, arguments); } } })); }; })(jQuery);
j:新建category.js处理节点的添加与编辑函数的编写
/** * 增加一级类别的函数 */ function addOneLevelCategory(){ var categoryOneLevelValue = window.prompt("请输入要添加的类别的分类",""); $.post( "categoryAdd.action", { categoryOneLevelValue:categoryOneLevelValue }, function (data,textStatus){ $("#navigation").empty(); $("#navigation").treeview({ animated: "fast",//由它来决定收缩和展开效果 collapsed: true, unique: true, persist: "location", url:"categoryFindAllServlet" }); } ); } /** * 删除所有的一级节点类别 */ function deleteAllOneLevelCategory(){ alert("你好"); } /** * 编辑一级节点的信息 */ function editOneLevelCategory(data){ var categoryOneLevelValue = window.prompt("请输入要修改的一级节点的名称",""); $.post( "categoryEdit.action", { categoryOneLevelValue:categoryOneLevelValue, categoryId:data.parentNode.id }, function (data,textStatus){ $("#navigation").empty(); $("#navigation").treeview({ animated: "fast",//由它来决定收缩和展开效果 collapsed: true, unique: true, persist: "location", url:"categoryFindAllServlet" }); } ); } function deleteOneLevelCategory(data){ var confim = window.confirm("你确定要删除这个类别一级其所有的自类别吗?"); if(confim){ $.post( "categoryDelete.action", { categoryId:data.parentNode.id }, function (data,textStatus){ $("#navigation").empty(); $("#navigation").treeview({ animated: "fast",//由它来决定收缩和展开效果 collapsed: true, unique: true, persist: "location", url:"categoryFindAllServlet" }); } ); } } /** * 像一个级别分类中中增加子类别 * @param {} data */ function addChildCategory(data){ var categoryOneLevelValue = window.prompt("请输入要添加的类别名称",""); $.post( "categoryChildAdd.action", { categoryOneLevelValue:categoryOneLevelValue, parentCategoryId:data.parentNode.id }, function (data,textStatus){ $("#navigation").empty(); $("#navigation").treeview({ animated: "fast",//由它来决定收缩和展开效果 collapsed: true, unique: true, persist: "location", url:"categoryFindAllServlet" }); } ); }
k:编写action类
package com.yangchenhui.action; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionSupport; import com.yangchenhui.model.Category; import com.yangchenhui.service.CategoryService; public class CategoryAddAction extends ActionSupport { private static final long serialVersionUID = 1L; private CategoryService categoryService; private String categoryOneLevelValue; @Override public String execute() throws Exception { Category category = new Category(); category.setCategoryName(categoryOneLevelValue); category.setDepth(1); if(!categoryService.queryCategoryByCategoryName(categoryOneLevelValue)){ categoryService.addOneLevelCategory(category); } return Action.SUCCESS; } public CategoryService getCategoryService() { return categoryService; } public void setCategoryService(CategoryService categoryService) { this.categoryService = categoryService; } public String getCategoryOneLevelValue() { return categoryOneLevelValue; } public void setCategoryOneLevelValue(String categoryOneLevelValue) { this.categoryOneLevelValue = categoryOneLevelValue; } }
package com.yangchenhui.action; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionSupport; import com.yangchenhui.model.Category; import com.yangchenhui.service.CategoryService; public class CategoryChildAdd extends ActionSupport { private static final long serialVersionUID = 1L; private CategoryService categoryService; private String categoryOneLevelValue; private Integer parentCategoryId; @Override public String execute() throws Exception { Category childCategory = new Category(); childCategory.setCategoryName(categoryOneLevelValue); if(!categoryService.queryCategoryByCategoryName(categoryOneLevelValue)){ categoryService.addCategoryToParent(parentCategoryId, childCategory); } return Action.SUCCESS; } public CategoryService getCategoryService() { return categoryService; } public void setCategoryService(CategoryService categoryService) { this.categoryService = categoryService; } public String getCategoryOneLevelValue() { return categoryOneLevelValue; } public void setCategoryOneLevelValue(String categoryOneLevelValue) { this.categoryOneLevelValue = categoryOneLevelValue; } public Integer getParentCategoryId() { return parentCategoryId; } public void setParentCategoryId(Integer parentCategoryId) { this.parentCategoryId = parentCategoryId; } }
package com.yangchenhui.action; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionSupport; import com.yangchenhui.service.CategoryService; public class CategoryDeleteAction extends ActionSupport { private static final long serialVersionUID = 1L; private CategoryService categoryService; private Integer categoryId; @Override public String execute() throws Exception { this.categoryService.deleteCategory(categoryId); return Action.SUCCESS; } public CategoryService getCategoryService() { return categoryService; } public void setCategoryService(CategoryService categoryService) { this.categoryService = categoryService; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } }package com.yangchenhui.action; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionSupport; import com.yangchenhui.model.Category; import com.yangchenhui.service.CategoryService; public class CategoryEditAction extends ActionSupport { private static final long serialVersionUID = 1L; private CategoryService categoryService; private String categoryOneLevelValue; private Integer categoryId; @Override public String execute() throws Exception { Category category = categoryService.findCategoryById(categoryId); category.setCategoryName(categoryOneLevelValue); if(!categoryService.queryCategoryByCategoryName(categoryOneLevelValue)){ categoryService.editCategory(category); } return Action.SUCCESS; } public CategoryService getCategoryService() { return categoryService; } public void setCategoryService(CategoryService categoryService) { this.categoryService = categoryService; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public String getCategoryOneLevelValue() { return categoryOneLevelValue; } public void setCategoryOneLevelValue(String categoryOneLevelValue) { this.categoryOneLevelValue = categoryOneLevelValue; } }
L: 编写CategoryService和CategoryServiceImplpackage com.yangchenhui.service; import java.util.List; import com.yangchenhui.model.Category; public interface CategoryService { /** * 得到所有的category * @return */ public List<Category> queryAllCategory(); /** * 得到所有的一级的父节点 * @return */ public List<Category> queryOneLevelParentsCategory(); /** * 根据父亲的id号得到父类别的所有的自类别 * @param parentId * @return */ public List<Category> queryChildrenCategoryByParentId(Integer parentId); /** * 添加一级节点 */ public void addOneLevelCategory(Category category); /** * 根据categoryId查找类别 * @param categoryId * @return */ public Category findCategoryById(Integer categoryId); /** * 更新类别 * @param category */ public void editCategory(Category category); /** * 删除一个类别,如果有任何的子类被,也将其删除 * @param categoryId */ public void deleteCategory(Integer categoryId); /** * 向父类别parentCategory中添加一个自类别 * @param parentCategoryId * @param childCategory */ public void addCategoryToParent(Integer parentCategoryId, Category childCategory); /** * 根据类别的名称去得到类别,查询是否有这个类别的名称 * @param categoryName */ public boolean queryCategoryByCategoryName(String categoryName); /** * 查询一个category是否具有子节点 * @param categoryId * @return */ public boolean hasChildren(Integer categoryId); }
[code ="java"]
package com.yangchenhui.service;
import java.util.List;
import com.yangchenhui.dao.CategoryDAO;
import com.yangchenhui.model.Category;
public class CategoryServiceImpl implements CategoryService {
private CategoryDAO categoryDAO;
@SuppressWarnings("unchecked")
@Override
public List<Category> queryAllCategory() {
return categoryDAO.findAll();
}
public CategoryDAO getCategoryDAO() {
return categoryDAO;
}
public void setCategoryDAO(CategoryDAO categoryDAO) {
this.categoryDAO = categoryDAO;
}
@SuppressWarnings("unchecked")
@Override
public List<Category> queryChildrenCategoryByParentId(Integer parentId) {
return this.categoryDAO.findByProperty("category", this.categoryDAO.findById(parentId));
}
@SuppressWarnings("unchecked")
@Override
public List<Category> queryOneLevelParentsCategory() {
return this.categoryDAO.findByProperty("depth", 1);
}
@Override
public void addOneLevelCategory(Category category) {
this.categoryDAO.save(category);
}
@Override
public Category findCategoryById(Integer categoryId) {
return this.categoryDAO.findById(categoryId);
}
@Override
public void editCategory(Category category) {
this.categoryDAO.attachDirty(category);
}
@Override
public void deleteCategory(Integer categoryId) {
this.categoryDAO.deleteCategoryByParentId(categoryId);
this.categoryDAO.delete(this.categoryDAO.findById(categoryId));
}
@Override
public void addCategoryToParent(Integer parentCategoryId,
Category childCategory) {
Category parentCategory = this.categoryDAO.findById(parentCategoryId);
childCategory.setDepth(parentCategory.getDepth()+1);
childCategory.setCategory(parentCategory);
this.categoryDAO.save(childCategory);
}
@Override
public boolean queryCategoryByCategoryName(String categoryName) {
List<Category> categories = this.categoryDAO.findByCategoryName(categoryName);
if(categories.size()==0){
return false;
}else{
return true;
}
}
@Override
public boolean hasChildren(Integer categoryId) {
List<Category> children = this.categoryDAO.findByProperty("category", this.categoryDAO.findById(categoryId));
if(children.size()==0){
return false;
}else{
return true;
}
}
}
M:applicationContext.xml的配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd " > <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation" value="classpath:hibernate.cfg.xml"> </property> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <bean id="categoryDAO" class="com.yangchenhui.dao.CategoryDAOImpl"> <property name="hibernateTemplate"> <ref bean="hibernateTemplate"/> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <tx:advice transaction-manager="transactionManager" id="txAdvice"> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="serviceMethods" expression="execution(* com.yangchenhui.service.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/> </aop:config> <bean id="categoryService" class="com.yangchenhui.service.CategoryServiceImpl"> <property name="categoryDAO" ref="categoryDAO"/> </bean> <bean id="categoryFindAllAction" class="com.yangchenhui.action.CategoryFindAllAction" scope="prototype"> <property name="categoryService" ref="categoryService"/> </bean> <bean id="categoryAddAction" class="com.yangchenhui.action.CategoryAddAction" scope="prototype"> <property name="categoryService" ref="categoryService"/> </bean> <bean id="categoryEditAction" class="com.yangchenhui.action.CategoryEditAction" scope="prototype"> <property name="categoryService" ref="categoryService"/> </bean> <bean id="categoryDeleteAction" class="com.yangchenhui.action.CategoryDeleteAction" scope="prototype"> <property name="categoryService" ref="categoryService"/> </bean> <bean id="categoryChildAddAction" class="com.yangchenhui.action.CategoryChildAdd" scope="prototype"> <property name="categoryService" ref="categoryService"/> </bean> </beans>
N: 结束:
M:源码:
评论
2 楼
TJYCHYANGCHENHUI
2012-04-24
jackyrong 写道
最好提供代码下载参考吧,另外强烈推荐一个国产的ZTREE,树的,功能很强大
建议参考
建议参考
谢谢你的提供,因为jar包大于10m所以就没有上传,但是源码我上传在了csdn上面 url[url]
http://download.csdn.net/detail/tjychyangchenhui/4245836
[/url]
1 楼
jackyrong
2012-04-21
最好提供代码下载参考吧,另外强烈推荐一个国产的ZTREE,树的,功能很强大
建议参考
建议参考
相关推荐
本项目“s2sh+freemarker+jquery+jquery-treeview 无限级树形菜单”就是这样一个解决方案,它整合了多种技术来实现这一功能。 首先,我们来看“s2sh”。这是Struts2、Spring和Hibernate三者的简称,它们分别是MVC...
前端+jQuery+实现烟花特效前端+jQuery+实现烟花特效前端+jQuery+实现烟花特效前端+jQuery+实现烟花特效前端+jQuery+实现烟花特效前端+jQuery+实现烟花特效前端+jQuery+实现烟花特效前端+jQuery+实现烟花特效前端+...
"jquery+ajax写的无限级选择框select"是一个常见的需求,它允许用户通过多级联动的方式进行选择,为用户提供更加灵活和丰富的数据导航体验。这个解决方案的核心是利用jQuery库的事件处理和AJAX技术来实现动态加载...
jQuery+CSS3实现动画相册代码.rar jQuery+CSS3实现动画相册代码.rar jQuery+CSS3实现动画相册代码.rar jQuery+CSS3实现动画相册代码.rar jQuery+CSS3实现动画相册代码.rar jQuery+CSS3实现动画相册代码.rar jQuery+...
本例子,使用struts+spring+hibernate +jquery 实现的jquery的treeview 和 contextmenu 插件的整合,实现了无限级的tree
这个项目实例将jQuery UI与S2SH框架整合,展示了如何在Java Web应用中利用jQuery UI增强用户界面交互性。通过jQuery UI,开发者可以快速创建美观且易于使用的界面元素,如使用Dialog展示弹窗提示,使用Datepicker...
这个案例——"jquery+js 实现无限级菜单(分销)树行结构",提供了一种利用JavaScript库jQuery来创建动态、可扩展的树形菜单的方法。无限级菜单意味着菜单可以包含任意多的子级,而不限于固定的几层。 首先,我们需要...
这个项目“ajax+asp+acces实现联动无限级下拉框”利用了AJAX(异步JavaScript和XML)、ASP(Active Server Pages)以及Access数据库来创建一个四级联动的下拉菜单系统。 首先,让我们了解一下每个技术的角色: 1. ...
jQuery+css3实现信封效果 jQuery+css3实现信封网页特效.zip
mvc+jquery+treemvc+jquery+treemvc+jquery+treemvc+jquery+treemvc+jquery+treemvc+jquery+treemvc+jquery+treemvc+jquery+treemvc+jquery+...treemvc+jquery+treemvc+jquery+treemvc+jquery+treemvc+jquery+tree
这个压缩包中的资源,"SSH+jQuery+json 实现的Ajax操作,绝对精华,代码简练清晰,绝对能看明白",显然提供了一个使用这些技术实现Ajax级联操作的实例。下面将详细介绍这些技术及其在Ajax操作中的应用。 **SSH ...
jQuery+CSS3实现的图片分割特效源码jQuery+CSS3实现的图片分割特效源码jQuery+CSS3实现的图片分割特效源码jQuery+CSS3实现的图片分割特效源码
摘要:ASP源码,Ajax相关,Ajax,树形菜单 jQuery+Ajax+ASP+MySQL 实现无限级树状菜单结构,并适时动态实现树形菜单内数据的增、删、改等编辑功能,是jQuery+Ajax+ASP+MySQL几种技术结合而开发的,主文件Sys_Module.asp...
实现JQuery+ajax+mock.js模拟注册,判断输入框是否输入正确
【S2SH+Jquery+Oracle+jFreeChart项目实例】是一个综合性的Web应用程序开发案例,主要结合了四个关键的技术:Struts2、Spring、Hibernate和jQuery,以及Oracle数据库和jFreeChart图表库。这个项目旨在展示如何在Java...
在线实时的斗兽棋游戏,时间赶,粗暴的使用jQuery + websoket 实现实时H5对战游戏 + java 在线实时的斗兽棋游戏,时间赶,粗暴的使用jQuery + websoket 实现实时H5对战游戏 + java 在线实时的斗兽棋游戏,时间赶,...
在IT行业中,jQuery、JavaScript、导航、Tree以及JS特效是前端开发的重要组成部分,它们共同构建了丰富多彩的用户体验。下面将详细解析这些知识点及其在实际应用中的作用。 首先,jQuery是一个高效、简洁、易用的...
jQuery+HTML5实现图片上传前预览效果,代码简洁,方便使用。
在网上找到了图片上传插件jquery.min.js,但没有上传功能,自己花了10分钟给加上去了哈,有bug留言,一般当天改完上传。 转自:素材火jQuery教程演示:http://www.sucaihuo.com/js/71.html