LayUI--动态树形菜单

发布于:2022-07-17 ⋅ 阅读:(283) ⋅ 点赞:(0)

目录

一、分析动态树形菜单

二、获取数据库表中的所有菜单数据

 1)编写实体类

 2)编写dao方法

  三、将数据在后台构建父子关系

TreeVo

BuildTree 

PermissionDao

PermissionAction 

配置xml---mvc.xml

 四、实现前端代码


一、分析动态树形菜单

MySQL中所用表t_oa_permission  表分析看图

 咱们将表中的数据展示到页面上去,像二级树形菜单那样⬇⬇⬇

 咱们可以去LayUI官方网站http://layui.org.cn/demo/index.html上去找源码

 我就用现有的了⬇⬇⬇⬇⬇

二、获取数据库表中的所有菜单数据

 1)编写实体类

package com.zking.entity;

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() {
		// TODO Auto-generated constructor stub
	}
	public Permission(long id, String name, String description, String url, long pid, int ismenu, long displayno) {
		super();
		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 "Permission [id=" + id + ", name=" + name + ", description=" + description + ", url=" + url + ", pid="
				+ pid + ", ismenu=" + ismenu + ", displayno=" + displayno + "]";
	}
}

 2)编写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.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);
	}
 
}

 此时咱们用Junit创建一个测试类测试一下

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);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 测试如下⬇⬇⬇⬇

咱们利用Junit在测试一下,是否为JSON数组

@Test
	public void testMenus() {
		try {
			List<TreeVo<Permission>> list = pd.menus(null, null);
			for (TreeVo<Permission> t : list) {
				System.out.println(t);
			}
			ObjectMapper om = new ObjectMapper();
			System.out.println(om.writeValueAsString(list));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

  三、将数据在后台构建父子关系

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) {
		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() {
		
	}
 
}

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;
	}
 
}

 PermissionDao

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>>  menu(Permission permission, PageBean pageBean) throws Exception {
		List<TreeVo<Permission>> trees = new ArrayList<TreeVo<Permission>>();
		List<Permission> list = this.list(permission, pageBean);
		for (Permission p : list) {
			TreeVo<Permission> vo = new TreeVo<>();
			vo.setId(p.getId()+"");
			vo.setText(p.getName());//节点名称
			vo.setParentId(p.getPid()+"");
			trees.add(vo);
		}
		return BuildTree.buildList(trees, "-1");
	}	
}

PermissionAction 

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.util.ResponseUtil;
import com.zking.util.TreeVo;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
 
public class PermissionAction extends ActionSupport implements ModelDriver<Permission>{
 
	private Permission permission=new Permission();
	private PermissionDao pd=new PermissionDao();
	
	@Override
	public Permission getModel() {
		return permission;
	}
 
	public String menus(HttpServletRequest req, HttpServletResponse resp) {
		try {
			List<TreeVo<Permission>> menus=pd.menus(null, null);
			//向前端响应树形结构的数据
			ResponseUtil.writeJson(resp, menus);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return super.execute(req, resp);
	}
}

 配置xml---mvc.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>

 四、实现前端代码

在上一期博客提到的主界面main.jsp中编辑前端代码,将上面提到的index.jsp记事本中的代码拷贝到main.jsp中

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet"
	href="${pageContext.request.contextPath }/static/js/layui/css/layui.css">
<!-- 引入layui.js -->
<script type="text/javascript"
	src="${pageContext.request.contextPath }/static/js/layui/layui.js"></script>
</head>
<body>
<div class="layui-layout layui-layout-admin">
  <div class="layui-header">
    <div class="layui-logo layui-hide-xs layui-bg-black">layout demo</div>
    <!-- 头部区域(可配合layui 已有的水平导航) -->
    <ul class="layui-nav layui-layout-left">
      <!-- 移动端显示 -->
      <li class="layui-nav-item layui-show-xs-inline-block layui-hide-sm" lay-header-event="menuLeft">
        <i class="layui-icon layui-icon-spread-left"></i>
      </li>
      <!-- Top导航栏 -->
      <li class="layui-nav-item layui-hide-xs"><a href="">nav 1</a></li>
      <li class="layui-nav-item layui-hide-xs"><a href="">nav 2</a></li>
      <li class="layui-nav-item layui-hide-xs"><a href="">nav 3</a></li>
      <li class="layui-nav-item">
        <a href="javascript:;">nav groups</a>
        <dl class="layui-nav-child">
          <dd><a href="">menu 11</a></dd>
          <dd><a href="">menu 22</a></dd>
          <dd><a href="">menu 33</a></dd>
        </dl>
      </li>
    </ul>
    <!-- 个人头像及账号操作 -->
    <ul class="layui-nav layui-layout-right">
      <li class="layui-nav-item layui-hide layui-show-md-inline-block">
        <a href="javascript:;">
          <img src="//tva1.sinaimg.cn/crop.0.0.118.118.180/5db11ff4gw1e77d3nqrv8j203b03cweg.jpg" class="layui-nav-img">
          tester
        </a>
        <dl class="layui-nav-child">
          <dd><a href="">Your Profile</a></dd>
          <dd><a href="">Settings</a></dd>
          <dd><a href="login.jsp">Sign out</a></dd>
        </dl>
      </li>
      <li class="layui-nav-item" lay-header-event="menuRight" lay-unselect>
        <a href="javascript:;">
          <i class="layui-icon layui-icon-more-vertical"></i>
        </a>
      </li>
    </ul>
  </div>
  
  <div class="layui-side layui-bg-black">
    <div class="layui-side-scroll">
      <!-- 左侧导航区域(可配合layui已有的垂直导航) -->
      <ul id="menu" class="layui-nav layui-nav-tree" lay-filter="menu">
      </ul>
    </div>
  </div>
  
  <div class="layui-body">
    <!-- 内容主体区域 -->
    <div style="padding: 15px;">内容主体区域。记得修改 layui.css 和 js 的路径</div>
  </div>
  
  <div class="layui-footer">
    <!-- 底部固定区域 -->
            底部固定区域
  </div>
</div>
<script type="text/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 str = '';
				$.each(data,function(i,n){
					str +='<li class="layui-nav-item layui-nav-itemed">';
					str +='		<a class="" href="javascript:;">'+data[i].text+'</a>';
					if(data[i].hasChildren){
						str +='<dl class="layui-nav-child">';
						let children = data[i].children;
						$.each(children,function(index,n){
							str +='<dd><a href="javascript:;">'+children[index].text+'</a></dd>';
							
						});
						str +='</dl>';
					}
					str +='</li>';
				});
				$('#menu').html(str);
			}
		});
	});

</script>
</body>
</html>

 前端搭建完成,咱们运行到页面看看

 

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到