jQuery+s2sh 实现无限级tree

1:成果预览图
   [img]

jQuery+s2sh 实现无限级tree_第1张图片

[/img]
2:实现过程
  a: 框架的搭建:效果图(因为本文章的重点是对treeView的实现,所以框架的搭建就不在多说)
  


jQuery+s2sh 实现无限级tree_第2张图片

  

  b:创建t_category 表格
 

jQuery+s2sh 实现无限级tree_第3张图片

  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:添加一些需要的文件

jQuery+s2sh 实现无限级tree_第4张图片

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和CategoryServiceImpl
package 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: 结束:

jQuery+s2sh 实现无限级tree_第5张图片


M:源码:

你可能感兴趣的:(JavaScript,jquery,json,Web,Ajax)