使用servlet和jsp实现页面信息的分页展示,数据从数据库中查询出来(首页,上一页,下一页,末页)

it2026-08-19  7

一 最终效果展示

1.数据从首页开始展示,所以没有前一页

2.第二页时包含前一页和后一页

3.末页时不包含后一页

4.也可以选择每一页要展示的数据条数

二 代码

1.先创建一个用来实现分页的实体类

package com.briup.model; import java.util.List; /** * 用来进行页面分页,切换页数的实体类 * @author MECHREVO * */ public class PageInfo<T> { private int pageSize = 5; //每页显示的数据条数 private int total; //总记录数 private int currentPage = 1; //当前页码 private int pages; //总页数。 private int prePage; //前一页 private int nextPage; //后一页 private int firstPage = 1; //首页 private int lastPage; //末页 private boolean hasPrePage; private boolean hasNextPage; private List<T> datas; //当前页要显示的所有数据。 public PageInfo(int total,int pageSize,int currentPage,List<T> datas) { this.total = total; this.pageSize = pageSize; this.currentPage = currentPage; this.datas = datas; //判断总页数,如果取余等于0则不加一,如果不等于则加一 this.pages = total%pageSize==0?total/pageSize:total/pageSize+1; this.prePage = currentPage<=1?currentPage:currentPage-1; this.nextPage = currentPage>=pages?currentPage:currentPage+1; this.lastPage = pages; this.hasNextPage = currentPage<pages; this.hasPrePage = currentPage>1; } public int getPageSize() { return pageSize; } public int getTotal() { return total; } public int getCurrentPage() { return currentPage; } public int getPages() { return pages; } public int getPrePage() { return prePage; } public int getNextPage() { return nextPage; } public int getFirstPage() { return firstPage; } public int getLastPage() { return lastPage; } public boolean isHasPrePage() { return hasPrePage; } public boolean isHasNextPage() { return hasNextPage; } public List<T> getDatas() { return datas; } }

2.展示信息的jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <!-- base设置文件相对的路径,可以避免页面跳转找不到的错误 --> <base href="${pageContext.request.contextPath}/"> <title>区域信息管理</title> <link style="text/css" rel="stylesheet" href="css/main.css"> </head> <body> <div class="main"> <div class="head"> <h1>企业信息管理系统</h1> </div> <div class="content"> <div class="left"> <ul> <li><a href="region/allregion.do">区域信息管理</a></li> <li><a href="depart/depart.html">部门信息管理</a></li> <li><a href="emp/emp.html">员工信息管理</a></li> </ul> </div> <div class="rigth"> <div class = "search"> <span> <input type="text" placeholder="请输入区域名称"> <button>检索</button> <button onclick="javascript:window.location.href='region/addRegion.html'">添加</button> </span> </div> <table> <thead> <tr> <th>区域编号</th> <th>区域名称</th> <th>操作</th> </tr> </thead> <tbody> <c:forEach var="region" items="${requestScope.pageInfo.datas }" varStatus="s"> <c:if test="${(s.index+1)%2==0 }"> <tr class="odd"> </c:if> <c:if test="${(s.index+1)%2!=0 }"> <tr> </c:if> <td>${region.id }</td> <td>${region.name }</td> <td><button>编辑</button> <button>删除</button></td> </tr> </c:forEach> </tbody> <tfoot> <tr> <td colspan="3" align="right"> <select name="pageSize" onchange="changeSize(this.value)"> <option value="5">5</option> <option value="10">10</option> <option value="15">15</option> <option value="20">20</option> </select> <!-- 设置后用于更改默认的展示条数 --> <script type="text/javascript"> pageSize = ${pageInfo.pageSize}; options = document.getElementsByTagName("option"); for(var i=0;i<options.length;i++){ if(options[i].value==pageSize){ options[i].selected='selected'; } } </script> <span><a href="region/allregion.do?currentPage=1&pageSize=${pageInfo.pageSize }">首 页</a></span> <!-- 判断有没有前一页 --> <c:if test="${ pageInfo.hasPrePage}"> <span><a href="region/allregion.do?currentPage=${pageInfo.prePage }&pageSize=${pageInfo.pageSize }">前一页</a></span> </c:if> <!-- 判断有没有后一页 --> <c:if test="${pageInfo.hasNextPage}"> <span><a href="region/allregion.do?currentPage=${pageInfo.nextPage }&pageSize=${pageInfo.pageSize }">后一页</a></span> </c:if> <span><a href="region/allregion.do?currentPage=${pageInfo.pages }&pageSize=${pageInfo.pageSize }">末 页</a></span> 共${pageInfo.total }条记录${pageInfo.pages }页 </td> </tr> </tfoot> </table> </div> </div> <div style="clear: both;"></div> <div class="footer"> 本系统最终解释权为我所有。 </div> </div> </body> <script type="text/javascript"> function changeSize(pageSize){ window.location.href="allregion.do?pageSize="+pageSize } </script> </html>

3.创建一个java类,书写SQL语句实现查询

package com.briup.dao.impl; import java.math.BigDecimal; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import com.briup.common.util.DBUtils; import com.briup.dao.IRegionDao; import com.briup.model.Region; public class RegionDaoImpl implements IRegionDao{ QueryRunner qr = new QueryRunner(); //查询数据总数 public int count() { try(Connection conn = DBUtils.getConnection();) { return qr.query(conn, "select count(*) from s_region", new ScalarHandler<BigDecimal>(1)).intValue(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } } public List<Region> findByPage(int currentPage,int pageSize){ //分页代码的核心SQL语句利伪列rownum来实现 try(Connection conn = DBUtils.getConnection();) { List<Region> list = qr.query(conn, "select id,name from " +"(select id,name,rownum r " +"from s_region) region " +"where r between ? and ?", new BeanListHandler<Region>(Region.class), (currentPage-1)*pageSize+1,currentPage*pageSize); System.out.println("list:"+list); return list; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } } }

4.创建一个类调用上面的方法来产生一个分页的实体对象

package com.briup.service.impl; import java.util.List; import com.briup.common.util.BeanFactory; import com.briup.dao.IRegionDao; import com.briup.model.PageInfo; import com.briup.model.Region; import com.briup.service.IRegionService; public class RegionServiceImpl implements IRegionService{ IRegionDao dao = (IRegionDao) BeanFactory.getBean(BeanFactory.GERION_DAO); public PageInfo<Region> findByPage(int currentPage,int pageSize){ int total = dao.count(); List<Region> list = dao.findByPage(currentPage, pageSize); System.out.println("------------------"+list); return new PageInfo<Region>(total, pageSize, currentPage, list); } }

5.写一个servlet实现页面信息的分页展示

package com.briup.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.briup.common.util.BeanFactory; import com.briup.model.PageInfo; import com.briup.model.Region; import com.briup.service.IRegionService; //多一个region/,是为了后面可以过滤region/* @WebServlet("/region/allregion.do") public class AllRegionServlet2 extends HttpServlet{ private static final long serialVersionUID = 1L; IRegionService service = (IRegionService) BeanFactory.getBean(BeanFactory.GERION_SERVICE); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pageSizeStr = req.getParameter("pageSize"); String currentPageStr = req.getParameter("currentPage"); //先给一个默认值,用来定义第一次加载显示的标准 int pageSize = 5; int currentPage = 1; //判断不为null 或者 去首尾空格后不为"" if(pageSizeStr!=null && !"".equals(pageSizeStr.trim())) { pageSize = Integer.parseInt(pageSizeStr); } if(currentPageStr!=null && !"".equals(currentPageStr.trim())) { currentPage = Integer.parseInt(currentPageStr); } try { PageInfo<Region> pageInfo = service.findByPage(currentPage, pageSize); req.setAttribute("pageInfo", pageInfo); req.getRequestDispatcher("/region/region.jsp").forward(req, resp);; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

6.上面用到的接口和产生对象的java类

package com.briup.dao; import java.util.List; import com.briup.model.Region; public interface IRegionDao { int count(); List<Region> findByPage(int currentPage,int pageSize); } package com.briup.service; import com.briup.model.PageInfo; import com.briup.model.Region; public interface IRegionService { PageInfo<Region> findByPage(int currentPage,int pageSize); }

产生对象的类,作用是用来解耦合

1.先写一个bean.properties文件用来保存要产生对象的权限类名

regionDao=com.briup.dao.impl.RegionDaoImpl regionService=com.briup.service.impl.RegionServiceImpl

2.写一个java类来解析这个文件,并产生对应的对象

package com.briup.common.util; import java.io.IOException; import java.util.Properties; public class BeanFactory { public final static String GERION_DAO = "regionDao"; public final static String GERION_SERVICE = "regionService"; private static Properties props = new Properties(); static { try { props.load(BeanFactory.class.getResourceAsStream("/bean.properties")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } } public static Object getBean(String name) { /*if(name.equals(GERION_DAO)) { return new RegionDaoImpl(); }else if(name.equals(GERION_SERVICE)){ return new RegionServiceImpl(); }else { return null; }*/ String clsName = props.getProperty(name); try { return Class.forName(clsName).newInstance(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } } }

 

 

最新回复(0)