Java 實現分頁功能


driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8
user=LF
password=LF
package cn.zr.testpage.entity;

public class User {
    
    private String name;
    private int age;
    private String hobby;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getHobby() {
        return hobby;
    }
    public void setHobby(String hobby) {
        this.hobby = hobby;
    }
    public User() {
    }
    public User(String name, int age, String hobby) {
        this.name = name;
        this.age = age;
        this.hobby = hobby;
    }
    @Override
    public String toString() {
        return "User [name=" + name + ", age=" + age + ", hobby=" + hobby + "]";
    }
    
    
    
}
package cn.zr.testpage.service;

import java.util.List;

import cn.zr.testpage.entity.User;
import cn.zr.testpage.utils.Page;

public interface UserService {

    /**
     * 獲取總數量
     * @return 返回總數
     */
    int getAmount();

    /**
     * 獲取當前頁的數據
     * @param page 
     * @return 返回前頁的數據
     */
    List<User> getUserInfo(Page page);

}
package cn.zr.testpage.service.impl;

import java.util.List;

import cn.zr.testpage.dao.UserDao;
import cn.zr.testpage.dao.impl.UserDaoImpl;
import cn.zr.testpage.entity.User;
import cn.zr.testpage.service.UserService;
import cn.zr.testpage.utils.Page;

public class UserServiceImpl implements UserService {
    private UserDao userDao;
    // 通過代碼塊加載實現類
    {
        userDao = new UserDaoImpl();
    }
    
    @Override
    public int getAmount() {
        return userDao.getAmount();
    }

    @Override
    public List<User> getUserInfo(Page page) {
        return userDao.getUserInfo(page);
    }

}
package cn.zr.testpage.dao;

import java.util.List;

import cn.zr.testpage.entity.User;
import cn.zr.testpage.utils.Page;

public interface UserDao {

    /**
     * 獲取總數量
     * @return 返回總數
     */
    int getAmount();

    /**
     * 獲取當前頁的數據
     * @param page 
     * @return 返回前頁的數據
     */
    List<User> getUserInfo(Page page);

}
package cn.zr.testpage.dao.impl;


import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.zr.testpage.dao.UserDao;
import cn.zr.testpage.entity.User;
import cn.zr.testpage.utils.JdbcUtils;
import cn.zr.testpage.utils.Page;
import cn.zr.testpage.utils.UserBasicalImpl;

public class UserDaoImpl extends UserBasicalImpl implements UserDao{
    
    
    /**
     * 獲取總數
     */
    @Override
    public int getAmount() {
        connection = JdbcUtils.getConnection();
        String sql = "SELECT COUNT(*) FROM USERINFO";
        int count = 0;
        try {
            pStatement = connection.prepareStatement(sql);
            rSet = pStatement.executeQuery();
            if(rSet.next()){
                count = rSet.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            // 調用父類方法關閉資源
            super.close();
        }
        return count;
    }

    /**
     * 獲取當前頁的數據
     * @param page 
     * @return 返回前頁的數據
     */
    @Override
    public List<User> getUserInfo(Page page) {

        connection = JdbcUtils.getConnection();
        //基於MySQL的函數的分頁
        String sql = "SELECT 姓名,年齡,愛好 FROM USERINFO LIMIT ?,?";
        // 創建集合
        List<User> list = new ArrayList<User>();
        try {
            pStatement = connection.prepareStatement(sql);
            //設置相關參數
            pStatement.setInt(1, page.getStart());
            pStatement.setInt(2, page.getSize());
            rSet = pStatement.executeQuery();
            while(rSet.next()){
                User user = new User();
                user.setName(rSet.getString("姓名"));
                user.setAge(rSet.getInt("年齡"));
                user.setHobby(rSet.getString("愛好"));
                list.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            // 調用父類方法關閉資源
            super.close();
        }
        return list;
    }

}
package cn.zr.testpage.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.zr.testpage.entity.User;
import cn.zr.testpage.service.UserService;
import cn.zr.testpage.service.impl.UserServiceImpl;
import cn.zr.testpage.utils.BaseServlet;
import cn.zr.testpage.utils.Page;

public class ListServlet extends BaseServlet{

    private static final long serialVersionUID = 1L;

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        
        System.out.println("...doGet...");
        
        // 獲取當前頁
        String curpage = req.getParameter("curpage");
        UserService userService = new UserServiceImpl();
        // 獲取總數量
        int count = userService.getAmount();
        //字符串轉成整型
        int currentpage = super.currentPage(curpage);
        // 創建page對象
        Page page = new Page(count, currentpage, pagesize);
        // 獲取當前頁的數據
        List<User> users = userService.getUserInfo(page);
        //將相關數據存儲起來
        req.setAttribute("page", page);
        req.setAttribute("users", users);
        
        System.out.println(count);
        System.out.println(users);
        //轉發
        req.getRequestDispatcher("/WEB-INF/jsp/list.jsp").forward(req, resp);

        
        
    }
    
    
}
package cn.zr.testpage.utils;

import javax.servlet.http.HttpServlet;


public class BaseServlet extends HttpServlet {
    
    public int pagesize = 2;
    
    
    public int currentPage(String cpage){
        int currentpage = cpage!=null && !"".equals(cpage) && isint(cpage)? currentpage=Integer.parseInt(cpage):1;
        return currentpage;
    }
    
    public boolean isint(String str){
        boolean bo = true;
        try {
            Integer.parseInt(str);
        } catch (Exception e) {
            bo = false;
        }
        return bo;
    }
    

}
package cn.zr.testpage.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
 * 
 * @author lf
 *
 */
public class JdbcUtils {
    
    // 獲取數據庫連接
    public static Connection getConnection() {
        String url="jdbc:mysql://localhost:3306/test?allowMultiQueries=true&useUnicode=true&amp;characterEncoding=utf8";
        String user="LF";
        String password ="LF";
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        
        try {
            connection =  DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return connection;
    }
}
package cn.zr.testpage.utils;


public class Page {

    // 頁數(第幾頁)
    private int currentpage;

    // 查詢數據庫里面對應的數據有多少條
    private int total;// 從數據庫查處的總記錄數

    // 每頁查詢的數量條
    private int size;

    // 下頁
    private int next;

    // 最后一頁
    private int last;
    
    private int lpage;
    
    private int rpage;
    
    //從哪條開始查
    private int start;
    
    public Page() {
        super();
    }

    public int getCurrentpage() {
        return currentpage;
    }

    /****
     * 
     * @param currentpage
     * @param total
     * @param pagesize
     */
    public void setCurrentpage(int currentpage,int total,int pagesize) {
        //如果整除表示正好分N頁,如果不能整除在N頁的基礎上+1頁
        int totalPages = total%pagesize==0? total/pagesize : (total/pagesize)+1;
        
        //總頁數
        this.last = totalPages;
        
        //判斷當前頁是否越界,如果越界,我們就查最后一頁
        if(currentpage>totalPages){
            this.currentpage = totalPages;
        }else{
            this.currentpage=currentpage;
        }
        if(currentpage<=0){
            this.currentpage=1;
        }
        
        //計算start   1----0    2  ------ 5
        this.start = (this.currentpage-1)*pagesize;
        
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public int getNext() {
        return  currentpage<last? currentpage+1: last;
    }


    //上一頁
    public int getUpper() {
        return currentpage>1? currentpage-1: currentpage;
    }

    public int getLast() {
        return last;
    }

    //總共有多少頁,即末頁
    public void setLast(int last) {
        this.last = total%size==0? total/size : (total/size)+1;
    }
    

    public int getLpage() {
        return lpage;
    }

    public void setLpage(int lpage) {
        this.lpage = lpage;
    }

    public int getRpage() {
        return rpage;
    }

    public void setRpage(int rpage) {
        this.rpage = rpage;
    }

    /****
     * 
     * @param total   總記錄數
     * @param currentpage    當前頁
     * @param pagesize    每頁顯示多少條
     */
    public Page(int total,int currentpage,int pagesize) {
        //總記錄數
        this.total = total;
        //每頁顯示多少條 
        this.size=pagesize;
        
        //計算當前頁和數據庫查詢起始值以及總頁數
        setCurrentpage(currentpage, total, pagesize);
        
        //分頁計算
        int leftcount =5,    //需要向上一頁執行多少次
            rightcount =4;
        //起點頁
        this.lpage =currentpage;
        //結束頁
        this.rpage =currentpage;
        
        //2點判斷
        this.lpage = currentpage-leftcount;            //正常情況下的起點
        this.rpage = currentpage+rightcount;        //正常情況下的終點
        
        //頁差=總頁數和結束頁的差
        int topdiv = this.last-rpage;                //判斷是否大於最大頁數
        
        /***
         * 起點頁
         * 1、頁差<0  起點頁=起點頁+頁差值
         * 2、頁差>=0 起點和終點判斷
         */   
        this.lpage=topdiv<0? this.lpage+topdiv:this.lpage;
        
        /***
         * 結束頁
         * 1、起點頁<=0   結束頁=|起點頁|+1
         * 2、起點頁>0    結束頁
         */
        this.rpage=this.lpage<=0? this.rpage+(this.lpage*-1)+1: this.rpage;
        
        /***
         * 當起點頁<=0  讓起點頁為第一頁
         * 否則不管
         */
        this.lpage=this.lpage<=0? 1:this.lpage;
        
        /***
         * 如果結束頁>總頁數   結束頁=總頁數 
         * 否則不管
         */
        this.rpage=this.rpage>last? this.last:this.rpage;
    }
    
    
    

    public int getStart() {
        return start;
    }

}
package cn.zr.testpage.utils;

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

public class UserBasicalImpl {
    
    protected Connection connection;
    protected PreparedStatement pStatement;
    protected ResultSet rSet;
    
    public void close(){
        // 關閉資源
        try {
            if (rSet!=null) {
                rSet.close();
            }
            if (pStatement!=null) {
                pStatement.close();
            }
            if (connection!=null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>用戶信息</title>

  </head>
  
  <body>

    <table>
        <tr>
            <th>姓名</th>
            <th>年齡</th>
            <th>愛好</th>
        </tr>
        <c:forEach items="${users }" var="user" varStatus="userindex">
            <tr>
                <td>${user.name }</td>
                <td>${user.age }</td>
                <td>${user.hobby }</td>
            </tr>
        </c:forEach>
    </table>    

    <div>
        <a href="?curpage=1">首頁</a>
        <c:forEach begin="${page.lpage}" end="${page.rpage}" var="pageNum">
            <a href="?curpage=${pageNum }">${pageNum }</a>
        </c:forEach>
        <a href="?curpage=${page.last }">尾頁</a>
    </div>
    

  </body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM