`
caojianwei
  • 浏览: 14051 次
  • 性别: Icon_minigender_1
  • 来自: 宜昌/上海
社区版块
存档分类
最新评论

使用Jquery,Ajax+Struts+Spring+Ibatis写的一个无限级树,供大家参考一下

阅读更多
先看看jsp页面,tree.jsp,Code如下:
<%@ page contentType="text/html;charset=UTF-8" %>
<% 
	String context = request.getContextPath();
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>树状菜单</title>
    <link type="text/css" href="<%=context%>/css/tree/tree.css" rel="stylesheet" rev="stylesheet" />
	<%@ include file="/common/commonTop.jsp"%>	
	<script type="text/javascript" src="<%=context%>/script/tree/tree.js"></script>
	<script type="text/javascript">
		function locationHref(functionID,functionUrl,forwardUrl,functionUrlParam){
			if(selectHrefID!=""){
				document.getElementById(selectHrefID+"_href").style.background="";
			}
			selectHrefID = functionID;
			document.getElementById(functionID+"_href").style.background="#0CA4CF";
			document.getElementById(functionID+"_href").target='mainFrame';
			document.getElementById("functionUrl").value=functionUrl;
			document.getElementById("functionUrlParam").value=functionUrlParam;
			document.getElementById(functionID+"_href").href=forwardUrl+"?functionUrl="+functionUrl+"&functionUrlParam="+functionUrlParam;
		}
	</script>
  </head>
  
  <body leftmargin="10" topmargin="0">
  	<input type="hidden" id="functionUrl" value="">
  	<input type="hidden" id="functionUrlParam" value="">
  	<input type="hidden" name="action" id="action" value="treeQuery">
  	<input type="hidden" name="url" id="url" value="<%=context%>/admin/treeAction.do">
  	<table>
  		<tr>
  			<td>
			  	<div id="selectStoreType" style="display: none">&nbsp;&nbsp;&nbsp;
			  		<select id="selectType"></select>
			  	</div>
		  	</td>
	  	</tr>
	  	<tr>
	  		<td>
	  			<div id="selectMsg"></div>
	  		</td>
	  	</tr>
	  	<tr>
	  		<td>
			  	<div id="treemenu" style="width:100%; height:auto;">   
					<div id="tree" style="display: none" align="left">
						&nbsp;&nbsp;&nbsp;<img src="<%= context %>/images/ajax-loader.gif">请稍等...
					</div>
				</div>
			</td>
		</tr>
	</table>
  </body>
</html>


再就是javascript,tree.js,如下:
var selectTypeID = "";
		$(document).ready(function(){
			storeTypeAjax();
			$("#selectType").change(function(){
				$("#tree").html("&nbsp;&nbsp;&nbsp;<img src=\"<%= context %>/images/ajax-loader.gif\">请稍等...");
				selectTypeID = $("#selectType").val();
				treeNodeAjax("0","tree",selectTypeID);
			});
		});
		
		//用于控制超级链接的背景色
		var selectHrefID = "";
		
		//异步生成树
		function treeNodeAjax(functionID,nodeID,storeTypeID){
			$("#selectMsg").hide();
			$("#"+nodeID).show();
			$.ajax({
	            type: "post",//使用get方法访问后台
	            dataType: "javascript",//返回文本格式的数据
	            url: $("#url").val(),//要访问的后台地址
	            data: "action="+$("#action").val()+"&function_id="+functionID+"&store_type_id="+storeTypeID,//要发送的数据
	            complete :function(){$(nodeID).show();},//AJAX请求完成时显示提示
	            error:function(msg){alert('加载错误');},
	            success: function(msg){//msg为返回的数据,在这里做数据绑定
	            	if(msg.indexOf("1003")!=-1){
	            		$("#selectMsg").html("<font color=red>&nbsp;&nbsp;&nbsp;"+msg+"</font>");
	            		$("#selectMsg").show();
	            		$("#"+nodeID).hide();
	            	}else{
	            		var msgarray = msg.split("|");
		            	var htmlNode = "";
		            	for(var i=0;i<msgarray.length;i++){
		            		var msgelement = msgarray[i].split(",");
		            		htmlNode += creatTreeNode(msgelement[0],msgelement[1],msgelement[2],msgelement[3],msgelement[4],msgelement[5],msgelement[6]);
		            	}
		            	$("#"+nodeID).html("<div id='"+msgelement[2]+"'><ul style=\"cursor: hand;\">"+htmlNode+"</ul></div>");
	            	}
	            	//alert($("#"+nodeID).html());
	            }
		    });
		}
		
		//异步生成树
		function storeTypeAjax(){
			$("#selectMsg").hide();
			var selectObj = document.getElementById("selectType");
			var options = new Option("请稍等...","");
			selectObj.add(options)
			$.ajax({
	            type: "post",//使用get方法访问后台
	            dataType: "javascript",//返回文本格式的数据
	            url: $("#url").val(),//要访问的后台地址
	            data: "action=storeTypeQuery",//要发送的数据
	            complete :function(){$("#selectStoreType").show();},//AJAX请求完成时显示提示
	            error:function(msg){alert('加载错误');},
	            success: function(msg){//msg为返回的数据,在这里做数据绑定
	            	if(msg.indexOf("1003")!=-1){
	            		$("#selectMsg").html("<font color=red>&nbsp;&nbsp;&nbsp;"+msg+"</font>");
	            		$("#selectMsg").show();
	            	}else{
	            		var msgarray = msg.split("|");
		            	var selectTypeNode = "";
		            	selectObj.options.length=0;
		            	for(var i=0;i<msgarray.length;i++){
		            		var msgelement = msgarray[i].split(",");
		            		var options = new Option(msgelement[2],msgelement[0]);
		            		selectObj.add(options);
		            	}
		            	selectTypeID = $("#selectType").val();
		            	treeNodeAjax("0","tree",selectTypeID);
	            	}
	            }
		    });
		}
		
		
		//生成树的结构
		function creatTreeNode(function_id,function_name,parent_id,function_url,count,forward_url,function_url_param){
			var htmlWrite = "";
			if(count>0){
				htmlWrite = "<li class=\"tree\" id='"+function_id+"_li' onclick=creatChildTreeNode('"+function_id+"','"+function_id+"')><a style=\"cursor: hand;\" id='"+function_id+"_href' onclick=\"locationHref('"+function_id+"','"+function_url+"','"+forward_url+"','"+function_url_param+"')\">"+function_name+"</a></li>";
			}else{
				htmlWrite = "<li><a style=\"cursor: hand;\" id='"+function_id+"_href' onclick=\"locationHref('"+function_id+"','"+function_url+"','"+forward_url+"','"+function_url_param+"')\">"+function_name+"</a></li>";
			}
			htmlWrite += "<div id='"+function_id+"' style=\"display: none\"><img src=\"<%= context %>/images/ajax-loader.gif\">请稍等...</div>";
			return htmlWrite;
		}
		
		//生成子节点,并重新给定onclick事件
		function creatChildTreeNode(functionID,nodeID,parentID){
			document.getElementById(functionID+"_li").className="notree";
			treeNodeAjax(functionID,nodeID,selectTypeID);
			document.getElementById(functionID+"_li").onclick=new Function("hideLi('"+functionID+"')");
		}
		
		function hideLi(functionID){
			document.getElementById(functionID+"_li").className="tree";
			$("#"+functionID).hide();
			document.getElementById(functionID+"_li").onclick=new Function("showLi('"+functionID+"')");
		}
		
		function showLi(functionID){
			document.getElementById(functionID+"_li").className="notree";
			$("#"+functionID).show();
			document.getElementById(functionID+"_li").onclick=new Function("hideLi('"+functionID+"')");
		}


StrutsAction代码如下,TreeAction.java:
package cn.action.tree;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import cn.bean.login.LoginBean;
import cn.dao.tree.TreeDao;

public class TreeAction extends DispatchAction {
	
	private TreeDao treeDao;
	
	public TreeDao getTreeDao() {
		return treeDao;
	}

	public void setTreeDao(TreeDao treeDao) {
		this.treeDao = treeDao;
	}
	
	Logger log = Logger.getLogger(this.getClass());
	
	//查询树节点
	public ActionForward treeQuery(ActionMapping mapping, 
							   ActionForm form,
							   HttpServletRequest request, 
							   HttpServletResponse response)throws Exception{
		HttpSession session = request.getSession();
		Object obj = session.getAttribute("userinfomation");
		LoginBean loginBean = new LoginBean();
		if(obj!=null){
			loginBean = (LoginBean)obj;
		}
		String functionID = request.getParameter("function_id");
		String storeTypeID = request.getParameter("store_type_id");
		if(storeTypeID==null){
			storeTypeID="3";
		}
		List list = this.treeDao.getTreeList(storeTypeID, functionID, loginBean.getFunction_ids());
		StringBuffer mapsb = new StringBuffer();
		response.setContentType("text/html;charset=UTF-8");
		if(list.size()>0){
			for(int i=0;i<list.size();i++){
				Map map = (Map)list.get(i);
				mapsb.append(map.get("function_id")+","+map.get("function_name")+","+map.get("parent_id")+","+map.get("function_url")+","+map.get("count")+","+map.get("forward_url")+","+map.get("function_url_param"));
				if(i!=(list.size()-1)){
					mapsb.append("|");
				}
			}
			response.getWriter().print(mapsb.toString());
		}else{
			response.getWriter().print("没有对应的信息!ErrorCode:1003");
		}
		return null;
	}
	
	//查询树节点上方的商店类型
	public ActionForward storeTypeQuery(ActionMapping mapping, 
								   ActionForm form,
								   HttpServletRequest request, 
								   HttpServletResponse response)throws Exception{
		HttpSession session = request.getSession();
		Object obj = session.getAttribute("userinfomation");
		LoginBean loginBean = new LoginBean();
		if(obj!=null){
			loginBean = (LoginBean)obj;
		}
		List list = this.treeDao.getTreeStoreType(loginBean.getStore_id());
		StringBuffer mapsb = new StringBuffer();
		response.setContentType("text/html;charset=UTF-8");
		if(list.size()>0){
			for(int i=0;i<list.size();i++){
				Map map = (Map)list.get(i);
				mapsb.append(map.get("store_type_id")+","+map.get("store_type_name")+","+map.get("store_name"));
				if(i!=(list.size()-1)){
					mapsb.append("|");
				}
			}
			response.getWriter().print(mapsb.toString());
		}else{
			response.getWriter().print("没有对应的信息!ErrorCode:1003");
		}
		return null;
	}
}



下面是Dao,TreeDao.java:
package cn.dao.tree;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.baseservice.EnterpriseService;

public class TreeDao {
	
	public EnterpriseService enterpriseService;
	
	public EnterpriseService getEnterpriseService() {
		return enterpriseService;
	}

	public void setEnterpriseService(EnterpriseService enterpriseService) {
		this.enterpriseService = enterpriseService;
	}
	
	public List getTreeList(String store_type_id,String functionID,String function_ids){
		Map paramMap = new HashMap();
		List function_ids_list = new ArrayList();
		paramMap.put("function_id", functionID);
		paramMap.put("store_type_id", store_type_id);
		String[] function_ids_array = function_ids.split(",");
		for(int i=0;i<function_ids_array.length;i++){
			function_ids_list.add(function_ids_array[i]);
		}
		paramMap.put("function_ids", function_ids_list);
		
		return enterpriseService.getList("Tree.node", paramMap);
	}
	
	public List getTreeStoreType(String stroe_id){
		Map paramMap = new HashMap();
		paramMap.put("stroe_id", stroe_id);
		return enterpriseService.getList("Tree.stroeType", paramMap);
	}
}



Ibatis,sqlconfig.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">  
<sqlMap namespace="Tree">
  <select id="node" parameterClass="java.util.HashMap" resultClass="java.util.HashMap">
  	select t.*,(SELECT COUNT(1) FROM tab_function a WHERE a.parent_id = t.function_id
  	<iterate prepend=" and a.function_id in " property="function_ids" open="(" close=")" conjunction=",">
  		#function_ids[]#
  	</iterate>
  	) AS count
  	 from tab_function t where 1=1 and t.store_type_id = #store_type_id# and t.parent_id = #function_id#
  	<iterate prepend=" and t.function_id in " property="function_ids" open="(" close=")" conjunction=",">
  		#function_ids[]#
  	</iterate>
  </select>
  
  <select id="stroeType" parameterClass="java.util.HashMap" resultClass="java.util.HashMap">
  	SELECT a.*, t.* FROM tab_store t INNER JOIN tab_store_type a ON t.store_type_id = a.store_type_id WHERE 1=1
  	<isNotEmpty prepend=" and " property="store_id">
  		t.store_id = #store_id#
  	</isNotEmpty>
  </select>
</sqlMap>


StrutsConfig配置:
<action path="/admin/treeAction" type="org.springframework.web.struts.DelegatingActionProxy" scope="request" parameter="action">
     </action>


Spring配置:
.....上面的就不写明了.....
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
		<property name="configLocation" value="/WEB-INF/config/ibatis-config/sqlmap-config.xml"/>
		<property name="dataSource" ref="dataSource"/>
	</bean>
	
	<bean id="enterpriseService" class="cn.baseservice.EnterpriseService">
        <property name="sqlMapClient" ref="sqlMapClient"/>
    </bean>
<bean id="treeDao" class="cn.dao.tree.TreeDao">
    	<property name="enterpriseService" ref="enterpriseService"/>
    </bean>
    
    <bean name="/admin/treeAction" class="cn.action.tree.TreeAction">
    	<property name="treeDao" ref="treeDao"/>
    </bean>


目前树结构没有使用css进行美化,大致的效果图如下:



工程附件及数据结构如下,可用eclipse直接打开:
  • 大小: 3.2 KB
2
4
分享到:
评论

相关推荐

    struts2+spring+ibatis+jquery ajax的登陆注册实时验证

    Struts2、Spring、iBatis和jQuery AJAX是Java Web开发中的四大核心技术,它们共同构建了一个功能强大的MVC(模型-视图-控制器)架构。本文将深入探讨这些技术在登录注册系统中的应用。 首先,Struts2是Apache基金会...

    四个struts1(2)+spring+ibatis+jquery整合实例

    Struts1(2)+Spring+Ibatis+jQuery是一个经典的Java Web开发框架组合,它们各自在Web应用的不同层面上发挥着关键作用。这个整合实例旨在展示如何将这四个技术有效地结合在一起,创建一个高效、可维护的Web应用程序...

    Jquery+Spring3+Struts2+Ibatis3框架源代码工程(含权限)

    标题 "Jquery+Spring3+Struts2+Ibatis3框架源代码工程(含权限)" 涉及的是一个基于Web开发的经典技术栈,其中包括前端的JQuery库,后端的Spring MVC、Struts2框架以及持久层的Ibatis3。这个项目提供了完整的源代码,...

    struts2+spring+mybatis+easyui的实现

    总的来说,"struts2+spring+mybatis+easyui"的实现是一个标准的Java Web项目结构,它利用Maven进行构建管理,通过整合四个组件,实现了后端的业务逻辑处理、数据访问和前端的用户界面展示。这种架构在实际开发中具有...

    struts2+ibatis+Spring+Json+jquery

    Struts2、Spring和iBatis是Java Web开发中常用的三个框架,它们分别负责不同的职责。Struts2作为MVC框架,主要处理用户请求并控制应用程序的流程;Spring则是一个全面的后端框架,提供了依赖注入、事务管理、AOP...

    struts2+spring+ibatis+jquery+json

    Struts2、Spring、iBatis和jQuery是四个在Java Web开发中广泛应用的框架和技术,它们共同构建了一个高效、灵活的后端系统,并通过JSON进行数据交互。下面将详细阐述这些技术及其相互间的整合。 **Struts2** 是一个...

    struts2+spring3+ibatis2.3+jquery_ajax1.7

    Struts2、Spring3、iBatis2.3和jQuery_AJAX1.7是经典的Java Web开发技术栈,它们各自扮演着不同的角色,构建出高效、灵活的应用系统。Struts2是一个MVC(Model-View-Controller)框架,负责处理用户请求并控制应用...

    Struts1.1+spring2.5+ibatis2.3+Ajax整合的源代码

    Struts1.1+Spring2.5+Ibatis2.3+Ajax整合是一个经典的Java Web开发框架组合,常用于构建企业级应用。这个源代码集合提供了如何将这四个技术有效地结合在一起的实例,以实现一个功能强大的、具有无刷新特性的用户界面...

    SSI(Struts2+Spring+IBatis)+Jquery做的无刷新小项目

    该项目是一个基于SSI(Struts2、Spring和iBatis)框架与jQuery技术构建的小型Web应用,主要实现了无刷新的数据增删改查功能。这里我们将深入探讨这些技术及其在项目中的应用。 首先,Struts2是Java Web开发中的一个...

    ibatis +spring+struts2+jquery.autocomplete实现产品自动补全功能(二) 附带源码

    在本项目中,"ibatis +spring+struts2+jquery.autocomplete实现产品自动补全功能(二) 附带源码",我们探讨的是如何整合四大技术来创建一个高效且用户友好的Web应用程序,特别是在搜索框中实现产品名称的自动补全...

    struts2+spring+ibatis 实例(含源码)

    Struts2、Spring和iBatis是Java Web开发中常用的三个框架,它们分别负责MVC模式中的控制器、依赖注入和数据访问层。本实例结合了这些框架,还引入了jQuery和DWR,提供了异步登录功能,对于初学者来说是一个很好的...

    struts2 spring2 ibatis2 jquery json 页面无刷新分页

    Struts2 负责请求调度,Spring2 管理业务逻辑和数据访问,iBatis2 执行SQL查询,jQuery 使用Ajax技术进行页面更新,而JSON则作为数据传输格式。这样的组合提供了高效、灵活且易于维护的解决方案,提高了Web应用的...

    Struts2.2.3Spring3.1ibatis2.0整合精典案例

    此案例是学习struts2 spring3 ibatis整合的极品案例,里面涉及到了增删改查,数据库使用oracle数据库。页面请求全部使用ajax请求,数据传输以JSON格式传输,并且使用的是struts2 的JSON技术。页面js使用Jquery1.6 ,...

    基于struts2、spring、ibatis实现的待办事宜管理系统

    这个项目是一个集成使用了Struts2、Spring和iBatis三大主流Java Web框架的待办事项管理应用。Struts2作为MVC(模型-视图-控制器)架构的实现,负责处理用户请求并转发到相应的业务逻辑;Spring框架则提供了全面的...

    javaweb,struts,spring,ibatis,hibernate,ajax等API及帮助文档

    本压缩包提供的资源涵盖了几个核心的Java Web框架和技术,包括Struts、Spring、iBatis、Hibernate以及Ajax,这些都是构建高效、动态Web应用程序的基石。下面,我们将详细探讨这些技术及其API,帮助你深入理解它们的...

    Struts spring ibatis json整合实例(附完整jar包)

    Struts2、Spring和Ibatis是Java开发中常用的三大框架,它们各自负责不同的职责:Struts2处理MVC模式中的Action层,Spring提供依赖注入和事务管理,而Ibatis则是轻量级的数据访问层,简化SQL操作。在这个整合实例中,...

    图书管理系统-BookM_Struts2_iBatis_Spring

    iBatis 是一个SQL映射框架,它允许开发者将SQL语句直接写在XML配置文件中,或者使用注解方式,与Java对象进行绑定,从而避免了JDBC代码的编写。iBatis提供了一种动态的SQL机制,可以根据条件动态生成SQL,简化了...

Global site tag (gtag.js) - Google Analytics