`
TJYCHYANGCHENHUI
  • 浏览: 12859 次
  • 性别: Icon_minigender_1
  • 来自: 天津
社区版块
存档分类
最新评论

jQuery+s2sh 实现无限级tree

    博客分类:
  • IT
阅读更多
1:成果预览图
   [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和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: 结束:




M:源码:
  • 大小: 7.9 KB
  • 大小: 10.9 KB
  • 大小: 20.6 KB
  • 大小: 23.1 KB
  • 大小: 8.3 KB
1
1
分享到:
评论
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 无限级树形菜单.rar

    本项目“s2sh+freemarker+jquery+jquery-treeview 无限级树形菜单”就是这样一个解决方案,它整合了多种技术来实现这一功能。 首先,我们来看“s2sh”。这是Struts2、Spring和Hibernate三者的简称,它们分别是MVC...

    jquery.simple.tree 动态加载,支持无限级分类(工程+数据库脚本)

    好久没用S2SH做东西了,闲来没事做了一个jQuery Tree 的Demo 支持无限级分类,异步加载数据,通过这个小程序可以了解一下jQuery动态加载数据的技巧,顺便复习了一下S2SH(struts2+spring+hiber)。

    基于s2sh+Extjs+dwr OA系统带全部JAR

    用的东西比较杂,主要为了学习一下知识呵呵: ssh2、dwr、jquery、extjs、jquery weekcalendar、jfreechart、jasperreport 联系人实现了拖动实现好友分组。可以把grid直接拖到tree,不同于其他的例子,拖动grid后会...

    ZTree 异步加载 SSH JSON

    ZTree是一款基于jQuery的树形插件,它具有丰富的功能和良好的可扩展性,常用于构建网站的导航菜单、文件目录展示等场景。在"ZTree 异步加载 SSH JSON"这个主题中,我们将深入探讨如何利用ZTree实现异步加载数据,并...

    员工晋升管理制度.doc

    员工晋升管理制度.doc

    基于MATLAB和CPLEX的综合能源系统中阶梯式碳交易与电制氢的热电优化研究

    内容概要:本文详细探讨了将阶梯式碳交易机制和电制氢技术应用于综合能源系统的热电优化方法。首先介绍了阶梯式碳交易的建模方式,通过分段线性化处理碳排放成本,使模型能够更好地反映现实中的碳市场价格波动。接着讨论了电制氢技术的应用,包括电解槽、甲烷反应器和氢燃料电池的具体实现及其在系统中的角色。此外,还提出了热电联产(CHP)系统中热电比动态调整的方法,提高了系统的灵活性和经济效益。文中提供了详细的MATLAB和CPLEX代码示例,展示了如何将这些复杂的技术和政策机制融入优化模型中。 适合人群:从事综合能源系统优化的研究人员、工程师以及对低碳技术和能源管理感兴趣的学者。 使用场景及目标:适用于需要进行低碳转型的企业和机构,旨在通过引入先进的碳交易机制和氢能技术,降低碳排放并提高能源利用效率。目标是在满足能源需求的同时,减少环境影响并降低成本。 其他说明:文中提到的优化模型不仅关注技术实现,还强调了经济性和环保效益之间的平衡。通过合理的参数设置和求解器配置,可以在不影响系统性能的前提下显著提升优化效果。

    MMC模块化多电平换流器7电平闭环控制系统仿真及其关键技术实现

    内容概要:本文详细介绍了7电平模块化多电平换流器(MMC)的闭环控制系统仿真,重点探讨了外环和内环控制、电容电压平衡、二倍频环流抑制以及载波移相调制等关键技术。作者通过MATLAB、Python和Verilog等多种编程语言实现了各个控制模块的具体算法,并分享了调试过程中遇到的问题及解决方案。实验结果显示,该系统能够将直流电压纹波控制在0.8%以内,环流幅值降至额定电流的3%以下,具有较强的鲁棒性和稳定性。 适合人群:电力电子工程师、高校师生及相关研究人员,特别是对MMC仿真感兴趣的初学者和技术爱好者。 使用场景及目标:适用于研究和开发高效稳定的MMC系统,特别是在高压直流输电领域的应用。主要目标是提高系统的稳定性和效率,减少电容电压失衡和环流震荡等问题。 其他说明:文中提供了详细的代码实现和调试技巧,有助于读者深入理解和掌握MMC闭环控制的关键技术和实践经验。同时,作者还提出了一些优化方向,如加入模糊控制器进一步提升系统性能。

    2. 亚马逊【官方选品方法论】《五三选品法》.pdf

    2. 亚马逊【官方选品方法论】《五三选品法》.pdf

    员工职业生涯规划表、能力开发需求表.docx

    员工职业生涯规划表、能力开发需求表

    MATLAB中小波阈值降噪技术及其应用场景详解

    内容概要:本文详细介绍了利用MATLAB实现的小波阈值降噪技术,涵盖三种主要方法:自定义阈值、智能推荐阈值以及分层精细处理。首先,通过生成带噪信号作为实验对象,展示了如何使用硬阈值和软阈值进行去噪。接着,探讨了智能推荐阈值的方法,如贝叶斯估计法,能够自动确定最优阈值。最后,深入讲解了分层处理的技术,通过对不同层次的细节系数分别设定阈值,达到更好的降噪效果。文中还提供了大量MATLAB代码实例,帮助读者理解和实践。 适合人群:具有一定MATLAB基础并希望深入了解小波变换理论及应用的研究人员和技术人员。 使用场景及目标:适用于各种含有噪声的数据处理任务,特别是机械振动信号、音频信号等领域。目标是提高信号质量,增强后续数据分析的有效性和准确性。 其他说明:文中强调了参数选择的重要性,如小波基的选择、分解层数的设定等,并给出了具体的调试建议。此外,还提到了一些常见的错误及解决办法,便于初学者快速上手。

    集团关怀活动方案.doc

    集团关怀活动方案.doc

    辞退面谈与赔偿金计算P23.pptx

    辞退面谈与赔偿金计算P23.pptx

    月度招聘报表.xlsx

    月度招聘报表.xlsx

    永磁同步电机无传感器控制:基于容积卡尔曼滤波与滑膜控制的技术实现

    内容概要:本文详细介绍了基于容积卡尔曼滤波(CKF)和滑膜控制(SMC)的永磁同步电机(PMSM)无传感器控制技术。首先阐述了CKF的工作原理及其在状态估计中的优势,包括状态预测、量测更新和状态后验分布的计算。接着讨论了滑膜控制的设计思路和实现方法,强调其在快速响应和鲁棒性方面的特点。文中还提供了Python和Matlab的代码示例,展示了这两种控制方法的具体实现。通过仿真和实验结果表明,该方法在转速估计和控制精度方面表现出色,具有广泛的应用前景。 适合人群:从事电机控制系统设计的研究人员和技术人员,尤其是关注高精度、高动态性能的无传感器控制方案的专业人士。 使用场景及目标:适用于需要高精度、高动态响应的电机应用场景,如工业自动化、航空航天等领域。主要目标是提高电机控制系统的精度和鲁棒性,降低系统成本和复杂度。 其他说明:文中提到的CKF和SMC方法不仅限于理论探讨,还包括了详细的代码实现和实验数据支持,有助于读者深入理解和实际应用。此外,文中还提到了一些优化技巧,如启动阶段误差补偿和高级CKF版本的选择,进一步提升了系统的性能。

    解聘职员申请表-模板.doc

    解聘职员申请表-模板.doc

    基于MATLAB的并联机器人运动学、动力学与轨迹跟踪控制仿真

    内容概要:本文详细介绍了如何使用MATLAB对并联机器人进行仿真实现,涵盖了运动学建模、动力学分析和轨迹跟踪控制三大方面。首先,通过定义关键参数和几何法求解逆运动学,建立了Delta并联机器人的运动学模型。接着,利用牛顿-欧拉法推导动力学方程,考虑了惯性力、重力等因素的影响。最后,采用PD+前馈控制方法实现轨迹跟踪,并通过仿真验证了控制效果。文中还提供了具体的MATLAB代码示例,帮助读者更好地理解和应用相关理论。 适合人群:对机器人技术感兴趣的科研人员、高校学生及工程技术人员。 使用场景及目标:适用于研究并联机器人的运动特性、优化控制系统性能、验证新算法的有效性等场景。目标是掌握并联机器人的建模与控制方法,提高仿真能力。 其他说明:文章强调了仿真过程中需要注意的问题,如奇异位形、数值稳定性等,并给出了相应的解决方案。同时,鼓励读者动手实践,通过调整参数和改进算法来深入探索并联机器人的行为特征。

    新员工入职引导及融入管理办法.docx

    新员工入职引导及融入管理办法

    光伏系统中基于扰动观察法的MPPT仿真与自建光伏电池模型的应用

    内容概要:本文详细介绍了光伏系统中最大功率点跟踪(MPPT)技术的一种常见实现方式——扰动观察法及其仿真模型的构建。文章首先阐述了扰动观察法的基本原理,即通过不断改变光伏电池的工作点并观察功率变化来逐步逼近最大功率点。接着,提供了具体的Python和MATLAB代码实现,展示了如何在MATLAB的Simulink环境中搭建光伏系统仿真模型,包括使用内置或自建光伏电池模型。文中强调了自建光伏电池模型的优势,如可根据实际情况调整参数,使仿真结果更为精确。此外,还讨论了仿真过程中可能出现的问题及解决方案,如电压振荡、误判和响应速度等,并通过视频解释进一步增强了理解和实用性。 适合人群:对光伏发电技术和MPPT算法感兴趣的科研人员、工程师和技术爱好者。 使用场景及目标:适用于希望深入了解光伏系统工作原理、掌握MPPT算法实现方法的研究人员;希望通过仿真验证和优化光伏系统性能的工程师;以及对光伏技术感兴趣的学习者。 其他说明:文章不仅提供了详细的理论讲解和技术实现步骤,还包括了实际案例分析和视频教程链接,便于读者更好地理解和实践。

    运动控制领域对称修正梯形加速度规律插补算法的推导与仿真

    内容概要:本文详细介绍了对称修正梯形加速度规律插补算法的推导与仿真实现。传统梯形加速度模型在加减速转换时会产生冲击,而对称修正梯形加速度通过引入过渡段使加速度变化更加平滑。文中首先推导了算法的基本原理,包括加速和减速阶段的分段处理方法,并给出了Python代码示例用于模拟加速阶段的速度变化。接着,利用MATLAB进行了仿真验证,展示了速度曲线的平滑过渡特性。此外,还讨论了实际应用场景中的参数选择和注意事项,如伺服电机的扭矩限制以及高阶多项式的使用风险。通过对机械臂的实际测试表明,该算法能够显著降低末端振动幅度,提高运动控制的精度和平稳性。 适合人群:从事运动控制、数控加工等相关领域的工程师和技术人员,尤其是希望深入了解加速度规律插补算法及其优化的人群。 使用场景及目标:适用于需要优化运动控制系统的场合,特别是那些对平稳性和精度有较高要求的应用,如机器人、数控机床等。目标是减少机械冲击,提升设备运行的稳定性和可靠性。 其他说明:文中提供了详细的数学推导和代码实现,帮助读者更好地理解和应用这一算法。同时提醒读者在实际应用中应注意参数的选择和硬件限制,确保算法的有效性和安全性。

    基于51单片机protues仿真的番茄计时器(仿真图、源代码、AD原理图、流程图、视频)

    基于51单片机protues仿真的番茄计时器(仿真图、源代码、AD原理图、流程图、视频) 设计一个番茄计时器。使用番茄工作法(番茄工作法是一种时间管理方法),选择一个待完成的任务,将番茄时间设为45分钟,专注工作,中途不允许做任何与该任务无关的事,直到番茄时钟响起,然后进行短暂休息一下(5分钟),然后再开始下一个番茄。每4个番茄时段再多休息5分钟。 按键1:单击设置45分钟倒计时,双击设置5分钟休息倒计时。 按键2:单击音乐播放,双击暂停。按键3:复位按键。 所需硬件:3个按键,1个动态数码管,1个蜂鸣器。 仿真图、源代码、AD原理图、流程图、视频

Global site tag (gtag.js) - Google Analytics