使用springboot和layui技术对数据进行增删改查操作

分享 已结 8 1062
老裴
老裴 2019-5-30
悬赏:20飞吻
使用springboot和layui技术对数据进行增删改查操作,具体描述如下,增加数据时跳转到新页面(也可使用弹出层不跳转页面),新页面使用form表单提交数据,添加完成后返回列表页,修改也是跳转到新页面(也可以使用弹出层),修改后提交后返回列表页,删除在当前页面直接修改,查看数据详情跳转页面到新页面(也可以使用弹出层直接显示在当前页面),将数据显示到表格中,还有获取复选框选中的个数,验证是否全选,获取选中的数据弹出显示,数据分页等功能,备注:只用于参考,前端页面有点丑 ,好多细节的逻辑本次未涉及到,多多包涵,希望对大家有一点点帮助,大家加油,老裴加油
前端代码 前端代码最重要的要搞清楚lay-filter 和 id 属性,啥时候用哪一个不要搞混了,可以参考官方文档,还有数据的接口,你引入的css和js的路径,改成你本地的路径

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>layui</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="../layui/layui/css/layui.css" media="all">
<!-- 注意:如果你直接复制所有代码到本地,上述css路径需要改成你本地的 -->
</head>
<body class="layui-container">
<div class="main">
<div class="layui-btn-group demoTable">
<button class="layui-btn" id="add-info">添加</button>
<button class="layui-btn" data-type="moreDetails">多条数据详情</button>//未实现
<button class="layui-btn" data-type="deleteMore">删除多条数据</button>
<button class="layui-btn" data-type="getCheckData">获取选中行数据</button>
<button class="layui-btn" data-type="getCheckLength">获取选中个数</button>
<button class="layui-btn" data-type="isAll">获取是否全选</button>
</div>

<table id="table-data" class="layui-table" lay-filter="demo"></table>
<div id="page"></div>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</a>
<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script src="../layui/layui/layui.js" charset="utf-8"></script>
<!-- 注意:如果你直接复制所有代码到本地,上述js路径需要改成你本地的 -->
<script>
layui.use(['table','form','laypage'], function(){//标准格式
var table = layui.table;
var form = layui.form;
var laypage=layui.laypage;
table.render({
elem: '#table-data'//表格id
,width: 1000
,height: 500
,url: 'users/index1' //数据接口
,page: true //开启分页
,cols: [[ //表头
{type:'checkbox', fixed: 'left'},
{field:'id',title:'ID', width:60},
{field:'username',title:'用户名', width:140},
{field:'password', title:'密码', width:140},
{field:'email',title:'邮箱', width:140},
{field:'phone',title:'电话', width:140},
{field:'address',title:'地址', width:140},
{fixed: 'right', width:178, align:'center',title:'操作', toolbar: '#barDemo'}
]]
,id:"idTest" 数据id,有了这个id就可以获取选中行的数据,
});
//监听表格复选框选择
table.on('checkbox(demo)', function(obj){
console.log(obj)
});
//监听工具条
table.on('tool(demo)', function(obj){
var data = obj.data;
if(obj.event === 'detail'){//t跳转详情页
location.href="detail.html?id="+data.id;
} else if(obj.event === 'del'){
layer.confirm('真的删除行么', function(index){
console.log(obj) //测试 发起ajax请求
$.get('/web/users/delete?id='+data.id,function(res) {
if(res.code == 0) {
location.href="index2.html";
} else {
}
})

});
} else if(obj.event === 'edit'){//跳转详情页
location.href="edit.html?id="+data.id;
}
});
var $ = layui.$, active = {
getCheckData: function(){ //获取选中数据
var checkStatus = table.checkStatus('idTest')
,data = checkStatus.data;
layer.alert(JSON.stringify(data));
}
,getCheckLength: function(){ //获取选中数目
var checkStatus = table.checkStatus('idTest')
,data = checkStatus.data;
layer.msg('选中了:'+ data.length + ' 个');
}
,isAll: function(){ //验证是否全选
var checkStatus = table.checkStatus('idTest');
layer.msg(checkStatus.isAll ? '全选': '未全选')
}
,moreDetails:function(){ //未实现
var checkStatus = table.checkStatus('idTest');
if(checkStatus.data.length==0){
layer.msg('请先选择要查看的数据行!', {icon: 2});
return ;
}
var ids = "";
var i;
for(i=0;i<checkStatus.data.length;i++){
ids += checkStatus.data[i].id+",";
}
$.get('web/users/moreDetails?ids='+ids,function(data){
if(data.code==0){
location.href="detail2.html?ids="+ids;
}
});
}
,deleteMore:function(){//删除多条数据
var checkStatus = table.checkStatus('idTest');
if(checkStatus.data.length==0){
layer.msg('请先选择要删除的数据行!', {icon: 2});
return ;
}
var ids = "";
var i;
for(i=0;i<checkStatus.data.length;i++){
ids += checkStatus.data[i].id+",";
}
layer.msg('删除中...', {icon: 16,shade: 0.3,time:5000});
$.get('/web/users/deleteMore?ids='+ids,
function(data){
layer.closeAll('loading');
if(data.code==0){
layer.msg('删除成功!', {icon: 1,time:2000,shade:0.2});
location.reload(true);
}else{
layer.msg('删除失败!', {icon: 2,time:3000,shade:0.2});
}
}
);
}
};
$('.demoTable .layui-btn').on('click', function(){
var type = $(this).data('type');
active[type] ? active[type].call(this) : '';
});
$('#add-info').click(function () {//跳转添加页面
location.href="addUser.html";
})
});
</script>
</body>
</html>

实体类 private int id;
private String username;
private String password;
private String email;
private String phone;
private String address;
private String ids;//多个id
private String start; //(起始页-1)*limit
private String limit;//每页数据条数

控制器层
控制器的基类
public abstract class BaseController {

/**
* 响应结果的状态:成功
*/
public static final Integer SUCCESS = 0;
/**
* 统一处理异常
*/
@ExceptionHandler(ServiceException.class) //方法中的参数的异常,要比括号中异常的范围要大
public ResponseResult<Void> handlerException(Throwable e){
ResponseResult<Void> rr = new ResponseResult<>();

if(e instanceof InsertException) {
//500-插入数据异常
rr.setCode(500);
}else if(e instanceof UpdateException) {
//501-数据更新失败
rr.setCode(501);
}else if(e instanceof DeleteException) {
//502-删除数据异常
rr.setCode(502);
}
rr.setMsg("");
rr.setCount(100);
return rr;
}

}
控制器
package cn.tedu.test1.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.tedu.test1.entity.User;
import cn.tedu.test1.service.IUserService;
import cn.tedu.test1.util.ResponseResult;


@RestController
@RequestMapping("web/users")
public class UserController extends BaseController{

@Autowired
private IUserService userService;

@RequestMapping("/index1")//查询列表数据
public Map showList(HttpSession session,int page,int limit){
Map<String,Object> map = new HashMap<String, Object>();
int start=(page-1)*limit;
List<User> data=userService.findList(start, limit);
map.put("code", 0);
map.put("msg", "成功");
map.put("count", 1000);
map.put("data", data);
return map;
}

@RequestMapping("/add")
public ResponseResult<Void> add(User user) {
userService.add(user);
return new ResponseResult<Void>(SUCCESS);
}

@RequestMapping("/delete")
public ResponseResult<Void> deleteData(int id){
userService.del(id);
return new ResponseResult<Void>(SUCCESS);
}

@RequestMapping("/update")
public ResponseResult<Void> changeInfo(User user){
userService.update(user);
return new ResponseResult<Void>(SUCCESS);

}

@GetMapping("/{id}/details")
public Map showDetails(@PathVariable("id") int id){
List<User> data= userService.find(id);
Map<String,Object> map = new HashMap<String, Object>();
map.put("code", 0);
map.put("msg", "成功");
map.put("count", 1000);
map.put("data", data);
return map;
}
@RequestMapping("/moreDetails")
public Map<String,Object> moreDetail(User user) {
String ids = user.getIds(); //ids和id都存在于实体类User
System.out.println(ids);//测试输出从前端拿到的ids(多个id)
String a[] = ids.split(",");
Map<String,Object> map = new HashMap<String, Object>();
try{
for (int i = 0; i < a.length; i++) {
int id = Integer.parseInt(a[i]);
List<User> data=userService.find(id);
map.put("data", data);
}
}catch (Exception e) {
e.printStackTrace();
map.put("code", -1);
}
map.put("code", 0);
map.put("msg", "成功");
map.put("count", 1000);
return map;
}

@RequestMapping("/deleteMore")
public ResponseResult<Void> delete(User user,Map<String, Object> map){
//后端如何接受多条参数(实体类的属性(如id))在实体类中添加一个关于这个属性的字段复数字段(ids)
String ids = user.getIds(); //ids和id都存在于实体类User
System.out.println(ids);//测试输出从前端拿到的ids(多个id)
String a[] = ids.split(",");
try{
for (int i = 0; i < a.length; i++) {
int id = Integer.parseInt(a[i]);
userService.del(id);
map.put("code", 0);
}
}catch (Exception e) {
e.printStackTrace();
map.put("code", -1);
}
return new ResponseResult<Void>(SUCCESS);
}
}
service层
service接口
void add(User user)throws InsertException;

List<User> find();

void del(int id)throws DeleteException;

void update(User user)throws UpdateException;

List<User> find(int id);

List<User> findList(int start,int limit);
service实现类
@Service
public class UserServiceImpl implements IUserService{

@Autowired
private UserMapper userMapper;

@Override
public void add(User user) {
insert(user);
}
@Override
public List<User> find() {
List<User> result=findById();
return result;
}

@Override
public void del(int id) throws InsertException {
delete(id);

}
@Override
public void update(User user) throws UpdateException {
updateInfo(user);
}
@Override
public List<User> find(int id) {
List<User> result=findById(id);
return result;
}
@Override
public List<User> findList(int start, int limit) {
System.out.println("start"+start+"limit"+limit);
List<User> list=findByLimit(start,limit);
return list;
}
private List<User> findById() {
return userMapper.findAll();
}
private void insert(User user) {
Integer rows=userMapper.insert(user);
if(rows!=1) {
throw new InsertException("插入数据异常");
}
}
private void delete(int id) {
Integer rows=userMapper.delete(id);
if(rows!=1) {
throw new DeleteException("删除数据异常");
}
}
private void updateInfo(User user) {
Integer rows=userMapper.updateInfo(user);
if(rows!=1) {
throw new UpdateException("修改数据时发生未知异常");
}
}
private List<User> findById(int id) {
return userMapper.findById(id);
}
private List<User> findByLimit(int start,int limit){
return userMapper.findByLimit(start, limit);
}
DAO层
mapper 接口
public interface UserMapper {

/**
* 插入数据
* @param user
* @return
*/
Integer insert(User user);


/**
* 查询数据
* @param id
* @return
*/
List<User> findAll();

/**
* 根据用户id删除数据
* @param id
* @return
*/
Integer delete(int id);

/**
* 根据用户id查询用户数据后修改用户数据
* @param id
* @return
*/
Integer updateInfo(User user);

/**
* 根据用户id查询用户详情
* @param id
* @return
*/
List<User> findById(int id);

/**
* 根据页数和每页数据条数查询用户的数据
* @param pageNo 页数
* @param pageSize 每页所包含的数据条数(几条数据)
* @return User数据(对象)集合
*/
List<User> findByLimit(int start,int limit);

mybatis映射层

<mapper namespace="cn.tedu.test1.mapper.UserMapper">

<!-- 插入用户数据 -->
<!-- Integer insert(User user) -->
<insert id="insert">
INSERT INTO user(
username,password,
phone,email,
address
)VALUES(
#{username},#{password},
#{phone},#{email},
#{address}
)
</insert>


<!-- 更新个人资料 -->
<!-- Integer updateInfo(User user); -->
<update id="updateInfo">
UPDATE
user
SET
phone=#{phone},email=#{email},
username=#{username},password=#{password},
address=#{address}
WHERE
id=#{id}
</update>


<!-- 根据用户id查询用户数据 -->
<!-- User find() -->
<select id="findAll" resultType="cn.tedu.test1.entity.User">
SELECT
username,phone,
email,address,
password,id
FROM
user

</select>

<!--/** * 根据用户id删除数据 * @param id * @return */ Integer delete(Integer id); -->

<delete id="delete">
delete from user where id=#{id}

</delete>

<select id="findById" resultType="cn.tedu.test1.entity.User">
select
username,password,
phone,email,address,id
from user
where id=#{id}
</select>
<!-- /**
* 根据页数和每页数据条数查询用户的数据
* @param start 页数
* @param pageSize 每页所包含的数据条数(几条数据)
* @return User数据(对象)集合
*/
List<User> findByLimit(int pageNo,int pageSize); -->
<select id="findByLimit" resultType="cn.tedu.test1.entity.User">
select * from user limit #{param1},#{param2};
</select>
</mapper>

前端添加页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>layui</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="../layui/layui/css/layui.css" media="all">
<!-- 注意:如果你直接复制所有代码到本地,上述css路径需要改成你本地的 -->
</head>
<body>                
<form class="layui-form" method="get">
<div class="layui-form-item">
<label class="layui-form-label">用户名</label>
<div class="layui-input-inline">
<input type="text" name="username" required 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-inline">
<input type="password" name="password" required
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-inline">
<input type="text" name="email" required lay-verify="email"
placeholder="请输入邮箱" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">电话</label>
<div class="layui-input-inline">
<input type="number" name="phone" required lay-verify="phone"placeholder="请输入电话"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">地址</label>
<div class="layui-input-inline">
<input type="text" name="address" required lay-verify="required"
placeholder="请输入地址" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="formAdd">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</form>
<script src="../layui/layui/layui.js" charset="utf-8"></script>
<script>
layui.use([ 'layer', 'form'], function() {
var form = layui.form;
var layer = layui.layer;
var laypage=layui.laypage;
$ = layui.jquery;
form.on('submit(formAdd)', function(data) {
$.ajax({
url : '/web/users/add',
method : 'get',
data : data.field,
dataType : 'JSON',
success : function(res) {
window.location.href="index2.html";
}
});

});
});
</script>
</body>
</html>

前端修改页面

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>layui</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="../layui/layui/css/layui.css" media="all">
<!-- 注意:如果你直接复制所有代码到本地,上述css路径需要改成你本地的 -->
</head>
<body>                
<form class="layui-form" method="get" lay-filter="editForm">
<div class="layui-form-item" hidden>
<label class="layui-form-label">ID</label>
<div class="layui-input-inline">
<input type="text" name="id" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">用户名</label>
<div class="layui-input-inline">
<input type="text" name="username" id="username" 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-inline">
<input type="password" name="password" id="password" 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-inline">
<input type="text" name="email" id="email" required lay-verify="email"
placeholder="请输入邮箱" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">电话</label>
<div class="layui-input-inline">
<input type="number" name="phone" id="phone" required
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">地址</label>
<div class="layui-input-inline">
<input type="text" name="address" id="address" required lay-verify="required"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="formEdit">修改</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</form>
<script src="../layui/layui/layui.js" charset="utf-8"></script>
<script>

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

$(document).ready(function(){
function GetQueryString(name){
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r!=null)
return unescape(r[2]);
return null;
}
var id=GetQueryString("id");
id=parseInt(id);
$.ajax({
url : '/web/users/'+id+'/details',
method : 'get',
dataType : 'json',
success : function(response) {
//如果response返回不为空,取返回数据的第一条
var data=response && response.data[0];
form.val("editForm", {
"id":data.id
,"username": data.username
,"password": data.password
,"email": data.email
,"phone": data.phone
,"address": data.address
})

}
});
});
form.on('submit(formEdit)',function(data){
console.log(data)
$.ajax({
url:'/web/users/update'
,method:'GET'
,data:data.field//获取表单里面的数据
,success:function(res){
window.location.href="index2.html";


}
});

});
});
</script>
</body>
</html>
详情页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>table模块快速使用</title>
<link rel="stylesheet" href="../layui/layui/css/layui.css" media="all">
</head>
<body>
<table id="demo" lay-filter="test"></table>
<script src="../layui/layui/layui.js" charset="utf-8"></script>
<script>
layui.use(['table','jquery'], function(){
var table = layui.table;
var $=layui.jquery;

$(document).ready(function(){
function GetQueryString(name){
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r!=null)
return unescape(r[2]);
return null;
}
var id=GetQueryString("id");
id=parseInt(id);


//第一个实例
table.render({
elem: '#demo'
,height: 312
,url: '/web/users/'+id+'/details' //数据接口
,page: false //开启分页
,cols: [[ //表头
,{field: 'username', title: '用户名', width:80}
,{field: 'password', title: '密码', width:80, sort: true}
,{field: 'email', title: '邮箱', width:80}
,{field: 'phone', title: '电话', width: 177}
,{field: 'address', title: '地址', width: 80, sort: true}
]]
});
});

});
</script>
</body>
</html>
回帖
  • Freedom丶
    2019-5-31
    兄弟,mybatis-Plus了解一下,CRUD能省你不少事
    0 回复
  • 老裴
    2019-5-31
    有没有参照的文档或者链接啊,我有一个问题
    分页查询和表格重载的sql怎么写,我的表是一张单表,兄弟帮帮忙
    0 回复
  • @老裴 分页用limit语句
    0 回复
  • 老裴
    2019-6-3
    分页加表格重载的这个sql语句写不出来,写了好几遍也不对
    0 回复
  • javal
    2019-6-6
    @老裴 分页的同时加上查询条件。
    参考一下,基于MP的操作。
    0 回复
  • 老裴
    2019-6-6
    好的,感谢感谢
    0 回复
  • GongAo啊
    2019-6-6
    请问html是不是放在templates下了
    0 回复
  • 老裴
    2019-6-11
    @GongAo啊 不是,放在resource下面,在resource下面建一个包,放在resource下面,
    0 回复