Layui精简版,快速入门

目录

LayUI之入门

1.什么是layui

2.layui入门

3.自定义模块

4.用户登录

5.主页搭建

LayUI之动态树

main.jsp

main.js

LayUI之动态选项卡

1.选项卡

main.jsp

main.js

2.用户登录

User.java

UserDao.java

UserAction.java

R.java

LayUI之用户管理

1.用户查询

[2.case when的处理](#2.case when的处理)

UserDao.java

UserAction.java

userManage.jsp

userManage.js

3.用户新增

UserAction.java

userManage.js

userEdit.jsp

userEdit.js

4.用户修改

5.用户删除

userManage.js


LayUI之入门


1.什么是layui

2.layui入门

3.自定义模块

参考 模块规范

4.用户登录

这里没有与数据库进行交互

5.主页搭建

参考网站布局

LayUI之动态树

思路

  1. 静态页面数据是什么样?
  2. 分析需要什么样的数据?
  3. 我们如何得到这些数据?
  4. 将现有的数据如何转换成我们需要的数据?
  5. 将具有层级关系的数据渲染成树形结构.

main.jsp

<div class="layui-side layui-bg-black">
    <div class="layui-side-scroll">
      <!-- 左侧导航区域(可配合layui已有的垂直导航) -->
      <ul class="layui-nav layui-nav-tree" lay-filter="test" id="layui_menus">
        <li class="layui-nav-item layui-nav-itemed">
          <a class="" href="javascript:;">menu group 1</a>
          <dl class="layui-nav-child">
            <dd><a href="javascript:;" onclick="openTab('','','')">menu 1</a></dd>
            <dd><a href="javascript:;">menu 2</a></dd>
            <dd><a href="javascript:;">menu 3</a></dd>
            <dd><a href="">the links</a></dd>
          </dl>
        </li>
        <li class="layui-nav-item">
          <a href="javascript:;">menu group 2</a>
          <dl class="layui-nav-child">
            <dd><a href="javascript:;">list 1</a></dd>
            <dd><a href="javascript:;">list 2</a></dd>
            <dd><a href="">超链接</a></dd>
          </dl>
        </li>
        <li class="layui-nav-item"><a href="javascript:;">click menu item</a></li>
        <li class="layui-nav-item"><a href="">the links</a></li>
      </ul>
    </div>
  </div>

此处后台代码...

main.js

let layer,$,element;
layui.use(['jquery', 'layer', 'element'], function(){
	layer = layui.layer
	,$ = layui.jquery
	,element = layui.element;
	$.ajax({
		url:'${pageContext.request.contextPath }/permission.action?methodName=menus'
		,dataType:'json'
		,success:function(data){
			let htmlstr = '';
			let json = data.data;
			$.each(json,function(i,n){
				htmlstr += '<li class="layui-nav-item layui-nav-itemed">';
				htmlstr += ' <a class="" href="javascript:;">'+json[i].text+'</a>';
				if(json[i].hasChildren){
					let children = json[i].children;
					$.each(children,function(index,node){
						htmlstr += '<dl class="layui-nav-child">';
						htmlstr += '<dd><a href="javascript:;" onclick="openTab(\''+children[index].text+'\',\''+children[index].attributes.self.url+'\',\''+children[index].id+'\');" >'+children[index].text+'</a></dd>';
						htmlstr += '</dl>';
					});
				}
				htmlstr += '</li>';
			})
			$("#layui_menus").html(htmlstr);
		}
	});
	
});

LayUI之动态选项卡

思路

  1. 选项卡简介
  2. 动态添加选项卡
  3. 重复选项卡的限定
  4. 切换指定选项卡
  5. 选项卡样式
  6. 用户登录-结果返回R类的增强

1.选项卡

<style>
	.layui-tab-title>li:first-child>i{
		display:none;
	}
	.layui-tab>.layui-tab-content{
		padding:0px;
	}
	body,html{
		padding:0px;
		margin:0px;
		overflow:hidden;
	}
</style>

main.jsp

<div class="layui-body">
    <!-- 内容主体区域 -->
    <div style="padding: 15px;">
    	<div class="layui-tab" lay-filter="openTab" lay-allowclose="true">
		  <ul class="layui-tab-title">
		    <li class="layui-this" lay-id="-1">首页</li>
		  </ul>
		  <div class="layui-tab-content">
		    <div class="layui-tab-item layui-show">首页内容</div>
		  </div>
		</div>
    </div>

main.js

function openTab(title,url,id){
	let $node = $("li[lay-id='"+id+"']");
	if($node.length == 0){
		element.tabAdd('openTab', {
	      title: title
	      ,content: "<iframe frameborder='0' src='"+url+"' scrolling='auto' style='width:100%;height:100%;'></iframe>"
	      ,id: id
	    })
	}
	element.tabChange('openTab', id); //切换到:用户管理
}

2.用户登录

User.java

package com.zking.entity;

public class User {
    private Long id;

    private String name;

    private String loginName;

    private String pwd;

    private Long rid;

	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 getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public Long getRid() {
		return rid;
	}

	public void setRid(Long rid) {
		this.rid = rid;
	}

	public User() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", loginName=" + loginName + ", pwd=" + pwd + ", rid=" + rid + "]";
	}
    
    
}

UserDao.java

package com.zking.dao;

import java.util.List;

import com.zking.entity.User;
import com.zking.util.BaseDao;
import com.zking.util.PageBean;
import com.zking.util.StringUtils;

public class UserDao extends BaseDao<User> {
	public User login(User user, PageBean pageBean) throws Exception {
		String loginName = user.getLoginName();
		String pwd = user.getPwd();
		String sql = "select * from t_oa_user where loginname = '" + loginName + "' and pwd = '"+pwd+"'";
		List<User> users = super.executeQuery(sql, User.class, pageBean);
		return users == null || users.size() == 0 ? null : users.get(0);
	}
}

UserAction.java

package com.zking.web;

import java.util.List;

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

import com.zking.dao.UserDao;
import com.zking.entity.User;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.CommonUtils;
import com.zking.util.PageBean;
import com.zking.util.R;
import com.zking.util.ResponseUtil;

public class UserAction extends ActionSupport implements ModelDriver<User> {
	private User user = new User();
	private UserDao userDao = new UserDao();

	public String login(HttpServletRequest req, HttpServletResponse resp) {
		try {
			User u = userDao.login(user, null);
			if (u != null) {
				ResponseUtil.writeJson(resp, R.ok(200, "登录成功"));
				req.getSession().setAttribute("user", u);
			}else {
				ResponseUtil.writeJson(resp, R.error(0, "登录失败"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			try {
				ResponseUtil.writeJson(resp, R.error(0, "登录失败"));
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public User getModel() {
		return user;
	}
}

R.java

package com.zking.util;

import java.util.HashMap;

public class R extends HashMap{
	public R data(String key, Object value) {
		this.put(key, value);
		return this;
	}
	
	public static R ok(int code, String msg) {
		R r = new R();
		r.data("success", true).data("code", code).data("msg", msg);
		return r;
	}
	
	public static R error(int code, String msg) {
		R r = new R();
		r.data("success", false).data("code", code).data("msg", msg);
		return r;
	}
	
	public static R ok(int code, String msg,Object data) {
		R r = new R();
		r.data("success", true).data("code", code).data("msg", msg).data("data", data);
		return r;
	}
	
	public static R ok(int code, String msg, long count, Object data) {
		R r = new R();
		r.data("success", true).data("code", code).data("msg", msg).data("count", count).data("data", data);
		return r;
	}
}

LayUI之用户管理

思路

  1. 用户查询
  2. 用户角色case when后台处理
  3. 用户新增
  4. 用户修改
  5. 用户删除

1.用户查询

2.case when的处理

UserDao.java

	public List<User> list(User user, PageBean pageBean) throws Exception {
		String sql = "select * from t_oa_user where 1=1 ";
		String name = user.getName();
		if (StringUtils.isNotBlank(name))
			sql += " and name like '%" + name + "%'";
		return super.executeQuery(sql, User.class, pageBean);
	}
	
	public List<Map<String, Object>> listUserRole(User user, PageBean pageBean) throws Exception {
		String sql = "select *,\r\n" + 
				"(case rid\r\n" + 
				"when 1 then '管理人员'\r\n" + 
				"when 4 then '参与者'\r\n" + 
				"else '其他角色' end) as rname\r\n" + 
				"from t_oa_user ";
		String name = user.getName();
		if (StringUtils.isNotBlank(name))
			sql += " and name like '%" + name + "%'";
		return super.executeQuery(sql, pageBean);
	}
	
	public int add(User user) throws Exception {
		String sql = "insert into t_oa_user(name,loginName,pwd) values(?,?,?)";
		return super.executeUpdate(sql, user, new String[] {"name","loginName","pwd"});
	}
	
	public int edit(User user) throws Exception {
		String sql = "update t_oa_user set name = ?,loginName = ?,pwd = ? where id = ?";
		return super.executeUpdate(sql, user, new String[] {"name","loginName","pwd","id"});
	}
	
	public int del(User user) throws Exception {
		String sql = "delete from t_oa_user where id = ?";
		return super.executeUpdate(sql, user, new String[] {"id"});
	}

UserAction.java

public String listUserRole(HttpServletRequest req, HttpServletResponse resp) {
		try {
			PageBean pageBean = new PageBean();
			pageBean.setRequest(req);
			List<Map<String, Object>> users = userDao.listUserRole(user, pageBean);
//			layui 的code 返回一定要是 0,不能是200,否者返回不了数据
			ResponseUtil.writeJson(resp, R.ok(0, "查询成功", pageBean.getTotal(), users));
		} catch (Exception e) {
			e.printStackTrace();
			try {
				ResponseUtil.writeJson(resp, R.error(0, "查询失败"));
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

userManage.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@include file="/common/head.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/system/userManage.js"></script>
<title>用户管理</title>
</head>
<body>
	<!-- 搜索栏 -->
	<div class="layui-form-item">
	  <div class="layui-inline">
	    <label class="layui-form-label">用户名:</label>
	    <div class="layui-input-inline">
	      <input type="text" id="name" placeholder="请输入用户名" autocomplete="off" class="layui-input">
	    </div>
	  </div>
	  
	  <div class="layui-inline">
	    <div class="layui-input-inline">
	      <button id="btn_search" type="button" class="layui-btn layui-btn-normal">
	      	<i class="layui-icon layui-icon-search"></i>
	      	查询
	      </button>
	      <button id="btn_add" type="button" class="layui-btn">新增</button>
	    </div>
	  </div>
	  
	</div>
	<!-- 数据表格及分页 -->
	<table id="tb" lay-filter="tb" class="layui-table" style="margin-top:-15px;"></table>
	<!-- 对话框(新增和编辑共用一个页面) -->
	
	<script type="text/html" id="toolbar">
 		<button class="layui-btn layui-btn-sm" lay-event="edit">编辑</button>
 		<button class="layui-btn layui-btn-sm" lay-event="del">删除</button>
 		<button class="layui-btn layui-btn-sm" lay-event="reset">重置密码</button>
	</script>
</body>
</html>

userManage.js

let layer,$,table;
layui.use(['jquery', 'layer', 'table'], function(){
	layer = layui.layer
	,$ = layui.jquery
	,table = layui.table;
	//初始化数据表格
	initTable();
	//绑定查询按钮的点击事件
	$('#btn_search').click(function(){
		query();
	});
});


//1.初始化数据表格
function initTable(){
	table.render({           //执行渲染
        elem: '#tb',         //指定原始表格元素选择器(推荐id选择器)
//        url: 'user.action?methodName=list',     //请求地址
        height: 340,         //自定义高度
        loading: false,      //是否显示加载条(默认 true)
        cols: [[             //设置表头
            {field: 'id', title: '用户编号', width: 120},
            {field: 'name', title: '用户名', width: 120},
            {field: 'loginName', title: '登录账号', width: 140},
            {field: '', title: '操作', width: 220,toolbar:'#toolbar'},
        ]]
    });
	
}
//2.点击查询
function query(){
	table.reload('tb', {
        url: $("#ctx").val()+'/user.action',     //请求地址
        method: 'POST',                    //请求方式,GET或者POST
        loading: true,                     //是否显示加载条(默认 true)
        page: true,                        //是否分页
        where: {                           //设定异步数据接口的额外参数,任意设
        	'methodName':'listUserRole',
        	'name':$('#name').val()
        },  
        request: {                         //自定义分页请求参数名
            pageName: 'page', //页码的参数名称,默认:page
            limitName: 'rows' //每页数据量的参数名,默认:limit
        }
   });
}

3.用户新增

UserAction.java

public String add(HttpServletRequest req, HttpServletResponse resp) {
		try {
			int rs = userDao.add(user);
			if (rs > 0) {
				ResponseUtil.writeJson(resp, R.ok(200, "用户新增成功"));
			}else {
				ResponseUtil.writeJson(resp, R.error(0, "用户新增失败"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			try {
				ResponseUtil.writeJson(resp, R.error(0, "用户新增失败"));
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}
	
	public String edit(HttpServletRequest req, HttpServletResponse resp) {
		try {
			int rs = userDao.edit(user);
			if (rs > 0) {
				ResponseUtil.writeJson(resp, R.ok(200, "用户修改成功"));
			}else {
				ResponseUtil.writeJson(resp, R.error(0, "用户修改失败"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			try {
				ResponseUtil.writeJson(resp, R.error(0, "用户修改失败"));
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}
	
	public String del(HttpServletRequest req, HttpServletResponse resp) {
		try {
			int rs = userDao.del(user);
			if (rs > 0) {
				ResponseUtil.writeJson(resp, R.ok(200, "用户删除成功"));
			}else {
				ResponseUtil.writeJson(resp, R.error(0, "用户删除失败"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			try {
				ResponseUtil.writeJson(resp, R.error(0, "用户删除失败"));
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

userManage.js

let layer,$,table;
var row;
layui.use(['jquery', 'layer', 'table'], function(){
	layer = layui.layer
	,$ = layui.jquery
	,table = layui.table;
	//初始化数据表格
	initTable();
	//绑定查询按钮的点击事件
	$('#btn_search').click(function(){
		query();
	});
	
	//绑定新增按钮的点击事件
	$('#btn_add').click(function(){
		row=null;
		open('新增');
	});
});

//3.对话框
function open(title){
    layer.open({
       type: 2,                    //layer提供了5种层类型。可传入的值有:0(信息框,默认)1(页面层)2(iframe层)3(加载层)4(tips层)
       title:title,
       area: ['660px', '340px'],   //宽高
       skin: 'layui-layer-rim',    //样式类名
       content:  $("#ctx").val()+'/jsp/system/userEdit.jsp', //书本编辑页面
       btn:['保存','关闭'],
       yes: function(index, layero){
    	   //调用子页面中提供的getData方法,快速获取子页面的form表单数据
           let data= $(layero).find("iframe")[0].contentWindow.getData();
           console.log(data);
           //判断title标题
           let methodName="add";
           if(title=="编辑")
        	   methodName="edit";
           $.post($("#ctx").val()+'/user.action?methodName='+methodName,
        		   data,function(rs){
        	   if(rs.success){
        		   //关闭对话框
        		   layer.closeAll();
        		   //调用查询方法刷新数据
        		   query();
        	   }else{
        		   layer.msg(rs.msg,function(){});
        	   }
           },'json');
       },
       btn2: function(index, layero){
    	   layer.closeAll();
       }
    });
 }

userEdit.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@include file="/common/head.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/system/userEdit.js"></script>
<title>用户新增</title>
</head>
<style>
.layui-form-select dl{
	max-height:150px;
}
</style>
<body>
<div style="padding:10px;">
    <form class="layui-form layui-form-pane" lay-filter="user">
        <input type="hidden" name="id"/>
        <div class="layui-form-item">
            <label class="layui-form-label">用户名称</label>
            <div class="layui-input-block">
                <input type="text" id="name" name="name" autocomplete="off" placeholder="请输入用户名" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户角色</label>
            <div class="layui-input-block">
                <select name="rid">
                    <option value="">---请选择---</option>
                    <option value="1">管理员</option>
                    <option value="2">发起者</option>
                    <option value="3">审批者</option>
                    <option value="4">参与者</option>
                    <option value="5">会议管理员</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">登录账号</label>
            <div class="layui-input-block">
                <input type="text" name="loginName" lay-verify="required" placeholder="请输入账号" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">登录密码</label>
            <div class="layui-input-block">
                <input type="password" name="pwd" placeholder="请输入密码" autocomplete="off" class="layui-input">
            </div>
        </div>
    </form>
</div>
</body>
</html>

userEdit.js

let layer,form,$;
layui.use(['layer','form','jquery'],function(){
	layer=layui.layer,form=layui.form,$=layui.jquery;
	initData();
});

function initData(){
	console.log(parent.row);
	if(null!=parent.row){
	     //因为layui.each内部的逻辑问题导致的所以要先深拷贝一份然后再去val
	     //parent.row:表格行对象
	     form.val('user',$.extend({}, parent.row||{}));
	     $('#name').attr('readonly','readonly');
	}
}

function getData(){
    return form.val('user');
}

4.用户修改

5.用户删除

userManage.js

//1.初始化数据表格
function initTable(){
	table.render({           //执行渲染
        elem: '#tb',         //指定原始表格元素选择器(推荐id选择器)
//        url: 'user.action?methodName=list',     //请求地址
        height: 340,         //自定义高度
        loading: false,      //是否显示加载条(默认 true)
        cols: [[             //设置表头
            {field: 'id', title: '用户编号', width: 120},
            {field: 'name', title: '用户名', width: 120},
            {field: 'loginName', title: '登录账号', width: 140},
            {field: '', title: '操作', width: 220,toolbar:'#toolbar'},
        ]]
    });
	
	//在页面中的<table>中必须配置lay-filter="tb_goods"属性才能触发属性!!!
	table.on('tool(tb)', function (obj) {
		row = obj.data;
		if (obj.event == "edit") {
			open("编辑");
		}else if(obj.event == "del"){
			layer.confirm('确认删除吗?', {icon: 3, title:'提示'}, function(index){
			  $.post($("#ctx").val()+'/user.action',{
				  'methodName':'del',
				  'id':row.id
			  },function(rs){
				  if(rs.success){
	        		   //调用查询方法刷新数据
	        		   query();
	        	   }else{
	        		   layer.msg(rs.msg,function(){});
	        	   }
			  },'json');
			  layer.close(index);
			});
		}else{

		}
	});
	
}
相关推荐
CT随7 分钟前
Redis内存碎片详解
java·开发语言
brrdg_sefg16 分钟前
gitlab代码推送
java
hanbarger39 分钟前
mybatis框架——缓存,分页
java·spring·mybatis
cdut_suye1 小时前
Linux工具使用指南:从apt管理、gcc编译到makefile构建与gdb调试
java·linux·运维·服务器·c++·人工智能·python
苹果醋31 小时前
2020重新出发,MySql基础,MySql表数据操作
java·运维·spring boot·mysql·nginx
小蜗牛慢慢爬行1 小时前
如何在 Spring Boot 微服务中设置和管理多个数据库
java·数据库·spring boot·后端·微服务·架构·hibernate
azhou的代码园1 小时前
基于JAVA+SpringBoot+Vue的制造装备物联及生产管理ERP系统
java·spring boot·制造
18号房客1 小时前
macOS开发环境配置与应用开发教程(一)
vscode·macos·visualstudio·eclipse·intellij-idea·phpstorm·visual studio
wm10432 小时前
java web springboot
java·spring boot·后端
smile-yan2 小时前
Provides transitive vulnerable dependency maven 提示依赖存在漏洞问题的解决方法
java·maven