web第四次课后作业--页面操作实现数据库的增删查改

一、环境配置

1. 创建一个java web(maven构建)的项目

2.  配置tomcat

3. 连接数据库

二、页面呈现

  • 登录页面
    在这里插入图片描述

  • 详细信息
    在这里插入图片描述

  • 删除一条信息后
    在这里插入图片描述

  • 更新
    在这里插入图片描述

  • 更新后的信息
    在这里插入图片描述


三、目录结构

在这里插入图片描述

四、代码实现

4.1 denglu.jsp

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

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>用户登录</title>
  <link rel="stylesheet" type="text/css" href="../css/style.css">
</head>
<body>
  <div class="form-container">
    <h2>用户登录</h2>
    <form action="zhuce/denglu_submit.jsp" method="post">
      <div class="form-group">
        <label for="username">账号:</label>
        <input type="text" id="username" name="username" />
      </div>
      <div class="form-group">
        <label for="pwd">密码:</label>
        <input type="password" id="pwd" name="pwd" />
      </div>
      <input type="submit" value="登陆" />
    </form>
  </div>
</body>
</html>

4.2 denglu_submit.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" import="java.sql.*" %>
<%
    request.setCharacterEncoding("UTF-8"); // 确保正确处理POST请求中的中文字符

    String name = request.getParameter("username");
    String password = request.getParameter("pwd");
    String message = "";
    boolean success = false;

    Connection conn = null;
    PreparedStatement pstmt = null;

    try {
        Class.forName("com.mysql.cj.jdbc.Driver"); // 更新驱动类名
        conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo?characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC",
                "root", "1234"); // 添加 useSSL=false 和 serverTimezone=UTC 推荐参数

        String sql = "INSERT INTO denglu (username, password) VALUES (?, ?)";//SQL 语句中应该使用问号 ?作为参数的占位符。
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, name);
        pstmt.setString(2, password);

        int r = pstmt.executeUpdate();

        if (r > 0) {
            System.out.println("成功插入 " + r + " 条记录: username=" + name);
            // 设置成功消息,可以通过 session 传递给下一个页面
            session.setAttribute("dbMessage", "用户 " + name + " 注册成功!" + r + "条记录已插入。");
            success = true;
        } else {
            System.out.println("插入失败,没有记录被影响: username=" + name);
            message = "用户注册失败,请重试。";
        }

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        message = "数据库驱动加载失败: " + e.getMessage();
        System.err.println("数据库驱动加载失败: " + e.getMessage());
    } catch (SQLException e) {
        e.printStackTrace();
        message = "数据库操作失败: " + e.getMessage();
        System.err.println("数据库操作失败: " + e.getMessage() + " SQLState: " + e.getSQLState());
    } finally {
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    if (success) {
        response.sendRedirect("user_select.jsp");
    } else {
        // 如果失败,可以重定向回注册页面并显示错误,或者在本页显示错误
        // 这里我们选择在本页显示错误,因为没有明确的错误展示页
%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>注册结果</title>
</head>
<body>
    <h2>注册处理结果</h2>
    <p style="color:red;"><%= message %></p>
    <p><a href="zhuce/denglu.jsp">返回注册页面</a></p>
</body>
</html>
<%
    }
%>

4.3 user_select.jsp

<%@ page import="java.sql.*" %><%--
  Created by IntelliJ IDEA.
  User: huawei
  Date: 2025/4/28
  Time: 12:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户信息</title>
    <link rel="stylesheet" type="text/css" href="../css/style.css">
</head>
<body>
<div class="form-container">
  <h2>用户列表</h2>
  <table class="data-table">
    <tr>
        <th>id</th>
        <th>姓名</th>
        <th>密码</th>
        <th>操作</th>
    </tr>
    <%
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try (Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo?characterEncoding=UTF-8",
                "root", "1234");
             Statement s = c.createStatement();
        ) {
            String sql = "select * from denglu";
            // 执行查询语句,并把结果集返回给ResultSet
            ResultSet rs = s.executeQuery(sql);
/*        if(rs.next())
            System.out.println("账号密码正确");
        else
            System.out.println("账号密码错误");
        */

/*        //输出到控制台
                while (rs.next()){
             out.println(rs.getString(2)+","+rs.getString(3)+";;");
        }*/
            while (rs.next()){
                //输出到页面表格中
                int id=rs.getInt(1);
    %>

    <tr>
        <td><%=id%></td>
        <td><%=rs.getString(2)%></td>
        <td><%=rs.getString(3)%></td>
        <td><a href="user_delete.jsp?id=<%=id%>">删除</a> &nbsp;&nbsp; <a href="user_update.jsp?id=<%=id%>">修改</a></td>
    </tr>


    <%
            }
            rs.close();
            c.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    %>

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

4.4 user_delelte.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" import="java.sql.*" %>
<%
    request.setCharacterEncoding("UTF-8");

    String paramId = request.getParameter("id");
    String message = "";
    boolean deleteSuccess = false;
    int userId = -1;

    if (paramId == null || paramId.trim().isEmpty()) {
        message = "错误:ID 不能为空。";
    } else {
        try {
            userId = Integer.parseInt(paramId);
        } catch (NumberFormatException e) {
            message = "错误:ID 格式不正确 (" + paramId + ")。";
        }
    }

    Connection conn = null;
    PreparedStatement pstmt = null;

    if (message.isEmpty()) { // 只有在初始参数校验通过后才执行数据库操作
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo?characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC",
                    "root", "1234");

            String sql = "DELETE FROM denglu WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, userId);

            int rowsAffected = pstmt.executeUpdate();

            if (rowsAffected > 0) {
                deleteSuccess = true;
                message = "ID " + userId + " 的用户删除成功!影响行数: " + rowsAffected;
                System.out.println(message);
            } else {
                message = "用户删除失败,未找到对应 ID (" + userId + ")。";
                System.out.println(message);
            }
        } catch (ClassNotFoundException e) {
            message = "数据库驱动加载失败: " + e.getMessage();
            e.printStackTrace();
        } catch (SQLException e) {
            message = "数据库操作失败: " + e.getMessage();
            e.printStackTrace();
        } finally {
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 无论成功与否(只要不是初始的严重错误),都设置消息并重定向
    session.setAttribute("dbMessage", message);
    response.sendRedirect("user_select.jsp");
%>

4.5 user_update.jsp

<%@ page import="java.sql.*" %>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>更新用户信息</title>
    <link rel="stylesheet" type="text/css" href="../css/style.css">
</head>
<body>
<%
    String id = request.getParameter("id");
    String name = ""; // Initialize to prevent errors if user not found
    String pwd = "";  // Initialize to prevent errors if user not found
    boolean userFound = false;

    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    try (Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo?characterEncoding=UTF-8",
            "root", "1234");
         Statement s = c.createStatement();
    ) {
        String sql = "select * from denglu where id="+id;
        ResultSet rs = s.executeQuery(sql);
        if (rs.next()){ // Use if instead of while, as we expect only one user or none
            userFound = true;
            name = rs.getString(2);
            pwd = rs.getString(3);
        }
        rs.close();
        // Connection and statement will be closed automatically by try-with-resources
    } catch (SQLException e) {
        e.printStackTrace();
        // Optionally, set an error message to display to the user
    }
%>

<div class="form-container">
    <h2>更新用户信息</h2>
    <% if (userFound) { %>
    <form action="user_update_submit.jsp" method="post">
        <input type="hidden" name="id" value="<%=id%>">
        <div class="form-group">
            <label for="username">账号:</label>
            <input type="text" id="username" name="username" value="<%=name%>" />
        </div>
        <div class="form-group">
            <label for="pwd">密码:</label>
            <input type="password" id="pwd" name="pwd"  value="<%=pwd%>" />
        </div>
        <input type="submit" value="更新" />
    </form>
    <% } else { %>
        <p>未找到ID为 <%=id%> 的用户,或加载用户信息时发生错误。</p>
        <p><a href="user_select.jsp">返回用户列表</a></p>
    <% } %>
</div>

</body>
</html>

4.6 user_update_submit.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" import="java.sql.*" %>
<%
    request.setCharacterEncoding("UTF-8");

    String paramId = request.getParameter("id");
    String name = request.getParameter("username");
    String password = request.getParameter("pwd");

    String message = "";
    boolean updateSuccess = false;
    int userId = -1;

    if (paramId == null || paramId.trim().isEmpty() || 
        name == null || name.trim().isEmpty() || 
        password == null || password.trim().isEmpty()) {
        message = "错误:ID、用户名和密码均不能为空。";
    } else {
        try {
            userId = Integer.parseInt(paramId);
        } catch (NumberFormatException e) {
            message = "错误:ID 格式不正确。";
        }
    }

    Connection conn = null;
    PreparedStatement pstmt = null;

    if (message.isEmpty()) { // 只有在初始参数校验通过后才执行数据库操作
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo?characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC",
                    "root", "1234");

            String sql = "UPDATE denglu SET username = ?, password = ? WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, name);
            pstmt.setString(2, password);
            pstmt.setInt(3, userId);
          

            int rowsAffected = pstmt.executeUpdate();

            if (rowsAffected > 0) {
                updateSuccess = true;
                message = "用户信息更新成功!影响行数: " + rowsAffected;
                System.out.println(message);
                session.setAttribute("dbMessage", message); // 为重定向后页面准备消息
            } else {
                message = "用户信息更新失败,未找到对应 ID 或数据无变化。";
                System.out.println(message);
            }
        } catch (ClassNotFoundException e) {
            message = "数据库驱动加载失败: " + e.getMessage();
            e.printStackTrace();
        } catch (SQLException e) {
            message = "数据库操作失败: " + e.getMessage();
            e.printStackTrace();
        } finally {
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    if (updateSuccess) {
        // 更新成功后重定向到用户列表页面
        response.sendRedirect("user_select.jsp"); // 假设 user_select.jsp 是显示用户列表的页面
    } else {
        // 如果失败,在此页面显示错误信息
%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>用户更新结果</title>
</head>
<body>
    <h2>用户更新处理结果</h2>
    <p style="color:red;"><%= message %></p>
    <p><a href="user_select.jsp">返回用户列表</a></p> <%-- 或者链接到具体的修改页面 user_update.jsp?id=<%=userId%> --%>
</body>
</html>
<%
    }
%>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值