基于Servlet实现分页查询

Servlet + JSP+JSTL +MySQL+Bootstrap 等技术实现分页查询功能。 

所用工具:IDEA 2022.3.3 + Navicat +Tomcat 等。

本文目录

一:运行效果

 二:代码详解

(1)index.jsp 

(2)PageBean 

(3)Servlet

(4)DAO层

(5)BaseDao

(6)JSP

 (7)所需数据表

 (8)案例项目结构

三:功能展示

点击下一页

点击尾页

点击上一页

点击首页


一:运行效果

运行之后如上图👆所示。

所包含的功能有: 首页、尾页、上一页、下一页、当前的页码总页码统计等。

至于关于分页的其他功能,如控制每一页显示几条数据、跳转到第几页等,有待后续更新...

 二:代码详解

(1)index.jsp 

首页发起请求。侧重功能实现,没做样式(可自行设计)。

<%--
  Created by IntelliJ IDEA.
  User: AdminSun
  Date: 2023/6/12
  Time: 15:44
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页</title>
  </head>
  <body>
      <h1>欢迎使用</h1>
      <a href="/RoomServlet">分页查询展示</a>
  </body>
</html>

(2)PageBean 

分页工具类:

package cn.shq.util;

import java.util.List;

public class PageBean {
    private Integer curPage;//当前页码
    private Integer pageSize;//每一页显示的条数
    private List datas; //每一页要显示的数据
    private Integer firstPage;//首页
    private Integer prevPage;//上一页
    private Integer nextPage;//下一页
    private Integer lastPage;//尾页
    private  Integer totalCount;//数据总条数
    private  Integer totalPages; //总页码

    public PageBean() {
    }

    /*   构造方法*/
    public PageBean(Integer curPage, Integer pageSize, List datas, Integer totalCount) {
        //初始化各个属性
        this.curPage = curPage;
        this.pageSize = pageSize;
        this.datas = datas;
        this.totalCount = totalCount;
        //计算出来其他的属性=====也算作初始化
        //计算总页码
        /*
         *    总页码  = 总条数 %  pageSize  ? 整除   则 总条数/pageSize
         *                                   有余数   总条数/pageSize+1
         * */
        this.totalPages=this.totalCount%this.pageSize==0?this.totalCount/this.pageSize:this.totalCount/this.pageSize+1;
        //   意思:   ↓↓↓↓
       /* if(totalCount%pageSize==0){
            this.totalPages=totalCount/pageSize;
        }else{
            this.totalPages=totalCount/pageSize+1;
        }*/
        this.firstPage=1;
        this.prevPage=this.curPage-1;
        this.nextPage=this.curPage+1;
        this.lastPage=this.totalPages;
        //对于超出范围的,加以限定
        //如果第一次访问的时候,
        if(curPage==null||curPage<1) curPage=1;
        //总页码
        if(this.totalPages==0) this.totalPages=1;
        //对于 上一页   当显示的页面为第一页的时候,不再递减
        if(prevPage<=0) this.prevPage=1;
        //对于下一页  最后一页的时候,下一页 停留在最后一页
        if(nextPage>=this.totalPages) this.nextPage=this.totalPages;
    }

    public Integer getCurPage() {
        return curPage;
    }

    public void setCurPage(Integer curPage) {
        this.curPage = curPage;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public List getDatas() {
        return datas;
    }

    public void setDatas(List datas) {
        this.datas = datas;
    }

    public Integer getFirstPage() {
        return firstPage;
    }

    public void setFirstPage(Integer firstPage) {
        this.firstPage = firstPage;
    }

    public Integer getPrevPage() {
        return prevPage;
    }

    public void setPrevPage(Integer prevPage) {
        this.prevPage = prevPage;
    }

    public Integer getNextPage() {
        return nextPage;
    }

    public void setNextPage(Integer nextPage) {
        this.nextPage = nextPage;
    }

    public Integer getLastPage() {
        return lastPage;
    }

    public void setLastPage(Integer lastPage) {
        this.lastPage = lastPage;
    }

    public Integer getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(Integer totalCount) {
        this.totalCount = totalCount;
    }

    public Integer getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(Integer totalPages) {
        this.totalPages = totalPages;
    }


}

(3)Servlet

控制器类:

package cn.shq.controller;

import cn.shq.dao.RoomDao;
import cn.shq.dao.impl.RoomDaoImp;
import cn.shq.util.PageBean;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "RoomServlet", value = "/RoomServlet")
public class RoomServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        RoomDao rm=new RoomDaoImp();
        String pageParam = req.getParameter("curPage");
        if (pageParam == null) pageParam = "1";
        if (pageParam == "") pageParam = "1";
        int curPage = Integer.parseInt(pageParam);
        //每一页显示的条数, 从页面下拉框获取
        String psize=req.getParameter("pageSize");
        if (psize == null) psize = "3";
        int pageSize = Integer.parseInt(psize);
        //调用dao,执行查询
        PageBean pageBean = rm.selByPage(curPage, pageSize);
        req.setAttribute("pager", pageBean);
        req.getRequestDispatcher("/admin/showRoom.jsp").forward(req, response);
    }

}

(4)DAO层

本案例中Servlet直接访问DAO层调用方法。

package cn.shq.dao.impl;

import cn.shq.dao.RoomDao;
import cn.shq.util.BaseDao;
import cn.shq.util.PageBean;

import java.util.List;
import java.util.Map;

public class RoomDaoImp implements RoomDao {
    @Override
    public PageBean selByPage(int curPage, int pageSize) {
        String sql="select r.rNum,r.rStatus,rs.roomstatus,rt.typeName,r.rPrice,r.rPhone,r.rPic \n" +
                "from room r,roomstatus rs,roomtype rt\n" +
                "where r.rType=rt.tid and r.rStatus=rs.sid\n" +
                "LIMIT ?,?";
        int startIndex=pageSize	* (curPage-1);
        List<Map<String, Object>> list = BaseDao.executeQuery(sql, startIndex, pageSize);
        sql="select count(*) pageNum from room";
        Long pageNum = (Long) BaseDao.executeQuery(sql).get(0).get("pageNum");
        PageBean pageBean = new PageBean(curPage,pageSize,list,pageNum.intValue());
        pageBean.setDatas(list);
        pageBean.setTotalCount(pageNum.intValue());
        return pageBean;
    }
}

(5)BaseDao

 访问数据库所用的工具类

package cn.shq.util;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseDao {
    protected static Connection conn = null;
    protected static PreparedStatement pstm = null;
    protected static ResultSet rs = null;

    private static String driver="com.mysql.jdbc.Driver";
    private static String url="jdbc:mysql://localhost:3306/bbs_xdy?useSSL=true";
    private static String username="root";
    private static String password="123456";

    private static Connection getConn(){
        try {
            Class.forName(driver);
            Connection connection = DriverManager.getConnection(url,username,password);
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /*
     * 通用关闭
     * */
    public static void closeAll(Connection conn,PreparedStatement pstm,ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (pstm != null) {
                pstm.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*
     * 增删改
     * */
    public static int executeUpdate(String sql, Object... obj) {
        try {
            conn = getConn();
            pstm = conn.prepareStatement(sql);
            setParam(obj);
            int num = pstm.executeUpdate();
            return num;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll(conn,pstm,rs);
        }
        return 0;
    }

    /*
     * 解决占位符参数的问题
     * */
    private static void setParam(Object... obj) {
        if (obj != null) {
            for (int i = 0; i < obj.length; i++) {
                try {
                    pstm.setObject(i + 1, obj[i]);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /*
     * 通用查询
     * */
    public static List<Map<String, Object>> executeQuery(String sql, Object... obj) {
        List<Map<String, Object>> list = new ArrayList();
        try {
            conn = getConn();
            pstm = conn.prepareStatement(sql);
            setParam(obj);
            rs = pstm.executeQuery();
            ResultSetMetaData rd = rs.getMetaData();
            int count = rd.getColumnCount();
            while (rs.next()) {
                Map<String, Object> map = new HashMap();
                for (int i = 0; i < count; i++) {
                    map.put(rd.getColumnName(i + 1), rs.getObject(i + 1));
                }
                list.add(map);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(conn,pstm,rs);
        }
        return list;
    }
}

(6)JSP

展示数据的页面。

<%--
  Created by IntelliJ IDEA.
  User: AdminSun 
  Date: 2020/12/08
  Time: 10:49
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<head>
    <title>住房管理</title>
    <link rel="stylesheet" href="../bootstrap/bootstrap-3.3.7-dist/css/bootstrap.css">
    <script src="../js/jquery-3.4.1.min.js"></script>
    <script src="../bootstrap/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
    <style>
        *{
            margin: 20px auto;
        }
    </style>
</head>
<body>
            <%--显示数据的表格--%>
            <table class="table table-hover table-bordered">
                <thead>
                <tr>
                    <th>序号</th>
                    <th>房号</th>
                    <th>房间图片</th>
                    <th>房间状态</th>
                    <th>房间类型</th>
                    <th>房间价格(元)</th>
                    <th>房间电话</th>
                </tr>
                </thead>
                <tbody>

                <c:if test="${empty pager.datas}">
                    <script>
                        alert("没有数据");
                    </script>
                </c:if>
                <c:if test="${ not empty pager.datas}">
                    <c:forEach items="${pager.datas}" var="room" varStatus="s">
                        <tr>
                            <td>${s.count}</td>
                            <td>${room.rNum}</td>
                            <td><img src="${room.rPic}" /></td>
                            <td>${room.roomstatus}</td>
                            <td>${room.typeName}</td>
                            <td>${room.rPrice}</td>
                            <td>${room.rPhone}</td>
                        </tr>
                    </c:forEach>
                </c:if>
                </tbody>
            </table>
        <%--分页控制--%>
            <ul class="pagination">
                <li>
                    <a href="/RoomServlet?op=selPage&&curPage=${pager.firstPage}">首页</a>
                </li>
                <li>
                    <a href="/RoomServlet?op=selPage&&curPage=${pager.prevPage}">上一页</a>
                </li>
                <li>
                    <a href="/RoomServlet?op=selPage&&curPage=${pager.nextPage}">下一页</a>
                </li>
                <li>
                    <a href="/RoomServlet?op=selPage&&curPage=${pager.lastPage}">尾页</a>
                </li>
                <li>
                    <a href="#">当前第 ${pager.curPage}页/共${pager.totalPages}页</a>
                </li>
            </ul>
</body>
</html>

该页面显示数据使用了JSTL标签库。

所以需要注意的是:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

 (7)所需数据表

仅展示主要表。其他表需自行创建。

 (8)案例项目结构

案例结构描述
src写Java源代码的根目录。
web/admin展示数据的JSP页面
web/bootstrap:案例中所需要的Bootstrap样式表和脚本库
web/img存放案例所需图片
web/js案例中jQuery所用库
web/WEB-INF/lib案例所用jar包(连接MySQL数据库和JSTL标签库)

三:功能展示

点击下一页

点击尾页

点击上一页

点击首页

 首页或尾页的时候,点击上一页或下一页不会进行跳转,停留在首页或尾页。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
单从表现层来说分页不是一个复杂的工作,稍微理一下思路,处于不同competence level的同学应该都能自己搞出来。 以上面的文章列表分页为例,我觉得分页有两点重要的, 一是:分页我们必须首先自己搞清楚,文章总数、每页显示文章数(页大小)、页数 二是:如何做好页脚的分页导航条 实际应用中,文章总数这个值我们从数据库可以得到;每页显示的文章数即分页的页大小可以自己定义;页数我们可以通过下面的个表达式简单得出。 假设: int pageSize = 10; //分页大小 int totalPosts = PagingDAO.entryList.size(); //总文章数 int totalPages = totalPosts/pageSize + ((totalPosts%pageSize)>0?1:0); //计算得出的总页数 每页的文章怎么取出来? 知道分页的大小之后,我们生成了页好的选取下拉框,每次选择第几页的时候,都会向Servlet传递当前选择页号的参数,这样Servlet调用后面的DAO相应的方法,取得文章列表信息,再回传到JSP以供显示。 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> page Size : ${pageSize} <br /> Total Posts: ${totalPosts} <br /> Total Pages: ${totalPages} <br /> Current Page: ${pageNumber} <hr /> <table> <thead> <tr align="center"> <td width="10%">Article ID</td> <td width="70%">Article Title</td> <td colspan="3">Actions</td> </tr> </thead> <tbody> <c:forEach items="${entryList}" var="entry"> <tr align="center"> <td>${entry.entryID}</td> <td>${entry.title}</td> <td><a href="viewEntry?entryID=${entry.entryID}">View</a></td> <td><a href="editEntry?entryID=${entry.entryID}">Edit</a></td> <td><a href="deleteEntry?entryID=${entry.entryID}">Delete</a></td> </tr> </c:forEach> </tbody> <tfoot> <tr align="center"> <td colspan="5"> <jsp:include page="paging_footer.jsp"></jsp:include> </td> </tr> </tfoot> </table> <hr/>
好的,下面我将详细介绍一下如何基于SpringMVC框架开发学生信息查询系统,实现分页查询显示学生选课信息表中的记录。为了方便演示,我将使用MySQL数据库和MyBatis框架。 1. 创建SpringMVC项目 首先,我们需要创建一个Maven项目,并在pom.xml文件中添加SpringMVC和MyBatis的依赖。 2. 配置数据源和MyBatis 在src/main/resources目录下创建一个jdbc.properties文件,用于配置数据源信息,例如: ``` jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/students?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password= ``` 然后,在src/main/resources目录下创建一个mybatis-config.xml文件,用于配置MyBatis的全局属性和类型别名。例如: ``` <configuration> <typeAliases> <package name="com.example.demo.entity"/> </typeAliases> <mapperScan basePackage="com.example.demo.mapper"/> </configuration> ``` 3. 创建数据库和表 在MySQL数据库中创建一个名为students的数据库,并在该数据库中创建一个名为student_course的表,用于存储学生选课信息。表结构如下: ``` CREATE TABLE `student_course` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '编号', `student_id` int(11) NOT NULL COMMENT '学生编号', `course_id` int(11) NOT NULL COMMENT '课程编号', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='学生选课信息表'; ``` 4. 编写实体类和Mapper接口 在com.example.demo.entity包下创建一个StudentCourse实体类,用于映射student_course表的记录。例如: ``` public class StudentCourse { private Integer id; private Integer studentId; private Integer courseId; // 省略getter和setter方法 } ``` 然后,在com.example.demo.mapper包下创建一个StudentCourseMapper接口,用于定义查询学生选课信息的方法。例如: ``` public interface StudentCourseMapper { List<StudentCourse> selectByPage(@Param("start") int start, @Param("pageSize") int pageSize); int count(); } ``` 5. 编写Service和Controller 在com.example.demo.service包下创建一个StudentCourseService接口和一个StudentCourseServiceImpl实现类,用于封装查询学生选课信息的方法。例如: ``` public interface StudentCourseService { PageResult<StudentCourse> selectByPage(int pageNum, int pageSize); } @Service public class StudentCourseServiceImpl implements StudentCourseService { @Autowired private StudentCourseMapper studentCourseMapper; @Override public PageResult<StudentCourse> selectByPage(int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); List<StudentCourse> list = studentCourseMapper.selectByPage(pageNum, pageSize); PageInfo<StudentCourse> pageInfo = new PageInfo<>(list); PageResult<StudentCourse> pageResult = new PageResult<>(); pageResult.setList(list); pageResult.setTotalCount(pageInfo.getTotal()); pageResult.setTotalPage(pageInfo.getPages()); pageResult.setPageSize(pageSize); pageResult.setPageNum(pageNum); return pageResult; } } ``` 然后,在com.example.demo.controller包下创建一个StudentCourseController类,用于处理分页查询的请求。例如: ``` @Controller @RequestMapping("/studentCourse") public class StudentCourseController { @Autowired private StudentCourseService studentCourseService; @RequestMapping("/list") public String list(@RequestParam(defaultValue = "1") int pageNum, Model model) { PageResult<StudentCourse> pageResult = studentCourseService.selectByPage(pageNum, 6); model.addAttribute("pageResult", pageResult); return "list"; } } ``` 6. 编写JSP页面 在src/main/webapp/WEB-INF/views目录下创建一个list.jsp页面,用于显示学生选课信息的列表。例如: ``` <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <title>学生选课信息列表</title> </head> <body> <table border="1"> <tr> <th>编号</th> <th>学生编号</th> <th>课程编号</th> </tr> <c:forEach items="${pageResult.list}" var="studentCourse"> <tr> <td>${studentCourse.id}</td> <td>${studentCourse.studentId}</td> <td>${studentCourse.courseId}</td> </tr> </c:forEach> </table> <br> <c:if test="${pageResult.pageNum > 1}"> <a href="${pageContext.request.contextPath}/studentCourse/list?pageNum=${pageResult.pageNum - 1}">上一页</a> </c:if> <c:if test="${pageResult.pageNum < pageResult.totalPage}"> <a href="${pageContext.request.contextPath}/studentCourse/list?pageNum=${pageResult.pageNum + 1}">下一页</a> </c:if> </body> </html> ``` 7. 配置DispatcherServlet 在web.xml文件中配置DispatcherServlet,用于处理所有的请求。例如: ``` <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> ``` 8. 配置SpringMVC 在src/main/resources目录下创建一个spring-mvc.xml文件,用于配置SpringMVC的相关属性和组件。例如: ``` <mvc:annotation-driven/> <context:component-scan base-package="com.example.demo.controller"/> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg ref="sqlSessionFactory"/> </bean> ``` 最后,启动项目,访问http://localhost:8080/studentCourse/list即可查看学生选课信息的列表,可以通过上一页和下一页链接进行分页浏览。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CiCi喜之郎

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值