layui二级菜单(动态树形结构)

11 篇文章 0 订阅

目录

一,分析

二,后台数据处理

        1.util包

        2.entity实体类

        3.dao方法

        4.web层

        5.xml配置

三,前台处理


一,分析

由图可见pid为-1为父级菜单,父级菜单的id与子菜单的pid相对应

想要的效果图   父目录下就是子目录

二,后台数据处理

        1.util包

连接数据库文件:

#mysql8
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/t280?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT&useSSL=true
user=root
pwd=123456

 DBAccess:

package com.zking.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 提供了一组获得或关闭数据库对象的方法
 * 
 */
public class DBAccess {
	private static String driver;
	private static String url;
	private static String user;
	private static String password;

	static {// 静态块执行一次,加载 驱动一次
		try {
			InputStream is = DBAccess.class
					.getResourceAsStream("config.properties");

			Properties properties = new Properties();
			properties.load(is);

			driver = properties.getProperty("driver");
			url = properties.getProperty("url");
			user = properties.getProperty("user");
			password = properties.getProperty("pwd");

			Class.forName(driver);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获得数据连接对象
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		try {
			Connection conn = DriverManager.getConnection(url, user, password);
			return conn;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public static void close(ResultSet rs) {
		if (null != rs) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(Statement stmt) {
		if (null != stmt) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(Connection conn) {
		if (null != conn) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(Connection conn, Statement stmt, ResultSet rs) {
		close(rs);
		close(stmt);
		close(conn);
	}

	public static boolean isOracle() {
		return "oracle.jdbc.driver.OracleDriver".equals(driver);
	}

	public static boolean isSQLServer() {
		return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver);
	}
	
	public static boolean isMysql() {
		return "com.mysql.cj.jdbc.Driver".equals(driver);
	}

	public static void main(String[] args) {
		Connection conn = DBAccess.getConnection();
		System.out.println(conn);
		DBAccess.close(conn);
		System.out.println("isOracle:" + isOracle());
		System.out.println("isSQLServer:" + isSQLServer());
		System.out.println("isMysql:" + isMysql());
		System.out.println("数据库连接(关闭)成功");
	}
}

BuildTree:

package com.zking.util;

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

public class BuildTree {

	/**
	 * 默认-1为顶级节点
	 * @param nodes
	 * @param <T>
	 * @return
	 */
	public static <T> TreeVo<T> build(List<TreeVo<T>> nodes) {

		if (nodes == null) {
			return null;
		}
		List<TreeVo<T>> topNodes = new ArrayList<TreeVo<T>>();

		for (TreeVo<T> children : nodes) {
			String pid = children.getParentId();
			if (pid == null || "-1".equals(pid)) {
				topNodes.add(children);

				continue;
			}

			for (TreeVo<T> parent : nodes) {
				String id = parent.getId();
				if (id != null && id.equals(pid)) {
					parent.getChildren().add(children);
					children.setHasParent(true);
					parent.setChildren(true);
					continue;
				}
			}

		}

		TreeVo<T> root = new TreeVo<T>();
		if (topNodes.size() == 1) {
			root = topNodes.get(0);
		} else {
			root.setId("000");
			root.setParentId("-1");
			root.setHasParent(false);
			root.setChildren(true);
			root.setChecked(true);
			root.setChildren(topNodes);
			root.setText("顶级节点");
			Map<String, Object> state = new HashMap<>(16);
			state.put("opened", true);
			root.setState(state);
		}

		return root;
	}

	/**
	 * 指定idparam为顶级节点
	 * @param nodes
	 * @param idParam
	 * @param <T>
	 * @return
	 */
	public static <T> List<TreeVo<T>> buildList(List<TreeVo<T>> nodes, String idParam) {
		if (nodes == null) {
			return null;
		}
		List<TreeVo<T>> topNodes = new ArrayList<TreeVo<T>>();

		for (TreeVo<T> children : nodes) {

			String pid = children.getParentId();
			if (pid == null || idParam.equals(pid)) {
				topNodes.add(children);

				continue;
			}

			for (TreeVo<T> parent : nodes) {
				String id = parent.getId();
				if (id != null && id.equals(pid)) {
					parent.getChildren().add(children);
					children.setHasParent(true);
					parent.setChildren(true);

					continue;
				}
			}

		}
		return topNodes;
	}

}

TreeVo:

package com.zking.util;

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


public class TreeVo<T> {
	/**
	 * 节点ID
	 */
	private String id;
	/**
	 * 显示节点文本
	 */
	private String text;
	/**
	 * 节点状态,open closed
	 */
	private Map<String, Object> state;
	/**
	 * 节点是否被选中 true false
	 */
	private boolean checked = false;
	/**
	 * 节点属性
	 */
	private Map<String, Object> attributes;

	/**
	 * 节点的子节点
	 */
	private List<TreeVo<T>> children = new ArrayList<TreeVo<T>>();

	/**
	 * 父ID
	 */
	private String parentId;
	/**
	 * 是否有父节点
	 */
	private boolean hasParent = false;
	/**
	 * 是否有子节点
	 */
	private boolean hasChildren = false;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public Map<String, Object> getState() {
		return state;
	}

	public void setState(Map<String, Object> state) {
		this.state = state;
	}

	public boolean isChecked() {
		return checked;
	}

	public void setChecked(boolean checked) {
		this.checked = checked;
	}

	public Map<String, Object> getAttributes() {
		return attributes;
	}

	public void setAttributes(Map<String, Object> attributes) {
		this.attributes = attributes;
	}

	public List<TreeVo<T>> getChildren() {
		return children;
	}

	public void setChildren(List<TreeVo<T>> children) {
		this.children = children;
	}

	public boolean isHasParent() {
		return hasParent;
	}

	public void setHasParent(boolean isParent) {
		this.hasParent = isParent;
	}

	public boolean isHasChildren() {
		return hasChildren;
	}

	public void setChildren(boolean isChildren) {
		this.hasChildren = isChildren;
	}

	public String getParentId() {
		return parentId;
	}

	public void setParentId(String parentId) {
		this.parentId = parentId;
	}

	public TreeVo(String id, String text, Map<String, Object> state, boolean checked, Map<String, Object> attributes,
                  List<TreeVo<T>> children, boolean isParent, boolean isChildren, String parentID) {
		super();
		this.id = id;
		this.text = text;
		this.state = state;
		this.checked = checked;
		this.attributes = attributes;
		this.children = children;
		this.hasParent = isParent;
		this.hasChildren = isChildren;
		this.parentId = parentID;
	}

	public TreeVo() {
		super();
	}

}

        2.entity实体类

构建的实体类要与表中的字段名保持一致 

 

package com.zking.entity;

//数据库中t_oa_permission对应的实体类

public class Permission {

	private long id;
	private String name;//菜单名
	private String description;//描述
	private String url;//点击菜单跳转页面
	private long pid;//父级菜单的ID
	private int ismenu;//菜单/按钮
	private long displayno;//显示的顺序
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public long getPid() {
		return pid;
	}
	public void setPid(long pid) {
		this.pid = pid;
	}
	public int getIsmenu() {
		return ismenu;
	}
	public void setIsmenu(int ismenu) {
		this.ismenu = ismenu;
	}
	public long getDisplayno() {
		return displayno;
	}
	public void setDisplayno(long displayno) {
		this.displayno = displayno;
	}
	
	public Permission() {

	}
	public Permission(long id, String name, String description, String url, long pid, int ismenu, long displayno) {
		this.id = id;
		this.name = name;
		this.description = description;
		this.url = url;
		this.pid = pid;
		this.ismenu = ismenu;
		this.displayno = displayno;
	}
	
	@Override
	public String toString() {
		return "PermissionDao [id=" + id + ", name=" + name + ", description=" + description + ", url=" + url + ", pid="
				+ pid + ", ismenu=" + ismenu + ", displayno=" + displayno + "]";
	}
	
}

        3.dao方法

package com.zking.dao;

import java.util.ArrayList;
import java.util.List;

import com.zking.entity.Permission;
import com.zking.util.BaseDao;
import com.zking.util.BuildTree;
import com.zking.util.PageBean;
import com.zking.util.TreeVo;

public class PermissionDao extends BaseDao<Permission>{

	//查询t_oa_permission表中的数据
	public List<Permission> list(Permission permission,PageBean pageBean) throws Exception{
		String sql = "select * from t_oa_permission";
		return super.executeQuery(sql, Permission.class, pageBean);
	}
	
	public List<TreeVo<Permission>> menus(Permission permission,PageBean pageBean) throws Exception{
		List<TreeVo<Permission>> trees = new ArrayList<TreeVo<Permission>>();
		//从数据库中拿到的菜单数据,此时数据是平级的,不具备父子关系
		List<Permission> list = this.list(permission, pageBean);
		for (Permission permission2 : list) {
			TreeVo<Permission> vo = new TreeVo<>();
			vo.setId(permission2.getId()+"");
			vo.setText(permission2.getName());//节点名称
			vo.setParentId(permission2.getPid()+"");
			trees.add(vo);
		}
		return BuildTree.buildList(trees, "-1");
	}
	
}

可以测试一下:

 

test测试:

package com.zking.dao;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zking.entity.Permission;
import com.zking.util.TreeVo;

public class PermissionDaoTest {
	private PermissionDao permissionDao = new PermissionDao();
	
	
	@Before
	public void setUp() throws Exception{
		
	}
	
	@After
	public void tearDown() throws Exception{
		
	}
	
	@Test
	public void testList() {
		
		try {
			List<Permission> list = permissionDao.list(null, null);
			for (Permission permission : list) {
				System.out.println(permission);
			}
			ObjectMapper om = new ObjectMapper();
			System.out.println(om.writeValueAsString(list));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
//		fail("Not yet implemented");
	}
	
	
	@Test
	public void testMenus() {
		
		try {
			List<TreeVo<Permission>> list = permissionDao.menus(null, null);
			for (TreeVo<Permission> Permission : list) {
				System.out.println(Permission);
			}
			ObjectMapper om = new ObjectMapper();
			System.out.println(om.writeValueAsString(list));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}

        4.web层

package com.zking.web;

import java.util.List;

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

import com.zking.dao.PermissionDao;
import com.zking.entity.Permission;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.ResponseUtil;
import com.zking.util.TreeVo;

public class PermissionAction extends ActionSupport implements ModelDriver<Permission>{

	private Permission permission = new Permission();
	private PermissionDao permissionDao = new PermissionDao();
	
	
	
	@Override
	public Permission getModel() {
		// TODO Auto-generated method stub
		return permission;
	}
	
	
	public String menus(HttpServletRequest req,HttpServletResponse resp) {
		try {
			List<TreeVo<Permission>> menus = permissionDao.menus(null,null);
			System.out.println(menus);
			//向前端响应树形结构的数据
			ResponseUtil.writeJson(resp, menus);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	

}

        5.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<config>
	<action path="/blog" type="com.zking.web.BlogAction">
		<forward name="list" path="/blogList.jsp" redirect="false" />
		<forward name="toList" path="/blog.action?methodName=list"
			redirect="true" />
		<forward name="toEdit" path="/blogEdit.jsp" redirect="false" />
	</action>


	<action path="/user" type="com.zking.web.UserAction">
	</action>

	<action path="/permission" type="com.zking.web.PermissionAction">
	</action>

</config>

配置一个路径: 

 

三,前台处理

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%@include file="commom/header.jsp" %>
<!DOCTYPE >
<html>
<head>
<title>Insert title here</title>
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
  <div class="layui-header">
    <div class="layui-logo">layui 后台布局</div>
    <!-- 头部区域(可配合layui已有的水平导航) -->
    <ul class="layui-nav layui-layout-left">
      <li class="layui-nav-item"><a href="">控制台</a></li>
      <li class="layui-nav-item"><a href="">商品管理</a></li>
      <li class="layui-nav-item"><a href="">用户</a></li>
      <li class="layui-nav-item">
        <a href="javascript:;">其它系统</a>
        <dl class="layui-nav-child">
          <dd><a href="">邮件管理</a></dd>
          <dd><a href="">消息管理</a></dd>
          <dd><a href="">授权管理</a></dd>
        </dl>
      </li>
    </ul>
    
    <!-- 登录用户信息 -->
    <ul class="layui-nav layui-layout-right">
      <li class="layui-nav-item">
        <a href="javascript:;"><img src="http://t.cn/RCzsdCq" class="layui-nav-img">贤心</a>
        <dl class="layui-nav-child">
          <dd><a href="">基本资料</a></dd>
          <dd><a href="">安全设置</a></dd>
        </dl>
      </li>
      <li class="layui-nav-item"><a href="">退了</a></li>
    </ul>
    
  </div>
  
  <div class="layui-side layui-bg-black">
    <div class="layui-side-scroll">
      <!-- 左侧导航区域(可配合layui已有的垂直导航) -->
      <ul class="layui-nav layui-nav-tree" id="menu" lay-filter="test">
       
      </ul>
    </div>
  </div>
  
  <div class="layui-body">
    <!-- 内容主体区域 -->
    <div style="padding: 0px;">
    	<div class="layui-tab" style="margin-top:0px;">
		  <ul class="layui-tab-title">
		    <li class="layui-this">网站设置</li>
		    <li>用户管理</li>
		    <li>权限分配</li>
		    <li>商品管理</li>
		    <li>订单管理</li>
		  </ul>
		  <div class="layui-tab-content">
		    <div class="layui-tab-item layui-show">内容1</div>
		    <div class="layui-tab-item">内容2</div>
		    <div class="layui-tab-item">内容3</div>
		    <div class="layui-tab-item">内容4</div>
		    <div class="layui-tab-item">内容5</div>
		  </div>
		</div>
    </div>
  </div>
  
  <div class="layui-footer">
    <!-- 底部固定区域 -->
    © layui.com - 底部固定区域
  </div>
</div>
<script>
//JavaScript代码区域
layui.use(['jquery'], function(){
 	let $ = layui.jquery;
 	$.ajax({
 		url:'${pageContext.request.contextPath }/permission.action?methodName=menus',
 		dataType:'json',
 		success:function(data){
 			console.log(data);
 			let htmlstr='';
 			$.each(data,function(i,n){
 				htmlstr +='<li class="layui-nav-item layui-nav-itemed">';
 				htmlstr +='<a class="" href="javascript:;">'+data[i].text+'</a>';
 				//判断节点是否存在子节点
 				if(data[i].hasChildren){
 					htmlstr +='<dl class="layui-nav-child">';
 					let children = data[i].children;
 					$.each(data,function(index,node){
 						htmlstr +='<dd><a href="javascript:;">'+children[index].text+'</a></dd>';
 					});
 					htmlstr +='</dl>';
 				}
 				htmlstr +='</li>';
 			});
 			$("#menu").html(htmlstr);
 		}
 	});
  
});
</script>
</body>
</html>

效果图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值