复习整理的DAY11_Servlet生命周期以及在web里分页操作

Servlet生命周期共分为五个阶段:
1.加载阶段
Servlet容器通过类加载器加载Servlet文件
2.创建阶段
通过构造方法创建Servlet对象,在Tomcat中,Servlet是单实例的。
3.初始化阶段。
用init()方法初始化,只调用一次。
4.响应客户请求阶段。
通过service方法响应客户请求,可以响应多次
5.销毁阶段。
停止服务器或者重新部署web应用时,用destroy方法销毁,释放占用的资源。
尝试了一下:

public class LifeServlet extends HttpServlet {

    public LifeServlet() {
        System.out.println("LifeServlet.LifeServlet");
    }

    @Override
    public void init() throws ServletException {
        super.init();
        System.out.println("LifeServlet.init");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LifeServlet.service");
    }

    @Override
    public void destroy() {
        super.destroy();
        System.out.println("LifeServlet.destroy");
    }
}

Servlet生命周期总结:
1.request请求
2.创建Servlet实例对象
3.调用servlet中init方法
4.调用service方法(多次)
5.response响应
6.调用destroy方法终止servlet。
##############################################
分页操作
在工具包中新增一个类PageInfo

public class PageInfo<T> {

    // 当前页数据集合
    private ArrayList<T> list;
    // 当前是第几页
    private Integer pageNo;
    // 一共多少页
    private Integer totalPage;
    // 一页多少数据
    private Integer pageSize;

    public PageInfo() {
    }

    public PageInfo(ArrayList<T> list, Integer pageNo, Integer totalPage, Integer pageSize) {
        this.list = list;
        this.pageNo = pageNo;
        this.totalPage = totalPage;
        this.pageSize = pageSize;
    }

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

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

    public Integer getPageNo() {
        return pageNo;
    }

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

    public Integer getTotalPage() {
        return totalPage;
    }

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

    public Integer getPageSize() {
        return pageSize;
    }

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

    @Override
    public String toString() {
        return "PageInfo{" +
                "list=" + list +
                ", pageNo=" + pageNo +
                ", totalPage=" + totalPage +
                ", pageSize=" + pageSize +
                '}';
    }
}

改成分页之后,不再需要把数据一次性全部展示,所以在StudentServlet类中放弃selectAll方法,增加了新的方法。
原理——分页需要的数据包括每一页的大小pageSize,本页是第几页pageNo,本页开头是从第几个数据开始offset,一共多少数据totalCount,一共多少页totalPage,每页的数据list。所以需要两个方法分别用来计算totalCount和list,通过计算得到offset和totalPage,再将得到的数据汇总,存到PageInfo里,最后转发到jsp页面进行处理。

@WebServlet("/student")
public class StudentServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 设置utf-8编码类型
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String method = req.getParameter("method");
        if (method == null || method.equals("")) {
            method = "selectByPage";
        }
        switch (method) {
            case "selectAll":
                selectAll(req, resp);
                break;
            case "deleteById":
                deleteById(req, resp);
                break;
            case "insert":
                insert(req, resp);
                break;
            case "selectById":
                selectById(req, resp);
                break;
            case "update":
                update(req,resp);
                break;
            case "selectByPage":
                selectByPage(req, resp);
                break;
        }

    }

    private void selectByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pageSizeStr = req.getParameter("pageSize");
        String pageNoStr = req.getParameter("pageNo");
        if (pageSizeStr == null || pageSizeStr.equals("")) {
            pageSizeStr = "5";
        }
        if (pageNoStr == null || pageNoStr.equals("")) {
            pageNoStr = "1";
        }
        int pageNo = Integer.parseInt(pageNoStr);
        int pageSize = Integer.parseInt(pageSizeStr);
        // 当前页开始序号
        int offset = (pageNo - 1) * pageSize;
        // 获得当前页数据集合
        ArrayList<Student> list = getCurrentPageList(offset, pageSize);
        // 获得数据条总数
        int totalCount = getTotalCount();
        int totalPage = (int)Math.ceil((double)totalCount/pageSize);
        PageInfo pageInfo = new PageInfo(list,pageNo,totalPage,pageSize);
        // 转发
        req.setAttribute("pageInfo", pageInfo);
        req.getRequestDispatcher("/student.jsp").forward(req,resp);
    }

    private int getTotalCount() {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        int count = 0;
        try {
            connection = JDBCUtil.getConnection();
            String sql = "select count(*) from student";
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            if (resultSet.next()) {
                count = resultSet.getInt(1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.close(connection, statement, resultSet);
        }
        return count;
    }

    private ArrayList<Student> getCurrentPageList(int offset, int pageSize) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        ArrayList<Student> list = new ArrayList<>();
        try {
            connection = JDBCUtil.getConnection();
            String sql = "select id, name, age, gender from student limit ?, ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,offset);
            statement.setInt(2,pageSize);
            System.out.println(statement);
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                String gender = resultSet.getString("gender");
                Student student = new Student(id, name, age, gender);
                list.add(student);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.close(connection, statement, resultSet);
        }
        return list;
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("StudentServlet.update");
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String gender = req.getParameter("gender");
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = JDBCUtil.getConnection();
            String sql = "update student set name = ?, age = ?, gender = ? where id = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,name);
            statement.setInt(2, Integer.parseInt(age));
            statement.setString(3, gender);
            statement.setInt(4, Integer.parseInt(id));
            System.out.println(statement);
            int count = statement.executeUpdate();
            System.out.println("count:" + count);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.close(connection, statement, null);
        }
        // 删除之后,展示
        // 重定向:让浏览器发送这个请求。/JavaWeb
        resp.sendRedirect(req.getContextPath() + "/student?method=selectByPage&pageNo=" + req.getParameter("pageNo"));
    }

    private void selectById(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        System.out.println("StudentServlet.selectById");
        int id = Integer.parseInt(req.getParameter("id"));
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        Student student = new Student();
        try {
            connection = JDBCUtil.getConnection();
            String sql = "select name,age,gender from student where id = " + id;
            statement = connection.prepareStatement(sql);
            System.out.println(statement);
            resultSet = statement.executeQuery();
            if (resultSet.next()) {
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                String gender = resultSet.getString("gender");
                student.setId(id);
                student.setName(name);
                student.setAge(age);
                student.setGender(gender);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.close(connection, statement, resultSet);
        }
        req.setAttribute("pageNo", req.getParameter("pageNo"));
        req.setAttribute("student", student);
        req.getRequestDispatcher("/student_update.jsp").forward(req,resp);
    }

    private void insert(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("StudentServlet.insert");
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String gender = req.getParameter("gender");
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = JDBCUtil.getConnection();
            if (id == "" || id == null) {
                String sql = "insert into student(name, age, gender) values(?,?,?)";
                statement = connection.prepareStatement(sql);
                statement.setString(1, name);
                statement.setInt(2, Integer.parseInt(age));
                statement.setString(3, gender);
                System.out.println(statement);
                int count = statement.executeUpdate();
                System.out.println("count:" + count);
            } else {
                String sql = "insert into student(id, name, age, gender) values(?,?,?,?)";
                statement = connection.prepareStatement(sql);
                statement.setInt(1, Integer.parseInt(id));
                statement.setString(2, name);
                statement.setInt(3, Integer.parseInt(age));
                statement.setString(4, gender);
                System.out.println(statement);
                int count = statement.executeUpdate();
                System.out.println("count:" + count);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.close(connection, statement, null);
        }
        // 删除之后,展示
        // 重定向:让浏览器发送这个请求。/JavaWeb
        resp.sendRedirect(req.getContextPath() + "/student?method=selectByPage");
    }

    private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("StudentServlet.deleteById");
        String id = req.getParameter("id");
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = JDBCUtil.getConnection();
            String sql = "delete from student where id = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, Integer.parseInt(id));
            System.out.println(statement);
            int count = statement.executeUpdate();
            System.out.println("count:" + count);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.close(connection, statement, null);
        }
        // 删除之后,展示
        // 重定向:让浏览器发送这个请求。/JavaWeb
        resp.sendRedirect(req.getContextPath() + "/student?method=selectPageNo");
    }

    private void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("StudentServlet.selectAll");
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        ArrayList<Student> list = new ArrayList<>();
        try {
            connection = JDBCUtil.getConnection();
            String sql = "select id, name, age, gender from student";
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();

            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                String gender = resultSet.getString("gender");
                Student student = new Student(id, name, age, gender);
                list.add(student);
            }
            /*for (Student student : list) {
                System.out.println(student);
            }*/
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.close(connection, statement, resultSet);
        }
        // 转发
        req.setAttribute("list", list);
        req.getRequestDispatcher("/student.jsp").forward(req, resp);
    }
}

student.jsp

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2021/8/10
  Time: 16:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="<%= request.getContextPath()%>/static/bootstrap-3.4.1-dist/css/bootstrap.css"/>
</head>
<body>
    <a class="btn btn-primary" href="<%= request.getContextPath()%>/student_insert.jsp">添加</a>
    <table border="1" cellspacing="0" class="table table-striped table-bordered table-hover">
        <tr>
            <td>ID</td>
            <td>名字</td>
            <td>年龄</td>
            <td>性别</td>
            <td>删除/修改</td>
        </tr>
        <%
            // 测试
            PageInfo<Student> pageInfo = (PageInfo<Student>)request.getAttribute("pageInfo");
            for (Student student : pageInfo.getList()) {
        %>
                <tr>
                    <td><%= student.getId()%></td>
                    <td><%= student.getName()%></td>
                    <td><%= student.getAge()%></td>
                    <td><%= student.getGender()%></td>
                    <td>
                        <a class="btn btn-danger btn-sm"  onclick="deleteById(<%= student.getId()%>)">删除</a>
                        <a class="btn btn-warning btn-sm" href="<%= request.getContextPath()%>/student?method=selectById&id=<%= student.getId()%>&pageNo=<%=pageInfo.getPageNo()%>">修改</a>
                    </td>
                </tr>
        <%
            }
        %>

    </table>
    <nav aria-label="Page navigation">
        <ul class="pagination">
            <%
                if(pageInfo.getPageNo()>1) {
            %>
            <li>
                <a href="<%=request.getContextPath()%>/student?method=selectByPage&pageNo=<%=pageInfo.getPageNo()-1%>" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
            <%
                } else {
            %>
            <li class="disabled">
                <a href="" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
            <%
                }
                for (int i = 1; i <= pageInfo.getTotalPage(); i++) {
                    if (i == pageInfo.getPageNo()) {
            %>
            <li class="active">
                <a href="<%=request.getContextPath()%>/student?method=selectByPage&pageNo=<%=i%>"><%=i%></a>
            </li>
            <%
                    } else {
            %>
            <li>
                <a href="<%=request.getContextPath()%>/student?method=selectByPage&pageNo=<%=i%>"><%=i%></a>
            </li>
            <%
                    }
                }
                if (pageInfo.getPageNo() < pageInfo.getTotalPage()) {
            %>
            <li>
                <a href="<%=request.getContextPath()%>/student?method=selectByPage&pageNo=<%=pageInfo.getPageNo()+1%>" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
            <%
                } else {
            %>
            <li class="disabled">
                <a href="" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
            <%
                }
            %>
        </ul>
    </nav>
    <script type="text/javascript">
        function deleteById(id) {
            var isDelete = confirm("您确认要删除吗?");
            if (isDelete) {
                location.href = '<%= request.getContextPath()%>/student?method=deleteById&id='+id;
            }
        }
    </script>
</body>
</html>

link里链接的是bootstrap,在一些class里添加了样式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值