【JavaWeb-Servlet】编程 --- 实现在线考试管理系统(JavaSE+MySQL+JDBC+Servlet )

楔子:


一、网站需要实现的三个功能:

  • 用户信息注册
  • 用户信息查询
  • 用户信息删除

 

二、准备工作:

1.创建用户信息表(SQL):

CREATE TABLE user (
  userId int NOT NULL AUTO_INCREMENT,#用户编号
  userName varchar(50) DEFAULT NULL,#用户名称
  password varchar(50) DEFAULT NULL,#用户密码
  sex varchar(1) DEFAULT NULL,#用户性别男或女
  email varchar(50) DEFAULT NULL,#用户邮箱
  PRIMARY KEY (userId)
);

在插入时,如果不给定具体用户编号,此时根据auto_increment的值递增添加

 

2.在src下 创建 com(包).burnyouth(包).entity(专门装实体类的包).Users(实体类)

 

3.在src下 创建 com(包).burnyouth(包).util(专门装工具类的包).JdbcUtil(工具类)

 

4.在src下 创建 com(包).burnyouth(包).dao(专门装对数据库中的数据进行增删改查等操作的类).UserDao

 

5.在src下 创建 com(包).burnyouth(包).controller(专门装Servlet实现类的包)

 

6.在web下WEB-INF下创建lib文件夹 ,存放 mysql 提供的 JDBC实现 jar 包

 

三、成型网站内部结构预览:

 

正文:


1、web下的xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0">

    <!--【创建用户】的Servlet实现类-->
    <servlet>
        <servlet-name>UserAddServlet</servlet-name>
        <servlet-class>com.burnyouth.controller.UserAddServlet</servlet-class>
    </servlet>
    <!--【查询所有用户信息】的Servlet实现类-->
    <servlet>
        <servlet-name>UserFindServlet</servlet-name>
        <servlet-class>com.burnyouth.controller.UserFindServlet</servlet-class>
    </servlet>
    <!--【删除用户】的Servlet实现类-->
    <servlet>
        <servlet-name>UserDeleteServlet</servlet-name>
        <servlet-class>com.burnyouth.controller.UserDeleteServlet</servlet-class>
    </servlet>
    <!--【用户登录】的Servlet实现类-->
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.burnyouth.controller.LoginServlet</servlet-class>
    </servlet>

    <!--为这几个java动态资源文件设置简短的请求别名-->
    <servlet-mapping>
        <servlet-name>UserAddServlet</servlet-name>
        <url-pattern>/user/add</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>UserFindServlet</servlet-name>
        <url-pattern>/user/find</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>UserDeleteServlet</servlet-name>
        <url-pattern>/user/delete</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

    <!--设置此在线考试管理系统网站的欢迎资源文件-->
    <welcome-file-list>
        <welcome-file>login.html</welcome-file>
    </welcome-file-list>
</web-app>

 

2、进入在线考试管理系统前的登录验证界面(web下的html文件):

1)登录html(此网站的欢迎资源文件):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/myWeb/login" method="post">
        <table border="1px">
            <tr>
                <td>用户名</td>
                <td><input type="text" name="userName"></td>
            </tr>
            <tr>
                <td>密码</td>
                <td><input type="password" name="password"></td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <input type="submit" value="登录">
                    <input type="reset" value="清空">
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

 

2)登录信息输入错误后,跳转到的html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/myWeb/login" method="post">
    <font style="color: red;font-size: 30px">登录信息错误,请重新登录</font>
    <table border="1px">
        <tr>
            <td>用户名</td>
            <td><input type="text" name="userName"></td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="password" name="password"></td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <input type="submit" value="登录">
                <input type="reset" value="清空">
            </td>
        </tr>
    </table>
</form>
</body>
</html>

 

3、登录成功后,跳转到的在线考试管理系统导航页面(web下的html文件):

1)将浏览器窗口划分为三个窗口的html:

<html >
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<frameset rows="15%,85%">
    <frame name="top" src="/myWeb/top.html"/>
    <frameset cols="15%,85%">
        <frame name="left" src="/myWeb/left.html"/>
        <frame name="right">
    </frameset>
</frameset>
</html>

 

2)浏览器的上窗口的html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body style="background-color: cadetblue">
<center>
    <font style="color: red;font-size: 55px">在线考试管理系统</font>
</center>

</body>
</html>

 

3)浏览器的左窗口的html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <ul>
        <li>用户信息管理
            <ol><a href="/myWeb/user_Add.html" target="right">用户信息注册</a></ol>
            <ol><a href="/myWeb/user/find" target="right">用户信息查询</a></ol>
        </li>
        <li>试题信息管理</li>
        <li>考试管理</li>
    </ul>
</body>
</html>

 

4)右窗口的"实现"由 com.burnyouth.controller.UserFindServlet 完成

 

4、创建新用户的页面(web下的html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/myWeb/user/add" method="get">
    <table border="1px">
        <tr>
            <td>用户姓名</td>
            <td><input type="text" name="userName"></td>
        </tr>
        <tr>
            <td>用户密码</td>
            <td><input type="text" name="password"></td>
        </tr>
        <tr>
            <td>用户性别</td>
            <td>
                男<input type="radio" name="sex" value="男">
                女<input type="radio" name="sex" value="女">
            </td>
        </tr>
        <tr>
            <td>用户邮箱</td>
            <td><input type="text" name="email"></td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <input type="submit" value="注册">
                <input type="reset" value="清空">
            </td>
        </tr>
    </table>
</form>
</body>
</html>

 

5、实体类包:

com.burnyouth.entity.User(用户实体类):

package com.burnyouth.entity;

public class User {
    private Integer userId;
    private String userName;
    private String password;
    private String sex;
    private String email;

    public User() {
    }

    public User(Integer userId, String userName, String password, String sex, String email) {
        this.userId = userId;
        this.userName = userName;
        this.password = password;
        this.sex = sex;
        this.email = email;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getUserId() {
        return userId;
    }

    public String getUserName() {
        return userName;
    }

    public String getPassword() {
        return password;
    }

    public String getSex() {
        return sex;
    }

    public String getEmail() {
        return email;
    }
}

 

6、工具类包:

com.burnyouth.util.JdbcUtil(JDBC工具类):

package com.burnyouth.util;

import java.sql.*;

/**
 * JDBC工具类
 */

public class JdbcUtil {

    /**
     * 工具类的构造方法都应该是私有的
     * 因为工具类是需要频繁使用的,所以我们要避免代码的重复书写
     * 将工具类方法都设为静态的,再将构造方法私有化(这样想new都new不出来),直接采用类名调用
     */

    //静态代码块在类加载时执行,并且只执行一次
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private JdbcUtil(){
    }

    /**
     * 获取数据库连接对象
     * @return 连接
     * @throws SQLException
     */
    //因为此方法是被调用的方法,所以出现异常直接上抛就行
    public static Connection getConnection () throws SQLException {
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/burning_youth"
                , "root", "888");
    }

    /**
     * 关闭资源
     * @param connection 连接资源
     * @param statement 数据库操作对象
     * @param resultSet 结果集
     */
    public static void close(Connection connection,Statement statement,ResultSet resultSet){
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

 

7、对数据库进行操作的包:

com.burnyouth.dao.UserDao(连接 mysql 数据库,完成增删改查等操作的 java 文件):

package com.burnyouth.dao;

import com.burnyouth.entity.User;
import com.burnyouth.util.JdbcUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    public UserDao() {
    }
    
    //向数据库中添加用户信息
    public int add(User user) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        int result = 0;
        try {
            connection = JdbcUtil.getConnection();
            String sql = "insert into user(userName,password,sex,email)" +
                    "values(?,?,?,?)";
            ps = connection.prepareStatement(sql);
            ps.setString(1, user.getUserName());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getSex());
            ps.setString(4, user.getEmail());
            result = ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JdbcUtil.close(connection, ps, resultSet);
        }
        return result;
    }

    //得到数据库中的所有用户信息
    public List findAll() {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        List userList = new ArrayList();
        try {
            connection = JdbcUtil.getConnection();
            String sql = "select * from user";
            ps = connection.prepareStatement(sql);
            resultSet = ps.executeQuery();
            while (resultSet.next()) {
                Integer userId = resultSet.getInt("userId");
                String userName = resultSet.getString("userName");
                String password = resultSet.getString("password");
                String sex = resultSet.getString("sex");
                String email = resultSet.getString("email");
                User user = new User(userId, userName, password, sex, email);
                userList.add(user);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JdbcUtil.close(connection, ps, resultSet);
        }
        return userList;
    }

    //删除数据库中的用户信息
    public int delete(String userId) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        int result = 0;
        try {
            connection = JdbcUtil.getConnection();
            String sql = "delete from user where userId=?";
            ps = connection.prepareStatement(sql);
            ps.setInt(1,Integer.valueOf(userId));
            result = ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JdbcUtil.close(connection,ps,resultSet);
        }
        return result;
    }

    //验证登录信息是否正确
    public int login(String userName, String password) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        int result = 0;
        try {
            connection = JdbcUtil.getConnection();
            String sql = "select count(*) from user where userName=? and password=?";
            ps = connection.prepareStatement(sql);
            ps.setString(1,userName);
            ps.setString(2,password);
            resultSet = ps.executeQuery();
            while (resultSet.next()) {
                result = resultSet.getInt("count(*)");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JdbcUtil.close(connection,ps,resultSet);
        }
        return result;
    }
}

 

8、动态资源文件包:

1)com.burnyouth.controller.LoginServlet(实现了用户登录验证功能):

package com.burnyouth.controller;

import com.burnyouth.dao.UserDao;
import jakarta.servlet.*;
import jakarta.servlet.http.*;

import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName, password;
        UserDao dao = new UserDao();
        int result = 0;

        //调用请求对象对请求体使用utf-8字符集进行重写编辑
        request.setCharacterEncoding("utf-8");
        
        //获取请求体中的参数信息
        userName = request.getParameter("userName");
        password = request.getParameter("password");
        
        //调用dao.login()方法,返回1/0(代表用户输入的信息是否正确)
        result = dao.login(userName,password);
        
        //根据result的值,将不同的资源文件地址写入到响应头,交给浏览器
        if (result == 1) {
            //登录成功,进入“真正”的在线考试管理系统界面
            response.sendRedirect("/myWeb/index.html");
        } else {
            //登录失败,跳转到登录失败的html
            response.sendRedirect("/myWeb/login_error.html");
        }
    }
}

 

2)com.burnyouth.controller.UserAddServlet(实现了添加用户信息功能):

用户信息注册流程图:

代码:

package com.burnyouth.controller;

import com.burnyouth.dao.UserDao;
import com.burnyouth.entity.User;
import jakarta.servlet.*;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.io.PrintWriter;

public class UserAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userName, password, sex, email;
        UserDao dao = new UserDao();
        User user = null;
        int result = 0;
        PrintWriter out = null;

        //1、调用【请求头对象】读取【请求头】参数信息---》得到用户信息
        userName = request.getParameter("userName");
        password = request.getParameter("password");
        sex = request.getParameter("sex");
        email = request.getParameter("email");

        //2、调用【UserDao】将用户信息填充到INSERT命令里,并借助JDBC规范发送到数据库服务器
        user = new User(null,userName,password,sex,email);
        result = dao.add(user);

        //3、调用【响应对象】将【处理结果】以二进制形式写入到响应体里
        response.setContentType("text/html;charset=utf-8");
        out = response.getWriter();
        if (result == 1) {
            out.print("<font style='color:red;font-size:50px'>用户信息注册成功</font>");
        } else {
            out.print("<font style='color:red;font-size:50px'>用户信息注册失败</font>");
        }
    }
}

 

3)com.burnyouth.controller.UserFindServlet(实现了查询用户信息功能):

用户信息查询流程图:

 

代码:

package com.burnyouth.controller;

import com.burnyouth.dao.UserDao;
import com.burnyouth.entity.User;
import jakarta.servlet.*;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class UserFindServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserDao dao = new UserDao();
        PrintWriter out = null;

        //1、【调用Dao】将查询命令推送到数据库服务器上,得到所有用户信息【List】
        List<User> userList = dao.findAll();

        //2、【调用响应对象】将用户信息结合<table>标签命令以二进制形式写入到响应体
        //设置响应头content-type属性
        response.setContentType("text/html;charset=utf-8");
        
        out = response.getWriter();
        out.print("<table border='2'>");
        out.print("<tr>");
        out.print("<td>用户编号</td>");
        out.print("<td>用户姓名</td>");
        out.print("<td>用户密码</td>");
        out.print("<td>用户性别</td>");
        out.print("<td>用户邮箱</td>");
        out.print("<td>操作</td>");
        out.print("</tr>");
        
        //应用foreach循环,将用户信息(除第一行表数据外)与删除用户的动态资源文件链接写入到表中
        for (User user : userList) {
            out.print("<tr>");
            out.print("<td>" + user.getUserId() + "</td>");
            out.print("<td>" + user.getUserName() + "</td>");
            out.print("<td>******</td>");
            out.print("<td>" + user.getSex() + "</td>");
            out.print("<td>" + user.getEmail() + "</td>");
            out.print("<td><a href='/myWeb/user/delete?userId="+user.getUserId()+"'>" +
                    "删除用户</a></td>");
            out.print("</tr>");
        }
        out.print("</table>");
    }
}

 

4)com.burnyouth.controller.UserDeleteServlet(实现了删除用户信息功能):

package com.burnyouth.controller;

import com.burnyouth.dao.UserDao;
import jakarta.servlet.*;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.io.PrintWriter;

public class UserDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserDao dao = new UserDao();
        String userId;
        int result = 0;
        PrintWriter out = null;

        //获取请求头中的userId参数信息
        userId = request.getParameter("userId");

        //调用dao类删除用户信息方法
        result = dao.delete(userId);

        //设置响应头content-type属性
        response.setContentType("text/html;charset:utf-8");
        out = response.getWriter();

        //根据dao.delete()返回的结果,向响应体中写入不用的HTML命令
        if (result == 1) {
            //删除数据库中的信息成功
            out.print("<font style='color:red;font-size:50px'>用户信息删除成功</font>");
        } else {
            //删除数据库中的信息失败
            out.print("<font style='color:red;font-size:50px'>用户信息删除失败</font>");
        }

    }
}

 

posted @ 2022-03-11 14:44  猿头猿脑的王狗蛋  阅读(742)  评论(0编辑  收藏  举报
1