项目结构:
(1)utils层存放数据库连接语句 (2)dao层定义一些数据库的增删改查方法 (3)controller层调用dao层方法实现数据库的增删改查 (4)model层封装实体类 项目展示: 1.登录界面:
登录时从数据库中查询用户是否存在,存在跳转主页面,否则跳转注册页面。 2.管理员注册界面:
为了实现特定用户才能注册管理员,这里加了一个邀请码,只有正确填写邀请码才能注册,否则跳转至错误页面。
3.主页面(前端属实没时间搞,瞎写了些…>^<)
4.新增信息页面:
5.显示所有信息页面:
6.修改信息页面:
这里使用了mes携带信息跳转至修改页面,所以能够显示出原本的信息。
7.删除页面:
删除成功后跳转至查询所有信息页面。 下面附上部分源代码-> AdminController:
package com.exam.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.exam.dao.AdminDao;
import com.exam.dao.MessageDao;
import com.exam.model.Admin;
import com.exam.model.Message;
/**
* 管理员功能控制类
* @author 1
*
*/
public class AdminController extends HttpServlet {
@Override //覆盖
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
if("exit".equalsIgnoreCase(action)) {
HttpSession session = req.getSession();
Admin admin = (Admin)session.getAttribute("admin");
if(admin !=null) {
//当前用户已经登录,可以执行退出登录
session.setAttribute("admin", null);
resp.sendRedirect("./login.jsp");
return;
}
return;
}else if("register".equalsIgnoreCase(action)) {
//跳转管理员注册页面
resp.sendRedirect("./adminregister.jsp");
return;
}
resp.sendRedirect("./login.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
if("add".equalsIgnoreCase(action)){
String name = req.getParameter("adminname");
String password = req.getParameter("password");
String password1 = req.getParameter("password1");
String invite = req.getParameter("invite");
//1.password和password1两者内容不相等,跳转错误页面
if(name == "" || password == "" || password1 == "" || !password.equalsIgnoreCase(password1)) {
resp.sendRedirect("./error.html");
return;
}
//非特定邀请用户,不接受注册
if(invite == "" || !"root".equalsIgnoreCase(invite)) {
resp.sendRedirect("./error.html");
return;
}
//2.两者内容一致且不为空,继续处理
AdminDao adminDao = new AdminDao();
Admin admin = new Admin();
admin.setUsername(name);
admin.setPassword(password);
admin.setStatus(1);
boolean isRegisterSuccess = adminDao.insertAdmin(admin);
if (isRegisterSuccess){
resp.sendRedirect("./login.jsp");
return;
}else {
resp.sendRedirect("./error.html");
return;
}
}
//1. 解析用户登录参数
String userName = req.getParameter("username");
String password = req.getParameter("password");
//2.封装对象
Admin admin = new Admin();
admin.setUsername(userName);
admin.setPassword(password);
//3.实例化Admin的数据库操作类对象,并调用方法AdminDao
AdminDao adminDao = new AdminDao();
//4.调用Dao层代码,实现数据库操作。
boolean isloginSuccess = adminDao.login(admin);
//条件判断
if(isloginSuccess) {
//跳转功能管理界面
//session,cookie
HttpSession ssion = req.getSession();
ssion.setAttribute("admin", admin);
//跳转主界面
//mess动态变量;携带学生数据
MessageDao messDao = new MessageDao();
List<Message> mess = messDao.GetAllMessages();
req.setAttribute("mess", mess);
req.setAttribute("admin", admin);
RequestDispatcher dispatcher = req.getRequestDispatcher("./index.jsp");
dispatcher.forward(req,resp);
//跳转主界面
}else {
//返回404.html
resp.sendRedirect("./error.html");
}
}
}
MessageController:
package com.exam.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.exam.dao.MessageDao;
import com.exam.model.Admin;
import com.exam.model.Message;
/**
* 考试信息业务逻辑处理
* @author 1
*
*/
public class MessageController extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
Admin admin = (Admin)session.getAttribute("admin");
if(admin == null) {
resp.sendRedirect("./error.html");
return;
}
String action = req.getParameter("action");
if("delete".equalsIgnoreCase(action)) {
String mid = req.getParameter("mid");
MessageDao messageDao = new MessageDao();
int id = Integer.parseInt(mid);
boolean isDelete = messageDao.DeleteMessById(id);
if(isDelete) {
MessageDao messDao = new MessageDao();
List<Message> mess = messDao.GetAllMessages();
req.setAttribute("mess", mess);
req.setAttribute("admin", admin);
RequestDispatcher dispatcher = req.getRequestDispatcher("./main.jsp");
dispatcher.forward(req, resp);
}else {
resp.sendRedirect("./error.html");
}
}
else if("update".equalsIgnoreCase(action)) {
String mid = req.getParameter("mid");
int id = Integer.parseInt(mid);
MessageDao messDao = new MessageDao();
Message mess = messDao.GetExInfoById(id);
if(mess == null) {
resp.sendRedirect("./error.html");
}else {
req.setAttribute("mes", mess);
RequestDispatcher dispatcher = req.getRequestDispatcher("./updatemes.jsp");
dispatcher.forward(req, resp);
}
}
else if("add".equalsIgnoreCase(action)){
resp.sendRedirect("./add.jsp");
}
else if("select".equalsIgnoreCase(action)) {
HttpSession ssion = req.getSession();
ssion.setAttribute("admin", admin);
MessageDao messDao = new MessageDao();
List<Message> mess = messDao.GetAllMessages();
req.setAttribute("mess", mess);
req.setAttribute("admin", admin);
RequestDispatcher dispatcher = req.getRequestDispatcher("./main.jsp");
dispatcher.forward(req, resp);
}
}
/**
* 处理MessageController请求下的POST请求
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
Admin admin = (Admin)session.getAttribute("admin");
if(admin == null) {
resp.sendRedirect("./error.html");
return;
}
String action = req.getParameter("action");
if("update".equalsIgnoreCase(action)) {
int id = Integer.parseInt(req.getParameter("mid"));
Message mes = new Message();
mes.setSubject( req.getParameter("subject"));
mes.setTeacher(req.getParameter("teacher"));
mes.setDate(req.getParameter("date"));
mes.setPlace(req.getParameter("place"));
mes.setMid(id);
MessageDao messDao = new MessageDao();
boolean isUpdateSuccess = messDao.UpdateExaInfo(mes);
if(isUpdateSuccess) {
List<Message> allMess = messDao.GetAllMessages();
req.setAttribute("mess", allMess);
RequestDispatcher dispatcher = req.getRequestDispatcher("./main.jsp");
dispatcher.forward(req, resp);
}else {
resp.sendRedirect("./error.html");
}
}
else if("add".equalsIgnoreCase(action)){
String subject = req.getParameter("subject");
String teacher = req.getParameter("teacher");
String date = req.getParameter("date");
String place= req.getParameter("place");
Message mes = new Message();
mes.setSubject(subject);
mes.setTeacher(teacher);
mes.setDate(date);
mes.setPlace(place);
MessageDao messDao = new MessageDao();
boolean isAddSuccess = messDao.AddExaInfo(mes);
if(isAddSuccess) {
List<Message>allMess = messDao.GetAllMessages();
req.setAttribute("mess", allMess);
RequestDispatcher dispatcher = req.getRequestDispatcher("./main.jsp");
dispatcher.forward(req, resp);
}else {
resp.sendRedirect("./error.html");
}
}
}
}
AdminDao:
package com.exam.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.exam.model.Admin;
import com.exam.utils.DButils;
/**
* 管理员数据库操作类
* @author 1
*
*/
public class AdminDao {
private static Connection conn;
public AdminDao(){
conn = DButils.getConn();
}
/**
* 保存一条数据到数据库
* @param admin
* @return
*/
public boolean insertAdmin(Admin admin) {
try {
PreparedStatement pst = conn.prepareStatement("insert into admin (username, password,status) values(?,?,?)");
pst.setString(1, admin.getUsername());
pst.setString(2, admin.getPassword());
pst.setInt(3, admin.getStatus());
int result = pst.executeUpdate();
return result >0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
/**
* 查询操作数据库并判断操作是否成功并返回结果。
* @param admin
* @return
*/
public boolean login(Admin admin) {
//创建一个PreparedStatement
String sql = "select * from admin where username= ? and password = ?";
try {
//准备Prepared对象
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, admin.getUsername());
pst.setString(2, admin.getPassword());
//执行exeute操作
ResultSet rst = pst.executeQuery();
//请求处理
if(rst.next()) {
System.out.println(rst.getString(1));
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
MessageDao:
package com.exam.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.exam.model.Message;
import com.exam.utils.DButils;
/**
* 信息数据库操作类
* @author 1
*
*/
public class MessageDao {
private Connection conn;
/**
* StudentDao的构造方法
*/
public MessageDao() {
conn = DButils.getConn();
}
/**
* 保存新记录到数据库
* @param message
* @return
*/
public boolean AddExaInfo(Message message) {
try {
PreparedStatement pst = conn.prepareStatement(" insert into message(subject,teacher,date,place) values(?,?,?,?)");
pst.setString(1, message.getSubject());
pst.setString(2, message.getTeacher());
pst.setString(3, message.getDate());
pst.setString(4, message.getPlace());
int result = pst.executeUpdate();
return result>0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
/**
* 修改考试信息到数据库
* @param message
* @return
*/
public boolean UpdateExaInfo(Message message) {
try {
PreparedStatement pst = conn.prepareStatement("update message set subject =?, teacher= ?, date = ?, place = ? where mid = ?");
pst.setString(1, message.getSubject());
pst.setString(2,message.getTeacher() );
pst.setString(3, message.getDate());
pst.setString(4, message.getPlace());
pst.setInt(5,message.getMid());
int result = pst.executeUpdate();
return result > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public Message GetExInfoById(int mid) {
try {
PreparedStatement pst = conn.prepareStatement("select * from message where mid = ?");
pst.setInt(1, mid);
ResultSet rst = pst.executeQuery();
if(rst.next()) {
Message mes = new Message();
mes.setMid(rst.getInt("mid"));
mes.setSubject(rst.getString("subject"));
mes.setTeacher(rst.getString("teacher"));
mes.setDate(rst.getString("date"));
mes. setPlace(rst.getString("place"));
return mes;
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public boolean DeleteMessById(int mid) {
PreparedStatement pst;
try {
pst = conn.prepareStatement("delete from message where mid = ?");
pst.setInt(1, mid);
int result = pst.executeUpdate();
return result>0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
/**
* 获取所有考试信息并返回
* @return
*/
public List<Message> GetAllMessages() {
List<Message> mess = new ArrayList<Message>();
try {
Statement st = conn.createStatement();
ResultSet rst = st.executeQuery("select * from message");
while(rst.next()) {
Message mes = new Message();
mes.setMid(rst.getInt("mid"));
mes.setSubject(rst.getString("subject"));
mes.setTeacher(rst.getString("teacher"));
mes.setDate(rst.getString("date"));
mes. setPlace(rst.getString("place"));
mess.add(mes);
}
} catch (SQLException e) {
e.printStackTrace();
}
return mess;
}
}
实体类部分就不放了 * ~ *
DButils:
package com.exam.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 实现jdbc连接
*/
public class DButils {
private static Connection Conn;
/**
* 加载JDBC类,连接数据库,返回connection对象
* @return
*/
public static Connection getConn(){
if (Conn != null){
return Conn;
}
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String connUrl = "jdbc:mysql://localhost:3306/exam_info?serverTimezone=GMT%2B8";
String user = "root";
String password = "root";
return DriverManager.getConnection(connUrl,user,password);
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}
return Conn;
}
}
最后,附上数据库文件
-- MySQL dump 10.13 Distrib 8.0.18, for Win64 (x86_64)
--
-- Host: localhost Database: exam_info
-- ------------------------------------------------------
-- Server version 8.0.18
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `admin`
--
DROP TABLE IF EXISTS `admin`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `admin` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`status` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `admin`
--
LOCK TABLES `admin` WRITE;
/*!40000 ALTER TABLE `admin` DISABLE KEYS */;
INSERT INTO `admin` VALUES (1,'root','123456',1),(2,'admin','123456',1),(3,'sa','sasa',1),(4,'moli','123456',1),(5,'moli','123456',1),(6,'moli','123',1),(7,'LL','123456',1),(8,'Molise','123123',1),(9,'chy','123456',1),(10,'Y','123456',1),(11,'SD','123',1);
/*!40000 ALTER TABLE `admin` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `message`
--
DROP TABLE IF EXISTS `message`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `message` (
`mid` int(11) NOT NULL AUTO_INCREMENT,
`subject` varchar(45) NOT NULL,
`teacher` varchar(45) NOT NULL,
`date` varchar(50) NOT NULL,
`place` varchar(45) NOT NULL,
PRIMARY KEY (`mid`)
) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `message`
--
LOCK TABLES `message` WRITE;
/*!40000 ALTER TABLE `message` DISABLE KEYS */;
INSERT INTO `message` VALUES (1,'C#','lily','2020-01-03','9'),(2,'English','lily','2019-12-01','4'),(3,'JAVa','wd','2020-01-01','9'),(4,'C++','Tony','2019-11-01','3');
/*!40000 ALTER TABLE `message` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `teacher`
--
DROP TABLE IF EXISTS `teacher`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `teacher` (
`tid` int(11) NOT NULL AUTO_INCREMENT,
`tname` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`age` varchar(45) NOT NULL,
`gender` varchar(45) NOT NULL,
PRIMARY KEY (`tid`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `teacher`
--
LOCK TABLES `teacher` WRITE;
/*!40000 ALTER TABLE `teacher` DISABLE KEYS */;
INSERT INTO `teacher` VALUES (1,'Lose','123456','39','women'),(2,'KK','123123','34','men'),(3,'KK','123123','34','men'),(4,'KKo','123456','22','women'),(5,'KKo','123123','34','men'),(6,'meimei','12341','34','men');
/*!40000 ALTER TABLE `teacher` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2019-12-28 18:35:08