首先,在JSP页面上创建一个表格用于展示查询结果,如下所示:

<table>
    <tr>
        <th>编号</th>
        <th>姓名</th>
        <th>年龄</th>
    </tr>
    <c:forEach var="user" items="${userList}">
        <tr>
            <td>${user.id}</td>
            <td>${user.name}</td>
            <td>${user.age}</td>
        </tr>
    </c:forEach>
</table>

然后,在控制器中编写查询和分页的逻辑代码,如下所示:

@RequestMapping("/query")
public String queryUsers(Model model, @RequestParam("pageNum") int pageNum) {
    int pageSize = 10; // 每页显示的记录数
    int totalRecord = userDao.queryTotalRecord(); // 总记录数
    int totalPage = (totalRecord + pageSize - 1) / pageSize; // 总页数

    if (pageNum < 1) {
        pageNum = 1;
    } else if (pageNum > totalPage) {
        pageNum = totalPage;
    }

    int startIndex = (pageNum - 1) * pageSize; // 起始索引

    List<User> userList = userDao.queryUsers(startIndex, pageSize); // 查询当前页的数据

    model.addAttribute("userList", userList);
    model.addAttribute("totalPage", totalPage);
    model.addAttribute("currentPage", pageNum);

    return "userList";
}

在上述代码中,userDao 是 MyBatis 的数据访问对象,queryTotalRecord() 方法用于查询总记录数,queryUsers() 方法用于查询当前页的数据。

接下来,在JSP页面上添加分页按钮,如下所示:

<c:if test="${currentPage > 1}">
    <a href="query?pageNum=1">首页</a>
    <a href="query?pageNum=${currentPage - 1}">上一页</a>
</c:if>

<c:if test="${currentPage < totalPage}">
    <a href="query?pageNum=${currentPage + 1}">下一页</a>
    <a href="query?pageNum=${totalPage}">尾页</a>
</c:if>

在上述代码中,${currentPage} 表示当前页码,${totalPage} 表示总页数。

最后,配置好相关的路由和视图解析器,启动应用程序,即可实现查询加分页效果

使用jsp+mybatis1实现查询加分页效果首页上一页下一页尾页

原文地址: https://www.cveoy.top/t/topic/ioM2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录