spring boot+layui实现增删改查实战
说明:
最近在做一个后台,希望用一个现成的前端模板,找了一圈发现Layui比较合适。我知道很多人都有这个需求,为了使大家快速上手,我把自己写的最实用的增删改查案例完整的展示出来。
源码地址:
https://gitee.com/indexman/boot-layui-curd
Layui官网:https://www.layui.com/doc/
后台:spring boot2.0,数据的话用的list没连接数据库。
前端:layui-v2.5.5
启动后访问: http://localhost:8080/admin.html
页面展示:
操作展示:
开发步骤:
1.搭建spring boot工程,引入layui资源
这一步很简单, 我就省了。
2.编写前端页面admin.html
这一步可以拿网上的直接改的。改过之后如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>layout 后台大布局 - Layui</title>
<link rel="stylesheet" href="js/layui/css/layui.css">
</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" lay-filter="test">
<li class="layui-nav-item layui-nav-itemed">
<a class="" href="javascript:;">所有商品</a>
<dl class="layui-nav-child">
<dd>
<a href="javascript:;">列表一</a>
</dd>
<dd>
<a href="javascript:;">列表二</a>
</dd>
<dd>
<a href="javascript:;">列表三</a>
</dd>
<dd>
<a href="http://www.baidu.com">超链接</a>
</dd>
</dl>
</li>
<li class="layui-nav-item">
<a href="javascript:;">解决方案</a>
<dl class="layui-nav-child">
<dd>
<a href="javascript:;">列表一</a>
</dd>
<dd>
<a href="javascript:;">列表二</a>
</dd>
<dd>
<a href="">超链接</a>
</dd>
</dl>
</li>
<li class="layui-nav-item">
<a href="">云市场</a>
</li>
<li class="layui-nav-item">
<a href="">发布商品</a>
</li>
</ul>
</div>
</div>
<div class="layui-body">
<!-- 内容主体区域 -->
<div style="padding: 15px;">
<!--<div class="demoTable" style="padding: 15px">
搜索:
<div class="layui-inline">
<input class="layui-input" id="find" autocomplete="off">
</div>
<button class="layui-btn" data-type="reload" id="queryRole">搜索</button>
</div>-->
<table id="tb-user" lay-filter="tb-user"></table>
</div>
</div>
<!--编辑表单-->
<div class="layui-row" id="editUser" style="display:none;">
<div class="layui-col-md10">
<form class="layui-form layui-from-pane" id="saveUser" style="margin-top:20px">
<div class="layui-form-item">
<label class="layui-form-label">用户名</label>
<div class="layui-input-block">
<input type="text" name="name" id="name" required lay-verify="required" autocomplete="off"
class="layui-input">
</div>
</div>
<input type="hidden" name="id" id="id">
<div class="layui-form-item">
<label class="layui-form-label">城市</label>
<div class="layui-input-block">
<input type="text" name="city" id="city" required lay-verify="required" 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="text" name="birthday" id="birthday" required lay-verify="required" autocomplete="off"
class="layui-input">
</div>
</div>
<div class="layui-form-item" style="margin-top:40px" id="check">
<div class="layui-input-block">
<button class="layui-btn layui-btn-submit " lay-submit="" lay-filter="saveUser">保存</button>
<!--<button type="reset" class="layui-btn layui-btn-primary">重置</button>-->
</div>
</div>
</form>
</div>
</div>
<script type="text/html" id="toolbarDemo">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="add"><i class="layui-icon"></i>新增</button>
<button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="remove"><i class="layui-icon"></i>删除</button>
</div>
<!--<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
<button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
<button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
</div>-->
</script>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-sm" lay-event="edit"><i class="layui-icon"></i> </a>
</script>
<div class="layui-footer">
<!-- 底部固定区域 -->
© layui.com - 底部固定区域
</div>
</div>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/layui/layui.all.js"></script>
<script>
var element, layer, laydate, table, form;
$(function () {
// 使用模块
layui.use(['element', 'layer', 'laydate', 'table','form'], function () {
element = layui.element;
layer = layui.layer;
laydate = layui.laydate;
table = layui.table;
form = layui.form;
});
laydate.render({
elem:"#birthday",
type: "date",
format:"yyyy-MM-dd",
value: ''
});
//第一个实例
var userTable = table.render({
elem: '#tb-user'
, height: 515
, url: '/api/layui/user/list' //数据接口
, page: true //开启分页
, toolbar: '#toolbarDemo'
/*, response: {
statusName: 'code', //规定返回的状态码字段为code
statusCode: 200 //规定成功的状态码味200
}*/
/* , parseData: function (res) {
return {
"code": res.code, //解析接口状态
"msg": res.msg, //解析提示文本
"data": res.data //解析数据列表
}
}*/
, cols: [[ //表头
{type: 'checkbox', fixed: 'left'}
, {field: 'id', title: 'ID', width: 80, sort: true, fixed: 'left'}
, {field: 'name', title: '用户名'}
, {field: 'city', title: '城市'}
, {
field: 'birthday', title: '出生日期', templet: function (d) {
var date = new Date(d.birthday)
var year = date.getFullYear() + '年';
var month = date.getMonth() + 1 + '月';
var date = date.getDate() + '日';
var date1 = [year, month, date].join('')
return date1;
}
}
, {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 120}
]]
});
//监听表单提交
// 修改
form.on('submit(saveUser)', function(data){
layer.alert(JSON.stringify(data.field));
$.ajax({
url: '/api/layui/user/save',
type: 'POST',
contentType: "application/json",
dataType: "json",
data: JSON.stringify(data.field),
success: function (result) {
if (result.code == 200) {
// layer.msg("修改成功!", {icon: 6});
setTimeout(function () {
layer.closeAll();//关闭所有的弹出层
userTable.reload();
}, 300);
} else {
layer.msg("操作失败!", {icon: 5});
}
}
});
return false;
});
//工具栏事件
table.on('toolbar(tb-user)', function (obj) {
var checkStatus = table.checkStatus(obj.config.id);
var checkData = checkStatus.data;
var ids=[];
switch (obj.event) {
// 新增
case 'add':
$("#name").val('');
$("#city").val('');
$("#id").val('');
$("#birthday").val('');
layer.open({
type: 1,
offset: '10px',
title: "新增用户",
area: ['500px', '400px'],
content: $("#editUser")
});
break;
// 删除
case 'remove':
if(checkData.length==0){
layer.alert('请选择要操作的行');
}else{
layer.confirm('确定要删除吗?',function (index) {
for(var i=0; i<checkData.length;i++){
ids.push(checkData[i].id);
}
//layer.alert(JSON.stringify(ids));
$.ajax({
url: '/api/layui/user/remove',
type: 'POST',
contentType: "application/json",
dataType: "json",
data: JSON.stringify(ids),
success: function (result) {
if (result.code == 200) {
setTimeout(function () {
layer.closeAll();//关闭所有的弹出层
userTable.reload();
}, 300);
}
}
});
});
}
break;
case 'getCheckData':
layer.alert(JSON.stringify(data));
break;
case 'getCheckLength':
var data = checkStatus.data;
layer.msg('选中了:' + data.length + ' 个');
break;
case 'isAll':
layer.msg(checkStatus.isAll ? '全选' : '未全选')
break;
}
;
});
// 监听工具条
table.on('tool(tb-user)', function (obj) {
var data = obj.data;
// 修改
if (obj.event === 'edit') {
$("#name").val(data.name);
$("#city").val(data.city);
$("#id").val(data.id);
$("#birthday").val(data.birthday);
layer.open({
type: 1,
offset: '10px',
title: "修改用户",
area: ['500px', '400px'],
content: $("#editUser")
});
}
});
});
</script>
</body>
</html>
3.编写后端代码
3.1 创建用户实体
package com.laoxu.test.helloweb.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
/**
* @Description: 用户实体
* @Author laoxu
* @Date 2019/12/21 9:56
**/
@Data
public class LayuiUser {
private int id;
private String name;
private String city;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd")
private Date birthday;
public LayuiUser(){}
public LayuiUser(int id, String name, String city, Date birthday) {
this.id = id;
this.name = name;
this.city = city;
this.birthday = birthday;
}
}
3.2 创建用户DAO
package com.laoxu.test.helloweb.dao;
import com.laoxu.test.helloweb.entity.LayuiUser;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* @Description: 操作用户数据
* @Author laoxu
* @Date 2019/12/21 10:07
**/
@Repository
public class LayuiUserDao {
private static List<LayuiUser> users = new ArrayList<>();
static {
for (int i = 1; i <= 100; i += 3) {
users.add(new LayuiUser(i, "张三" + i, "上海", new Date()));
users.add(new LayuiUser(i + 1, "李四" + i, "北京", new Date()));
users.add(new LayuiUser(i + 2, "王二麻" + i, "广州", new Date()));
}
}
//http://www.layui.com/demo/table/user/?page=1&limit=10
/**
* 获得所有用户
*/
public List<LayuiUser> getPager(int page, int limit) {
List<LayuiUser> list = new ArrayList<>();
int start = (page - 1) * limit;
for (int i = start; i < start + limit && i < users.size(); i++) {
list.add(users.get(i));
}
return list;
}
/**
* 获得所有用户
*/
public List<LayuiUser> getAllUsers() {
return users;
}
/**
* 添加用户
*/
public void addUser(LayuiUser user) {
if (user.getId() <= 0) { // 未设置id
int index = users.size() - 1; // 获得最后一个用户的索引号
if (index < 0) { // 如没有一个用户
user.setId(1); // 编号为1
} else {
user.setId(users.get(index).getId() + 1); // 获得最后一个用户的编号+1
}
}
users.add(user);
}
/**
* 删除用户
*/
public void delUser(int id) {
LayuiUser delUser = null;
for (LayuiUser user : users) {
if (user.getId() == id) {
delUser = user;
break;
}
}
users.remove(delUser);
}
/**
* 删除用户(多选)
*/
public void delUsers(int[] ids) {
LayuiUser delUser = null;
for (int i = 0; i < ids.length; i++) {
for (int j = 0; j < users.size(); j++) {
if (users.get(j).getId() == ids[i]) {
users.remove(j);
}
}
}
}
public void updateUser(LayuiUser obj) {
LayuiUser editUser = null;
for (LayuiUser user : users) {
if (user.getId() == obj.getId()) {
editUser = user;
break;
}
}
editUser.setName(obj.getName());
editUser.setCity(obj.getCity());
editUser.setBirthday(obj.getBirthday());
}
}
3.3 创建用户Service
package com.laoxu.test.helloweb.service;
import com.laoxu.test.helloweb.dao.LayuiUserDao;
import com.laoxu.test.helloweb.entity.LayuiUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Description: 用户service
* @Author laoxu
* @Date 2019/12/21 10:42
**/
@Service
public class LayuiUserService {
@Autowired
LayuiUserDao userDao;
public List<LayuiUser> getPager(int page, int limit){
return userDao.getPager(page,limit);
}
public List<LayuiUser> getAllUsers() {
return userDao.getAllUsers();
}
public void addUser(LayuiUser user) {
userDao.addUser(user);
}
public void delUser(int id) {
userDao.delUser(id);
}
public void delUsers(int[] ids) {
userDao.delUsers(ids);
}
public void updateUser(LayuiUser user) {
userDao.updateUser(user);
}
}
3.4 创建用户Controller
package com.laoxu.test.helloweb.controller;
import com.laoxu.test.helloweb.dao.LayuiUserDao;
import com.laoxu.test.helloweb.entity.LayuiUser;
import com.laoxu.test.helloweb.entity.ResultBean;
import com.laoxu.test.helloweb.service.LayuiUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @Description: 用户controller
* @Author laoxu
* @Date 2019/12/21 10:11
**/
@RestController
@RequestMapping("/api/layui/user")
public class LayuiUserController {
@Autowired
LayuiUserService userService;
@GetMapping("/list")
public ResultBean list(@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer limit){
List<LayuiUser> users = userService.getPager(page,limit);
int count = userService.getAllUsers().size();
ResultBean result = new ResultBean(0,"查询成功",count,users);
return result;
}
@PostMapping("/save")
public ResultBean save(@RequestBody LayuiUser user){
// 判断是新增还是修改
if(user.getId()==0){
userService.addUser(user);
}else{
userService.updateUser(user);
}
return new ResultBean(200,"保存成功",0,"");
}
@PostMapping("/remove")
public ResultBean modify(@RequestBody int[] ids){
userService.delUsers(ids);
return new ResultBean(200,"删除成功",0,"");
}
}
源码地址:https://gitee.com/indexman/boot-layui-curd