1、关于Java分页实现的流程图
2、在分页的实现中,关键的几个类,以及代码的实现,QueryInfo,QueryResult,PageBean
QueryInfo的代码实现
public class QueryInfo { private int currentpage = 1; //用户当前看的页 private int pagesize = 5; //记住用户想看的页面大小 private int startindex; //记住用户看的页的数据在数据库的起始位置 public int getCurrentpage() { return currentpage; } public void setCurrentpage(int currentpage) { this.currentpage = currentpage; } public int getPagesize() { return pagesize; } public void setPagesize(int pagesize) { this.pagesize = pagesize; } public int getStartindex() { this.startindex = (this.currentpage-1)*this.pagesize; return startindex; } }
QueryResult的代码实现
public class QueryResult { private List list; //记住用户看的页的数据 private int totalrecord; //记往总记录数 public List getList() { return list; } public void setList(List list) { this.list = list; } public int getTotalrecord() { return totalrecord; } public void setTotalrecord(int totalrecord) { this.totalrecord = totalrecord; } }
PageBean的代码实现
public class PageBean { private List list; private int totalrecord; private int pagesize; private int totalpage; private int currentpage; private int previouspage; private int nextpage; private int[] pagebar; public List getList() { return list; } public void setList(List list) { this.list = list; } public int getTotalrecord() { return totalrecord; } public void setTotalrecord(int totalrecord) { this.totalrecord = totalrecord; } public int getPagesize() { return pagesize; } public void setPagesize(int pagesize) { this.pagesize = pagesize; } public int getTotalpage() { //100 5 20 //101 5 21 //99 5 20 if(this.totalrecord%this.pagesize==0){ this.totalpage = this.totalrecord/this.pagesize; }else{ this.totalpage = this.totalrecord/this.pagesize+1; } return totalpage; } public int getCurrentpage() { return currentpage; } public void setCurrentpage(int currentpage) { this.currentpage = currentpage; } public int getPreviouspage() { if(this.currentpage-1<1){ this.previouspage = 1; }else{ this.previouspage = this.currentpage-1; } return previouspage; } public int getNextpage() { if(this.currentpage+1>=this.totalpage){ this.nextpage = this.totalpage; }else{ this.nextpage = this.currentpage +1; } return nextpage; } public int[] getPagebar() { int startpage; int endpage; int pagebar[] = null; if(this.totalpage<=10){ pagebar = new int[this.totalpage]; startpage = 1; endpage = this.totalpage; }else{ pagebar = new int[10]; startpage = this.currentpage - 4; endpage = this.currentpage + 5; //总页数=30 3 -1 //总页数=30 29 34 21 30 if(startpage<1){ startpage = 1; endpage = 10; } if(endpage>this.totalpage){ endpage = this.totalpage; startpage = this.totalpage - 9; } } int index = 0; for(int i=startpage;i<=endpage;i++){ pagebar[index++] = i; } this.pagebar = pagebar; return this.pagebar; /*int pagebar[] = new int[this.totalpage]; for(int i=1;i<=this.totalpage;i++){ pagebar[i-1] = i; } this.pagebar = pagebar; return pagebar;*/ } }
Student实体类的代码
package cn.itcast.domain; public class Student { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
3、关于dao层StudentDao,serive层StudentSerive,controller层StudentServlet层的实现
关于dao层StudentDao
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import cn.itcast.domain.QueryResult; import cn.itcast.domain.Student; import cn.itcast.utils.JdbcUtils; public class StudentDao { public QueryResult pageQuery(int startindex,int pagesize){ Connection conn = null; PreparedStatement st = null; ResultSet rs = null; QueryResult qr = new QueryResult(); try{ conn = JdbcUtils.getConnection(); String sql = "select * from student limit ?,?"; st = conn.prepareStatement(sql); st.setInt(1, startindex); st.setInt(2, pagesize); rs = st.executeQuery(); List list = new ArrayList(); while(rs.next()){ Student s = new Student(); s.setId(rs.getString("id")); s.setName(rs.getString("name")); list.add(s); } qr.setList(list); sql = "select count(*) from student"; rs = conn.prepareStatement(sql).executeQuery(); if(rs.next()){ qr.setTotalrecord(rs.getInt(1)); } return qr; }catch (Exception e) { throw new RuntimeException(e); }finally{ JdbcUtils.release(conn, st, rs); } } }
serive层StudentSerive
import cn.itcast.dao.StudentDao; import cn.itcast.domain.PageBean; import cn.itcast.domain.QueryInfo; import cn.itcast.domain.QueryResult; public class StudentService { public PageBean pageQuery(QueryInfo info){ StudentDao dao = new StudentDao(); QueryResult qr = dao.pageQuery(info.getStartindex(), info.getPagesize()); PageBean bean = new PageBean(); bean.setCurrentpage(info.getCurrentpage()); bean.setList(qr.getList()); bean.setPagesize(info.getPagesize()); bean.setTotalrecord(qr.getTotalrecord()); return bean; } }
controller层StudentServlet层的实现
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.itcast.domain.PageBean; import cn.itcast.domain.QueryInfo; import cn.itcast.service.BusinessService; import cn.itcast.utils.WebUtils; public class ListStudentServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { QueryInfo info = WebUtils.request2Bean(request, QueryInfo.class); BusinessService service = new BusinessService(); PageBean bean = service.pageQuery(info); request.setAttribute("pagebean", bean); request.getRequestDispatcher("/liststudent.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
4、用到的工具类JdbcUtils和WebUtils
工具类JdbcUtils
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class JdbcUtils { private static Properties config = new Properties(); static{ try { config.load(JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties")); Class.forName(config.getProperty("driver")); } catch (Exception e) { throw new ExceptionInInitializerError(e); } } public static Connection getConnection() throws SQLException{ return DriverManager.getConnection(config.getProperty("url"), config.getProperty("username"), config.getProperty("password")); } public static void release(Connection conn,Statement st,ResultSet rs){ if(rs!=null){ try{ rs.close(); //throw new }catch (Exception e) { e.printStackTrace(); } rs = null; } if(st!=null){ try{ st.close(); }catch (Exception e) { e.printStackTrace(); } st = null; } if(conn!=null){ try{ conn.close(); }catch (Exception e) { e.printStackTrace(); } } } }
db.properties的配置
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/student username=root password=root
工具类WebUtils
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.Converter; public class WebUtils { public static <T> T request2Bean(HttpServletRequest request,Class<T> beanClass){ try{ T bean = beanClass.newInstance(); //得到request里面所有数据 Map map = request.getParameterMap(); //map{name=aa,password=bb,birthday=1990-09-09} bean(name=aa,password=dd,birthday=Date) ConvertUtils.register(new Converter(){ public Object convert(Class type, Object value) { if(value==null){ return null; } String str = (String) value; if(str.trim().equals("")){ return null; } SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { return df.parse(str); } catch (ParseException e) { throw new RuntimeException(e); } } }, Date.class); BeanUtils.populate(bean, map); return bean; }catch (Exception e) { throw new RuntimeException(e); } } public static String generateID(){ return UUID.randomUUID().toString(); } }
关于页面的显示,主要利用EL表达式和JSTL来获取数据
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>显示学生分页数据</title> </head> <body> <c:forEach var="s" items="${pagebean.list}"> ${s.id } ${s.name } <br/> </c:forEach> <script type="text/javascript"> function gotopage(currentpage){ var pagesize = document.getElementById("pagesize").value; window.location.href = ‘${pageContext.request.contextPath}/servlet/ListStudentServlet?currentpage=‘ + currentpage + ‘&pagesize=‘ + pagesize; } </script> 共[${pagebean.totalrecord }]条记录, 每页<input type="text" id="pagesize" value="${pagebean.pagesize }" onchange="gotopage(${pagebean.currentpage })" style="width: 30px" maxlength="2">条, 共[${pagebean.totalpage }]页, 当前[${pagebean.currentpage }]页 <a href="javascript:void(0)" onclick="gotopage(${pagebean.previouspage })">上一页</a> <c:forEach var="pagenum" items="${pagebean.pagebar}"> <c:if test="${pagenum==pagebean.currentpage}"> <font color="red">${pagenum }</font> </c:if> <c:if test="${pagenum!=pagebean.currentpage}"> <a href="javascript:void(0)" onclick="gotopage(${pagenum })">${pagenum }</a> </c:if> </c:forEach> <a href="javascript:void(0)" onclick="gotopage(${pagebean.nextpage })">下一页</a> <input type="text" id="pagenum" style="width: 30px"> <input type="button" value=" GO " onclick="gotopage(document.getElementById(‘pagenum‘).value)"> </body> </html>
时间: 2024-10-09 21:05:09