数据分页
这个东西就像是百度最下端的那个东西一样的功能的,如下:
功能说明:
1、在不使用上方搜索功能时,能够查看到所有的数据
2、下面的分页功能将数据分成了许多页,下方的分页我规定只让他显示十页(总共不止十页,后面的要所在页面移动才能够显示出其他的页面,就像百度的分页功能一样的),每一页只显示十行数据
3、上面的查询功能也是借用了数据库的模糊查询功能实现的
当然了,这个小项目还需要使用到三个jar包:c3p0-0.9.1.2.jar、commons-dbutils-1.4.jar、mysql-connector-java-5.1.5-bin.jar
下面是代码:
配置文件:c3p0-config.xml
<c3p0-config> <!-- 默认配置,如果没有指定则使用这个配置 --> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl"> <![CDATA[jdbc:mysql://127.0.0.1:3306/mydata?useUnicode=true&characterEncoding=UTF-8]]> </property> <property name="user">root</property> <property name="password"></property> <!-- 初始化池大小 --> <property name="initialPoolSize">2</property> <!-- 最大空闲时间 --> <property name="maxIdleTime">30</property> <!-- 最多有多少个连接 --> <property name="maxPoolSize">10</property> <!-- 最少几个连接 --> <property name="minPoolSize">2</property> <!-- 每次最多可以执行多少个批处理语句 --> <property name="maxStatements">50</property> </default-config> <!-- 命名的配置 --> <named-config name="hncu"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/mydb</property> <property name="user">root</property> <property name="password"></property> <property name="acquireIncrement">5</property><!-- 如果池中数据连接不够时一次增长多少个 --> <property name="initialPoolSize">100</property> <property name="minPoolSize">50</property> <property name="maxPoolSize">1000</property> <property name="maxStatements">0</property> <property name="maxStatementsPerConnection">5</property> <!-- he's important, but there's only one of him --> </named-config> </c3p0-config>
index.jsp
<%@ 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>PagesDivided</title> </head> <body> <a href="<c:url value='PageServlet2'/>">数据分页的分页</a> </body> </html> show2.jsp
<%@ 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>showDividedPage</title> <link rel="stylesheet" href="<c:url value='/css/table.css'/>"/> <script type="text/javascript"> function change(obj){ window.location.href="<c:url value='/PageServlet2?page='/>"+obj.value; } </script> </head> <body> <h3>数据查询</h3> <form action='<c:url value="/PageServlet2"/>' method="post"> ID:<input type="text" name="id" value="${stud.id}"/> Name:<input type="text" name="name" value="${stud.name}"/> <input type="submit" value="模糊查询"/> </form> <hr/> <h3 align="center">当前页面内容</h3> <table> <tr><th>学号</th><th>姓名</th></tr> <c:forEach items="${result.datas}" var="map"> <tr> <td>${map.id}</td> <td>${map.name}</td> </tr> </c:forEach> </table> <br/><br/> <c:if test="${1!=result.currentPage}"> <a href="<c:url value='/PageServlet2?page=${result.currentPage-1}'/>">上一页</a> </c:if> <c:forEach begin="${showStart}" end="${showEnd}" var="idx"> <c:if test="${idx==result.currentPage}"> ${idx} </c:if> <c:if test="${idx!=result.currentPage}"> <span id="unselectedPage"> <a href="<c:url value='/PageServlet2?page=${idx}'/>">${idx}</a> </span> </c:if> </c:forEach> <c:if test="${result.pageCount!=result.currentPage}"> <a href="<c:url value='/PageServlet2?page=${result.currentPage+1}'/>">下一页</a> </c:if> <select οnchange="change(this)"> <c:forEach begin="1" end="${result.pageCount}" var="idx"> <option <c:if test="${idx==result.currentPage}">selected</c:if> value="${idx}"> 第${idx}页 </option> </c:forEach> </select> </body> </html> table.css
table{ clear:left; border: 1px solid blue; width:500px; border-collapse: collapse; margin: auto; } td{ border: 1px solid blue; text-align: center; } th{ border: 1px solid blue; } body{ text-align: center; } a{ text-decoration: none; } #unselectedPage{ border: 1px solid blue; width:500px; margin: auto; } 公共类C3p0Pool.java
package cn.hncu.pubs; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; //我们的这个包装,只是为了把c3p0池做成让每个线程(客户端)获得的是同一个连接,方便做b/s框架下的事务 public class C3p0Pool { private static DataSource pool; private static ThreadLocal<Connection> t=new ThreadLocal<Connection>(); static { pool=new ComboPooledDataSource(); } public static DataSource getDataSource(){ return pool; } public static Connection getConnection() throws SQLException{ Connection con=t.get(); if (con==null){ con=pool.getConnection(); t.set(con); } return con; } } DAO层
接口:IPageDAO2.java
package cn.hncu.page2.dao; import java.util.Map; import cn.hncu.page2.domain.Stud; public interface IPageDAO2 { public Map<String, Object> query(Integer pageNo, Stud stud) throws Exception; }实现类:PageJdbc2.java
package cn.hncu.page2.dao; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.MapListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import cn.hncu.page2.domain.Stud; import cn.hncu.pubs.C3p0Pool; public class PageJdbc2 implements IPageDAO2 { private final int pageSize=10; @Override public Map<String, Object> query(Integer pageNo, Stud stud) throws Exception { Map<String, Object> result=new HashMap<String, Object>(); //总行数 String sql="select count(1) from dbutilsstud where 1=1 ";//查总行数 String sql2="select * from dbutilsstud where 1=1 ";//查内容 if (stud.getId()!=null&&stud.getId().trim().length()!=0){ sql+="and id like '%"+stud.getId()+"%'"; sql2+="and id like '%"+stud.getId()+"%'"; } if (stud.getName()!=null&&stud.getName().trim().length()!=0){ sql+="and name like '%"+stud.getName()+"%'"; sql2+="and name like '%"+stud.getName()+"%'"; } QueryRunner run=new QueryRunner(C3p0Pool.getDataSource()); int rows=Integer.parseInt(""+run.query(sql, new ScalarHandler())); //总页数 int pageCount=rows/pageSize + (rows%pageSize==0 ? 0:1); result.put("pageCount", pageCount); //分页面内容 int startNo=(pageNo-1)*pageSize; sql2=sql2+" limit "+startNo+", "+pageSize; List<Map<String, Object>> datas=run.query(sql2, new MapListHandler()); result.put("datas", datas); return result; } } service层
接口:IPageService2.java
package cn.hncu.page2.service; import java.util.Map; import cn.hncu.page2.domain.Stud; public interface IPageService2 { public Map<String, Object> query(Integer pageNo, Stud stud) throws Exception; }实现类:PageServiceImpl2.java
package cn.hncu.page2.service; import java.util.Map; import cn.hncu.page2.dao.IPageDAO2; import cn.hncu.page2.dao.PageJdbc2; import cn.hncu.page2.domain.Stud; public class PageServiceImpl2 implements IPageService2 { //注入dao IPageDAO2 dao=new PageJdbc2(); @Override public Map<String, Object> query(Integer pageNo, Stud stud) throws Exception { return dao.query(pageNo, stud); } } servlet :PageServlet2.java
package cn.hncu.page2.servlet; import java.io.IOException; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.hncu.page2.domain.Stud; import cn.hncu.page2.service.IPageService2; import cn.hncu.page2.service.PageServiceImpl2; public class PageServlet2 extends HttpServlet { //注入service IPageService2 service=new PageServiceImpl2(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pageNo=request.getParameter("page"); if (pageNo==null||pageNo.trim().length()==0){ pageNo="1"; } Stud stud=null; if (request.getMethod().equalsIgnoreCase("GET")){ stud=(Stud) request.getSession().getAttribute("stud"); if (stud==null){ stud=new Stud(); } } else { stud=new Stud(); String id=request.getParameter("id"); String name=request.getParameter("name"); stud.setId(id); stud.setName(name); request.getSession().setAttribute("stud", stud); } try { Integer iPageNo=Integer.parseInt(pageNo); Map<String, Object> result=service.query(iPageNo,stud); //给结果集补一个数据: currentPage result.put("currentPage", iPageNo); //把结果集放入容器中 request.setAttribute("result", result); int showSize=10; int showStart=0; int showEnd=0; int pageCount=Integer.parseInt(""+result.get("pageCount")); if (pageCount<showSize){ showStart=1; showEnd=pageCount; } else { if (iPageNo<=(showSize/2+(showSize%2==0?0:1))){ showStart=1; showEnd=showSize; } else { showStart=iPageNo-showSize/2; showEnd=showStart+showSize-1; } if (showEnd>pageCount){ showEnd=pageCount; showStart=showEnd-showSize+1; } } request.setAttribute("showStart", showStart); request.setAttribute("showEnd", showEnd); //转到结果页面 request.getRequestDispatcher("/jsps/show2.jsp").forward(request, response); } catch (NumberFormatException e) { throw new RuntimeException("当前页格式转换错误", e); } catch (Exception e) { e.printStackTrace(); } } } 值对象层:Stud.java
package cn.hncu.page2.domain; public class Stud { private String id; private String name; public Stud() { } 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; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Stud other = (Stud) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
具体的分包图像如下:
这个小项目我是放在了page2这个包里面的,page1是这个项目的另一个版本,就没贴上来了;另外下面的show.jsp也是给另一个用的,这个项目使用的是show2.jsp
