手把手教你做一个简单WEB系统———在线考试

 

 版权声明:本文为博主原创文章,转载请附上原链接https://blog.csdn.net/qq_39543984

WEB中经常会用的三层架构:

VO层

package vo;

public class Student {
	private String id;
	private String stuName;
	private int score;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getStuName() {
		return stuName;
	}

	public void setStuName(String stuName) {
		this.stuName = stuName;
	}

	public int getScore() {
		return score;
	}

	public void setScore(int score) {
		this.score = score;
	}

	public Student(String id, String stuName, int score) {
		super();
		this.id = id;
		this.stuName = stuName;
		this.score = score;
	}

	public Student() {
		super();
	}
}

由于没把分数放到数据库里,所​​以多建了一层结构,也可以把分数存到数据库里。建立相应的获取和设置方法及构造方法

博主所用的是MySQL的的数据库

建立tb_exam表

建立tb_stu表

DAO层

package dao;

import java.sql.*;

public class BaseDao {
	private static final String driver = "com.mysql.jdbc.Driver";
	private static final String url = "jdbc:mysql://localhost:3306/javawebdb?serverTimezone=GMT%2B8";
	private static final String user = "root";
	private static final String pwd = "123456";
	Connection conn = null;

	// 建立与数据库的连接
	public Connection getConnection() {
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, user, pwd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	public void close(Connection conn, Statement st, ResultSet rst) {
		try {
			if (rst != null) {
				rst.close();
			}
			if (st != null) {
				st.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void close(Connection conn, Statement st) {
		this.close(conn, st, null);
	}
}

 

login.jsp页面

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登陆界面</title>
</head>
<body>
	<form action="LoginServlet" method="post">
		学生证号:<input type="text" name="id" /><br />
		密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码:<input type="password"
			name="pwd" /><br /> <input type="checkbox" name="autoLogin"
			value="y" />自动登录<br /> <input type="submit" value="登录" /> <a
			href="register.jsp"><input type="button" value="注册" /></a> <a
			href="returnPwd.jsp"><input type="button" value="忘记密码" /></a>
	</form>

</body>
</html>

登录过程中可能会出现错误

error.jsp页面

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
	学生证号或密码错误,请重新登录或注册
	<br>
	<a href="register.jsp">注册</a>
	<br>
	<br>
	<a href="login.jsp">重新登录</a>
	<br>
</body>
</html>

 

 register.jsp页面

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>注册用户</title>
</head>
<body>
<body>
	<form action="RegisterServlet" method="post" onsubmit="return validate()">
		学生证号:<input type="text" name="id"> <br> <br>姓名:<input
			type="text" name="name"><br> <br> 密码:<input
			type="password" name="pwd"><br> <br> 密码确定:<input
			type="password" name="cpwd"><br> <br> 密码提问:<select
			name="question">
			<option>你的父亲叫什么名字</option>
			<option>你的母亲叫什么名字</option>
		</select>(用于找回密码) <br> <br>问题答案:<input type="text" name="answer"><br>
		<br> <input type="submit" name="submit" value="提交"> <input
			type="reset" name="reset">
	</form>
</body>
</body>

</html>

returnPwd.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>找回密码界面</title>
</head>
<body>
	<form action="ReturnPwdSvt" method="post">
		输入学生证号:<input type="text" name="id"> <br> <br> 选择提问:<select
			name="question">
			<option>你的父亲叫什么名字</option>
			<option>你的母亲叫什么名字</option>
		</select> <br> <br>输入答案:<input type="text" name="answer"><br>
		<br> <input type="submit" name="submit" value="提交"> <input
			type="reset" name="reset">
	</form>
</body>
</html>

 

success.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>找回密码成功界面</title>
</head>
<body>
	恭喜你,查找密码成功
	<br>
	<%="学生证号:" + session.getAttribute("id")%><br />
	<%="你的密码为:" + session.getAttribute("pwd")%><br />
	<a href="login.jsp">返回登录</a>
</body>
</html>

 

exam.jsp

      

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>考试界面</title>
</head>
<body onload="examTime()">
	<div>
		<span>满分100分</span>&nbsp;&nbsp;&nbsp;&nbsp;<span>单选题40分</span>&nbsp;&nbsp;&nbsp;&nbsp;<span>多选题60分</span><br />
		<span>考试时间:&nbsp;&nbsp;2分钟</span>&nbsp;&nbsp;&nbsp;&nbsp;<span>计时:</span><span
			id="time" style="color: red"></span>
		<form action="ExamServlet" method="post" name="exam">
			<p>一. 单选题(总分40分,答错不得分)</p>
			1.zzzzz<br /> <input type="radio" name="one" value="A" />A z <br />
			<input type="radio" name="one" value="B" />B x <br /> <input
				type="radio" name="one" value="C" />C c <br /> <input type="radio"
				name="one" value="D" />D v <br /> 2.网络营销的发展历经几个阶段?<br /> <input
				type="radio" name="two" value="A" />A 2个 <br /> <input
				type="radio" name="two" value="B" />B 3个 <br /> <input
				type="radio" name="two" value="C" />C 5个 <br /> <input
				type="radio" name="two" value="D" />D 6个 <br />
			<p>二. 多选题(总分60分,答错不得分)</p>
			1.Internet提供的基本服务有那些?<br /> <input type="checkbox" name="three"
				value="A" />A E-mail <br /> <input type="checkbox" name="three"
				value="B" />B FTP <br /> <input type="checkbox" name="three"
				value="C" />C Telnet <br /> <input type="checkbox" name="three"
				value="D" />D WWW <br />
			<p>
				<input type="submit" value="交卷" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a
					id="a" href="login.jsp">退出当前系统</a>
			</p>
		</form>
	</div>
</body>
<script>
	var time = 2 * 60;
	function examTime() {
		//得到class为time的span标签
		var spanTime = document.getElementById("time");
		--time;
		//获取小时
		var hour = parseInt(time / 3600);
		//获取分钟
		var min = parseInt(time % 3600 / 60);
		//获取秒
		var second = time - hour * 3600 - min * 60;
		//将这个标签设置为time
		spanTime.innerHTML = min + "分钟" + second + "秒";
		//判断时间到了就提交
		if (time == 0) {
			alert("考试结束")
			document.exam.submit();
		}
		setTimeout("examTime()", 1000);
	};
</script>
</html>

 

show.jsp

<%@page import="vo.Student"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>显示分数界面</title>
</head>
<body>
	<%
		Student student = (Student) session.getAttribute("student");
	%>
	学生编号:<%=student.getId()%><br /> 姓名:<%=student.getStuName()%><br />
	总分:<%=student.getScore()%>

</body>
</html>

建立相应的业务逻辑

LoginServlet

package servlet;

import java.io.IOException;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.BaseDao;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public LoginServlet() {
		super();
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 设置编码格式
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");

		// 获取session
		HttpSession session = req.getSession();
		// 得到学生注册证号
		String id = req.getParameter("id");
		// 得到学生注册密码
		String pwd = req.getParameter("pwd");
		// 判断是否勾选自动登录
		String flag = req.getParameter("autologin");
		if ("y".equals(flag)) {
			// 创建两个Cookie对象
			Cookie nameCookie = new Cookie("username", id);
			// 设置Cookie的有效期为3天
			nameCookie.setMaxAge(60 * 60 * 24 * 3);
			Cookie pwdCookie = new Cookie("password", pwd);
			pwdCookie.setMaxAge(60 * 60 * 24 * 3);
			// 保存到Cookie
			resp.addCookie(nameCookie);
			resp.addCookie(pwdCookie);
			req.getRequestDispatcher("exam.jsp").forward(req, resp);
		}
		// 先查询数据库,看是否存在
		BaseDao dao = new BaseDao();
		Connection conn = dao.getConnection();
		String sql = " select*from tb_stu where stuId=? and pwd=? ";
		try {
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, id);
			pst.setString(2, pwd);
			ResultSet rst = pst.executeQuery();
			if (rst.next()) {
				// 请求转发至考试页面
				String stuName = rst.getString("stuName");
				session.setAttribute("id", id);
				session.setAttribute("stuName", stuName);
				req.getRequestDispatcher("exam.jsp").forward(req, resp);
			} else {
				// 如果没有,那么重定向到错误界面,需要注册
				resp.sendRedirect("error.jsp");
			}
			dao.close(conn, pst, rst);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

RegisterServlet

package servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

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 javax.servlet.http.HttpSession;

import dao.BaseDao;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public RegisterServlet() {
		super();

	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 设置编码格式
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		// 获取session
		HttpSession session = req.getSession();

		// 得到学生注册的基本信息
		// 得到学生注册证号
		String id = req.getParameter("id");
		// 得到学生注册姓名
		String stuName = req.getParameter("name");
		// 得到学生注册密码
		String pwd = req.getParameter("pwd");
		// 得到学生注册确认密码
		String cpwd = req.getParameter("cpwd");
		// 得到学生注册密码提问的问题
		String question = req.getParameter("question");
		// 得到学生注册的问题答案
		String result = req.getParameter("answer");

		// 向数据库内插入该用户
		try {
			BaseDao dao = new BaseDao();
			Connection conn = dao.getConnection();
			String sql = " insert into tb_stu values(default,?,?,?,?,?,?) ";
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, id);
			pst.setString(2, stuName);
			pst.setString(3, pwd);
			pst.setString(4, cpwd);
			pst.setString(5, question);
			pst.setString(6, result);
			// 执行更新操作
			int row = pst.executeUpdate();
			if (row > 0) { 
				// 表示以及在数据库中插入了该用户
				session.setAttribute("id", id);
				session.setAttribute("pwd", pwd);
				// 注册成功重定向到login.jsp中
				resp.sendRedirect("login.jsp");
			} else {
				// 注册失败重定向到error.jsp中
				resp.sendRedirect("error.jsp");
			}
			dao.close(conn, pst, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

ReturnPwdSvt

package servlet;

import java.io.IOException;
import java.sql.*;

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 javax.servlet.http.HttpSession;

import dao.BaseDao;

@WebServlet("/ReturnPwdSvt")
public class ReturnPwdSvt extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public ReturnPwdSvt() {
		super();

	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 设置编码格式
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		// 获取session
		HttpSession session = req.getSession();

		// 得到输入的学生证号
		String id = req.getParameter("id");
		// 得到选择提问的信息
		String question = req.getParameter("question");
		// 得到问题答案
		String answer = req.getParameter("answer");
		// 与数据库信息进行匹对
		try {
			BaseDao dao = new BaseDao();
			Connection conn = dao.getConnection();
			String sql = " select * from tb_stu where stuId=? and question=? and result=? ";
			PreparedStatement pst = conn.prepareStatement(sql);
			pst.setString(1, id);
			pst.setString(2, question);
			pst.setString(3, answer);
			ResultSet rst = pst.executeQuery();
			if (rst.next()) {
				// 找回密码成功
				session.setAttribute("id", id);
				session.setAttribute("pwd", rst.getString("pwd"));
				resp.sendRedirect("success.jsp");
			} else {
				// 找回密码失败重新找回密码
				resp.sendRedirect("returnPwd.jsp");
			}
			dao.close(conn, pst, rst);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

ExamServlet

package servlet;

import java.io.IOException;
import java.sql.*;

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 javax.servlet.http.HttpSession;

import dao.BaseDao;
import vo.Student;

@WebServlet("/ExamServlet")
public class ExamServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public ExamServlet() {
		super();
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	int score = 0;

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 设置编码格式
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		// 获取session
		HttpSession session = req.getSession();
		// 获取学生信息
		String id = (String) session.getAttribute("id");
		String stuName = (String) session.getAttribute("stuName");
		System.out.println(id + ":" + stuName);// 测试是否取得学生信息
		// 查询该学生考试题目的勾选情况
		String one = req.getParameter("one");
		String two = req.getParameter("two");
		String[] three = req.getParameterValues("three");
		if (!one.equals("") && !two.equals("") && three.length > 0) {
			// 判断题目的勾选情况
			String threeT = "";
			for (String th : three) {
				threeT = threeT + th;
				System.out.println(threeT);
			}
			// 与数据库中正确答案进行比对
			Student student = new Student();
			try {
				BaseDao dao = new BaseDao();
				Connection conn = dao.getConnection();
				String sql1 = " select *from tb_exam where answer='one' and result=? ";
				String sql2 = " select *from tb_exam where answer='two' and result=? ";
				String sql3 = " select *from tb_exam where answer='three' and result=? ";
				// 判断第一题
				PreparedStatement pst = conn.prepareStatement(sql1);
				pst.setString(1, one);
				ResultSet rst = pst.executeQuery();
				if (rst.next()) {
					// 第一题答对了
					score = 20;
					student.setId(id);
					student.setStuName(stuName);
					student.setScore(score);
				} else {
					// 第一题答错了
					student.setId(id);
					student.setStuName(stuName);
					student.setScore(score);
				}

				// 判断第二题
				pst = conn.prepareStatement(sql2);
				pst.setString(1, two);
				rst = pst.executeQuery();
				if (rst.next()) {
					// 第二题答对了
					score = 20;
					student.setScore(student.getScore() + score);
				} else {
					// 第二题答错了
					student.setScore(student.getScore());
				}

				// 判断第三题
				pst = conn.prepareStatement(sql3);
				pst.setString(1, threeT);
				rst = pst.executeQuery();
				if (rst.next()) {
					// 第三题答对了
					score = 60;
					student.setScore(student.getScore() + score);
				} else {
					// 第三题答错了
					student.setScore(student.getScore());
				}
				session.setAttribute("student", student);
				// 将这个对象保存到session中,然后到显示分数的页面
				resp.sendRedirect("show.jsp");
				dao.close(conn, pst, rst);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			resp.sendRedirect("show.jsp");
		}
	}
}


总结:我们始终要记住JSP的优点在于显示页面,Servlet的优点在于处理业务逻辑,servlet的的创建是根据页面是否需要处理业务逻辑来创建相应的servlet.

 

本博客由于时间匆忙未处理自动登录功能和考试时间的相关的错误,后来者可以处理相关的错误。本博客所用技术非常简陋,仅供初学者学习交流所用,望各位大佬勿喷!本博客已讲解非常到位,非常简单,如果有无法实现和不懂之处。请自行度。ervlet的优点在于处理业务逻辑,servlet的的创建是根据页面是否需要处理业务逻辑来创建相应的servlet.

本博客由于时间匆忙未处理自动登录功能和考试时间的相关的错误,后来者可以处理相关的错误。本博客所用技术非常简陋,仅供初学者学习交流所用,望各位大佬勿喷!本博客已讲解非常到位,非常简单,如果有无法实现和不懂之处。请自行百度。

©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页