JDBC实现JavaWeb分页

JDBC实现JavaWeb分页_第1张图片
JDBC实现JavaWeb分页_第2张图片

  1. JDBC工具类
package cn.rzpt.dbutil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBConnection {
	private static String driver = "com.mysql.cj.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/world?serverTimezone=UTC";
    private static String username = "root";
    private static String password = "root";
    static {
        try {
            /**
             * 加载驱动
             */
            Class.forName(driver);
        }catch(Exception ex) {
            ex.printStackTrace();
        }
    }
    public static Connection getConnection() {
        /**
         * 创建连接对象
         */
        Connection conn=null;
        try {
            conn=(Connection) DriverManager.getConnection(url,username,password);
        }catch(Exception ex) {
            ex.printStackTrace();
        }
        return conn;
    }
    /**
     * 关闭相关流
     */
    public static void closeAll(ResultSet rs,Statement st,Connection conn) {
        try {
            if(rs!=null) {
                rs.close();
            }
            if(st!=null) {
                st.close();
            }
            if(conn!=null) {
                conn.close();
            }
        }catch(SQLException e) {
            e.printStackTrace();
        }
    }
    public static void closePst(ResultSet rs,PreparedStatement pst,Connection conn) {
        try {
            if(rs!=null) {
                rs.close();
            }
            if(pst!=null) {
                pst.close();
            }
            if(conn!=null) {
                conn.close();
            }
        }catch(SQLException e) {
            e.printStackTrace();
        }
    }
}

  1. 用户实体类
package cn.rzpt.entity;

public class User {
	private String name;
	private String passowrd;
	
	public User() {
	}

	public User(String name, String passowrd) {
		this.name = name;
		this.passowrd = passowrd;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassowrd() {
		return passowrd;
	}

	public void setPassowrd(String passowrd) {
		this.passowrd = passowrd;
	}

	@Override
	public String toString() {
		return "User [name=" + name + ", passowrd=" + passowrd + "]";
	}
	
}

  1. 分页信息的实体类
package cn.rzpt.entity;

import java.util.List;

/** 
 * 封装分页信息 
 * @author Administrator 
 * 
 */  
public class PageModel<E> {  
    //结果集  
    private List<E> list;  
    //查询记录数  
    private int totalRecords;   
    //每页多少条数据  
    private int pageSize;  
    //第几页  
    private int pageNo;  
      
    /** 
     * 总页数 
     * @return 
     */  
    public int getTotalPages() {  
//        return (totalRecords + pageSize - 1) / pageSize;
        return (totalRecords%pageSize==0?(totalRecords/pageSize):(totalRecords/pageSize+1));
    }  
      
    /** 
     * 取得首页 
     * @return 
     */  
    public int getTopPageNo() {  
        return 1;  
    }  
      
    /** 
     * 上一页 
     * @return 
     */  
    public int getPreviousPageNo() {  
        if (pageNo <= 1) {  
            return 1;  
        }  
        return pageNo - 1;  
    }  
      
    /** 
     * 下一页 
     * @return 
     */  
    public int getNextPageNo() {  
        if (pageNo >= getBottomPageNo()) {  
            return getBottomPageNo();  
        }  
        return pageNo + 1;    
    }  
      
    /** 
     * 取得尾页 
     * @return 
     */  
    public int getBottomPageNo() {  
        return getTotalPages();  
    }  
    /**
     * get set函数  
     * @return
     */
    public List<E> getList() {  
        return list;  
    }  
  
    public void setList(List<E> list) {  
        this.list = list;  
    }  
  
    public int getTotalRecords() {  
        return totalRecords;  
    }  
  
    public void setTotalRecords(int totalRecords) {  
        this.totalRecords = totalRecords;  
    }  
  
    public int getPageSize() {  
        return pageSize;  
    }  
  
    public void setPageSize(int pageSize) {  
        this.pageSize = pageSize;  
    }  
  
    public int getPageNo() {  
        return pageNo;  
    }  
  
    public void setPageNo(int pageNo) {  
        this.pageNo = pageNo;  
    }  
}

  1. Dao操作
package cn.rzpt.page;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.rzpt.dbutil.DBConnection;
import cn.rzpt.entity.PageModel;
import cn.rzpt.entity.User;

public class PageDao {
	public PageModel<User> findData(String pageNo,String pageSize){
		
        PageModel<User> pageModel=null; 
        Connection conn=DBConnection.getConnection();
        
        String sql="select * from user limit ?,?";  
         
        PreparedStatement pst=null;  
        ResultSet rs=null;  
        User user=null;  
        List<User> list=new ArrayList<User>();  
        
        try {  
              pst=conn.prepareStatement(sql); 
              //pstm.setInt(1, (pageNo-1)*pageSize); 
              //pstm.setInt(2, pageNo*pageSize);
              pst.setInt(1, (Integer.parseInt(pageNo)-1)*Integer.parseInt(pageSize));
              pst.setInt(2, Integer.parseInt(pageSize));  
              rs=pst.executeQuery();
              while(rs.next()){  
                  user=new User();  
                  user.setName(rs.getString("name"));  
                  user.setPassowrd(rs.getString("password"));  
                  list.add(user);  
               }
              
              //总的数据条数 
               ResultSet rs2=pst.executeQuery("select count(*) from user");
               int total=0;  
               if(rs2.next()){
                   total=rs2.getInt(1);
               }
               
                pageModel=new PageModel<User>();  
                pageModel.setPageNo(Integer.parseInt(pageNo));  
                pageModel.setPageSize(Integer.parseInt(pageSize));  
                pageModel.setTotalRecords(total);  
                pageModel.setList(list); 
            } catch (SQLException e) {  
                e.printStackTrace();  
            }finally{  
               DBConnection.closePst(rs, pst, conn); 
            } 
        return pageModel;  
    }  
      

}

  1. Servlet
package cn.rzpt.control;

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 cn.rzpt.entity.PageModel;
import cn.rzpt.entity.User;
import cn.rzpt.page.PageDao;

@WebServlet("/pageServlet")
public class PageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 	request.setCharacterEncoding("UTF-8");
	        response.setCharacterEncoding("UTF-8");
	        
	        String pageSize = request.getParameter("pageSize");// 每页显示行数
	        String pageNo = request.getParameter("pageNo");// 当前显示页次
	        
	        if (pageSize == null) {// 为空时设置默认页大小为10
	            pageSize = "10";
	        }
	       
	        if (pageNo == null) {// 为空时设置默认为第1页
	            pageNo = "1";
	        }
	        
	        //System.out.println("pageNo="+pageNo+"pageSize="+pageSize);
	        // 保存分页参数,传递给下一个页面
	        
	        request.setAttribute("pageSize", pageSize);
	        request.setAttribute("pageNo", pageNo);
	        
	        //新建Dao对象,获取pageModel
	        PageDao client=new PageDao();
	        PageModel<User> pageModel=client.findData(pageNo,pageSize); 
	        request.setAttribute("pageModel", pageModel);//前端获取这个值
	        request.getRequestDispatcher("showinfo.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="pageServlet">
	<input type="submit" value="查看所有用户信息">
</form>
</body>
</html>
<%@page import="cn.rzpt.entity.User" %>
<%@page import="cn.rzpt.entity.PageModel"%>
<%@page import="cn.rzpt.page.PageDao"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<%
	String pageSize = (String) request.getAttribute("pageSize");
	String pageNo = (String) request.getAttribute("pageNo");
	PageModel<User> pageModel = (PageModel<User>)request.getAttribute("pageModel");
	List<User> list=pageModel.getList();
%>
<body>
<table align="center" >
        <tr>
            <td align="center" colspan="3">
                <h2>用户所有信息</h2>
            </td>
        </tr>
        <tr align="center">
            <td><b>用户名称</b></td>
            <td><b>用户密码</b></td>
        </tr> 
         
  <%
    if(list==null||list.size()<1){
        %><p align="center">还没有任何数据!</p>
    <%}else{
        for(User user:list){
  %>   
  <tr>
     <td><%=user.getName() %></td>
     <td><%=user.getPassowrd()%></td>     
  </tr>
  <%
        }
    }    
  %>
 
</table>
    <form name="form1" action="pageServlet" method="post">
        <TABLE border="0" width="100%" >
            <TR>
                <TD align="left"><a>每页条数</a>
                <select name="pageSize"
                    onchange="document.all.pageNo.value='1';document.all.form1.submit();">
                    <option value="10" <%if(pageSize.equals("10")){%>
                        selected="selected" <%}%>>10</option>
                    <option value="20" <%if(pageSize.equals("20")){%>
                        selected="selected" <%}%>>20</option>
                    <option value="30" <%if(pageSize.equals("30")){%>
                        selected="selected" <%}%>>30</option>
                </select></TD>
                <TD align="right">
                <a
                    href="javascript:document.all.pageNo.value='<%= pageModel.getTopPageNo() %>';document.all.form1.submit();">首页</a>
                <a
                    href="javascript:document.all.pageNo.value='<%= pageModel.getPreviousPageNo() %>';document.all.form1.submit();">上一页</a>
                <a
                    href="javascript:document.all.pageNo.value='<%= pageModel.getNextPageNo()%>';document.all.form1.submit();">下一页</a>
                <a
                    href="javascript:document.all.pageNo.value='<%= pageModel.getBottomPageNo()%>';document.all.form1.submit();">尾页</a>
                <a></a>
                <select name="pageNo" onchange="document.all.form1.submit();">
                    <%
                        int pageCount = pageModel.getTotalPages();
                    %>
                    <%
                        for (int i = 1; i <= pageCount; i++) {
                    %>
                    <option value="<%=i%>" <%if(pageNo.equals(i+"")){%>
                        selected="selected" <%}%>><%=i%></option>
                    <%
                        }
                    %>
                </select><a></a></TD>
            </TR>
        </TABLE>

        </form>
</body>
</html>

你可能感兴趣的:(JavaWeb)