分頁查詢功能(包含pageBean封裝)


 
        
PageQuerryServlet.java
package com.exp.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.exp.model.Book; import com.exp.model.PageResult; import com.exp.service.BooksServiceImpl; /** * 分頁查詢demo */ @WebServlet("/PageQuerryServlet") public class PageQuerryServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.獲取請求參數
        int page = Integer.parseInt(request.getParameter("page")); //2.調用服務層
        BooksServiceImpl service = new BooksServiceImpl(); //3.調起服務層方法
        PageResult<Book> pr = service.findBookByPage(page); System.out.println(pr.toString()); System.out.println(pr.getList()); } }
 
         
         
        

 





BooksDaoImpl.java
package com.exp.dao;

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

import javax.sql.DataSource;

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 com.exp.model.Book;
import com.exp.model.PageResult;

import utils.C3P0Utils;


//import com.exp.utils.C3P0Utils;

public class BooksDaoImpl {
    private static DataSource ds = C3P0Utils.getDataSource();
    /*
     * 方法:添加書本信息
     */
    public void addBook(Book book) throws SQLException{
        QueryRunner qr = new QueryRunner(ds);
        String sql = "insert into books(name,pnum,price,category,description) values(?,?,?,?,?)";
        Object[] params = new Object[5];
//        params[0] = UUID.randomUUID().toString();
        params[0] = book.getName();
        params[1] = book.getPnum();
        params[2] = book.getPrice();
        params[3] = book.getCategory();
        params[4] = book.getDescription();
        int r = qr.update(sql,params);
        System.out.println("r:"+r);
    }
    /*
     * 方法:獲取所有書本列表
     */
    public List<Book> getbookList() throws SQLException{
        QueryRunner qr = new QueryRunner(ds);
        String sql = "select * from books";
        return qr.query(sql, new BeanListHandler<Book>(Book.class));
    }
    /*
     * 方法:獲取書本id
     */
    public Book findBookId(int id) throws SQLException{
        QueryRunner qr = new QueryRunner(ds);
        String sql = "select * from books where id =?";
        return qr.query(sql, new BeanHandler<Book>(Book.class),id);
    }
    /*
     * 方法:更新修改當前書本信息
     */
    public void editBook(Book book) throws SQLException{
        QueryRunner qr = new QueryRunner(ds);
        String sql = "update books set name=?,pnum=?,price=?,category=?,description=? where id=?";
        int r = qr.update(sql,book.getName(),book.getPnum(),book.getPrice(),book.getCategory(),book.getDescription(),book.getId());
        System.out.println("受影響結果:"+r+"條");
    }
    /*
     * 方法:刪除當前書本信息
     */
    public void deleteBook(int id) throws SQLException{
        QueryRunner qr = new QueryRunner(ds);
        String sql = "delete from books where id=?";
        int r = qr.update(sql,id);
        System.out.println("受影響結果:"+r+"條");
    }
    /*
     * 方法:批量刪除書本  (執行多次sql)
     */
    public void BatchBookByids1(String ids) {
        QueryRunner qr = new QueryRunner(ds);
        String[] idArr = ids.split(",");
        String sql = "delete from books where id=?";
        for(String id:idArr){
            try {
                int r = qr.update(sql,id);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }
    /*
     * 方法:批量刪除書本  (執行一次sql)
     */
    public void BatchBookByids(String ids) {
        QueryRunner qr = new QueryRunner(ds);
        String[] idArr = ids.split(",");
        String sql = "delete from books where id=?";
        Object[][] params = new Object[idArr.length][];
        for(int i=0;i<idArr.length;i++){
            params[i] = new Object[]{idArr[i]};
        }
        
        //批量刪除
        try {
            qr.batch(sql, params);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
    /*
     * 方法:多條件查詢書本
     */
    public List<Book> findBookBySearchkey(String id, String name, String category, String minprice, String maxprice) throws SQLException {
        QueryRunner qr = new QueryRunner(ds);
        String sql = "select * from books where 1=1";
        if(!"".equals(id)){
            sql += " and id="+ id;
        }
        if(!"".equals(name)){
            sql += " and name like'%"+ name +"%'";
        }
        if(!"".equals(category)){
            sql += " and category='"+ category +"'";
        }
        if(!"".equals(minprice)){
            sql += " and price >="+ minprice;
        }
        if(!"".equals(maxprice)){
            sql += " and price <="+ maxprice;
        }
        System.out.println(sql);
        return qr.query(sql, new BeanListHandler<Book>(Book.class));
    }
    /*
     * 方法:分頁查詢
    */
    public PageResult findBookByPage(int page) throws SQLException{
        
        QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
        
        //1.創建PageResult對象
        PageResult<Book> pr = new PageResult<Book>();
        
        //2.設置totalCount【總記錄數】
        long totalCount = (long) qr.query("select count(*) from books", new ScalarHandler());
        pr.setTotalCount(totalCount);;
        
        //3.設置總頁數 5/10
        long totalPage = totalCount % pr.getLimit() == 0 ? totalCount/pr.getLimit() :totalCount/pr.getLimit() + 1;
        pr.setTotalPage(totalPage);
        
        //4.設置當前頁碼
        pr.setCurrentPage(page);
        
        //5.設置pageresult里的list數據【庫存排序】
        String sql = "select * from books order by pnum limit ?,?";
        int start = (page -1)*pr.getLimit();
        List<Book> books =  qr.query(sql, new BeanListHandler<Book>(Book.class),start,pr.getLimit());
        pr.setList(books);
        
        return pr;
    }
}


PageResult.java
package com.exp.model;

import java.util.List;

public class PageResult<T> {
    private List<T> list;//當前頁數據集合
    private int currentPage;//當前頁碼
    private int limit = 3;//每頁條數
    private long totalCount;//總記錄數
    private long totalPage;//總頁數
    
    public PageResult(List<T> list, int currentPage, int limit, long totalCount, long totalPage) {
        super();
        this.list = list;
        this.currentPage = currentPage;
        this.limit = limit;
        this.totalCount = totalCount;
        this.totalPage = totalPage;
    }

    public PageResult() {
        super();
        // TODO Auto-generated constructor stub
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public int getCurrentPage() {
        return currentPage;
    }

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

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    public long getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(long totalCount) {
        this.totalCount = totalCount;
    }

    public long getTotalPage() {
        return totalPage;
    }

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

    @Override
    public String toString() {
        return "PageResult [list=" + list + ", currentPage=" + currentPage + ", limit=" + limit + ", totalCount="
                + totalCount + ", totalPage=" + totalPage + "]";
    }
    
}

 

 

 

 

 


免責聲明!

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



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