从0开始码第一个Spring Boot项目(javaweb个人博客系统)之手写实现Mysql简单分页功能

源码

个人博客系统长期更新,所有源码都放在了我的GitHub上了,需要下载的可以去看看。

github地址:https://github.com/Wanik666/community
回顾
上一篇我们实现了文章列表展示功能,但是如果后期我们数据越来越多,那么就会出现网页数据量大,对服务器和数据库都有很大的压力,所以,我们需要实现简单分页功能。
1.演示

首先进入到我们的首页,我们模拟了很多数据,默认展示第一页,每页显示5条。
分页栏

2.主要代码片段
2.1分页数据传输类PaginationDTO.java
PaginationDTO.java

@Data
public class PaginationDTO {
    private boolean hasPrePage; //是否有上一页
    private boolean hasNextPage; //是否有下一页
    private boolean hasFirstPage;   //是否显示首页
    private boolean hasLastPage;    //是否显示尾页
    private int offset; //mysql分页语法中的偏移量
    private int page;   //页码
    private int size;   //每页显示数据数
    private int countPage;  //总页数
    private List<Integer> pageList = new ArrayList<>(); //分页列表中的页码

    //具体计算分页数据类,并设置值
    public void setPagination(int page, int size, int totalCount) {
        this.page = page;
        //计算总页数
        if(totalCount%size==0){
            countPage = totalCount/size;
        }else{
            countPage = totalCount/size +1;
        }

        //限制页码范围,防止用户输入导致越界
        if(page<1){
            page = 1;
        }else if (page>countPage){
            page = countPage;
        }

        //显示的页码列表
        pageList.add(page);
        for(int i = 1;i<=3;i++){
            if(page-i>=1){
                pageList.add(0,page-i);
            }
            if(page+i<=countPage){
                pageList.add(page+i);
            }
        }

        //首页、尾页、上一页、下一页是否展示
        if(pageList.contains(1)){
            hasFirstPage = false;
        }else{
            hasFirstPage = true;
        }
        if(pageList.contains(countPage)){
            hasLastPage = false;
        }else {
            hasLastPage = true;
        }
        if(page!=1){
            hasPrePage = true;
        }else{
            hasPrePage = false;
        }
        if(page!=countPage){
            hasNextPage = true;
        }else {
            hasNextPage = false;
        }
        
        //用于数据库偏移量
        this.offset = (page-1)*size;

    }

}
2.2 数据库语句ArticleMapper.java
ArticleMapper .java
@Mapper
public interface ArticleMapper {

    @Insert("insert into article (title,description,tag,author_id,create_time,modified_time) values " +
            "(#{title},#{description},#{tag},#{authorId},#{createTime},#{modifiedTime})")
    int addArticle(Article article);

    //查询文章列表信息
    @Select("select u.*,a.id as aid,a.title,a.description,a.read_count,a.answer_count,a.like_count,a.create_time from article a,user u where a.author_id = u.id limit #{page},#{size}")
    @Results(id="ArticleUser",value = {
            @Result(id=true,property = "id",column = "id"),
            @Result(property = "id",column = "aid"),
            @Result(property = "title",column = "title"),
            @Result(property = "description",column = "description"),
            @Result(property = "authorId",column = "author_id"),
            @Result(property = "readCount",column = "read_count"),
            @Result(property = "answerCount",column = "answer_count"),
            @Result(property = "likeCount",column = "like_count"),
            @Result(property = "user.name",column = "name"),
            @Result(property = "user.avatarUrl",column = "avatar_url")
    })
    List<Article> list(@Param(value = "page") int page,@Param(value = "size") int size);

    //查询总文章数
    @Select("select count(1) from article a,user u where a.author_id = u.id")
    int count();
}
2.3 将获取到的分页数据放在model中用于前端页面获取
IndexController.java主要修改代码片段
int totalCount = articleMapper.count();
PaginationDTO paginationDTO =  paginationService.getPageInfo(page,size,totalCount);

model.addAttribute("paginationInfo",paginationDTO);
2.4Service层PaginationService的getPageInfo方法
@Service
public class PaginationService {

    public PaginationDTO getPageInfo(int page, int size, int totalCount) {
        PaginationDTO paginationDTO = new PaginationDTO();
        paginationDTO.setPagination(page,size,totalCount);
        return paginationDTO;
    }
}
2.5 主页添加分页布局
index.html
<!-- 分页 -->
        <nav aria-label="Page navigation">
            <ul class="pagination">
                <li th:if="${paginationInfo.isHasFirstPage()}">
                    <a th:href="@{/(page=1)}" aria-label="First">
                        <span aria-hidden="true">&lt;&lt;</span>
                    </a>
                </li>
                <li th:if="${paginationInfo.isHasPrePage()}">
                    <a th:href="@{/(page=${paginationInfo.page-1})}" aria-label="Previous">
                        <span aria-hidden="true">&lt;</span>
                    </a>
                </li>
                <li th:each="page: ${paginationInfo.getPageList()}" th:class="${page==paginationInfo.page}? 'active'"><a th:href="@{/(page = ${page})}" th:text="${page}"></a></li>
                <li th:if="${paginationInfo.isHasNextPage()}">
                    <a th:href="@{/(page=${paginationInfo.page+1})}" aria-label="Next">
                        <span aria-hidden="true">&gt;</span>
                    </a>
                </li>
                <li th:if="${paginationInfo.isHasLastPage()}">
                    <a th:href="@{/(page=${paginationInfo.getCountPage()})}" aria-label="Last">
                        <span aria-hidden="true">&gt;&gt;</span>
                    </a>
                </li>
            </ul>
        </nav>

以上就是本次分页功能核心代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java Web中实现MySQL分页功能,可以按照以下步骤进行: 1. 获取总记录数:使用SQL语句查询数据表中的总记录数,例如: ```sql SELECT COUNT(*) FROM table_name; ``` 2. 计算总页数:根据每页显示的记录数和总记录数计算出总页数,例如: ```java int pageSize = 10; // 每页显示的记录数 int totalCount = 100; // 总记录数 int totalPages = (totalCount + pageSize - 1) / pageSize; // 计算总页数 ``` 3. 查询当前页的数据:使用LIMIT关键字限制查询结果的范围,例如: ```sql SELECT * FROM table_name LIMIT start, pageSize; ``` 其中,start表示查询结果的起始位置,可以根据当前页和每页显示的记录数计算得出: ```java int currentPage = 1; // 当前页 int start = (currentPage - 1) * pageSize; // 计算查询结果的起始位置 ``` 4. 将查询结果封装成List对象并返回给前端。 完整的MySQL分页功能实现如下所示: ```java public List<User> findByPage(int currentPage, int pageSize) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; List<User> userList = new ArrayList<>(); try { // 获取数据库连接 conn = JdbcUtils.getConnection(); // 获取总记录数 String countSql = "SELECT COUNT(*) FROM user"; pstmt = conn.prepareStatement(countSql); rs = pstmt.executeQuery(); int totalCount = 0; if (rs.next()) { totalCount = rs.getInt(1); } // 计算总页数 int totalPages = (totalCount + pageSize - 1) / pageSize; // 查询当前页的数据 String dataSql = "SELECT * FROM user LIMIT ?, ?"; pstmt = conn.prepareStatement(dataSql); pstmt.setInt(1, (currentPage - 1) * pageSize); pstmt.setInt(2, pageSize); rs = pstmt.executeQuery(); while (rs.next()) { User user = new User(); user.setId(rs.getInt("id")); user.setName(rs.getString("name")); user.setAge(rs.getInt("age")); userList.add(user); } } catch (SQLException e) { e.printStackTrace(); } finally { JdbcUtils.close(conn, pstmt, rs); } return userList; } ``` 在实际应用中,可以将上述代封装成一个通用的分页工具类,方便其他模块的调用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值