【JavaWeb开发】JavaWeb之MVC中真分页的实现

分页分为真分页和假分页;

假分页就是还是一次性查到所有数据,但通过前端的一些技巧看起来像是在分页,对数据库一样很有压力;

真分页就是利用limit在查询的时候的限制,每次查的就是这么多数据;

本章讲述的是在纯MVC环境下,在条件查询的情况下添加分页。例子就是一个简单的商品增删查改。

首先介绍一下具体的层次

【JavaWeb开发】JavaWeb之MVC中真分页的实现_第1张图片

1.构建分页实体类Page(使用了泛型,可以在多种对象中复用)

由于总条数一定是要去数据库每次都查一遍的,那么就在调setTotalPage的时候一次性计算完page的所有属性。

package org.hc.homework.entity;

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

//分页
public class Page implements Serializable {
    private static final long serialVersionUID = -4147209130619898593L;

    private int pageSize;//每页的条数,也是limit读取的个数
    private int currentPage;//当前页号
    private int totalCount;//总条数——从数据库中拿到
    private int start;//数据库limit开始条数 = (currentPage-1)*pageSize
    private int totalPage;//总页数 = 总条数/每页的条数

    private List lists=new ArrayList<>();//用于存储数据库查出的数据


    public List getLists() {
        return lists;
    }

    public void setLists(List lists) {
        this.lists = lists;
    }

    public int getPageSize() {
        return pageSize;
    }

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

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        if (currentPage <= 0) {
            this.currentPage = 1;
        } else {
            this.currentPage = currentPage;
        }
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {//在set总条数的时候将所有数据全部计算完成
        this.totalCount = totalCount;
        //总页数的计算
        if (totalCount / pageSize <1) {
            this.totalPage = 1;
        } else if (totalCount % pageSize == 0) {
            this.totalPage = totalCount / pageSize;
        } else {
            this.totalPage = totalCount / pageSize + 1;
        }
        //limit开始序号的计算
        this.start = (currentPage - 1) * pageSize;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public int getStart() {
        return start;
    }

}

1.1 实体类Shop

package org.hc.homework.entity;

import java.io.Serializable;
//数据库具体属性
/* `no` varchar(50) NOT NULL,
  `name` varchar(50) NOT NULL,
  `time` varchar(50) NOT NULL,
  `address` varchar(50) NOT NULL,
  `type` varchar(50) NOT NULL,*/
public class Shop implements Serializable {
    private static final long serialVersionUID = -3998521295785926249L;
    private String no;
    private String name;
    private String time;
    private String address;
    private String type;

    public Shop(String no, String name, String time, String address, String type) {
        this.no = no;
        this.name = name;
        this.time = time;
        this.address = address;
        this.type = type;
    }
    public Shop(){}

    public String getNo() {
        return no;
    }

    public void setNo(String no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

2.MYSQL连接工具类 JdbcUtil (根据实际情况更改)

package org.hc.homework.utils;


import java.sql.*;

public class JdbcUtil {
    //数据库驱动类
    public static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    //数据库的连接地址
    public static final String URL = "jdbc:mysql://localhost:3306/javawebjdbcdemo?serverTimezone=UTC";
    //账号
    public static final String UID = "root";
    //密码
    public static final String PWD = "123";

    //获取Connection实例
    public static Connection getCon() {
        Connection con = null;
        try {
            Class.forName(DRIVER);//ClassNotFoundException
            con = DriverManager.getConnection(URL, UID, PWD);//SQLException
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    //关闭Connection对象
    public static void closeCon(Connection con, PreparedStatement ps, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


3.数据访问层 dao

ShopDao

package org.hc.homework.dao;

import org.hc.homework.entity.Page;
import org.hc.homework.entity.Shop;

public interface ShopDao {
    //查询——添加分页功能 增加新参数Page page
    Page getShopsInPage(Page page);
    //查询 BY no
    Shop getShopByNo(String no);
    //查询条件查询总条数
    int getCount(Shop shop);
    //删除
    boolean deleteShop(String no);
    //修改
    boolean updateShop(Shop shop, String updateNo);
    //新增
    boolean addShop(Shop shop);

}

ShopDaoImpl

package org.hc.homework.dao.daoImpl;

import org.hc.homework.dao.ShopDao;
import org.hc.homework.entity.Page;
import org.hc.homework.entity.Shop;
import org.hc.homework.utils.JdbcUtil;

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

public class ShopDaoImpl implements ShopDao {
    //jdbc API
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    //查询 -全查 -模糊查询 -分页
    @Override
    public Page getShopsInPage(Page page) {
        try {
            List shops = new ArrayList<>();//符合查询条件的数据会放在这个集合中,最后放入page.setList()里
            List wenhao = new ArrayList<>();//问号替换的集合
            Shop newshop = new Shop();//每一行数据
            StringBuffer sql = new StringBuffer("select * from shop where 1=1");
            //从page中拿出查询条件
            if (page.getLists().size() != 0) {
                newshop = page.getLists().get(0);
            }
            //条件查询添加的sql
            if (newshop.getType() != null) {
                //type精确查询
                if (newshop.getType() != null && !newshop.getType().trim().isEmpty()) {
                    sql.append(" and type like ? ");
                    wenhao.add("%" + newshop.getType() + "%");
                }
                //name模糊查询
                if (newshop.getName() != null && !newshop.getName().trim().isEmpty()) {
                    sql.append(" and name like ? ");
                    wenhao.add("%" + newshop.getName() + "%");
                }
                //address模糊查询
                if (newshop.getAddress() != null && !newshop.getAddress().trim().isEmpty()) {
                    sql.append(" and address like ? ");
                    wenhao.add("%" + newshop.getAddress() + "%");
                }
                //time模糊查询
                if (newshop.getTime() != null && !newshop.getTime().trim().isEmpty()) {
                    sql.append(" and time like ? ");
                    wenhao.add("%" + newshop.getTime() + "%");
                }
            }
            //分页添加的sql 由于limit只能放在where结束后,所以放在这里
            sql.append(" limit ?,?");
            //预编译后,将所有问号依次替换
            con = JdbcUtil.getCon();
            ps = con.prepareStatement(sql.toString());
            //只把除limit的两个问号都替换掉
            for (int i = 0; i < wenhao.size(); i++) {
                ps.setString(i + 1, wenhao.get(i));
            }
            //替换limit的两个问号
            ps.setInt(wenhao.size() + 1, page.getStart());
            ps.setInt(wenhao.size() + 2, page.getPageSize());
            rs = ps.executeQuery();
            while (rs.next()) {
                newshop = new Shop(
                        rs.getString(1),
                        rs.getString(2),
                        rs.getString(3),
                        rs.getString(4),
                        rs.getString(5)
                );
                shops.add(newshop);
                page.setLists(shops);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.closeCon(con, ps, rs);
        }
        return page;
    }

    //单行查询 通过no
    @Override
    public Shop getShopByNo(String no) {
        Shop shop = null;
        try {
            String sql = "select * from shop where no=?";
            con = JdbcUtil.getCon();
            ps = con.prepareStatement(sql);
            ps.setString(1, no);
            rs = ps.executeQuery();
            if (rs.next()) {
                shop = new Shop(
                        rs.getString(1),
                        rs.getString(2),
                        rs.getString(3),
                        rs.getString(4),
                        rs.getString(5)
                );
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.closeCon(con, ps, rs);
        }

        return shop;
    }

    //count需要根据条件查询改变
    @Override
    public int getCount(Shop shop) {
        int count = 0;
        try {
            ArrayList wenhao = new ArrayList<>();//问号替换的集合
            StringBuffer sql = new StringBuffer("select count(*) from shop where 1=1 ");
            if (shop != null) {
                //type精确查询
                if (shop.getType() != null && !shop.getType().trim().isEmpty()) {
                    sql.append(" and type like ? ");
                    wenhao.add("%" + shop.getType() + "%");
                }
                //name模糊查询
                if (shop.getName() != null && !shop.getName().trim().isEmpty()) {
                    sql.append(" and name like ? ");
                    wenhao.add("%" + shop.getName() + "%");
                }
                //address模糊查询
                if (shop.getAddress() != null && !shop.getAddress().trim().isEmpty()) {
                    sql.append(" and address like ? ");
                    wenhao.add("%" + shop.getAddress() + "%");
                }
                //time模糊查询
                if (shop.getTime() != null && !shop.getTime().trim().isEmpty()) {
                    sql.append(" and time like ? ");
                    wenhao.add("%" + shop.getTime() + "%");
                }
            }
            con = JdbcUtil.getCon();
            ps = con.prepareStatement(sql.toString());
            //替换问号
            for (int i = 0; i < wenhao.size(); i++) {
                ps.setString(i + 1, wenhao.get(i));
            }
            rs = ps.executeQuery();
            if (rs.next()) {
                count = rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.closeCon(con, ps, rs);
        }
        return count;
    }

    //删除 通过no
    @Override
    public boolean deleteShop(String no) {
        try {
            String sql = "delete from shop where no=?";
            con = JdbcUtil.getCon();
            ps = con.prepareStatement(sql);
            ps.setString(1, no);
            ps.execute();
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.closeCon(con, ps, rs);
        }
        return false;
    }

    //修改 通过shop对象 where=no
    @Override
    public boolean updateShop(Shop shop, String updateNo) {
        try {
            String sql = "update shop set no=?,name=?,address=?,type=? where no =?";
            con = JdbcUtil.getCon();
            ps = con.prepareStatement(sql);
            ps.setString(1, shop.getNo());
            ps.setString(2, shop.getName());
            ps.setString(3, shop.getAddress());
            ps.setString(4, shop.getType());
            ps.setString(5, updateNo);
            ps.execute();
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.closeCon(con, ps, rs);
        }
        return false;
    }

    //新增
    @Override
    public boolean addShop(Shop shop) {
        try {
            String sql = "insert into shop values(?,?,?,?,?)";
            con = JdbcUtil.getCon();
            ps = con.prepareStatement(sql);
            ps.setString(1, shop.getNo());
            ps.setString(2, shop.getName());
            ps.setString(3, shop.getTime());
            ps.setString(4, shop.getAddress());
            ps.setString(5, shop.getType());
            ps.execute();
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.closeCon(con, ps, rs);
        }
        return false;
    }
}

4.业务逻辑层 service

ShopService

package org.hc.homework.service;

import org.hc.homework.entity.Page;
import org.hc.homework.entity.Shop;

public interface ShopService {
    //查询-分页
    Page getShopsInPage(Page page);
    //查询 BY no
    Shop getShopByNo(String no);
    //删除
    boolean deleteShop(String no);
    //修改
    boolean updateShop(Shop shop, String updateNo);
    //新增
    boolean addShop(Shop shop);
}

ShopServiceImpl

package org.hc.homework.service.serviceImpl;

import org.hc.homework.dao.ShopDao;
import org.hc.homework.dao.daoImpl.ShopDaoImpl;
import org.hc.homework.entity.Page;
import org.hc.homework.entity.Shop;
import org.hc.homework.service.ShopService;


public class ShopServiceImpl implements ShopService {
    ShopDao shopDao=new ShopDaoImpl();

    @Override
    public Page getShopsInPage(Page page) {
        if (page.getLists().size()==0){
            page.setTotalCount(shopDao.getCount(new Shop()));//总条数赋值进去
        }else{
            page.setTotalCount(shopDao.getCount(page.getLists().get(0)));//总条数赋值进去
        }
        return shopDao.getShopsInPage(page);
    }

    @Override
    public Shop getShopByNo(String no) {
        return shopDao.getShopByNo(no);
    }

    @Override
    public boolean deleteShop(String no) {
        return shopDao.deleteShop(no);
    }

    @Override
    public boolean updateShop(Shop shop, String updateNo) {
        return shopDao.updateShop(shop,updateNo);
    }

    @Override
    public boolean addShop(Shop shop) {
        return shopDao.addShop(shop);
    }
}

5.控制层 Servlet

通过每次跳到控制器的opereation的值决定是哪个操作

package org.hc.homework.servlet;

import org.hc.homework.entity.Page;
import org.hc.homework.entity.Shop;
import org.hc.homework.service.ShopService;
import org.hc.homework.service.serviceImpl.ShopServiceImpl;

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.util.ArrayList;

@WebServlet(name = "ShopServlet")
public class ShopServlet extends HttpServlet {
    private static final long serialVersionUID = -6283161696285843678L;
    ShopService shopService = new ShopServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        ArrayList shops = null;
        String operation = request.getParameter("operation");//操作字符
        Page page = new Page();
        if (request.getParameter("currentPage") != null) {
            page.setCurrentPage(Integer.parseInt(request.getParameter("currentPage")));//当前页
        } else {
            page.setCurrentPage(1);
        }
        if (request.getParameter("pageSize") != null) {
            page.setPageSize(Integer.parseInt(request.getParameter("pageSize")));//每页的条数
        } else {
            page.setPageSize(4);
        }

        //判断业务
        if (operation.equals("queryAll")) {
            //全查
            page = shopService.getShopsInPage(page);
        } else if (operation.equals("query")) {
            //条件查询
            Shop shop = new Shop(
                    null,
                    request.getParameter("name"),
                    request.getParameter("time"),
                    request.getParameter("address"),
                    request.getParameter("type")
            );
            request.setAttribute("queryShop", shop);
            page.getLists().add(shop);
            page = shopService.getShopsInPage(page);
            //测试
            log("条件查询page的各个属性:" +
                    "\npage.getTotalCount=" + page.getTotalCount() +
                    "\npage.getPageSize=" + page.getPageSize() +
                    "\npage.getStart=" + page.getStart() +
                    "\npage.getCurrentPage=" + page.getCurrentPage() +
                    "\npage.getName=" + shop.getName() +
                    "\npage.getType=" + shop.getType() +
                    "\npage.getTime=" + shop.getTime() +
                    "\npage.getAddress=" + shop.getAddress()
            );
        } else if (operation.split("&")[0].equals("delete")) {
            //删除,由&拆分字符串,拿下标为0的数组内容
            String no = operation.split("&")[1];
            boolean flag = shopService.deleteShop(no);
            if (flag) {
                request.setAttribute("Success", "");
            } else {
                request.setAttribute("Success", "");
            }
            page = shopService.getShopsInPage(page);//全查
        } else if (operation.split("&")[0].equals("toUpdate")) {
            //to修改,由&拆分字符串,拿下标为0的数组内容
            String no = operation.split("&")[1];
            Shop shop = shopService.getShopByNo(no);
            request.setAttribute("shop", shop);//返回原数据
            request.getRequestDispatcher("updateList.jsp").forward(request, response);
            return;
        } else if (operation.equals("update")) {
            //修改
            String updateNo = request.getParameter("updateNo");
            Shop shop = new Shop(
                    request.getParameter("no"),
                    request.getParameter("name"),
                    request.getParameter("time"),
                    request.getParameter("address"),
                    request.getParameter("type")
            );
            boolean flag = shopService.updateShop(shop, updateNo);
            if (flag) {
                request.setAttribute("Success", "");
            } else {
                request.setAttribute("Success", "");
            }
            page = shopService.getShopsInPage(page);//全查
        } else if (operation.equals("add")) {
            //新增
            Shop shop = new Shop(
                    request.getParameter("no"),
                    request.getParameter("name"),
                    request.getParameter("time"),
                    request.getParameter("address"),
                    request.getParameter("type")
            );
            boolean flag = shopService.addShop(shop);
            if (flag) {
                request.setAttribute("Success", "");
            } else {
                request.setAttribute("Success", "");
            }
            page = shopService.getShopsInPage(page);//全查
        } else if (operation.equals("toAdd")) {
            //to新增
            request.getRequestDispatcher("addList.jsp").forward(request, response);
            return;
        }
        request.setAttribute("page", page);
        request.getRequestDispatcher("list.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

java类就在此结束了,下面是JSP和CSS

6.JSP和CSS

center.css

body,div,table,form{
    margin: 0 auto;
    text-align: center;
}
#div1{
    margin-top: 30px;
}
#div2{
    margin-top: 50px;
}
#list{
    margin-top: 20px;
}

index.jsp(初始界面)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

  
    welcome
  
  
  

list.jsp(全查列表)使用了EL表达式和JSTL,需要导入JSTL的包

<%@ page contentType="text/html;charset=UTF-8" %>
<%-- 引入JSTL --%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


    
    列表
    


<%--是否删除、修改、新增成功--%>

    ${Success}



<%-- 搜索,条件查询 operation=qeury --%>
商品名: 商品种类: 产地: 生产日期:
<%-- 新增 --%>
<%--列表--%>
商品编号 商品名 生产日期 产地 商品类型 删除 修改
${shop.no} ${shop.name} ${shop.time} ${shop.address} ${shop.type}
<%-- 不是首页和尾页,即中间页,即 首页 上一页 下一页 尾页 --%> 首页 上一页 下一页 尾页 <%-- 尾页,只有 首页 上一页 --%> 首页 上一页 <%-- 首页,只有 下一页 尾页 --%> 下一页 尾页

addList.jsp(新增页面)

<%@ page contentType="text/html;charset=UTF-8"
         language="java"
         import="org.hc.homework.entity.Shop"
%>


    新增
    


新增商品信息
商品编号 商品名称
商品产地 商品类型
生产日期

updateList.jsp(修改页面)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%-- 引入JSTL --%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


    修改
    


修改商品信息
商品编号 商品名称
商品产地 商品类型

7.在tomcat环境下跑起来

【JavaWeb开发】JavaWeb之MVC中真分页的实现_第2张图片

【JavaWeb开发】JavaWeb之MVC中真分页的实现_第3张图片

【JavaWeb开发】JavaWeb之MVC中真分页的实现_第4张图片

【JavaWeb开发】JavaWeb之MVC中真分页的实现_第5张图片

主要是分页功能的展示,其他就不展示啦

如果您觉得本文章对您有帮助,请点个赞支持一下作者~

 

 

 

 

你可能感兴趣的:(javaWeb)