Java开发实用工具

一:SpringBoot+MyBatis+PageHelper+Layui+thymeleaf+MySQL实现分页

第一步:
在pom文件中引入坐标

		<!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--测试用-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
         <!--引入thymeleaf的依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--    分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>3.7.5</version>
        </dependency>

第二步: 在springboot启动类中配置PageHelper

@MapperScan("com.tgh.hospitalproject.mapper")
@SpringBootApplication
public class HospitalProjectApplication {

    public static void main(String[] args) {
        SpringApplication.run(HospitalProjectApplication.class, args);
    }
	//创建pageHelper,设置其属性,然后将pageHelper对象交给spring容器管理
    @Bean
    public PageHelper pageHelper() {
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("offsetAsPageNum", "true");
        properties.setProperty("rowBoundsWithCount", "true");
        properties.setProperty("reasonable", "true");
        properties.setProperty("dialect", "mysql");
        pageHelper.setProperties(properties);
        return pageHelper;
    }
}

properties.setProperty("offsetAsPageNum", "true");开启用页码和页面大小进行分页
properties.setProperty("rowBoundsWithCount", "true");进行count查询
properties.setProperty("reasonable", "true");使页码参数合理,当页码<=0时查询第一页,页码>总页面时查询最后一页。
properties.setProperty("dialect", "mysql");使用mysql方言
第三步: application.yml文件配置

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/hospital?serverTimezone=GMT%2B8&characterEncoding=utf-8
    username: root
    password: root
    type: com.alibaba.druid.pool.DruidDataSource
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    cache: false
    mode: HTML5
    encoding: UTF-8
logging:
  level:
    com.tgh.hospitalproject.dao : debug

第四步: 后台前台代码准备
前台页面:(完整代码请参考项目

<html xmlns:th="http://www.thymeleaf.org">
<div th:fragment="head">
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/my.css">
    <script src="/js/jquery-3.5.1.js"></script>
    <script src="/layui/layui.js"></script>
<div class="layui-header">
    <div class="layui-logo"><span>欢迎进入</span>医疗系统<span>后台管理</span></div>
    <!-- 头部区域(可配合layui已有的水平导航) -->
    <ul class="layui-nav layui-layout-left">
        <li class="layui-nav-item">
            <a href="javascript:">系统管理</a>
            <dl class="layui-nav-child">
                <dd><a href="/admin/doctor/manage">医生管理</a></dd>
                <dd><a href="/admin/patient/manage">患者管理</a></dd>
                <dd><a href="/admin/drugs/manage">药品管理</a></dd>
                <dd><a href="/admin/option/manage">科目查询管理</a></dd>
                <dd><a href="/admin/illness/manage">疾病管理</a></dd>
            </dl>
        </li>
        <li class="layui-nav-item" ><a href="/admin/appointment/manage">预约管理</a></li>
        <li class="layui-nav-item" ><a href="/admin/medicalHistory/manage">病史管理</a></li>
        <li class="layui-nav-item" ><a href="/admin/hospitalization/manage">住院信息管理</a></li>
        <li class="layui-nav-item" ><a href="/admin/user/manage">管理员管理</a></li>
    </ul>
    <ul class="layui-nav layui-layout-right">
        <li class="layui-nav-item">
            <a href="javascript:;">
                &nbsp;&nbsp;&nbsp;&nbsp;欢迎: [[${session.user!=null?session.user.username:'admin'}]]
            </a>
        </li>
        <li class="layui-nav-item"><a href="/home/user/logout">退出登录</a></li>
    </ul>
</div>
</div>
</html>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>医生管理界面</title>
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
    <!-- 引入公共头部开始 -->
    <div th:insert="admin/common/header :: head"></div>
    <!-- 引入公共头部结束 -->
    <div class="layui-body">
        <!-- 内容主体区域 -->
        <div style="padding: 15px;">
            <h5>
                <span class="layui-breadcrumb">
                <a href="javascript:;">系统管理</a>
                <a><cite>医生管理</cite></a>
                </span>
            </h5>
            <form action="/admin/doctor/manage" method="get">
                <table>
                    <tr>
                        <td>昵称:</td>
                        <td><input name="name"  required autocomplete="off" th:value="${name}" class="layui-input lay-size=sm" ></td>
                        <td>&nbsp;&nbsp;证件号:</td>
                        <td><input name="certId" required autocomplete="off" th:value="${certId}" class="layui-input lay-size=sm" ></td>
                        <td>   <button class="layui-btn" type="submit"><i class="layui-icon">&#xe615;</i></button></td>
                    </tr>
                </table>
            </form>
            <table class="layui-table">
                <colgroup align="center">
                </colgroup>
                <thead>
                <tr>
                    <th>序号</th>
                    <th>昵称</th>
                    <th>是否为专家</th>
                    <th>年纪</th>
                    <th>性别</th>
                    <th>证件号</th>
                    <th>所属部门</th>
                    <th>家庭住址</th>
                    <th>操作&nbsp;&nbsp;&nbsp;&nbsp;
                        <button class="layui-btn" onclick="showAdd('/admin/doctor/')"><i class="layui-icon">&#xe608;</i> 添加</button>
                    </th>
                </tr>
                </thead>
                <tbody>
                <div type="hidden"  ></div>
                    <div th:each=" doctors : ${doctorList}">
                        <tr>
                            <td>[[${doctors.getId()}]]</td>

                            <td>[[${doctors.getName}]]</td>
                            <td>
                                [[${doctors.getExpert() == 1? '专家' : '非专家'}]]
                            </td>
                            <td>
                                [[${doctors.getAge()}]]
                            </td>
                            <td>
                                [[${doctors.getSex() == 0 ? '男' : '女'}]]
                            </td>
                            <td>[[${doctors.getCertId()}]]</td>
                            <td>[[${doctors.getDepartment()}]]</td>
                            <td>[[${doctors.getAddress()}]]</td>
                            <td>
                                <button class="layui-btn" th:onclick="edit('/admin/doctor/',[[${doctors.getId()}]])"><i class="layui-icon">&#xe642;</i></button>
                                <button class="layui-btn" th:onclick="del('/admin/doctor/',[[${doctors.getId()}]])"><i class="layui-icon">&#xe640;</i></button>
                            </td>
                        </tr>
                    </div>
                </tbody>
            </table>
            <div id="pagination"></div>
        </div>
    </div>
    <!-- 引入公共脚部文件开始 -->
    <div th:insert="admin/common/footer :: footer"></div>
    <!-- 引入公共脚部文件结束 -->
    <!-- 引入公共分页脚本文件开始 -->
    <div th:insert="admin/common/page :: page"></div>
    <!-- 引入公共分页脚本文件结束 -->
</div>
</body>
</html>
<div xmlns:th="http://www.thymeleaf.org">
<div th:fragment="page">
    <script>
        layui.use('element', function(){
            var element = layui.element;
        });
        layui.use(['laypage', 'layer',"form","table"], function() {
            var laypage = layui.laypage
                , layer = layui.layer;
            //完整功能
            laypage.render({
                elem: 'pagination'
                , count: [[${page.total}]]
                , limits:[ 10]
                , layout: [ 'prev', 'page', 'next', 'limit', 'refresh','skip','count']
                , loading: true
                , curr: [[${page.pageNum}]] //动态获取当前页
                , jump: function (obj,first) {
                    //在jump函数里面完成跳转处理
                    //obj包含当前分页的所有参数
                    console.log(obj)
                    //非第一次执行
                    if (!first) {
                        //注意跳转路径与后台的接受变量保持一致
                        window.location.href = "[[${path}]]?pageNo=" + obj.curr + "&limit=" + obj.limit;
                    }
                }
            });
        });
    </script>
</div>
</div>

后台Controller:(思路:将查询到的医生数据放到model中,前台从model取出数据展现)

    //分页显示所有数据
    @RequestMapping("/manage")
    public String findPageList(@RequestParam(required = false, defaultValue = "1") Integer pageNo,
                               @RequestParam(required = false, defaultValue = "10") Integer limit,
                               @RequestParam(required = false) String name,
                               @RequestParam(required = false) String certId,
                               Model model){
        PageInfo<Doctor> doctorInfo = doctorService.findDoctorInfo(pageNo, limit, name, certId);
        model.addAttribute("doctorList",doctorInfo.getList());
        model.addAttribute("page",doctorInfo);
        model.addAttribute("name",name);
        model.addAttribute("certId",certId);
        model.addAttribute("path","/admin/doctor/manage");
        return "admin/doctorManage";
    }

后台Service实现:(思路:在进行mapper操作之前执行PageHelper.startPage(页码,页面大小);

    @Override
    public PageInfo<Doctor> findDoctorInfo(Integer pageNo, Integer limit, String name, String cerId) {
        //由名字和身份证查询部分用户
        if(!StringUtils.isEmpty(name) || !StringUtils.isEmpty(cerId)) {
            PageHelper.startPage(pageNo,limit);
            List<Doctor> doctorPart = doctorMapper.findByNameAndCerId(name, cerId);
            PageInfo<Doctor> pageInfo = new PageInfo<>(doctorPart);
            return pageInfo;
        } else {
            //查询所有用户
            PageHelper.startPage(pageNo,limit);
            List<Doctor> doctorAll = doctorMapper.findAll();
            PageInfo<Doctor> pageInfo = new PageInfo<>(doctorAll);
            return pageInfo;
        }
    }

咱们关注doctorMapper.findAll(),返回的是lb_doctor表中的所有数据
后台Mapper:

    @Select({
            "select * from lb_doctor"
    })
    @Results({
            @Result(column="id", property="id", jdbcType= JdbcType.INTEGER, id=true),
            @Result(column="name", property="name", jdbcType=JdbcType.VARCHAR),
            @Result(column="age", property="age", jdbcType=JdbcType.INTEGER),
            @Result(column="cert_id", property="certId", jdbcType=JdbcType.VARCHAR),
            @Result(column="sex", property="sex", jdbcType=JdbcType.INTEGER),
            @Result(column="department", property="department", jdbcType=JdbcType.VARCHAR),
            @Result(column="address", property="address", jdbcType=JdbcType.VARCHAR),
            @Result(column="user_id", property="userId", jdbcType=JdbcType.INTEGER),
            @Result(column="text", property="text", jdbcType=JdbcType.VARCHAR),
            @Result(column="expert", property="expert", jdbcType=JdbcType.INTEGER),
    })
    List<Doctor> findAllByPage();

核心代码

使用PageHelper的核心点在与后台Service实现部分
PageHelper.startPage(pageNo,limit); 对紧跟其的第一条语句末尾插入limit语句实现分页
List doctorPart = doctorMapper.findByNameAndCerId(name, cerId);
PageInfo pageInfo = new PageInfo<>(doctorPart); 对查询结果进行封装,包含分页信息和数据信息
查看PageInfo源码,发现是把结果数据封装在List集合里面

public class PageInfo<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    //当前页
    private int pageNum;
    //每页的数量
    private int pageSize;
    //当前页的数量
    private int size;
    //由于startRow和endRow不常用,这里说个具体的用法
    //可以在页面中"显示startRow到endRow 共size条数据"

    //当前页面第一个元素在数据库中的行号
    private int startRow;
    //当前页面最后一个元素在数据库中的行号
    private int endRow;
    //总记录数
    private long total;
    //总页数
    private int pages;
    //结果集
    private List<T> list;
    ...以下省略

固Controller层使用doctorInfo.getList()获取结果数据
页面展示:
在这里插入图片描述

总结

PageHelper具体使用参照核心代码即可
本测试中layui主要用到了分页,样式可参考layui分页
本测试中thymeleaf用来从后台Model域中获取数据,用到了th:each 、内联表达式 [[]]等,关于thymeleaf更多特性可参考前端爬坑一、thymeleaf在标签内部获得数据作为js函数的参数

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值