【JavaWeb】基于Servlet&Jsp&JDBC技术的前后端交叉响应技术(第三篇:开发详细技巧之新增、修改、删除指定行)

继上一篇博客之后,是否get到了一些开发的小技巧呢?本次我将会把剩下几个比较实用的功能实现的逻辑都罗列出来:

       1、新增用户信息:当我们点击新增按钮的时候,就会跳转到一个新增用户信息的jsp页面,然后通过在这个页面中填写好的信息内容,通过form表单提交的方式传输到指定的action路径,传到Servlet层,此时Servlet层可以通过getParameter、getParameterMap(获取所有的数据封装成一个map集合)两种方式来获取我们表单中填好的所有数据;再将这个新增的数据传入Service层,Service层调用Dao层进行数据库的新增操作,最后再在Servlet层中重新调用findAllServlet方法来重新查看我们所有的数据内容。

       2、删除某一行数据:当我们点击表格中某一行的按钮的时候,就可以直接删除本行的所有数据,同时删除数据库中的指定行。这个功能的原理主要是每一行数据其实都有一个对应的student.sno,这个sno可以通过form表单提交、超链接href的方式,指定?id=${student.sno},这样就相当于在get请求中在网址栏目显示所有参数一样,其中id就可以在Servlet层直接用request.getParameter(”name(id)“)的方式直接获取到我们的id,然后再根据这个id来查找Dao层中数据库的指定sno的那一行数据,直接删除数据库中那一行的信息内容,最后再在Service层调用findAllServlet()方法就可以看到我们的页面更新成功了!

       3、通过复选框进行多选删除:我们可以多选进行删除,这里我们还是用到了form表单里面嵌套table的方式,并且直接指定了在action中路径最后加入?id=${student.sno},这个数据在from表单的action中可以添入作为我们页面跳转的时候地址栏包含的信息内容,这样的话我们就可以直接在Servlet中getParameter("id")获取到我们要删除的id号了;

       因为我们显示数据的<tr><td>是放在foreach语句中的,所以这个form表单一定要包含到我们整个table中,否则其提交的作用域是在foreach循环之外的话,会导致无法提交具体的${student.sno}数据到Servlet层,或者说这个请求是无效的。在Servlet层获取到要删除的id之后直接调用在Service和Dao层的delete(int sno)即可。

     (注意:由于input type=checkbox复选框中,当我们进行表单提交操作的时候,我们选中的checkbox在JavaWeb中是会默认返回true的,也就是说当我们选中这个checkbox,提交的时候在地址栏中可以直接看到其对应的name,所以这里我们只需要对checkbox的value值进行赋值即可!进行多选删除的时候由于我们所选的每个checkbox都有一个对应的value=${student.sno}值,所以在获取的时候我们只需要使用String[] array = getParameterValues("name")的方式获取value数组[我们选中的所有value]值都保存在这个String数组中了,重复调用delete方法即可完成多选删除操作)

       4、通过复选框进行全选删除:这里实现原理只是通过jsj代码,把全选的checkbox和所有相同name的checkbox进行checked同步操作,也就是说当我们的全选checkbox选中,所有的checkbox都会选中,此时我们提交表单相当于把所有的行都选上,每一个checkbox都有一个对应的value值,在Servlet层中直接调用delete方法即可完成全选删除操作了。

!!!所有要功能都展示在一个页面上啦!大家可以查看一下面的图哈!

Dao层代码:

package dao;

import com.sun.jndi.toolkit.dir.HierMemDirCtx;
import domain.Student;
import jdk.nashorn.internal.scripts.JD;
import utils.JDBCUtils;

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 StudentDao {

    /**
     * @return 封装好数据的student集合对象
     */
    public List<Student> findAll(){

        //创建一个用于封装对象的list集合
        List list = new ArrayList();

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = JDBCUtils.getConnection();
            String sql = "select * from stu";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()){
                Student student = new Student();
                student.setSno(rs.getInt("sno"));
                student.setName(rs.getString("name"));
                student.setPassword(rs.getString("password"));
                student.setEmail(rs.getString("email"));
                student.setQq(rs.getString("qq"));
                student.setAge(rs.getInt("age"));
                list.add(student);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(rs,pstmt,conn);
        }
        return list;
    }

    /**
     * 根据用户输入的账号和密码进行登录的方法
     * @param username 用户输入的账号
     * @param password 用户输入的密码
     * @return 找到则登录成功/true、否则false
     */
    public boolean login(String username,String password){

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = JDBCUtils.getConnection();
            String sql = "select * from stu where name = ? and password = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                String current_username = rs.getString("name");
                String current_password = rs.getString("password");

                //如果账号和密码匹配正确的话就直接返回true
                if (username.equals(current_username) && password.equals(current_password)) {
                    return true;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭连接资源
            JDBCUtils.close(rs,pstmt,conn);
        }
        return false;
    }

    /**
     * 新增学生信息的方法
     */
    public void add(int sno,String name,String password,String email,String qq,int age){

        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "insert into stu values(?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,"" + sno);
            pstmt.setString(2,name);
            pstmt.setString(3,password);
            pstmt.setString(4,email);
            pstmt.setString(5,qq);
            pstmt.setString(6,"" + age);

            //执行sql
            pstmt.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(pstmt,conn);
        }
    }

    //根据提供的student.id来进行查询操作
    public List<Student> findById(int stu_sno){

        List<Student> list = new ArrayList<Student>();

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = JDBCUtils.getConnection();
            String sql = "select * from stu where sno = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,""+stu_sno);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                Student student = new Student();
                student.setSno(rs.getInt("sno"));
                student.setName(rs.getString("name"));
                student.setPassword(rs.getString("password"));
                student.setEmail(rs.getString("email"));
                student.setQq(rs.getString("qq"));
                student.setAge(rs.getInt("age"));
                list.add(student);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(rs,pstmt,conn);
        }
        //返回false则说明没有在数据库中找到这个数据
        return list;
    }

    /**
     * 这里就是用户输入新的信息之后修改数据库中的表
     * @param sno
     * @param name
     * @param password
     * @param email
     * @param qq
     * @param age
     * @return
     */
    public void update(int sno,String name,String password,String email,String qq,int age){

        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = JDBCUtils.getConnection();
            //根据指定的id号进行修改
            String sql = "update stu set name = ?,password = ?,email = ?,qq = ?,age = ? where sno = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,name);
            pstmt.setString(2,password);
            pstmt.setString(3,email);
            pstmt.setString(4,qq);
            pstmt.setString(5,""+age);
            pstmt.setString(6,""+sno);
            //执行sql
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(pstmt,conn);
        }
    }

    /**
     * 根据用户输入的id进行删除操作
     * @param sno
     */
    public void delete(int sno){

        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = JDBCUtils.getConnection();
            String sql = "delete from stu where sno = ?";
            pstmt = conn.prepareStatement(sql);

            pstmt.setString(1,""+sno);
            pstmt.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(pstmt,conn);
        }

    }
}

根据id来进行查找并且在最后返回一个封装好数据的某一行数据库数据的集合方法:findByIdServlet

package servlet;

import domain.Student;
import service.StudentService;

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.List;

@WebServlet("/findByIdServlet")
public class FindByIdServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置字符集编码格式为utf-8
        request.setCharacterEncoding("utf-8");

        //获取用户输入的id的值,这里我们指定的是href超链接(包含参数),所以href中name=id,value就是具体的id值
        int sno = Integer.parseInt(request.getParameter("id"));

        //调用Service,查询是否存在这个学生号
        StudentService studentService = new StudentService();
        //这里直接返回一个封装好对象的list集合
        List<Student> list = studentService.findByIdService(sno);

        //这里直接共享新的数据过去给修改的jsp页面
        request.setAttribute("student_id",list);
        request.getRequestDispatcher("/update.jsp").forward(request,response);
    }

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

最重要的主页面:list.jsp

<%--
  Created by IntelliJ IDEA.
  User: Simon
  Date: 2019/11/3
  Time: 19:55
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <style type="text/css">
        table{
            width: 800px;
            text-align: center;
            margin: auto;
        }

        h3{
            text-align: center;
        }

        #form2{
            display: inline-block;
        }
    </style>
    <script>

        function addUser(){
            location.href="/addUser.jsp";
        }

        //删除我们选中的所有value
        function deleteSelect(){
            if(confirm("您确定要删除选中条目吗?")){
                //返回true,提交表单,这里其实就是点击按钮之后触发onsubmit提交表单
                document.getElementById("DelForm").submit();
            }
        }

        //这个jsp主要用于
        function sel(a){
                o = document.getElementsByName(a);
                for (var i = 0; i < o.length; i++) {
                    o[i].checked = event.srcElement.checked;
                }
            }

    </script>
</head>
<body>
    <h3>学生信息表</h3>
    <div style="float: right;margin: 5px;">

        <button onclick="addUser()">新增联系人</button>
        <button onclick="deleteSelect()">删除联系人</button>

    </div>

    <form id="DelForm" action="${pageContext.request.contextPath}/deleteSelectServlet" method="post">

    <table border="1px" cellspacing="0px" >
        <tr>
            <th><input type="checkbox" onclick="sel('choice')">全选</th>
            <th>序号</th>
            <th>姓名</th>
            <th>密码</th>
            <th>邮箱</th>
            <th>qq</th>
            <th>年龄</th>
            <th>修改</th>
        </tr>

        <c:forEach items="${requestScope.students}" var="student" varStatus="s">
            <tr>
                <%--
                    这里我们需要进行选中删除的操作,主要是通过表单提交的方式来进行删除
                    当我们选中这一行数据之后,其就会同时对应一个sno的value值
                    可以通过getParameterVlues的方式来获取每一个value值
                    最后还是通过点击删除选择按钮的onclick来进行submit提交操作
                --%>
                    <td><input type="checkbox" name="choice" value="${student.sno}"></td>
                    <td>${s.count}</td>
                    <td>${student.name}</td>
                    <td>${student.password}</td>
                    <td>${student.email}</td>
                    <td>${student.qq}</td>
                    <td>${student.age}</td>

                <td>
                    <form id="form2" action="${pageContext.request.contextPath}/deleteServlet?id=${student.sno}" method="post">
                        <input type="submit" name="delete" value="删除">
                    </form>

                    <%--<a href="${pageContext.request.contextPath}/findByIdServlet?id=${student.sno}">修改</a>--%>
                    <form id="form2" action="${pageContext.request.contextPath}/findByIdServlet?id=${student.sno}" method="post">
                        <input type="submit" name="alter" value="修改">
                    </form>
                </td>
            </tr>
        </c:forEach>
    </form>

    </table>
</body>
</html>

修改用户数据的update.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>修改学生信息页面</title>
</head>
<body>
<h3>学生信息修改界面</h3>
    <form action="${pageContext.request.contextPath}/updateServlet" method="post">
        <c:forEach items="${requestScope.student_id}" var="student" varStatus="v">
            学号:<input type="text" name="sno" id="sno" readonly="readonly" value="${student.sno}"/><br/>
            姓名:<input type="text" name="name" id="name" value="${student.name}"/><br/>
            密码:<input type="password" name="password" id="password" value="${student.password}"/><br/>
            邮箱:<input type="text" name="email" id="email" value="${student.email}"/><br/>
            qq号:<input type="text" name="qq" id="qq" value="${student.qq}"/><br/>
            年龄:<input type="text" name="age" id="age" value="${student.age}"/><br/>
        </c:forEach>
        <input type="submit" value="修改学生信息"/>
    </form>
</body>
</html>

(多选删除)根据指定id进行删除的Servlet

package servlet;

import service.StudentService;

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;

@WebServlet("/deleteSelectServlet")
public class DeleteSelectServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式为utf-8
        request.setCharacterEncoding("utf-8");
        //获取所有复选框选中的对象的value值
        String[] choice = request.getParameterValues("choice");
        //调用service层,传choice数组进去进行删除
        StudentService studentService = new StudentService();
        studentService.deleteSelectService(choice);
        //删除完毕之后重新返回list的显示servlet
        response.sendRedirect(request.getContextPath()+"/findAllServlet");
    }

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

当用户点击删除按钮的时候进行删除的Servlet:

package servlet;

import service.StudentService;

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;

@WebServlet("/deleteServlet")
public class DeleteServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式
        request.setCharacterEncoding("utf-8");
        //获取用户选择删除的id号
        int sno = Integer.parseInt(request.getParameter("id"));

        //根据id号进行删除,调用service层
        StudentService studentService = new StudentService();
        //直接进行删除操作
        studentService.deleteService(sno);

        //删完了之后重新返回显示列表的页面查看
        response.sendRedirect(request.getContextPath()+"/findAllServlet");

    }

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

新增用户信息的Servlet:

package servlet;

import service.StudentService;

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.Map;

@WebServlet("/addStudentServlet")
public class AddStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式
        request.setCharacterEncoding("utf-8");

        StudentService studentService = new StudentService();

        //获取用户输入的内容
        int sno = Integer.parseInt(request.getParameter("sno"));
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String qq = request.getParameter("qq");
        int age = Integer.parseInt(request.getParameter("age"));

        //把用户输入的信息内容录入数据库中去
        studentService.addService(sno,name,password,email,qq,age);

        //重新查询所有的学生信息表
        response.sendRedirect(request.getContextPath()+"/findAllServlet");
    }

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

 

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值