当前位置:   article > 正文

Springboot+MyBatis-Plus整合Layui实现分页_使用springboot+mybatis-plus+jsp+layui实现单表的crud操作

使用springboot+mybatis-plus+jsp+layui实现单表的crud操作

MyBatis-Plus 使用简单,内置通用 Mapper、通用 Service,仅仅通过少量配置,即可实现单表大部分 CRUD 操作。下面介绍使用 service 中的 page 方法结合 Layui 前端框架,较快速的实现分页效果。

1.导入MyBatis-Plus依赖

  1. <!--mybatis-plus的springboot支持-->
  2. <dependency>
  3. <groupId>com.baomidou</groupId>
  4. <artifactId>mybatis-plus-boot-starter</artifactId>
  5. <version>3.1.1</version>
  6. </dependency>

2.编写接口--UserMapper

  1. package com.jk.mapper;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import com.jk.entity.Userinfo;
  4. public interface UserMapper extends BaseMapper<Userinfo> {
  5. }

3.编写 service 接口--UserService ,并继承 IService。

  1. package com.jk.service;
  2. import com.baomidou.mybatisplus.extension.service.IService;
  3. import com.jk.entity.Userinfo;
  4. public interface UserService extends IService<Userinfo> {
  5. }

4.编写 service 实现类--UserServiceImpl,继承 MyBatis-Plus 的 ServiceImpl ,同时实现 UserService 接口。

  1. package com.jk.service.impl;
  2. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  3. import com.jk.entity.Userinfo;
  4. import com.jk.mapper.UserMapper;
  5. import com.jk.service.UserService;
  6. import org.springframework.stereotype.Service;
  7. @Service
  8. public class UserServiceImpl extends ServiceImpl<UserMapper, Userinfo> implements UserService {
  9. }

5.编写MyBatis-plus 分页配置类--MybatisPlusConfig

  1. package com.jk.conf;
  2. import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
  3. import org.mybatis.spring.annotation.MapperScan;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. @Configuration
  7. @MapperScan("com.jk.mapper")
  8. public class MybatisPlusConfig {
  9. /**
  10. * 分页插件
  11. */
  12. @Bean
  13. public PaginationInterceptor paginationInterceptor() {
  14. return new PaginationInterceptor();
  15. }
  16. }

6.编写json格式返回工具类--ResultUtil

  1. package com.jk.utils;
  2. import java.io.Serializable;
  3. /**
  4. * json格式返回工具类
  5. */
  6. public class ResultUtil implements Serializable {
  7. private Integer code; //返回状态码 0代表成功
  8. private String msg = ""; //返回提示信息
  9. private Long count = 0L;
  10. private Object data; //返回数据
  11. public ResultUtil() {
  12. super();
  13. }
  14. public ResultUtil(Integer code) {
  15. super();
  16. this.code = code;
  17. }
  18. public ResultUtil(Integer code, Long count, Object data) {
  19. this.code = code;
  20. this.count = count;
  21. this.data = data;
  22. }
  23. public ResultUtil(Integer code, String msg) {
  24. super();
  25. this.code = code;
  26. this.msg = msg;
  27. }
  28. public Integer getCode() {
  29. return code;
  30. }
  31. public void setCode(Integer code) {
  32. this.code = code;
  33. }
  34. public String getMsg() {
  35. return msg;
  36. }
  37. public void setMsg(String msg) {
  38. this.msg = msg;
  39. }
  40. public Long getCount() {
  41. return count;
  42. }
  43. public void setCount(Long count) {
  44. this.count = count;
  45. }
  46. public Object getData() {
  47. return data;
  48. }
  49. public void setData(Object data) {
  50. this.data = data;
  51. }
  52. public static ResultUtil ok() {
  53. return new ResultUtil(0);
  54. }
  55. public static ResultUtil ok(Object list) {
  56. ResultUtil result = new ResultUtil();
  57. result.setCode(0);
  58. result.setData(list);
  59. ;
  60. return result;
  61. }
  62. public static ResultUtil ok(String msg) {
  63. ResultUtil result = new ResultUtil();
  64. result.setCode(0);
  65. result.setMsg(msg);
  66. return result;
  67. }
  68. public static ResultUtil error() {
  69. return new ResultUtil(500, "没有此权限,请联系超管!");
  70. }
  71. public static ResultUtil error(String str) {
  72. return new ResultUtil(500, str);
  73. }
  74. }

7.编写controller 类--UserController

  1. package com.jk.controller;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.baomidou.mybatisplus.core.metadata.IPage;
  4. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  5. import com.jk.entity.Userinfo;
  6. import com.jk.service.impl.UserServiceImpl;
  7. import com.jk.utils.ResultUtil;
  8. import org.apache.commons.lang.StringUtils;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.stereotype.Controller;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.ResponseBody;
  13. import java.util.List;
  14. @Controller
  15. public class UserController {
  16. @Autowired
  17. private UserServiceImpl userService;
  18. /**
  19. * 跳转到列表页面
  20. * @return
  21. */
  22. @RequestMapping("/manage/userinfoList")
  23. public String goList(){
  24. return "manage/userinfo/userinfoList";
  25. }
  26. /**
  27. * 分页条件查询
  28. * @param page
  29. * @param limit
  30. * @param name
  31. * @param sex
  32. * @return
  33. */
  34. @RequestMapping("/manage/getList")
  35. @ResponseBody
  36. public ResultUtil getList(Integer page, Integer limit,String name,String sex){
  37. // 传入分页的属性
  38. Page<Userinfo> objectPage = new Page<>(page, limit);
  39. QueryWrapper<Userinfo> wrapper = new QueryWrapper<>();
  40. // 条件查询:不为空且长度不为0且不由空白符(whitespace) 构成
  41. wrapper.like(StringUtils.isNotBlank(name),"name",name);
  42. wrapper.eq(StringUtils.isNotBlank(sex),"sex",sex);
  43. // 分页查询
  44. IPage<Userinfo> userinfoIPage = userService.page(objectPage, wrapper);
  45. // 信息总条数
  46. long total = userinfoIPage.getTotal();
  47. // 分页数据
  48. List<Userinfo> records = userinfoIPage.getRecords();
  49. // 回写数据
  50. return new ResultUtil(0,total,records);
  51. }
  52. }

8.userinfo列表页面:

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8" %>
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  4. <c:set var="ctx" value="${pageContext.request.contextPath}"/>
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  6. <html>
  7. <head>
  8. <meta charset="utf-8">
  9. <title>用户信息列表</title>
  10. <meta name="renderer" content="webkit">
  11. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  12. <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  13. <meta name="apple-mobile-web-app-status-bar-style" content="black">
  14. <meta name="apple-mobile-web-app-capable" content="yes">
  15. <meta name="format-detection" content="telephone=no">
  16. <link rel="stylesheet" href="${ctx}/static/layui/css/layui.css" media="all"/>
  17. <link rel="stylesheet" href="${ctx}/static/css/font_eolqem241z66flxr.css" media="all"/>
  18. <link rel="stylesheet" href="${ctx}/static/css/list.css" media="all"/>
  19. <script>
  20. var ctx = "${ctx}"; //js全局项目路径
  21. </script>
  22. <style type="text/css">
  23. </style>
  24. </head>
  25. <body class="childrenBody">
  26. <blockquote class="layui-elem-quote list_search">
  27. <div class="layui-form-item">
  28. <label class="layui-form-label">姓名</label>
  29. <div class="layui-input-block" style="margin-left: 0px;">
  30. <input type="text" name="name" id="name" lay-verify autocomplete="off"
  31. placeholder="请输入名称"
  32. class="layui-input" style="display: inline;width: 500px">
  33. 性别:
  34. <select name="sex" id="sex" class="layui-select" style="width: 500px">
  35. <option value="">请选择性别</option>
  36. <option value="男"></option>
  37. <option value="女"></option>
  38. </select>
  39. <button class="layui-btn" id="sel">查询</button>
  40. </div>
  41. </div>
  42. <div class="layui-inline">
  43. <a class="layui-btn layui-btn-normal addBtn"><i class="layui-icon">&#xe608;</i> 添加商品信息</a>
  44. </div>
  45. <div class="layui-inline">
  46. <div class="layui-form-mid layui-word-aux"></div>
  47. </div>
  48. </blockquote>
  49. <!-- 数据表格 -->
  50. <table id="userinfoList" lay-filter="test"></table>
  51. <script type="text/javascript" src="${ctx}/static/layui/layui.js"></script>
  52. <script type="text/javascript" src="${ctx}/static/js/common.js"></script>
  53. <script type="text/javascript" src="${ctx}/static/js/userinfoList.js"></script>
  54. <script type="text/html" id="barEdit">
  55. <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="infoDetail">查看</a>
  56. <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  57. <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
  58. <%-- <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="chongzhi">充值</a>--%>
  59. </script>
  60. <script type="text/html" id="tableImg">
  61. <%--图片显示模板--%>
  62. <img src="{{d.picurl}}" style="height:48px;width:48px;line-height:48px!important;"/>
  63. </script>
  64. <style>
  65. .layui-table-cell {
  66. height: 36px;
  67. line-height: 36px;
  68. }
  69. </style>
  70. </body>
  71. </html>

8.编写页面对应js文件:

  1. layui.config({
  2. base: "js/"
  3. }).use(['form', 'layer', 'jquery', 'laypage', 'table', 'laytpl'], function () {
  4. var form = layui.form, table = layui.table;
  5. layer = parent.layer === undefined ? layui.layer : parent.layer,
  6. laypage = layui.laypage,
  7. $ = layui.jquery;
  8. //数据表格
  9. table.render({
  10. id: 'userinfoList',
  11. elem: '#userinfoList'
  12. , url: ctx + '/manage/getList' //数据接口
  13. , cellMinWidth: 80
  14. , limit: 10//每页默认数
  15. , limits: [10, 20, 30, 40]
  16. , cols: [[ //表头
  17. /*{type: 'checkbox'},*/
  18. {field: 'id', title: 'ID', width: 60, align: 'center', sort: true},
  19. {field: 'name', title: '姓名', width: 140, align: 'center'},
  20. {field: 'phone', title: '电话', width: 140, align: 'center'},
  21. {field: 'email', title: '邮箱', width: 140, align: 'center'},
  22. {field: 'picurl', title: '头像', templet: '#tableImg'},
  23. {field: 'money', title: '金额', width: 140, align: 'center'},
  24. {field: 'sex', title: '性别', width: 140, align: 'center'},
  25. {field: 'password', title: '密码', width: 140, align: 'center'},
  26. {field: 'role', title: '权限', width: 140, align: 'center'},
  27. {
  28. field: 'createtime',
  29. title: '创建时间',
  30. templet: '<div>{{ formatTime(d.createtime,"yyyy-MM-dd hh:mm:ss")}}</div>'
  31. },
  32. {title: '操作', toolbar: '#barEdit'}
  33. ]]
  34. , page: true //开启分页
  35. });
  36. //监听工具条
  37. table.on('tool(test)', function (obj) {
  38. var data = obj.data;
  39. if (obj.event === 'del') {
  40. layer.confirm('真的删除行么?', function (index) {
  41. $.ajax({
  42. url: ctx + '/manage/deleteUserinfo?id=' + data.id,
  43. type: "get",
  44. success: function (d) {
  45. if (d.code == 0) {
  46. table.reload('userinfoList', {})
  47. } else {
  48. layer.msg("操作失败,请重试", {icon: 5});
  49. }
  50. }
  51. })
  52. layer.close(index);
  53. });
  54. } else if (obj.event === 'edit') {
  55. var url = ctx + "/manage/editUserinfo?id=" + data.id;//路径拼接
  56. location.href = url;
  57. } else if (obj.event === 'chongzhi') {
  58. var url = ctx + "/manage/chongzhi?id=" + data.id;//路径拼接
  59. location.href = url;
  60. }else if (obj.event === 'infoDetail') {
  61. var url = ctx + "/manage/userinfoInfo?id=" + data.id;
  62. layer.open({
  63. type: 2,
  64. btn: ['关闭'],
  65. btnAlign: 'c',
  66. title: "用户信息详情查看",
  67. skin: 'layui-layer-molv', //加上边框
  68. area: ['500px', '400px'], //宽高
  69. shadeClose: true,
  70. content: url
  71. });
  72. }
  73. });
  74. //添加用户信息
  75. $(".addBtn").click(function () {
  76. var url = ctx + "/manage/addUserinfo";
  77. location.href = url; //路径跳转
  78. })
  79. //搜索
  80. $("#sel").click(function () {
  81. table.reload('userinfoList', {
  82. where: {
  83. name: $("#name").val(),
  84. sex: $("#sex").val()
  85. }
  86. })
  87. })
  88. //批量删除用户信息
  89. $(".batchDel").click(function () {
  90. var checkStatus = table.checkStatus('userinfoList')
  91. , data = checkStatus.data, idsStr = '';
  92. // layer.alert(JSON.stringify(data));
  93. if (data.length > 0) {
  94. $.each(data, function (n, value) {
  95. idsStr += value.id + ',';
  96. });
  97. idsStr = idsStr.substring(0, idsStr.length - 1);
  98. layer.confirm('真的要删除<strong>' + data.length + '</strong>条数据吗?', function (index) {
  99. //调用删除接口
  100. $.ajax({
  101. url: 'deletesUserinfo?idsStr=' + idsStr,//接口地址
  102. type: "get",
  103. success: function (d) {
  104. if (d.code == 0) {
  105. //重载表格
  106. table.reload('userinfoList', {})
  107. } else {
  108. layer.msg("删除错误,稍后再试!", {icon: 5});
  109. }
  110. }
  111. })
  112. layer.close(index);
  113. });
  114. } else {
  115. layer.msg("请选择要操作的数据!");
  116. }
  117. })
  118. })

最后看下效果:

 完结,撒花!!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/155683?site
推荐阅读
相关标签
  

闽ICP备14008679号