学习博客:javaweb分页功能的实现---至顶向下

这个功能,想起来简单,做起来真的烦,关键还只是为了美观,我这里打算从顶写到尾,就是从servlet层写到dao层,这种方法更像是一种捏造方法的方法emmm,就是你没有方法,然后凭空丢出来一个,然后让下一层的接口去实现,然后再来写下一层:
这里我们进行下功能分析:

由分页的视图分析出分页的对象模型Page类
pageNo当前页码
pageTotal总页码
pageTotalCount总记录数
pageSize每页显示数量
itens当前页数据
pageNo当前页码是由客户端进行传递
pageSize每页显示数量由两种因素决定。
一:客户端进行传递
二:由页面布局决定
pageTotalCount总记录数可以由sq1语句求得。.
sqI语句是: select count() from 表名。
pageTotalCount.总记录数可以由sq|语句求得。,
sql语句是: select count(
) from 表名。
pageTotal总页码可以由总记录数/每页数量得到。
注:总记录数%每页数量>0,则 总页码+1
itens是当前页数据,也是可以由sq1语句求得。
sq1语句是: select * from表名limit begin , pageSize;
begin可以由公式求得: (pageNo-1) x pageSize;
假设,当前是第1页,每页4条记录,则begin = (1-1) x 4得: 0
假设,当前是第2页,每页4条记录,则begin= (2-1)x4得: 4
假设,当前是第3页,每页4条记录,则begin= (3-1) x 4得: 8

我们这次从顶层写到底层: servlet这里实现page方法,
然后他会要求我去写个page接口的Service

package cn.zsp.web;

import cn.zsp.pojo.Book;
import cn.zsp.pojo.Page;
import cn.zsp.service.impl.BookServiceImpl;
import cn.zsp.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class BookServlet extends  BaseServlet{
        private BookServiceImpl bookService =new BookServiceImpl();

    /**
     * 处理分页功能
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//      1获取请求的参数pageNo和pageSize
        int pageNo=WebUtils.parseInt(req.getParameter("pageNo"),1);
        int pageSize=WebUtils.parseInt(req.getParameter("pageSize"),4);
//      2调用BookService . page(pageNo, pagesize): Page对象
        Page<Book> page = bookService.page(pageNo, pageSize);
//      3保存Page对象到Request域中
        req.setAttribute("page",page);
//      4请求转发到pages/manager/book_ manager. jsp页面
        req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req,resp);
    }

    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1,获取请求的参数==封装成为Book对象
            Book book = WebUtils.copyParamToBean(req.getParameterMap(),
                    new Book());
//        2,调用BookService. addBook()保存图书
            bookService.addBook(book);
//        3,跳到图书列表页面
//            req.getRequestDispatcher("manager/bookServlet?action=list");
//        这里使用转发如果用户在完成页面重复按f5会重复添加所以我们这里使用请求重定向来实现跳转
        resp.sendRedirect(req.getContextPath()+"/manager/bookServlet" +
                "?action=list");
    }
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        bookService.deleteBookById(WebUtils.parseInt(id));
        resp.sendRedirect(req.getContextPath()+"/manager/bookServlet" +
                "?action=list");
    }
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Book book = WebUtils.copyParamToBean(req.getParameterMap(), new Book());
        System.out.println(book.getId());
        bookService.updateBook(book);
        resp.sendRedirect(req.getContextPath()+"/manager/bookServlet?action=list");
    }
    protected void getBook(HttpServletRequest req,
                           HttpServletResponse resp) throws ServletException, IOException {
        String id =req.getParameter("id");
        Book book = bookService.queryBookById(WebUtils.parseInt(id));
        req.setAttribute("books",book);
        req.getRequestDispatcher("/pages/manager/book_edit.jsp").forward(req,resp);
    }

    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        通过BookService查询全部图书
//        把全部图书保存到Request域中
//        请求转发到/pages/manager/book_ manager. jsp页面
        List<Book>  books = bookService.queryBooks();
        req.setAttribute("books",books);
        req.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(req,resp);
    }
}

这是被迫写下的page接口,然后要再去继承类那里实现下这个方法:

package cn.zsp.service;

import cn.zsp.pojo.Book;
import cn.zsp.pojo.Page;

import java.util.List;

public interface   BookService {
    public void addBook(Book book);
    public void deleteBookById(Integer id);
    public void updateBook(Book book);
    public Book queryBookById(Integer id);
    public List<Book> queryBooks();

    Page<Book> page(int pageNo, int pageSize);
}

写这个service层的时候我们需要用到dao层的数据库查询,所以你懂的,我们照样捏造个方法queryForPageItems然后在dao的接口实现:

package cn.zsp.service.impl;

import cn.zsp.dao.BookDao;
import cn.zsp.dao.impl.BookDaoImpl;
import cn.zsp.pojo.Book;
import cn.zsp.pojo.Page;
import cn.zsp.service.BookService;

import java.util.List;

public class BookServiceImpl implements BookService {
    BookDao bookDao= new BookDaoImpl();
    @Override
    public void addBook(Book book) {
    bookDao.addBook(book);
    }

    @Override
    public void deleteBookById(Integer id) {
    bookDao.deleteBookById(id);
    }


    @Override
    public void updateBook(Book book) {
    bookDao.updateBook(book);
    }

    @Override
    public Book queryBookById(Integer id) {
        return bookDao.queryBookById(id);
    }

    @Override
    public List<Book> queryBooks() {
        return bookDao.queryBooks();
    }

    /**
     * 获取这五个信息:
     * 当前页码
     * 总页码
     * 总记录数
     * 每页显示数量
     * 当前页数据
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public Page<Book> page(int pageNo, int pageSize) {
        Page<Book> page =new Page<Book>();
//        设置当前页码
        page.setPageNo(pageNo);
//        每页显示数量
        page.setPageSize(pageSize);
//        获取总记录数
        Integer pageTotalCount = bookDao.queryForPageTotalCount();
//        设置总记录数
        page.setPageTotalCount(pageTotalCount);
//        获取总页码
        Integer pageTotal=pageTotalCount/pageSize;
        if (pageTotalCount%pageSize>0)
        {
           pageTotal+=1;
        }
//        设置总页码
        page.setPageTotal(pageTotal);
        int begin=(pageNo-1)*pageSize;
        List<Book> items=bookDao.queryForPageItems(begin,pageSize);
//        设置当前页数据
        page.setItems(items);
        return page;
    }

}

然后我们在dao这里添加两个查询方法:

package cn.zsp.dao;

import cn.zsp.pojo.Book;

import java.util.List;

public interface BookDao {
    public int addBook(Book book);
    public int deleteBookById(Integer id);
    public int updateBook(Book book);
    public Book queryBookById(Integer id);
    public List<Book> queryBooks();

    Integer queryForPageTotalCount();

    List<Book> queryForPageItems(int begin,int pageSize);
}

实现的继承类:

package cn.zsp.dao.impl;

import cn.zsp.dao.BookDao;
import cn.zsp.pojo.Book;

import java.util.List;

public class BookDaoImpl extends BaseDao implements BookDao {
    @Override
    public int addBook(Book book) {
        String sql="insert into t_book (name,price,author,sales," +
                "stock,img_path)values(?,?,?,?,?,?)";
        return update(sql,book.getName(),book.getPrice(),
                book.getAuthor(),book.getSales(),book.getStock(),
                book.getImgPath());
    }

    @Override
    public int deleteBookById(Integer id) {
        String sql="delete from t_book where id=?";
        return update(sql,id);
    }

    @Override
    public int updateBook(Book book) {
        String sql="update t_book set `name`=? , `author`=? , `price`=? , " +
                "`sales`=? , `stock` =?, `img_path`=? where id=?";
        return  update(sql,book.getName(), book.getAuthor(),
                book.getPrice(),book.getSales(),book.getStock(),
                book.getImgPath(),book.getId());
    }

    @Override
    public Book queryBookById(Integer id) {
        String sql="select `id`,`name` , `author` , `price` , `sales` ," +
                " " +
                "`stock` , `img_path` imgPath from t_book where id=?";
        return queryForOne(Book.class,sql,id);
    }

    @Override
    public List<Book> queryBooks() {
        String sql= "select `id`,`name` , `author` , `price` , `sales` ,`stock` , `img_path` imgPath from t_book ";
        return queryForList(Book.class,sql);
    }

    @Override
    public Integer queryForPageTotalCount() {
        String sql ="select count(*) from t_book";
         Number number= (Number) queryForSingleValue(sql);
         return number.intValue();
    }

    @Override
    public List<Book> queryForPageItems(int begin, int pageSize) {
        String sql="select `id`,`name` , `author` , `price` , `sales` ," +
                "`stock` , `img_path` imgPath  from t_book limit ?,?";

        return queryForList(Book.class,sql,begin,pageSize);
    }
}

这里是javabean类:

package cn.zsp.pojo;
import java.util.List;

/**
 * 为了让分页不仅仅服务于图书信息,所以我们这里使用泛型
 * @param <T>是具体的模块的javaBean类
 */
public class Page <T>{
      public  static final Integer PAGE_SIZE =4;
//    pageNo     当前页码
      private Integer pageNo;
//    pageTotal总页码
      private Integer pageTotal;
//    pageTotalCount总记录数
      private Integer pageTotalCount;
//    pageSize 每页显示数量
      private Integer pageSize=PAGE_SIZE;
//    items 当前页数据
      private List<T> items;

    public Page() {
    }

    public Page(Integer pageNo, Integer pageTotal, Integer pageTotalCount, Integer pageSize, List<T> items) {
        this.pageNo = pageNo;
        this.pageTotal = pageTotal;
        this.pageTotalCount = pageTotalCount;
        this.pageSize = pageSize;
        this.items = items;
    }

    public Integer getPageNo() {
        return pageNo;
    }

    public void setPageNo(Integer pageNo) {
        this.pageNo = pageNo;
    }

    public Integer getPageTotal() {
        return pageTotal;
    }

    public void setPageTotal(Integer pageTotal) {
        this.pageTotal = pageTotal;
    }

    public Integer getPageTotalCount() {
        return pageTotalCount;
    }

    public void setPageTotalCount(Integer pageTotalCount) {
        this.pageTotalCount = pageTotalCount;
    }

    public Integer getPageSize() {
        return pageSize;
    }

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

    public List<T> getItems() {
        return items;
    }

    public void setItems(List<T> items) {
        this.items = items;
    }

    @Override
    public String toString() {
        return "Page{" +
                "pageNo=" + pageNo +
                ", pageTotal=" + pageTotal +
                ", pageTotalCount=" + pageTotalCount +
                ", pageSize=" + pageSize +
                ", items=" + items +
                '}';
    }
}

这里的页面端,我用的是jsp因为还么的学其他的页面:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图书管理</title>
	<%@include file="/pages/common/head.jsp"%>
	<script type="text/javascript">
		 $(function () {
			$("a.deleteClass").click(function () {
				var src=$(this).parent().parent().find("td:first").text();
			 return confirm("你确定要删除【"+ src +"】吗?");

			});
		 });
	</script>
</head>
<body>
	
	<div id="header">
			<img class="logo_img" alt="" src="../../static/img/logo.gif" >
			<span class="wel_word">图书管理系统</span>
		<%@include file="/pages/common/manager_menu.jsp"%>
	</div>
	
	<div id="main">
		<table>
			<tr>
				<td>名称</td>
				<td>价格</td>
				<td>作者</td>
				<td>销量</td>
				<td>库存</td>
				<td colspan="2">操作</td>
			</tr>		
		 	<c:forEach items="${requestScope.page.items}"
					   var="book">


			<tr>
				<td>${book.name}</td>
				<td>${book.price}</td>
				<td>${book.author}</td>
				<td>${book.sales}</td>
				<td>${book.stock}</td>

				<td><a
						href="manager/bookServlet?action=getBook&id=${book.id}">修改	 </a></td>

				<td>
					<a class="deleteClass"
							href="manager/bookServlet?action=delete&id=${book.id}">删除
				</a></td>
			</tr>
			</c:forEach>
			<tr>
				<td></td>
				<td></td>
				<td></td>
				<td></td>
				<td></td>
				<td></td>
				<td><a href="pages/manager/book_edit.jsp">添加图书</a></td>
			</tr>	
		</table>
		<div id="page_nav">
			<c:if test="${requestScope.page.pageNo>1}">
			<a href="manager/bookServlet?action=page&pageNo=1 ">首页</a>
			<a href="manager/bookServlet?action=page&pageNo=${requestScope.page.pageNo-1}">上一页</a>
			</c:if>
			<a href="manager/bookServlet?action=page&pageNo=3">3</a>
			【${requestScope.page.pageNo}<a href="manager/bookServlet?action=page&pageNo=5">5</a>
			<c:if test="${requestScope.page.pageNo<requestScope.page.pageTotal}">
			<a href="manager/bookServlet?action=page&pageNo=${requestScope.page.pageNo+1}">下一页</a>
			<a href="manager/bookServlet?action=page&pageNo=${requestScope.page.pageTotal}">末页</a>
			</c:if>
			共${requestScope.page.pageTotal}页,${requestScope.page.pageTotalCount}条记录
			到第<input value="4" name="pn" id="pn_input"/><input type="button" value="确定">
		</div>

	</div>

	<div id="bottom">
		<%@include file="/pages/common/footer.jsp"%></div>
</body>
</html>
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页