JSP+Servlet实现一个简单的带有增删改查的学生信息管理系统

项目准备

导入相关Jar包
Jar包
将三个Jar包复制到项目的lib目录下,右击添加至构建路径
下载链接:jstl.jar,standard.jar,mysql-connector-java-8.0.16.jar,数据库版本5.0需要使用mysql-connector-java-5.1.39-bin.jar

第一步:创建数据库

根据实际情况创建数据库表

JSP+Servlet实现一个简单的带有增删改查的学生信息管理系统_第1张图片 stuNo:学号,字符串类型,作为主键;
name:学生姓名,字符串类型;
sex:性别,字符串类型;
birthday:出生日期,date类型;
introduce:个人简介,text长文本类型;
salary:奖学金,int类型;

第二步:创建实体类

根据数据库建的stu表,创建实体类,成员变量类型尽量统一或易转换
package model;

public class Student {
	
	private String stuNo;
	private String name;
	private String sex;
	private String birthday;
	private String introduce;
	private int salary;
	
	public String getStuNo() {
		return stuNo;
	}
	public void setStuNo(String stuNo) {
		this.stuNo = stuNo;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getBirthday() {
		return birthday;
	}
	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}
	public String getIntroduce() {
		return introduce;
	}
	public void setIntroduce(String introduce) {
		this.introduce = introduce;
	}
	public int getSalary() {
		return salary;
	}
	public void setSalary(int salary) {
		this.salary = salary;
	}	
}

第三步:Dao实现对Student类的CRUD(增删改查)方法

数据库工具类:Util.java

package dao;

import java.sql.*;

public class Util {
	
	private static String DRIVER="com.mysql.cj.jdbc.Driver";//数据库连接jar包5.0是com.mysql.jdbc.Driver,此为8.0的驱动路径
    private static String URL="jdbc:mysql://localhost:3306/student?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&autoReconnect=true";  //指定连接的数据库以及连接属性设置
	private static String USERNAME="root";//用户名
	private static String PWD="password";//密码
	
	public static Connection getConnection() throws ClassNotFoundException, SQLException {//获得连接
		Connection connection=null;
		Class.forName(DRIVER);
		connection=DriverManager.getConnection(URL, USERNAME, PWD);
		return connection;
	}
	
	public static void closeAll(Connection connection,Statement statement,ResultSet resultSet) throws SQLException {//关闭连接
		if(connection!=null) connection.close();
		if(statement!=null) statement.close();
		if(resultSet!=null) resultSet.close();
	}
	
	public static void closeAll(Connection connection,Statement statement) throws SQLException {//关闭连接
		if(connection!=null) connection.close();
		if(statement!=null) statement.close();
	}

}

具体实现:StudentDao.java

package dao;

import java.sql.*;
import java.util.Vector;

import model.Student;

public class StudentDao extends Util{
	
	//返回所有学生的集合
	public static Vector<Student> getAllStudent() throws ClassNotFoundException, SQLException {
		Vector<Student> students=new Vector<>();
		Connection connection=getConnection();
		Statement statement=connection.createStatement();
		ResultSet resultSet=statement.executeQuery("select * from stu");
		while(resultSet.next()) {
			Student student=new Student();
			student.setStuNo(resultSet.getString(1));
			student.setName(resultSet.getString(2));
			student.setSex(resultSet.getString(3));
			student.setBirthday(resultSet.getString(4));
			student.setIntroduce(resultSet.getString(5));
			student.setSalary(resultSet.getInt(6));
			students.add(student);
		}
		closeAll(connection, statement,resultSet);
		return students;
	}
	
	//通过学号查询并返回某个学生
	public static Student getOneStudent(String id) throws ClassNotFoundException, SQLException {
		Student student=null;
		Connection connection=getConnection();
		PreparedStatement statement=connection.prepareStatement("select * from stu where stuNo=?");
		statement.setString(1, id);
		ResultSet resultSet=statement.executeQuery();
		while(resultSet.next()) {
			student=new Student();
			student.setStuNo(resultSet.getString(1));
			student.setName(resultSet.getString(2));
			student.setSex(resultSet.getString(3));
			student.setBirthday(resultSet.getString(4));
			student.setIntroduce(resultSet.getString(5));
			student.setSalary(resultSet.getInt(6));
		}
		closeAll(connection, statement,resultSet);
		return student;
	}
	
	//向学生列表添加某学生
	public static void addOneStudent(Student student) throws ClassNotFoundException, SQLException {
		Connection connection=getConnection();
		PreparedStatement statement=connection.prepareStatement(
				"insert into stu values(?,?,?,?,?,?)");
		statement.setString(1, student.getStuNo());
		statement.setString(2, student.getName());
		statement.setString(3, student.getSex());
		statement.setString(4, student.getBirthday());
		statement.setString(5, student.getIntroduce());
		statement.setInt(6, student.getSalary());
		statement.executeUpdate();
		closeAll(connection, statement);
	}
	
	//通过学号删除某学生
	public static void delOneStudent(String id) throws ClassNotFoundException, SQLException {
		Connection connection=getConnection();
		PreparedStatement statement=connection.prepareStatement(
				"delete from stu where stuNo=?");
		statement.setString(1, id);
		statement.executeUpdate();
		closeAll(connection, statement);
	}
	
	//通过学号修改某学生信息
	public static void updateOneStudent(Student student) throws ClassNotFoundException, SQLException {
		Connection connection=getConnection();
		PreparedStatement statement=connection.prepareStatement(
				"update stu set name=?,sex=?,birthday=?,introduce=?,salary=?"
				+ " where stuNo=?");
		statement.setString(1, student.getName());
		statement.setString(2, student.getSex());
		statement.setString(3, student.getBirthday());
		statement.setString(4, student.getIntroduce());
		statement.setInt(5, student.getSalary());
		statement.setString(6, student.getStuNo());
		statement.executeUpdate();
		closeAll(connection, statement);
	}

}

第四步:Servlet实现

可以通过Servlet实现对数据变量的初始化,然后转到JSP页面,在JSP页面中利用JSTL和EL表达式对数据进行显示

数据初始化InitServlet.java(ps:作为项目的启动文件,实现对信息的初始化,将信息从数据库读取都存入session中,然后跳转到index.jsp)

package servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Vector;

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.websocket.Session;

import dao.StudentDao;
import model.Student;

/**
 * Servlet implementation class InitServlet
 */
@WebServlet("/InitServlet")
public class InitServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public InitServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Vector<Student> students=StudentDao.getAllStudent();
			request.getSession().setAttribute("students", students);
			response.sendRedirect("index.jsp");
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)  {
		
	}
}

添加学生AddServlet.java(ps:添加学生,从请求中读取用户的输入,然后封装进Student类中,再调用StudentDao的添加学生的方法,将其存储进数据库后,返回所有学生的集合并存储进session中,跳转到index.jsp)

package servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Vector;

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 dao.StudentDao;
import model.Student;

/**
 * Servlet implementation class AddServlet
 */
@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		Student student=new Student();
		student.setStuNo(request.getParameter("stuNo"));
		student.setName(request.getParameter("name"));
		student.setSex(request.getParameter("sex"));
		student.setBirthday(request.getParameter("birthday"));
		student.setIntroduce(request.getParameter("introduce"));
		student.setSalary(Integer.parseInt(request.getParameter("salary")));
		try {
			StudentDao.addOneStudent(student);
			Vector<Student> students=StudentDao.getAllStudent();
			request.getSession().setAttribute("students", students);
			response.sendRedirect("index.jsp");
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}

}

删除学生DeleteServlet.java(ps:根据传入的学生的学号,调用StudentDao中的删除学生的方法,实现数据库的学生删除,然后重新设置session后,跳转到index.jsp)

package servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Vector;

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 dao.StudentDao;
import model.Student;

/**
 * Servlet implementation class DeleteServlet
 */
@WebServlet("/DeleteServlet")
public class DeleteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DeleteServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id=request.getParameter("id");
		try {
			StudentDao.delOneStudent(id);
			Vector<Student> students=StudentDao.getAllStudent();
			request.getSession().setAttribute("students", students);
			response.sendRedirect("index.jsp");
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

查询学生SerchServlet.java(ps:根据传入的学号,返回某一个学生,跳转到修改update.jsp)

package servlets;

import java.io.IOException;
import java.sql.SQLException;

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 dao.StudentDao;
import model.Student;

/**
 * Servlet implementation class SerchServlet
 */
@WebServlet("/SerchServlet")
public class SerchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SerchServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Student one=StudentDao.getOneStudent(request.getParameter("id"));
			request.getSession().setAttribute("one", one);
			response.sendRedirect("update.jsp");
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

修改学生UpdateServlet.java(ps:根据传入的学生,实现数据库更新后,重新设置session后,跳转到index.jsp)

package servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Vector;

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 dao.StudentDao;
import model.Student;

/**
 * Servlet implementation class UpdateServlet
 */
@WebServlet("/UpdateServlet")
public class UpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Student student=StudentDao.getOneStudent(request.getParameter("id"));
			request.getSession().setAttribute("one", student);
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		Student student=new Student();
		student.setStuNo(request.getParameter("stuNo"));
		student.setName(request.getParameter("name"));
		student.setSex(request.getParameter("sex"));
		student.setBirthday(request.getParameter("birthday"));
		student.setIntroduce(request.getParameter("introduce"));
		student.setSalary(Integer.parseInt(request.getParameter("salary")));
		try {
			StudentDao.updateOneStudent(student);
			Vector<Student> students=StudentDao.getAllStudent();
			request.getSession().setAttribute("students", students);
			response.sendRedirect("index.jsp");
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}
}

第五步:JSP页面实现(视图层)

首页index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>主页</title>
<link type="text/css" rel="styleSheet"  href="css/style.css" />
</head>
<body>
	<table border="2">
		<tr>
			<th>学号</th>
			<th>姓名</th>
			<th>性别</th>
			<th>出生年月</th>
			<th>简历</th>
			<th>奖学金</th>
			<th>操作</th>
		</tr>
		<c:forEach items="${students}" var="student">
			<tr>
				<td>${student.stuNo}</td>
				<td>${student.name}</td>
				<td>${student.sex}</td>
				<td>${student.birthday}</td>
				<td>${student.introduce}</td>
				<td>${student.salary}</td>
				<td><a href=DeleteServlet?id=${student.stuNo}>删除</a> <a
					href=SerchServlet?id=${student.stuNo}>修改</a></td>
			</tr>
		</c:forEach>
		<tr>
			<form action="AddServlet" method="post">
				<td><input type="text" name="stuNo" placeholder="学号" /></td>
				<td><input type="text" name="name" placeholder="姓名" /></td>
				<td><select name="sex">
						<option value="男"></option>
						<option value="女"></option>
				</select></td>
				<td><input type="date" name="birthday" /></td>
				<td><input type="text" name="introduce" placeholder="简介" /></td>
				<td><input type="number" name="salary" placeholder="奖学金" /></td>
				<td><input type="submit" value="添加" /></td>
			</form>
		</tr>
	</table>
</body>
</html>

二级修改页面update.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改</title>
<link type="text/css" rel="styleSheet"  href="css/style.css" />
</head>
<body>
	<form action=UpdateServlet?stuNo=${one.stuNo} method="post">
		<table border="1">
			<tr>
				<th></th>
				<th>修改前</th>
				<th>修改后</th>
			</tr>
			<tr>
				<th>姓名</th>
				<td> ${one.name} </td>
				<td><input type="text" name="name"></td>
			</tr>
			<tr>
				<th>性别</th>
				<td> ${one.sex}</td>
				<td><select name="sex">
						<option value="男"></option>
						<option value="女"></option>
				</select></td>
			</tr>
			<tr>
				<th>出生日期</th>
				<td> ${one.birthday}</td>
				<td><input type="date" name="birthday"></td>
			</tr>
			<tr>
				<th>简介</th>
				<td> ${one.introduce}</td>
				<td><input type="text" name="introduce"></td>
			</tr>
			<tr>
				<th>奖学金</th>
				<td> ${one.salary}</td>
				<td><input type="number" name="salary"></td>
			</tr>
			<tr>
				<th>操作</th>
				<td><input type="button" value="返回" onclick="window.location.href='index.jsp'">
				</td>
				<td><input type="submit" value="保存"></td>
			</tr>
		</table>
	</form>

</body>
</html>

样式style.css

body {
	background-color: skyblue;
}

table {
	margin: 100px auto;
}

td {
	text-align: center;
}

第六步:在web.xml中设置启动项目文件

将InitServlet作为启动文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
 id="WebApp_ID" version="3.0">
  <display-name>Work</display-name>
  <welcome-file-list>
    <welcome-file>InitServlet</welcome-file>
  </welcome-file-list>
</web-app>

第七步:右击运行项目

JSP+Servlet实现一个简单的带有增删改查的学生信息管理系统_第2张图片JSP+Servlet实现一个简单的带有增删改查的学生信息管理系统_第3张图片

整个项目目录结构预览

JSP+Servlet实现一个简单的带有增删改查的学生信息管理系统_第4张图片

你可能感兴趣的:(复习预览)