JAVA--高級基礎開發--分頁技術

=========《分頁技術:》==============
前端代碼:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>分頁技術</title>
    <script src="js/jquery-3.4.1.js"></script>
</head>
<body>
<h2 style="color: darkmagenta">分頁技術的展現頁面</h2>
   <table border="100%" width="100%">
       <h2 style="color: firebrick;" align="center">省份信息的展現</h2>
       <tr>
           <th>ID</th>
           <th>省份的代號</th>
           <th>省份</th>
       </tr>
       <c:forEach items="${pp.datas}" var="ss">
           <tr align="center">
               <td>
                   ${ss.id}
               </td>
               <td>
                   ${ss.provinceid}
               </td>
               <td>
                   ${ss.province}
               </td>
           </tr>
       </c:forEach>
   </table>
    總記錄數:${pp.tatolCount}行&nbsp;&nbsp;&nbsp;&nbsp; 總頁數:${pp.pageCount}頁&nbsp;&nbsp;&nbsp;&nbsp;當前是第:${pp.pageNo}頁&nbsp;&nbsp;&nbsp;&nbsp;每頁顯示:${pp. pageSize}條數據
        <select name="pageSize" id="pageSize">
            <option value="10">10</option>
            <option value="15">15</option>
            <option value="20">20</option>
            <option value="25">25</option>
         </select>
&nbsp;&nbsp;&nbsp;&nbsp;<a href="selected?pageNo=${pp.pageNo==pp.pageCount?pp.pageCount:pp.pageNo+1}">下一頁</a>
&nbsp;&nbsp;&nbsp;&nbsp;<a href="selected?pageNo=${pp.pageNo==1?1:pp.pageNo-1}">上一頁</a>

</body>
</html>
<script>
    $(function(){ //頁面加載事件
       $("#pageSize").change(function(){
           var pages=$(this).val();
       })
    })
</script>

DAO接口html

public interface ProvincesDao {

    //獲取表中的總記錄數
    public int  SumConut();

    //每一頁顯示的記錄數:pageNO:默認顯示第一頁;PageSize:每一頁有多少條數據記錄
    public PageModel<Provinces> findy(int pageNo, int   pageSize);

DAO接口的實現類前端

import com.Dao.ProvincesDao;
import com.model.PageModel;
import com.model.Provinces;
import org.apache.commons.dbutils.QueryRunner;

import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

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

public class ProvincesDaoImp implements ProvincesDao {
    private QueryRunner qr;
    private DataSource ds;

    public ProvincesDaoImp(DataSource ds){
        qr=new QueryRunner(ds);
    }
    //獲取表中放入總記錄數
    @Override
    public int SumConut(){
        String  sql="select  count(id)  from  provinces";
        int  count=0;
        try{
         Long lo=qr.query(sql,new ScalarHandler<Long>());
           if(lo!=null){
               count=lo.intValue();
           }

        }catch (SQLException  ce){
            ce.printStackTrace();
        }
        return count;
    }


    //分頁查詢,把數據保存到PageModel中
    @Override
    public PageModel<Provinces> findy(int pageNo, int  pageSize){
        //limit:從start開始,到end結束
        String  sql="select  *  from provinces limit ?,? ";
        Object[]prams={(pageNo-1)*pageSize, pageSize};
        //建立一個PageModel對象,
        PageModel<Provinces>model=new PageModel<>(pageSize,pageNo);
        try{
            List<Provinces>list=qr.query(sql,new BeanListHandler<Provinces>(Provinces.class),prams);
           //獲取總的記錄數
            int totalCount=SumConut();
            //設置分頁的信息到PageModel中
            model.setTatolCount(totalCount);
            //設置每一頁的數據
            model.setDatas(list);
        }catch (SQLException  ce){
            ce.printStackTrace();
        }
        return model;
    }
}

Dao的代理類java

package com.Dao.proxy;

import com.Dao.ProvincesDao;
import com.Dao.impl.ProvincesDaoImp;
import com.Utils.DatabaseConnection;
import com.model.PageModel;
import com.model.Provinces;

import javax.sql.DataSource;


public class ProvincesDaoProxy implements ProvincesDao {
    private ProvincesDao provincesDao;
    private DataSource ds;
    public ProvincesDaoProxy(){
        ds= DatabaseConnection.getDateSource();
        provincesDao=new ProvincesDaoImp(ds);
    }

    @Override
    public int SumConut(){
        return provincesDao.SumConut();
    }

    @Override
    public PageModel<Provinces> findy(int pageNo, int  pageSize) {
        return provincesDao.findy(pageNo, pageSize);
    }
}

業務層:Ljquery

import com.Dao.ProvincesDao;
import com.Factory.Daofactory;
import com.model.PageModel;
import com.model.Provinces;

import java.util.List;

public class ProvincesService {
    private ProvincesDao provincesDao= Daofactory.getInstance("UserProvinces",ProvincesDao.class);

    //定義查詢的方法;
    public int SumCount(){
        return provincesDao.SumConut();
    }
    public PageModel<Provinces>findy(int pageNo,int  pageSize){
        return provincesDao.findy(pageNo, pageSize);
    }
}

Servlet服務器端sql

package com.Servlet;

import com.Servcice.ProvincesService;
import com.alibaba.fastjson.JSON;
import com.model.PageModel;
import com.model.Provinces;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

//查詢頁數
@WebServlet("/selected")
public class ProvincesServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

      //獲取當前頁數
        String page=req.getParameter("pageNo");
        int pageNo=1;
        if(page==null) { //若果當前頁爲空,我就讓他顯示第一頁,
            pageNo=1;
        }else{
            pageNo=Integer.parseInt(page);
        }
        //建立業務層的對象
        ProvincesService  service=new ProvincesService();
        //表示從當前頁開始,每一頁顯示10條數據。
        PageModel<Provinces>pageModel=service.findy(pageNo,10);

        //設置到請求域中
        req.setAttribute("pp",pageModel);
        //請求分派到展現的頁面
        req.getRequestDispatcher("list.jsp").forward(req,resp);

    }
}
工具類
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @PACKAGE_NAME: com.Model.utils
 * @ClASS_NAME: DaoFactory
 * @Description DAO工廠類
 * @Author: Model
 * @DATE: 2019/8/23 15:34
 * @Version : 1.0
 **/
public class Daofactory {

    private static Properties p;
    //map集合用來充當緩存,key要和dao.properties中的key一致
    //值,DAO接口的實例對象
    private static Map<String,Object> cache;

    //初始化
    static{
        p=new Properties();
        cache=new HashMap<>();
        //加載dao.properties屬性文件
        InputStream is=Thread.currentThread().getContextClassLoader().getResourceAsStream("dao.properties");
        try {
            p.load(is);
        }catch (IOException ce){
            ce.printStackTrace();
        }
    }

    /**
     * 線程安全的泛型方法
     * @param daoName  就是dao.properties屬性文件中key的名字
     * @param daoClass 就是key所對應值得父接口或者接口的實現類
     * @param <T>
     * @return
     */
    public synchronized static<T> T getInstance(String daoName,Class daoClass){

        //先從map集合中,根據KEY去查找,有沒有對應的值
        T t=(T)cache.get(daoName);
        if(t==null){//說明map集合中不存在當前daoName鎖對應的鍵值對
            //去屬性文件中查找指定KEY是否存在,若是存在,則獲取key所對應的值
            //值就是某個DAO接口的實現類的全限定名
            String className=p.getProperty(daoName);

            if(null!=className&&!"".equals(className)){//說明key-value存在
                try {
                    //把指定類的字節碼文件加載JVM虛擬機中
                    Class clazz = Class.forName(className);
                    //經過反射機制調用類中無參數的構造方法建立clazz的對象
                    t=(T)daoClass.cast(clazz.getDeclaredConstructor().newInstance());
                    //把對象添加到map集合中
                    cache.put(daoName,t);
                }catch (Exception ce){
                    ce.printStackTrace();
                }
            }
        }
        return t;
    }

}
import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

//專門負責數據庫打開與關閉操做的類
public class DatabaseConnection {
    //建立阿里巴巴鏈接池對象
    private  static DruidDataSource ds;
    private  static Properties P;

    static {
        ds=new DruidDataSource();
        P=new Properties();
        //讀取屬性文件
        InputStream input=Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties");
        //加載P對象
        try{
            P.load(input);
        }catch(IOException ce){
            ce.printStackTrace();
        }
        //根據鍵獲取值
        ds.setDriverClassName(P.getProperty("driverClass"));
        ds.setUrl(P.getProperty("url"));
        ds.setUsername(P.getProperty("user"));
        ds.setPassword(P.getProperty("password"));
        //配鏈接池的參數
        ds.setInitialSize(Integer.parseInt(P.getProperty("initialSize")));
        ds.setMinIdle(Integer.parseInt(P.getProperty("minIdle")));
        ds.setMaxActive(Integer.parseInt(P.getProperty("maxActive")));
        ds.setMaxWait(Integer.parseInt(P.getProperty("maxWait")));
        ds.setTimeBetweenEvictionRunsMillis(Integer.parseInt(P.getProperty("timeBetweenEvictionRunsMillis")));
    }
    public  static DataSource getDateSource(){
        return ds;
    }
    //獲取數據庫鏈接對象
    public  static Connection getConnection()throws SQLException {
        return ds.getConnection();
    }


    //關閉數據庫鏈接對象之insert  delete update的操做
    public static  void  close(Connection  con, Statement state)throws SQLException{
        con.close();;
        state.close();
    }
    //關閉數據庫鏈接的對象之 select 查找查詢的操做
    public static  void close(Connection  con, Statement  state, ResultSet set)throws SQLException{
        set.close();
        state.close();
        con.close();
    }
    //關閉獲取數據庫鏈接對象
    public  static  void  close(Connection  con)throws SQLException{
        con.close();
    }
    // 關閉執行Statement執行SQL 語句的對象
    public static  void close(Statement  state)throws SQLException{
        state.close();
    }
    //關閉結果集對象ResultSet對象
    public static  void close(ResultSet  set)throws SQLException{
        set.close();
    }
}
相關文章
相關標籤/搜索