web分頁教程

aNoobCoder發表於2017-02-04

web分頁的兩種基本方式

大致有兩種方案

方案1

從本地資料庫讀取出所有的資料,然後封裝成一個model連結串列,根據需要對list進行分片(subList(fromIndex, toIndex))

  • 優點:簡單

  • 缺點:每次分頁都要對資料庫查詢結果的所有內容進行訪問,記憶體和時間開銷都很大,使用者體驗較差

  • 建議:不建議使用

方案2

利用資料庫查詢結果優化,如Mysql的limit語句

  • 優點:記憶體和時間開銷都小,使用者體驗較好

  • 缺點:每次分頁都要對sql語句進行修改(這根本不是事)

  • 建議:建議使用

程式碼示例

  • 1.先建立Pager模板類
package com.Android.bean;

import java.io.Serializable;
import java.util.List;

public class Pager<T> implements Serializable {

    private static final long serialVersionUID = -8741766802354222579L;

    private int pageSize; // 每頁顯示多少條記錄

    private int currentPage; //當前第幾頁資料

    private int totalRecord; // 一共多少條記錄

    private int totalPage; // 一共多少頁記錄

    private List<T> dataList; //要顯示的資料



    public Pager(){

    }

    public Pager(int pageSize, int currentPage, int totalRecord, int totalPage,
            List<T> dataList) {
        super();
        this.pageSize = pageSize;
        this.currentPage = currentPage;
        this.totalRecord = totalRecord;
        this.totalPage = totalPage;
        this.dataList = dataList;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getTotalRecord() {
        return totalRecord;
    }

    public void setTotalRecord(int totalRecord) {
        this.totalRecord = totalRecord;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public List<T> getDataList() {
        return dataList;
    }

    public void setDataList(List<T> dataList) {
        this.dataList = dataList;
    }

}
  • 2.建立資料庫連線池,優化資料庫連線所造成的資源消耗
package com.Android.util;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public final class ConnectionManager {

    // 表示定義資料庫的使用者名稱
    private static String USERNAME;

    // 定義資料庫的密碼
    private static String PASSWORD;

    // 定義資料庫的驅動資訊
    private static String DRIVER;

    // 定義訪問資料庫的地址
    private static String URL;

    // 使用單利模式建立資料庫連線池
    private static ConnectionManager instance;
    private static ComboPooledDataSource dataSource;

    static {
        // 載入資料庫配置資訊,並給相關的屬性賦值
        loadConfig();
    }

    public static void loadConfig() {
        try {
            InputStream in = ConnectionManager.class
                    .getResourceAsStream("/JDBCConfig.properties");
            Properties properties = new Properties();
            properties.load(in);
            USERNAME = properties.getProperty("jdbc.username");
            PASSWORD = properties.getProperty("jdbc.password");
            DRIVER = properties.getProperty("jdbc.driver");
            URL = properties.getProperty("jdbc.url");
        } catch (Exception e) {
            throw new RuntimeException("載入資料庫配置檔案異常!!!!", e);
        }
    }

    private ConnectionManager() throws SQLException, PropertyVetoException {
        dataSource = new ComboPooledDataSource();

        dataSource.setUser(USERNAME); // 使用者名稱
        dataSource.setPassword(PASSWORD); // 密碼
        dataSource.setJdbcUrl(URL);// 資料庫地址
        dataSource.setDriverClass(DRIVER);
        dataSource.setInitialPoolSize(5); // 初始化連線數
        dataSource.setMinPoolSize(1);// 最小連線數
        dataSource.setMaxPoolSize(10);// 最大連線數
        dataSource.setMaxStatements(50);// 最長等待時間
        dataSource.setMaxIdleTime(60);// 最大空閒時間,單位毫秒
    }

    public static final ConnectionManager getInstance() {
        if (instance == null) {
            try {
                instance = new ConnectionManager();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return instance;
    }

    public synchronized final Connection getConnection() {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}


  • 3.建立資料庫工具類,方便統一管理與控制

package com.Android.util;

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

public class JdbcUtil {

// 定義資料庫的連結  
private Connection connection;  

// 定義sql語句的執行物件  
private PreparedStatement pstmt;  

// 定義查詢返回的結果集合  
private ResultSet resultSet;  


public JdbcUtil() {  
    //從資料庫獲取資料庫連線
    connection = ConnectionManager.getInstance().getConnection();
}  


/** 
 * 執行更新操作 
 *  
 * @param sql 
 *            sql語句 
 * @param params 
 *            執行引數 
 * @return 執行結果 
 * @throws SQLException 
 */  
public boolean updateByPreparedStatement(String sql, List<?> params)  
        throws SQLException {  
    boolean flag = false;  
    int result = -1;// 表示當使用者執行新增刪除和修改的時候所影響資料庫的行數  
    pstmt = connection.prepareStatement(sql);  
    int index = 1;  
    // 填充sql語句中的佔位符  
    if (params != null && !params.isEmpty()) {  
        for (int i = 0; i < params.size(); i++) {  
            pstmt.setObject(index++, params.get(i));  
        }  
    }  
    result = pstmt.executeUpdate();  
    flag = result > 0 ? true : false;  
    return flag;  
}  

/** 
 * 執行查詢操作 
 *  
 * @param sql 
 *            sql語句 
 * @param params 
 *            執行引數 
 * @return 
 * @throws SQLException 
 */  
public List<Map<String, Object>> findResult(String sql, List<?> params)  
        throws SQLException {  
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
    int index = 1;  
    pstmt = connection.prepareStatement(sql);  
    if (params != null && !params.isEmpty()) {  
        for (int i = 0; i < params.size(); i++) {  
            pstmt.setObject(index++, params.get(i));  
        }  
    }  
    resultSet = pstmt.executeQuery();  
    ResultSetMetaData metaData = resultSet.getMetaData();  
    int cols_len = metaData.getColumnCount();  
    while (resultSet.next()) {  
        Map<String, Object> map = new HashMap<String, Object>();  
        for (int i = 0; i < cols_len; i++) {  
            String cols_name = metaData.getColumnName(i + 1);  
            Object cols_value = resultSet.getObject(cols_name);  
            if (cols_value == null) {  
                cols_value = "";  
            }  
            map.put(cols_name, cols_value);  
        }  
        list.add(map);  
    }  
    return list;  
}  

/** 
 * 執行查詢操作 
 *  
 * @param sql 
 *            sql語句 
 * @param params 
 *            執行引數 
 * @return 
 * @throws SQLException 
 */  
public List findResultToBeanList(String sql, List<?> params, Class<?> cls )  
        throws SQLException {  
    List<?> list = null;
    int index = 1;  
    pstmt = connection.prepareStatement(sql);  
    if (params != null && !params.isEmpty()) {  
        for (int i = 0; i < params.size(); i++) {  
            pstmt.setObject(index++, params.get(i));  
        }  
    }  
    resultSet = pstmt.executeQuery();  

    try {
        list =  GetData.resultSetToList(resultSet, cls);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    return list;
}  

/** 
 * 執行查詢操作 
 *  
 * @param sql 
 *            sql語句 
 * @param params 
 *            執行引數 
 * @return 
 * @throws SQLException 
 */  
public int findResultTotalNumber(String sql, List<?> params )  
        throws SQLException {  
    int totalNumber = 0;
    int index = 1;  
    pstmt = connection.prepareStatement(sql);  
    if (params != null && !params.isEmpty()) {  
        for (int i = 0; i < params.size(); i++) {  
            pstmt.setObject(index++, params.get(i));  
        }  
    }  
    resultSet = pstmt.executeQuery();  

    try {
        if(resultSet.next()){
            totalNumber = resultSet.getInt(1);  
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    return totalNumber;
}

/** 
 * 釋放資源 
 */  
public void releaseConn() {  
    if (resultSet != null) {  
        try {  
            resultSet.close();  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
    }  
    if (pstmt != null) {  
        try {  
            pstmt.close();  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
    }  
    if (connection != null) {  
        try {  
            connection.close();  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
    }  
}  

public static void main(String[] args) {  
    JdbcUtil jdbcUtil = new JdbcUtil();  

    try {  
        List<Map<String, Object>> result = jdbcUtil.findResult(  
                "select * from newsTable", null);  
        for (Map<String, Object> m : result) {  
            System.out.println(m);  
        }  
    } catch (SQLException e) {  
        e.printStackTrace();  
    } finally {  
        jdbcUtil.releaseConn();  
    }  
}  

}

  • 4.建立dao層,MVC模式
package com.Android.DAO;

import java.util.ArrayList;
import java.util.List;

import com.Android.bean.*;
import com.Android.util.JdbcUtil;

public class NewsDAO {
    private final static int pageSize = 8;

    public Pager getNews(int newsType, int currentPage){
        List<ShowNewsBean> newsList = null;
        Pager pager = null;
        try{
            String sql = "SELECT * FROM newsTable WHERE newsState = 1 AND newsType = ? limit ?,?;";
            List<Object> params = new ArrayList<Object>(); 
            params.add(newsType);
            params.add((currentPage-1)*pageSize);
            params.add(currentPage*pageSize);
            JdbcUtil jdbcUtil = new JdbcUtil();
            pager = new Pager();
            newsList = jdbcUtil.findResultToBeanList(sql, params, ShowNewsBean.class);
            jdbcUtil.releaseConn();

        }catch(Exception e){
            System.out.println(e.toString());
        }
        return pager;
    }

    public Pager getNews(int currentPage){
        List<ShowNewsBean> dataList = null;
        Pager pager = null;
        try{                                                      
            String sql1 = "SELECT * FROM newsTable WHERE newsState = 1;";
            String sql2 = "SELECT * FROM newsTable WHERE newsState = 1 limit ?, ?;";
            //獲得資料
            dataList = getPageData(sql2, currentPage, pageSize);
            JdbcUtil jdbcUtil = new JdbcUtil();
            jdbcUtil.releaseConn();
            //獲取一共有多少條記錄
            int totalRecord = getTotalRecord(sql1);
            //一共有多少頁
            int totalNum = (totalRecord%pageSize == 0) ? totalRecord/pageSize : totalRecord/pageSize + 1;
            //返回pager物件
            pager = new Pager<ShowNewsBean>(pageSize, currentPage, totalRecord, totalNum,
                    dataList);
        }catch(Exception e){
            System.out.println(e.toString());
        }
        return pager;
    }

    public List<ShowNewsBean> getPageData(String sql, int currentPage, int pageSize){
         List<ShowNewsBean> newsList = null;
        try{
            //設定引數
            List<Object> params = new ArrayList<Object>(); 
            params.add((currentPage-1)*pageSize);
            params.add(pageSize);

            JdbcUtil jdbcUtil = new JdbcUtil();
            newsList = jdbcUtil.findResultToBeanList(sql, params, ShowNewsBean.class);
            System.out.println(sql+params.toString());
            jdbcUtil.releaseConn();

        }catch(Exception e){
            System.out.println(e.toString());
        }
        return newsList;
    }

    public int getTotalRecord(String sql){
        int totalRecord = 0;
        try{

            JdbcUtil jdbcUtil = new JdbcUtil();

            totalRecord                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           = jdbcUtil.findResultTotalNumber(sql, null);
            jdbcUtil.releaseConn();

        }catch(Exception e){
            System.out.println(e.toString());
        }
        return totalRecord;
    }

    public static void main(String[] args){
        NewsDAO newsDAO = new NewsDAO();
        newsDAO.getNews(1);
    }
}

相關文章