分页工具类
package com.nanjing.page; import javax.servlet.http.HttpServletRequest; public class PageUtils { //总共记录数 private int totalResult; //总共页数 private int totalPage; //当前页数 private int currentPage=1; //每页显示的记录数 private int pageSize=2; private HttpServletRequest request; //当前页的第一条记录 private int fisrtIndex; //当前页的最后一天记录 private int lastIndex; public PageUtils() { } public void init(){ setTotalPage(); setCurrentPage(); if(request.getParameter("page")==null){ request.setAttribute("currentPage",1); }else{ request.setAttribute("currentPage",request.getParameter("page")); currentPage=Integer.parseInt(request.getParameter("page")); } setFisrtIndex(); setLastIndex(); request.setAttribute("totalPage", totalPage); request.setAttribute("pageTargetURL", request.getRequestURL()); } public int getTotalResult() { return totalResult; } public void setTotalResult(int totalResult) { this.totalResult = totalResult; } public int getTotalPage() { return totalPage; } public void setTotalPage() { if(totalResult<=pageSize){ totalResult=1; }else{ if(totalResult%pageSize>0){ this.totalPage = totalResult/pageSize+1; }else{ this.totalPage = totalResult/pageSize; } } } public int getCurrentPage() { return currentPage; } public void setCurrentPage() { if(request.getParameter("currentPage")==null){ currentPage=1; }else{ this.currentPage = Integer.parseInt(request.getParameter("currentPage")); } } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public HttpServletRequest getRequest() { return request; } public void setRequest(HttpServletRequest request) { this.request = request; } public int getFisrtIndex() { return fisrtIndex; } public void setFisrtIndex() { if(currentPage==1){ this.fisrtIndex=0; }else{ this.fisrtIndex=(currentPage-1)*pageSize; } } public int getLastIndex() { return lastIndex; } public void setLastIndex() { this.lastIndex = currentPage*pageSize; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } }
实体类
package com.nanjing.page; public class User { private int user_id; private String username; private String password; private String sex; public int getUser_id() { return user_id; } public void setUser_id(int userId) { user_id = userId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "User [password=" + password + ", sex=" + sex + ", user_id=" + user_id + ", username=" + username + "]"; } }
dao
package com.nanjing.page; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; public class Userdao { private final String oracleRownum="SELECT a.* FROM (SELECT B.*, ROWNUM R FROM ( #sql WHERE ROWNUM <= #lastIndex) B ) a WHERE a.R > #firstIndex"; public Statement getStatement() throws ClassNotFoundException, SQLException{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection conn=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:ORCL","alyssa","alyssa"); Statement statement=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); return statement; } public ResultSet doQueryCommon(PageUtils pageUtils,String sql) throws SQLException, ClassNotFoundException{ String pagesql=pageHandle(pageUtils,sql); ResultSet rs=getStatement().executeQuery(pagesql); return rs; } public ResultSet doQueryTotal(String sql) throws SQLException, ClassNotFoundException{ ResultSet rs=getStatement().executeQuery(sql); return rs; } public String pageHandle(PageUtils pageUtils,String sql){ return oracleRownum.replaceAll("#sql", sql) .replaceAll("#firstIndex", String.valueOf(pageUtils.getFisrtIndex())) .replaceAll("#lastIndex", String.valueOf(pageUtils.getLastIndex())); } public List<User> queryUser(PageUtils pageUtils,String sql) throws SQLException, ClassNotFoundException{ ResultSet rs=doQueryCommon(pageUtils,sql); List<User> userlist=new ArrayList<User>(); while(rs.next()){ int userId=rs.getInt("user_id"); String username=rs.getString("username"); String password=rs.getString("password"); String sex=rs.getString("sex"); User user=new User(); user.setUser_id(userId); user.setPassword(password); user.setUsername(username); user.setSex(sex); userlist.add(user); } return userlist; } public int queryTotalResult(String tablename) throws SQLException, ClassNotFoundException{ ResultSet rs=doQueryTotal("SELECT COUNT(*) c FROM "+tablename); int count=0; while(rs.next()){ count=rs.getInt("c"); } return count; } }
逻辑处理类
package com.nanjing.page; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class UserServlet extends HttpServlet{ private Userdao userdao=new Userdao(); private List<User> userlist=new ArrayList<User>(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { int totalResult=userdao.queryTotalResult("my_user"); PageUtils pageUtils=new PageUtils(); pageUtils.setRequest(req); pageUtils.setTotalResult(totalResult); pageUtils.init(); userlist=userdao.queryUser(pageUtils,"select *from my_user"); req.setAttribute("userlist", userlist); req.getRequestDispatcher("/user.jsp").forward(req, resp); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
分页页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <script type="text/javascript"> function fowordPage(){ var num=/^[0-9]+$/; var myPage=document.getElementById("myPage").value; if(num.test(myPage) && 0<parseInt(myPage) && parseInt(myPage)<${totalPage}){ document.getElementById("myPage_a").href="${pageTargetURL}?page="+myPage; }else{ alert("跳转页数输入不正确"); document.getElementById("myPage_a").href="javascript:void(0)"; } } </script> <a href="${pageTargetURL}?page=1">首页</a> <c:choose> <c:when test="${currentPage<=1}">上一页</c:when> <c:otherwise><a href="${pageTargetURL}?page=${currentPage-1}">上一页</a></c:otherwise> </c:choose> <c:choose> <c:when test="${currentPage>=totalPage}">下一页</c:when> <c:otherwise><a href="${pageTargetURL}?page=${currentPage+1}">下一页</a></c:otherwise> </c:choose> 跳到第<input type="text" id="myPage">页 <a href="" onclick="fowordPage()" id="myPage_a">跳转</a> <a href="${pageTargetURL}?page=${totalPage}">尾页</a> 当前第${currentPage}页,总共${totalPage}页 </body> </html>
测试页面:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <table> <tr> <th>id</th> <th>用户名</th> <th>密码</th> <th>性别</th> </tr> <c:forEach items="${userlist}" var="u"> <tr> <td>${u.user_id}</td> <td>${u.username}</td> <td>${u.password}</td> <td>${u.sex}</td> </tr> </c:forEach> <tr> <td colspan="4"><jsp:include page="page.jsp"></jsp:include></td> </tr> </table> </body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>test</display-name> <servlet> <servlet-name>user</servlet-name> <servlet-class>com.nanjing.page.UserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>user</servlet-name> <url-pattern>/userServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
脚本:
---------------------------------------------- -- Export file for user ALYSSA -- -- Created by alyssa on 2012/8/13, 20:46:24 -- ---------------------------------------------- spool 11.log prompt prompt Creating table MY_USER prompt ====================== prompt create table ALYSSA.MY_USER ( user_id INTEGER not null, username VARCHAR2(100), password VARCHAR2(100), sex VARCHAR2(200) ) tablespace ALYSSA_TEBLESPACE pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); comment on table ALYSSA.MY_USER is '用户表'; comment on column ALYSSA.MY_USER.username is '用户名'; spool off
http://localhost:8080/test/userServlet访问