基于javaweb+mysql的jsp+servlet在线考试管理系统(java+jsp+jquery+servlet+mysql)

基于javaweb+mysql的jsp+servlet在线考试管理系统(java+jsp+jquery+servlet+mysql)

运行环境

Java≥8、MySQL≥5.7、Tomcat≥8

开发工具

eclipse/idea/myeclipse/sts等均可配置运行

适用

课程设计,大作业,毕业设计,项目练习,学习演示等

功能说明

基于javaweb+mysql的JSP+Servlet在线考试管理系统(java+jsp+jquery+servlet+mysql)

项目介绍

本项目包含管理员与学生两个角色; 管理员角色包含以下功能: 登录页面,管理员首页,考生信息管理,成绩管理,考生录入,题库管理,题目录入,试卷管理等功能。

学生角色包含以下功能: 学生登录,学生主页,开始考试,查看成绩等功能。

PS:在添加学生或者添加试题的时候,可以上传文件来实现,文件的模板在管理试题和管理学生的时候,点击下载就有了。

环境需要

1.运行环境:最好是java jdk 1.8,我们在这个平台上运行的。其他版本理论上也可以。 2.IDE环境:IDEA,Eclipse,Myeclipse都可以。推荐IDEA; 3.tomcat环境:Tomcat 7.x,8.x,9.x版本均可 4.硬件环境:windows 7/8/10 1G内存以上;或者 Mac OS; 5.数据库:MySql 5.7版本; 6.是否Maven项目:否;

技术栈

  1. 后端:Servlet 2. 前端:JSP+jQuery

使用说明

  1. 使用Navicat或者其它工具,在mysql中创建对应名称的数据库,并导入项目的sql文件; 2. 使用IDEA/Eclipse/MyEclipse导入项目,Eclipse/MyEclipse导入时,若为maven项目请选择maven;若为maven项目,导入成功后请执行maven clean;maven install命令,然后运行; 3. 将项目中配置文件中的数据库配置改为自己的配置; 4. 运行项目,输入localhost:8080/ 登录
			break;
		case 1:
			grade = "良好";
			break;
		case 2:
			grade = "中等";
			break;
		case 3:
			grade = "及格";
			break;
		case 4:
			grade = "不及格";
			break;
		case 5:
			grade = "缺考";
			break;
		default:
			break;
		}
		
		try {
			//实例化数据库连接对象,把上面计算到的分值分别存入数据库中
			DatabassAccessObject db = new DatabassAccessObject();
			LoginBean loginBean = (LoginBean) session.getAttribute("loginBean");
			String ID = loginBean.getID();
			db.insert("update student set score = ? where ID = ? ", score, ID);
			
			ResultSet rs = db.query("select * from score where id = ?", ID);
			if (!rs.next()) {
				db.insert("insert into score values(?,?,?,?,?,?,?,?)", ID, score, score_sing, score_muti, score_jud,
						score_fill, score_ess,grade);
			} else {
				db.modify(
						"update score set score = ? , score_sing = ? , score_muti= ? , score_jud = ? , score_fill = ? , score_ess = ?,grade = ? where ID = ?  ;",
						score, score_sing, score_muti, score_jud, score_fill, score_ess,grade, ID);
			}
			rs = db.query("select * from student where id = ?", ID);
			rs.first();
			
		} catch (Exception e) {
				queBeanAllList.add(queBean);
				total++;
			}
			ArrayList<QuestionBean> queTableList = new ArrayList<QuestionBean>();
			for (int i = cpage * per; i < cpage * per + per && i < total; i++) {
				queTableList.add(queBeanAllList.get(i));
			}
			String temp=request.getParameter("modify_id");
			request.setAttribute("modify_id", temp);
			request.setAttribute("total", total);
			request.setAttribute("queTableList", queTableList);
			request.getRequestDispatcher("/teacher/teacher_que_manage.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
package examservlet.control;

@WebServlet("/ShowScorePage")
public class ScoreShowByPage extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException {
		// 如果没有参数传递过来,初定每页显示10条记录,显示第一页。
		// 然后把这两个参数压到request容器传到前台页面。request容器是前台页面收到即销毁的容器。
		int cpage = 0;
			LinkedList<Integer> list5 = new LinkedList<Integer>();
			while (rs.next()) {	//遍历整个题库表
				switch (rs.getString(2)) {	//多分支语句区分题型
				case "单选题":
					list1.add(rs.getRow());//获取所有选择题的行号
					break;
				case "多选题":
					list2.add(rs.getRow());
					break;
				case "判断题":
					list3.add(rs.getRow());
					break;
				case "填空题":
					list4.add(rs.getRow());
					break;
				case "简答题":
					list5.add(rs.getRow());
					break;
				default:
					break;
				}
			}

					
			listALL.addAll(randomQue(list1, rs,num1));	
			listALL.addAll(randomQue(list2, rs,num2));	
			listALL.addAll(randomQue(list3, rs,num3));	
			listALL.addAll(randomQue(list4, rs,num4));	
			listALL.addAll(randomQue(list5, rs,num5));	

			tihao=0;	//题号从0开始
			HttpSession session = request.getSession();
			session.setAttribute("examTime", examTime);
			session.setAttribute("ques", listALL);	//把试卷数组保存到Session对象
			//重定向到试卷页面,供考生作答
			response.sendRedirect(request.getContextPath()+"/student/student_exam_paper.jsp");

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	/**
	 * 负责每种题型、指定数量的随机抽题
	 * @param list	题目链表(存储了一类题型的行号)
	 * @param rs	数据表结果集
	 * @param count 抽取指定的题目数量
	 * @return		返回一个(存储了count条指定类型的题目)数组
	 */
	public ArrayList<QuestionBean> randomQue(LinkedList<Integer> list,ResultSet rs,int count) {
		int m = -1;
		int index = -1;

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

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		
		Integer mode = Integer.valueOf(request.getParameter("mode"));
		HSSFWorkbook workbook=null;
		String createExcelname = "";
		switch (mode) {
		case 1:
			workbook=(HSSFWorkbook) StuInfoExcelService.getAllByDatabase();
			createExcelname = "tb_student.xls";
			break;
		case 2:
			workbook=(HSSFWorkbook) QuestionExcelService.getAllByDatabase();
			createExcelname = "tb_question.xls";
			break;
		case 3:
			workbook=(HSSFWorkbook) ScoreExcleService.getAllByDatabase();
			createExcelname = "tb_student_score.xls";
			break;
		default:
			break;
		}
		
		
		String dir = request.getSession().getServletContext().getRealPath("/images");
		File fileLocation = new File(dir);
		if (!fileLocation.exists()) {
			boolean isCreated = fileLocation.mkdir();
		}
		String webUrl = request.getSession().getServletContext().getRealPath("/images");
		String outputFile = webUrl + File.separator + createExcelname;
		FileOutputStream fop = new FileOutputStream(outputFile);
		workbook.write(fop);
		fop.flush();
		fop.close();
		File f = new File(outputFile);
		if (f.exists() && f.isFile()) {
			try {
				FileInputStream fis = new FileInputStream(f);
				URLEncoder.encode(f.getName(), "utf-8");
		if (request.getParameter("cpage") != null) {
			cpage = Integer.parseInt(request.getParameter("cpage"));
		}
		request.setAttribute("cpage", cpage);
		if (request.getParameter("per") != null) {
			per = Integer.parseInt(request.getParameter("per"));
		}
		request.setAttribute("per", per);
		
		try {
			// 数据库的查询结果有多少条记录
			DatabassAccessObject db=new DatabassAccessObject();
			ResultSet rsTotal = db
					.query("select count(*) as total from student");
			if (rsTotal.next()) {
				// 求出总页数压到request容器传递给前台页面。
				request.setAttribute("totalPage", 1
						+ (rsTotal.getInt("total") - 1) / per);
			}
			// 新建一个动态数组用来存放查询结果
			ArrayList<StudentInfoBean> stuBeanAllList = new ArrayList<StudentInfoBean>();
			ResultSet rs=null;
			String s_ID=request.getParameter("s_ID");
			if (s_ID!=null) {
				rs=db.query("select score.ID,class,name,score_sing,score_muti,score_jud,score_fill,score_ess,score.score,grade from student join score on student.id=score.id where score.id LIKE '%"+s_ID+"%' ;");
			}else {
				rs = db.query("select score.ID,class,name,score_sing,score_muti,score_jud,score_fill,score_ess,score.score,grade from student join score on student.id=score.id order by ID ;");
			}
			

			int total = 0;
			while (rs.next()) {
				String ID=rs.getString(1);
				String CLASS=rs.getString(2);
				String name=rs.getString(3);
				Float score_sing=Float.valueOf(rs.getString(4));
				Float score_muti=Float.valueOf(rs.getString(5));
				Float score_jud=Float.valueOf(rs.getString(6));
				Float score_fill=Float.valueOf(rs.getString(7));
				Float score_ess=Float.valueOf(rs.getString(8));
				Float score=Float.valueOf(rs.getString(9));
				String grade=rs.getString(10);
				stuBeanAllList.add(new StudentInfoBean(ID, CLASS, name, score_sing, score_muti, score_jud, score_fill, score_ess, score,grade));
				total++;
			}
			// 再通过根据cpage与per求出要推回给前台显示的数组
			ArrayList<StudentInfoBean> stuTableList = new ArrayList<StudentInfoBean>();
			for (int i = cpage * per; i < cpage * per + per && i < total; i++) {
				stuTableList.add(stuBeanAllList.get(i));
			}
			String temp=request.getParameter("modify_id");
				// 上传按钮也是part对象,在这里用if条件语句过滤它
				// 只接受part名称标头为"img"的正文图片数据
				String fileName1 = imgPath.getSubmittedFileName(); // 获取单张图片的文件名
				if (fileName1 == null || fileName1.length() == 0)
					break;
				try {
					imgPath.write(savePath + "/" + fileName1); // 写入图片到tomcat的发布目录下
					
				} catch (Exception e) {
					System.out.println(e);
				}

				/**
				 * 接下来要把图片从【tomcat发布目录】拷贝到【当前项目目录】 原因:发布目录在tomcat重启会重新发布,上传的图片需要迁移到永久保留的位置
				 * 目的:把图片拷贝到项目目录,上传的图片得以保留,可以任意次数发布
				 */
				try {// try能保证流被正确关闭
					Path sorcePath = Paths.get(savePath + "/" + fileName1); // 图片的原始路径(tomcat的发布目录下)
					// 图片的的目标路径(当前项目目录)
					Path targetPath = Paths.get("E:\\WorkSpace_All\\cli_workspace\\" + request.getContextPath()
							+ "/WebRoot/images/" + fileName1);
					Files.copy(sorcePath, targetPath, StandardCopyOption.REPLACE_EXISTING); // 复制文件,并替换已存在的文件
				} catch (Exception e) {
				}

			}
		}

		try {
			DatabassAccessObject db;
			switch (mode) {
			case 1:
				List<QuestionBean> listExcel = QuestionExcelService.getAllByExcel(excelSorcePath);
				db = new DatabassAccessObject();
				for (QuestionBean queBean : listExcel) {
					if (!QuestionExcelService.isExist(queBean.getQ_id())) {
						db.insert("insert into question values (?,?,?,?,?,?,?) ; ", queBean.getQ_id(),
								queBean.getQ_type(), queBean.getQ_title(), queBean.getQ_select(), queBean.getQ_score(),
								queBean.getQ_key(), queBean.getQ_img());
					} else {
						db.modify(
								"update question set type = ? , title  = ? , `select` = ? , score = ? , `key` = ? , img = ? where number = ? ;",
								queBean.getQ_type(), queBean.getQ_title(), queBean.getQ_select(), queBean.getQ_score(),
								queBean.getQ_key(), queBean.getQ_img(), queBean.getQ_id());
					}
				}
			}
		}
		return listA;
	}
}
package examservlet.control;

/**
 * 该类实现修改学生信息表功能
 */
@WebServlet("/HandleStuInfo")
public class StudentModifyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		try {
			Class.forName("com.mysql.jdbc.Driver"); // 数据库驱动
		} catch (Exception e) {
		}
	}

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

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8"); // 编码处理
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		String executeMode = request.getParameter("executeMode");
		int mode = Integer.parseInt(executeMode); // 转化整形
		System.out.println(mode);

		int cpage = 0;
		int per = 10;
		
		try {
			// 数据库的查询结果有多少条记录
			DatabassAccessObject db=new DatabassAccessObject();
			ResultSet rsTotal = db
					.query("select count(*) as total from student");
			if (rsTotal.next()) {
				// 求出总页数压到request容器传递给前台页面。
				request.setAttribute("totalPage", 1
						+ (rsTotal.getInt("total") - 1) / per);
			}
			// 新建一个动态数组用来存放查询结果
			ArrayList<StudentInfoBean> stuBeanAllList = new ArrayList<StudentInfoBean>();
			ResultSet rs=null;
			String s_ID=request.getParameter("s_ID");
			if (s_ID!=null) {
				rs=db.query("select score.ID,class,name,score_sing,score_muti,score_jud,score_fill,score_ess,score.score,grade from student join score on student.id=score.id where score.id LIKE '%"+s_ID+"%' ;");
			}else {
				rs = db.query("select score.ID,class,name,score_sing,score_muti,score_jud,score_fill,score_ess,score.score,grade from student join score on student.id=score.id order by ID ;");
			}
			

			int total = 0;
			while (rs.next()) {
				String ID=rs.getString(1);
				String CLASS=rs.getString(2);
				String name=rs.getString(3);
				Float score_sing=Float.valueOf(rs.getString(4));
				Float score_muti=Float.valueOf(rs.getString(5));
				Float score_jud=Float.valueOf(rs.getString(6));
				Float score_fill=Float.valueOf(rs.getString(7));
				Float score_ess=Float.valueOf(rs.getString(8));
				Float score=Float.valueOf(rs.getString(9));
				String grade=rs.getString(10);
				stuBeanAllList.add(new StudentInfoBean(ID, CLASS, name, score_sing, score_muti, score_jud, score_fill, score_ess, score,grade));
				total++;
			}
			// 再通过根据cpage与per求出要推回给前台显示的数组
			ArrayList<StudentInfoBean> stuTableList = new ArrayList<StudentInfoBean>();
			for (int i = cpage * per; i < cpage * per + per && i < total; i++) {
				stuTableList.add(stuBeanAllList.get(i));
			}
			String temp=request.getParameter("modify_id");
		String ID = request.getParameter("ID").trim();
		String password = request.getParameter("password").trim();
		String userRole = request.getParameter("role").trim();

		boolean boo = (ID.length() > 0) && (password.length() > 0);
		try {
			DatabassAccessObject db = new DatabassAccessObject();
			con = db.con;
			String condition = "select * from " + userRole + " where ID = '" + ID + "' and password ='" + password
					+ "'";
			sql = con.createStatement();
			if (boo) {
				ResultSet rs = sql.executeQuery(condition);
				boolean isExist = rs.next();
				if (isExist == true) {
					success(request, response, rs, userRole);
					response.sendRedirect(userRole + "/" + userRole + ".jsp");
				} else {
					String backNews = "您输入的学号不存在/密码不匹配";
					fail(request, response, ID, backNews);
				}
			} else {
				String backNews = "请输入用户名和密码";
				fail(request, response, ID, backNews);
			}
			con.close();
		} catch (Exception exp) {
			String backNews = "" + exp;
			fail(request, response, ID, backNews);
		}

	}

	/**
	 * 如果账号密码匹配成功,就把登录信息存储到Bean,
	 * 然后重定向进入与角色相相应的管理页面
	 * @param request	请求对象
	 * @param response	响应对象
	 * @param rs	查询结果数据集
	 * @param role	用户角色
	 */
	private void success(HttpServletRequest request, HttpServletResponse response, ResultSet rs, String role) {
		HttpSession session = request.getSession(true);
		LoginBean loginBean = new LoginBean();
		try {
			rs.first();

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		
		Integer mode = Integer.valueOf(request.getParameter("mode"));
		HSSFWorkbook workbook=null;
		String createExcelname = "";
		switch (mode) {
		case 1:
			workbook=(HSSFWorkbook) StuInfoExcelService.getAllByDatabase();
			createExcelname = "tb_student.xls";
			break;
		case 2:
			workbook=(HSSFWorkbook) QuestionExcelService.getAllByDatabase();
			createExcelname = "tb_question.xls";
			break;
		case 3:
			workbook=(HSSFWorkbook) ScoreExcleService.getAllByDatabase();
			createExcelname = "tb_student_score.xls";
			break;
		default:
			break;
		}
		
		
		String dir = request.getSession().getServletContext().getRealPath("/images");
		File fileLocation = new File(dir);
		if (!fileLocation.exists()) {
			boolean isCreated = fileLocation.mkdir();
		}
		String webUrl = request.getSession().getServletContext().getRealPath("/images");
		String outputFile = webUrl + File.separator + createExcelname;
		FileOutputStream fop = new FileOutputStream(outputFile);
		workbook.write(fop);
		fop.flush();
		fop.close();
		File f = new File(outputFile);
		if (f.exists() && f.isFile()) {
			try {
				FileInputStream fis = new FileInputStream(f);
				URLEncoder.encode(f.getName(), "utf-8");
				byte[] b = new byte[fis.available()];
				fis.read(b);
				response.setCharacterEncoding("utf-8");
				response.setHeader("Content-Disposition", "attachment; filename=" + createExcelname + "");
				ServletOutputStream out = response.getOutputStream();
				out.write(b);
				out.flush();
				out.close();
			switch (mode) {
			case 1:
				List<QuestionBean> listExcel = QuestionExcelService.getAllByExcel(excelSorcePath);
				db = new DatabassAccessObject();
				for (QuestionBean queBean : listExcel) {
					if (!QuestionExcelService.isExist(queBean.getQ_id())) {
						db.insert("insert into question values (?,?,?,?,?,?,?) ; ", queBean.getQ_id(),
								queBean.getQ_type(), queBean.getQ_title(), queBean.getQ_select(), queBean.getQ_score(),
								queBean.getQ_key(), queBean.getQ_img());
					} else {
						db.modify(
								"update question set type = ? , title  = ? , `select` = ? , score = ? , `key` = ? , img = ? where number = ? ;",
								queBean.getQ_type(), queBean.getQ_title(), queBean.getQ_select(), queBean.getQ_score(),
								queBean.getQ_key(), queBean.getQ_img(), queBean.getQ_id());
					}
				}

				System.out.println("数据导入成功");
				PrintWriter out = response.getWriter();
				out.println("<script language=javascript>alert('数据导入成功');window.location='" + request.getContextPath()
						+ "/ShowQuePage';script>");
				break;
			case 2:
				List<StudentInfoBean> stuListExcel = StuInfoExcelService.getAllByExcel(excelSorcePath);

				db = new DatabassAccessObject();
				for (StudentInfoBean stuBean : stuListExcel) {
					if (!StuInfoExcelService.isExist(stuBean.getID())) {
						db.insert("INSERT INTO student (ID,password,name,class,score) VALUES (?,?,?,?,?) ; ",
								stuBean.getID(), stuBean.getPassword(), stuBean.getName(), stuBean.getCLASS(),
								stuBean.getScore());
					} else {
						db.modify("UPDATE student SET  password = ? , name = ? , class = ? , score = ? WHERE ID = ? ;",
								stuBean.getPassword(), stuBean.getName(), stuBean.getCLASS(), stuBean.getScore(),
								stuBean.getID());
					}
				}

				System.out.println("数据导入成功");
				PrintWriter out2 = response.getWriter();
				out2.println("<script language=javascript>alert('数据导入成功');window.location='" + request.getContextPath()
						+ "/ShowStuPage';script>");
			default:
				break;
			}

		} catch (Exception e1) {
			// TODO Auto-generated catch block
						case "多选题":
							score_muti += Float.parseFloat(que.getQ_score());
							break;
						case "判断题":
							score_jud += Float.parseFloat(que.getQ_score());
							break;
						case "填空题":
							score_fill += Float.parseFloat(que.getQ_score());
							break;
						default:
							break;
						}
					}
				}
			} else { //简答题的判断方法
				String[] KEY_WORD = que.getQ_key().split("\\@");	//拆分正确答案中的关键词
				Float totalScore = Float.parseFloat(que.getQ_score());	//获取简答题分值
				Float singleScore = 0.0f;	//每个的分点的细分
				String stuAns = "";
				if (stuAnsArr != null) {
					for (int j = 0; j < stuAnsArr.length; j++) {
						stuAns += stuAnsArr[j];	//组装学生答案
					}
				}
				// 使用contains方法
				if (KEY_WORD != null) {	//如果关键词存在
					singleScore = totalScore / KEY_WORD.length; //按照关键词数量细分分值
					for (int j = 0; j < KEY_WORD.length; j++) {
						if (stuAns.contains(KEY_WORD[j])) { //判断考生答案中是否出现关键词
							System.out.println(stuAns + "包含关键词:" + KEY_WORD[j]);
							score_ess += singleScore;
						} else {
							System.out.println("不包含关键词:" + KEY_WORD[j]);
						}
					}
				}

			}
		}
		
		score = score_sing + score_muti + score_jud + score_fill + score_ess;
	int tihao = 0;
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		ArrayList<QuestionBean> listALL = new ArrayList<QuestionBean>();
		
		//抽题数量
		//单选题抽5道,多选题抽4道,判断题抽5道,填空题抽5道,简答题抽3道
		int num1=5,num2=4,num3=5,num4=5,num5=3;
		int examTime=30;
		try {
			DatabassAccessObject db = new DatabassAccessObject();
			ResultSet rs=db.query("select * from paper");
			num1=Integer.valueOf(rs.getString("qty_sing"));
			num2=Integer.valueOf(rs.getString("qty_muti"));
			num3=Integer.valueOf(rs.getString("qty_jud"));
			num4=Integer.valueOf(rs.getString("qty_fill"));
			num5=Integer.valueOf(rs.getString("qty_ess"));
			examTime=Integer.valueOf(rs.getString("time"));
		} catch (Exception e) {
			
		}
		
		try {
			DatabassAccessObject db = new DatabassAccessObject();
			ResultSet rs = db.query("SELECT * FROM question");
			//区分每种题型,将所有相同题型的行号存入双向循环链表,用于随机取题目
			LinkedList<Integer> list1 = new LinkedList<Integer>();
			LinkedList<Integer> list2 = new LinkedList<Integer>();
			LinkedList<Integer> list3 = new LinkedList<Integer>();
			LinkedList<Integer> list4 = new LinkedList<Integer>();
			LinkedList<Integer> list5 = new LinkedList<Integer>();
			while (rs.next()) {	//遍历整个题库表
				switch (rs.getString(2)) {	//多分支语句区分题型
				case "单选题":
					list1.add(rs.getRow());//获取所有选择题的行号
					break;
				case "多选题":
					list2.add(rs.getRow());
					break;
				case "判断题":
					list3.add(rs.getRow());
					break;
				case "填空题":
					list4.add(rs.getRow());
					break;
				case "简答题":
					list5.add(rs.getRow());
					break;
					if (stuAns.equalsIgnoreCase(que.getQ_key())) {	//匹配学生答案和正确答案
						switch (que.getQ_type()) { //每道题分别记分
						case "单选题":
							score_sing += Float.parseFloat(que.getQ_score());
							break;
						case "多选题":
							score_muti += Float.parseFloat(que.getQ_score());
							break;
						case "判断题":
							score_jud += Float.parseFloat(que.getQ_score());
							break;
						case "填空题":
							score_fill += Float.parseFloat(que.getQ_score());
							break;
						default:
							break;
						}
					}
				}
			} else { //简答题的判断方法
				String[] KEY_WORD = que.getQ_key().split("\\@");	//拆分正确答案中的关键词
				Float totalScore = Float.parseFloat(que.getQ_score());	//获取简答题分值
				Float singleScore = 0.0f;	//每个的分点的细分
				String stuAns = "";
				if (stuAnsArr != null) {
					for (int j = 0; j < stuAnsArr.length; j++) {
						stuAns += stuAnsArr[j];	//组装学生答案
					}
				}
				// 使用contains方法
				if (KEY_WORD != null) {	//如果关键词存在
					singleScore = totalScore / KEY_WORD.length; //按照关键词数量细分分值
					for (int j = 0; j < KEY_WORD.length; j++) {
						if (stuAns.contains(KEY_WORD[j])) { //判断考生答案中是否出现关键词
							System.out.println(stuAns + "包含关键词:" + KEY_WORD[j]);
							score_ess += singleScore;
						} else {
							System.out.println("不包含关键词:" + KEY_WORD[j]);
						}
					}
				}

			}
		}
		
		score = score_sing + score_muti + score_jud + score_fill + score_ess;
		String grade = "";
		int f = Math.round(score);
		int g = ((f < 0) == true ? 1 : 0) + ((f < 60) == true ? 1 : 0) + ((f < 75) == true ? 1 : 0)
				+ ((f < 85) == true ? 1 : 0) + ((f < 95) == true ? 1 : 0);
		switch (g) {
		case 0:
			grade = "优秀";
				Float totalScore = Float.parseFloat(que.getQ_score());	//获取简答题分值
				Float singleScore = 0.0f;	//每个的分点的细分
				String stuAns = "";
				if (stuAnsArr != null) {
					for (int j = 0; j < stuAnsArr.length; j++) {
						stuAns += stuAnsArr[j];	//组装学生答案
					}
				}
				// 使用contains方法
				if (KEY_WORD != null) {	//如果关键词存在
					singleScore = totalScore / KEY_WORD.length; //按照关键词数量细分分值
					for (int j = 0; j < KEY_WORD.length; j++) {
						if (stuAns.contains(KEY_WORD[j])) { //判断考生答案中是否出现关键词
							System.out.println(stuAns + "包含关键词:" + KEY_WORD[j]);
							score_ess += singleScore;
						} else {
							System.out.println("不包含关键词:" + KEY_WORD[j]);
						}
					}
				}

			}
		}
		
		score = score_sing + score_muti + score_jud + score_fill + score_ess;
		String grade = "";
		int f = Math.round(score);
		int g = ((f < 0) == true ? 1 : 0) + ((f < 60) == true ? 1 : 0) + ((f < 75) == true ? 1 : 0)
				+ ((f < 85) == true ? 1 : 0) + ((f < 95) == true ? 1 : 0);
		switch (g) {
		case 0:
			grade = "优秀";
			break;
		case 1:
			grade = "良好";
			break;
		case 2:
			grade = "中等";
			break;
		case 3:
			grade = "及格";
			break;
		case 4:
			grade = "不及格";
			break;
				db.modify("update question set type = ? , title  = ? , `select` = ? , score = ? , `key` = ? , img = ? where number = ? ;",type,title,select,score,key,fileName,number);
				}else {
					db.modify("update question set type = ? , title  = ? , `select` = ? , score = ? , `key` = ?  where number = ? ;",type,title,select,score,key,number);
				}
				break;
			case 2://删
				db.modify("delete from question where number = ? ; ", number);
				break;
			default:
				break;
			}		
		} catch (Exception e) {
		}
		
		if (mode==0) {
			PrintWriter out = response.getWriter();
		}else
		response.sendRedirect("ShowQuePage");

	}

}
package examservlet.control;

/**
 * 该类负责处理登录操作
 * 匹配账号密码是否对应
			HttpSession session = request.getSession();
			session.setAttribute("examTime", examTime);
			session.setAttribute("ques", listALL);	//把试卷数组保存到Session对象
			//重定向到试卷页面,供考生作答
			response.sendRedirect(request.getContextPath()+"/student/student_exam_paper.jsp");

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	/**
	 * 负责每种题型、指定数量的随机抽题
	 * @param list	题目链表(存储了一类题型的行号)
	 * @param rs	数据表结果集
	 * @param count 抽取指定的题目数量
	 * @return		返回一个(存储了count条指定类型的题目)数组
	 */
	public ArrayList<QuestionBean> randomQue(LinkedList<Integer> list,ResultSet rs,int count) {
		int m = -1;
		int index = -1;
		ArrayList<QuestionBean> listA = new ArrayList<QuestionBean>();
		while (list.size() > 0&&count>0) {
			count--;
			m = (int) (Math.random() * list.size());
			index = list.get(m);
			System.out.println(index);
			list.remove(m);
			tihao++;
			try {
				rs.absolute(index);
				QuestionBean queBean = new QuestionBean();
				queBean.setQ_id(String.valueOf(tihao));
				queBean.setQ_type(rs.getString(2));
				queBean.setQ_title(rs.getString(3));
				String selectString = rs.getString(4);
				System.out.println(rs.getString(2));
				queBean.setQ_score(rs.getString(5));
				queBean.setQ_key(rs.getString(6));
				queBean.setQ_img(rs.getString(7));
				if (selectString != null) {
					queBean.setQ_select(selectString);
					String[] temp = selectString.split("\\@");
					queBean.setOptions(temp);
				}

/**
 * 该类实现修改学生信息表功能
 */
@WebServlet("/HandleStuInfo")
public class StudentModifyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		try {
			Class.forName("com.mysql.jdbc.Driver"); // 数据库驱动
		} catch (Exception e) {
		}
	}

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

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8"); // 编码处理
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		String executeMode = request.getParameter("executeMode");
		int mode = Integer.parseInt(executeMode); // 转化整形
		System.out.println(mode);

		int cpage = 0;
		int per = 10;
		if (request.getParameter("cpage") != null) {
			cpage = Integer.parseInt(request.getParameter("cpage"));
		}
		request.setAttribute("cpage", cpage);
		if (request.getParameter("per") != null) {
			per = Integer.parseInt(request.getParameter("per"));
			case 0://增
				db.insert("insert into question values (?,?,?,?,?,?,?) ; ",number,type,title,select,score,key,fileName);
				break;
			case 1://if (fileName!="") {
				db.modify("update question set type = ? , title  = ? , `select` = ? , score = ? , `key` = ? , img = ? where number = ? ;",type,title,select,score,key,fileName,number);
				}else {
					db.modify("update question set type = ? , title  = ? , `select` = ? , score = ? , `key` = ?  where number = ? ;",type,title,select,score,key,number);
				}
				break;
			case 2://删
				db.modify("delete from question where number = ? ; ", number);
				break;
			default:
				break;
			}		
		} catch (Exception e) {
		}
		
		if (mode==0) {
			PrintWriter out = response.getWriter();
		}else
		response.sendRedirect("ShowQuePage");

	}

}
package examservlet.control;

/**
 * 该类负责处理登录操作
 * 匹配账号密码是否对应
 * 将登录信息存储到loginBean
		}

	}

}
package examservlet.control;

/**
 * 该类是自动抽提组卷类,实现功能:
 * 1.每种题型随机抽取指定条数,例:选择题抽5条;
 * 2.被抽中的题目信息传入QuestionBean储存;
 * 3.把Bean存入动态数组ArrayList组成试卷数组;
 * 4.把试卷数组存入Session对象,供考生作答。
 */
@WebServlet("/HandlePaper")
public class QuestionExtractServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	int tihao = 0;
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		ArrayList<QuestionBean> listALL = new ArrayList<QuestionBean>();
		
		//抽题数量
		//单选题抽5道,多选题抽4道,判断题抽5道,填空题抽5道,简答题抽3道
		int num1=5,num2=4,num3=5,num4=5,num5=3;
		int examTime=30;
		try {
			DatabassAccessObject db = new DatabassAccessObject();
								queBean.getQ_type(), queBean.getQ_title(), queBean.getQ_select(), queBean.getQ_score(),
								queBean.getQ_key(), queBean.getQ_img(), queBean.getQ_id());
					}
				}

				System.out.println("数据导入成功");
				PrintWriter out = response.getWriter();
				out.println("<script language=javascript>alert('数据导入成功');window.location='" + request.getContextPath()
						+ "/ShowQuePage';script>");
				break;
			case 2:
				List<StudentInfoBean> stuListExcel = StuInfoExcelService.getAllByExcel(excelSorcePath);

				db = new DatabassAccessObject();
				for (StudentInfoBean stuBean : stuListExcel) {
					if (!StuInfoExcelService.isExist(stuBean.getID())) {
						db.insert("INSERT INTO student (ID,password,name,class,score) VALUES (?,?,?,?,?) ; ",
								stuBean.getID(), stuBean.getPassword(), stuBean.getName(), stuBean.getCLASS(),
								stuBean.getScore());
					} else {
						db.modify("UPDATE student SET  password = ? , name = ? , class = ? , score = ? WHERE ID = ? ;",
								stuBean.getPassword(), stuBean.getName(), stuBean.getCLASS(), stuBean.getScore(),
								stuBean.getID());
					}
				}

				System.out.println("数据导入成功");
				PrintWriter out2 = response.getWriter();
				out2.println("<script language=javascript>alert('数据导入成功');window.location='" + request.getContextPath()
						+ "/ShowStuPage';script>");
			default:
				break;
			}

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

}
package examservlet.control;

			}else {
				rs = db.query("select score.ID,class,name,score_sing,score_muti,score_jud,score_fill,score_ess,score.score,grade from student join score on student.id=score.id order by ID ;");
			}
			

			int total = 0;
			while (rs.next()) {
				String ID=rs.getString(1);
				String CLASS=rs.getString(2);
				String name=rs.getString(3);
				Float score_sing=Float.valueOf(rs.getString(4));
				Float score_muti=Float.valueOf(rs.getString(5));
				Float score_jud=Float.valueOf(rs.getString(6));
				Float score_fill=Float.valueOf(rs.getString(7));
				Float score_ess=Float.valueOf(rs.getString(8));
				Float score=Float.valueOf(rs.getString(9));
				String grade=rs.getString(10);
				stuBeanAllList.add(new StudentInfoBean(ID, CLASS, name, score_sing, score_muti, score_jud, score_fill, score_ess, score,grade));
				total++;
			}
			// 再通过根据cpage与per求出要推回给前台显示的数组
			ArrayList<StudentInfoBean> stuTableList = new ArrayList<StudentInfoBean>();
			for (int i = cpage * per; i < cpage * per + per && i < total; i++) {
				stuTableList.add(stuBeanAllList.get(i));
			}
			String temp=request.getParameter("modify_id");
			System.out.println(temp);
			request.setAttribute("modify_id", temp);
			request.setAttribute("total", total);
			request.setAttribute("stuTableList", stuTableList);
			request.getRequestDispatcher("/teacher/teacher_score_manage.jsp").forward(request,
					response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
package examservlet.control;

@WebServlet("/ScoreModify")
			while (rs.next()) {
				StudentInfoBean stuBean = new StudentInfoBean();
				stuBean.setID(rs.getString("Id"));
				stuBean.setPassword(rs.getString("password"));
				stuBean.setName(rs.getString("Name"));
				stuBean.setCLASS(rs.getString("class"));
				stuBean.setScore(rs.getFloat("score"));
				stuBeanAllList.add(stuBean);
				total++;
			}
			// 再通过根据cpage与per求出要推回给前台显示的数组
			ArrayList<StudentInfoBean> stuTableList = new ArrayList<StudentInfoBean>();
			for (int i = cpage * per; i < cpage * per + per && i < total; i++) {
				stuTableList.add(stuBeanAllList.get(i));
			}
			String temp=request.getParameter("modify_id");
			System.out.println(temp);
			request.setAttribute("modify_id", temp);
			request.setAttribute("total", total);
			request.setAttribute("stuTableList", stuTableList);
			request.getRequestDispatcher("/teacher/teacher_stu_manage.jsp").forward(request,
					response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
package examservlet.control;

	 */
	public ArrayList<QuestionBean> randomQue(LinkedList<Integer> list,ResultSet rs,int count) {
		int m = -1;
		int index = -1;
		ArrayList<QuestionBean> listA = new ArrayList<QuestionBean>();
		while (list.size() > 0&&count>0) {
			count--;
			m = (int) (Math.random() * list.size());
			index = list.get(m);
			System.out.println(index);
			list.remove(m);
			tihao++;
			try {
				rs.absolute(index);
				QuestionBean queBean = new QuestionBean();
				queBean.setQ_id(String.valueOf(tihao));
				queBean.setQ_type(rs.getString(2));
				queBean.setQ_title(rs.getString(3));
				String selectString = rs.getString(4);
				System.out.println(rs.getString(2));
				queBean.setQ_score(rs.getString(5));
				queBean.setQ_key(rs.getString(6));
				queBean.setQ_img(rs.getString(7));
				if (selectString != null) {
					queBean.setQ_select(selectString);
					String[] temp = selectString.split("\\@");
					queBean.setOptions(temp);
				}
				listA.add(queBean);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return listA;
	}
}
package examservlet.control;

/**

/**
 * 该类负责处理登录操作
 * 匹配账号密码是否对应
 * 将登录信息存储到loginBean
 */
@WebServlet("/HandleLogin")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (Exception e) {
		}
	}

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

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		Connection con;
		Statement sql;
		String ID = request.getParameter("ID").trim();
 * 此外,还可以接受批量上传的图片,并保存到工程目录下
 */
@WebServlet("/HandleBatchAdd")
@MultipartConfig // 支持文件上传
public class BatchAdditionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

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

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8"); // 编码处理
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		String excelSorcePath = "";
		Integer mode = Integer.valueOf(request.getParameter("mode"));
		String savePath = getServletContext().getRealPath("/images");

		/**
		 * 以下部分为获取上传Excel文件并保存到发布目录
		 */
		Part part = request.getPart("excel"); // Excle文件
		String fileName = part.getSubmittedFileName(); // 获取part对象所携带的文件名称
		if (fileName.length() > 0) { // 如果文件不为空
			savePath = getServletContext().getRealPath("/images");
			part.write(savePath + "/" + fileName);// 上传文件到发布目录下
			excelSorcePath = savePath + "/" + fileName;
			// 图片的目标路径(当前项目目录)
		}

		/**
		 * 以下部分为获取批量上传的配图
		 */
		for (Part imgPath : request.getParts()) { // 遍历上传的每一个part
			if (imgPath.getName().startsWith("img")) {
				// 上传按钮也是part对象,在这里用if条件语句过滤它
				// 只接受part名称标头为"img"的正文图片数据
				String fileName1 = imgPath.getSubmittedFileName(); // 获取单张图片的文件名
				if (fileName1 == null || fileName1.length() == 0)
					break;
				try {
					imgPath.write(savePath + "/" + fileName1); // 写入图片到tomcat的发布目录下
					

基于javaweb+mysql的jsp+servlet在线考试管理系统(java+jsp+jquery+servlet+mysql)_第1张图片

基于javaweb+mysql的jsp+servlet在线考试管理系统(java+jsp+jquery+servlet+mysql)_第2张图片
基于javaweb+mysql的jsp+servlet在线考试管理系统(java+jsp+jquery+servlet+mysql)_第3张图片
基于javaweb+mysql的jsp+servlet在线考试管理系统(java+jsp+jquery+servlet+mysql)_第4张图片
基于javaweb+mysql的jsp+servlet在线考试管理系统(java+jsp+jquery+servlet+mysql)_第5张图片
基于javaweb+mysql的jsp+servlet在线考试管理系统(java+jsp+jquery+servlet+mysql)_第6张图片

你可能感兴趣的:(mysql,java,servlet)