不得不承认,学生管理系统是一款烂大街的项目,但是你有没有考虑他为什么被这么多人不知疲倦的去写?正是由于此项目简单的逻辑,重要的功能(crud)对于新手程序员非常友好的,入手项目的第一选择!话不多说,开撸!!!
首先需要创建一个maven项目,建议使用webapp模板
后面的一直点下一步就完事了
本人使用的数据库名为 student_system ,并创建一个student表,表内字段如下
注意:id字段应当设置为自动增长
jdbc.properties代码如下
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/student_system?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=226013li
记得修改要使用的数据库,以及数据库的账号密码
在我的上一篇文章
JDBC封装
有详细说明这个封装工具包,小伙伴可以先去学习,我先把工具包连接放下面可以自取
工具类资源
提取码:skr8
@Data //这就是刚刚在pom文件中加的lombok依赖,只要在类的上面加上@Data注解,就会自动认为该类有get, set, 有参 , 无参 , tostring 方法
public class Student {
private Integer id;
private String name;
private Integer age;
private Boolean gender;
private Integer score;
private String address;
}
public interface StudentDao {
List<Map<String, Object>> findAllStudent() throws SQLException;
}
定义一个方法findAllStudent(),该方法返回值如何确定呢?每一个学生他有多个属性,每一个属性可以都可以看做是一个键值对,这样的话刚好符合Map集合的形态,而我们要得到所有的学生,因此需要在外面淘哥List集合
StudentDaoImpl实现类代码
public class StudentDaoImpl extends BaseDao implements StudentDao { //这里我们需要用到JDBC工具类,因此让实现类同时继承工具类
@Override
public List<Map<String, Object>> findAllStudent() throws SQLException {
String sql = "select id, name, age from student"; //sql语句
return super.queryMapList(sql); //调用工具类中的通用查询方法
}
}
StudentService接口代码如下
public interface StudentService {
List<Map<String, Object>> findAllStudent();
}
实现类代码如下
public class StudentServiceImpl implements StudentService {
/**
* Service 需要操作 Dao 层进行数据库功能实现,需要提供给当前 Service 对应 Dao 的实例化对象
*/
private final StudentDao studentDao = new StudentDaoImpl();
@Override
public List<Map<String, Object>> findAllStudent() {
List<Map<String, Object>> allStudent = null;
try {
allStudent = studentDao.findAllStudent(); //让Dao层的对象去操作数据库,返回数据,待会供Controller层使用
} catch (SQLException e) {
e.printStackTrace();
}
return allStudent;
}
}
在controller包下新建一个类:AllStudentServlet
代码如下
@WebServlet("/allStudent") //使用注解方式设置请求地址
public class AllStudentServlet extends HttpServlet {
private final StudentService studentService = new StudentServiceImpl(); //要想获得service层的数据需要先提供给当前servlet层service对象
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8"); //设置客户端(浏览器)向服务器请求的编码集
resp.setContentType("text/html;charset=utf-8"); //设置服务器反馈给客户端(浏览器)的相应数据内容和编码方式
List<Map<String, Object>> allStudent = studentService.findAllStudent(); //service对象调用方法得到数据
String html = "" +
"" +
"" +
" " +
" 所有学生信息列表 " +
" " +
"" +
"" +
" "+
"" +
" " +
" ID " +
" Name " +
" Age " +
" ";
if (allStudent != null) {
for (Map<String, Object> map : allStudent) {
html += "" +
" " + map.get("id") + " " +
" " + map.get("name") + " " +
" " + map.get("age") + " " +
" ";
}
html += "" +
" " +
" 删除 " +
" 修改 " +
" 条件查询 " +
" 添加 " +
" "; //这4个超链接是我们待会要完成的crud功能
}
html += "
" +
"" +
"";
resp.getWriter().append(html); //前端知识,也可以在后端java代码中写,这段代码作用就是创建表格,把刚刚service对象获得的数据进行遍历,在前端页面进行显示
}
}
3.5 效果展示
完美
4 增加学生功能实现
4.1 DAO层
StudentDao接口
public interface StudentDao {
List<Map<String, Object>> findAllStudent() throws SQLException;
/**
* 添加学生对象数据到数据库相关方法
*
* @param stu Student 类型对象
* @return 当前 SQL 语句操作针对于数据表的影响行数
* @throws SQLException SQL 异常
*/
int addStudent(Student stu) throws SQLException;
}
StudentDaoImp
public class StudentDaoImpl extends BaseDao implements StudentDao {
@Override
public List<Map<String, Object>> findAllStudent() throws SQLException {
String sql = "select id, name, age ,gender,score,address from student";
return super.queryMapList(sql);
}
@Override
public int addStudent(Student stu) throws SQLException {
String sql = "insert into student(name, age, gender, score, address) VALUES (?, ?, ?, ?, ?)"; //jdbc学过的预处理
return super.update(sql, stu.getName(), stu.getAge(), stu.getGender(), stu.getScore(), stu.getAddress());//工具类方法
}
}
4.2 service层
StudentService接口
public interface StudentService {
List<Map<String, Object>> findAllStudent();
boolean addStudent(Map<String, String[]> map); //传入学生对象,以Map集合形式
}
StudentServiceImp实现类
public class StudentServiceImpl implements StudentService {
/**
* Service 需要操作 Dao 层进行数据库功能实现,需要提供给当前 Service 对应 Dao 的实例化对象
*/
private final StudentDao studentDao = new StudentDaoImpl();
@Override
public List<Map<String, Object>> findAllStudent() {
List<Map<String, Object>> allStudent = null;
try {
allStudent = studentDao.findAllStudent();
} catch (SQLException e) {
e.printStackTrace();
}
return allStudent;
}
@Override
public boolean addStudent(Map<String, String[]> map) {
Student student = new Student(); //创建学生对象
boolean flag = false;
try {
BeanUtils.populate(student, map); //使用工具类给这个学生对象赋值
flag = studentDao.addStudent(student) != 0; //调用dao层的方法添加学生,判断是否添加成功
} catch (IllegalAccessException | InvocationTargetException | SQLException e) {
e.printStackTrace();
}
return flag;
}
4.3 controller层
创建AddStudentServlet类
代码如下
@WebServlet("/addStudent")
public class AddStudentServlet extends HttpServlet {
/**
* Servlet Controller 需要 StudentService 对象来提供对应的学生操作相关服务
*/
private final StudentService studentService = new StudentServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
// 1. 收数据
Map<String, String[]> parameterMap = req.getParameterMap();//使用HttpServletRequest 的方法,Map集合形式返回url中的资源后面,问号后面的字符串请求数据。
if (studentService.addStudent(parameterMap)) {
resp.getWriter().append("添加成功
");
} else {
resp.getWriter().append("添加失败
");
//通过service对象调用方法来时间增加学生对象,返回的整数判断是否添加成功
}
resp.setHeader("refresh", "3;url=allStudent");
}
}
4.5添加功能前端模块
在webapp包下创建addStudent.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="css/1.css">
</head>
<body>
<div id="navbar">学生管理系统</div>
<form action="addStudent" method="post"> //注意这里的action要和controller层的请求地址相同
<table>
<tr>
<th colspan="2">添加学生操作</th>
</tr>
<tr>
<td>姓名</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>年龄</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" name="gender" value="0"> 男
<input type="radio" name="gender" value="1"> 女
</td>
</tr>
<tr>
<td>成绩</td>
<td><input type="number" name="score"></td>
</tr>
<tr>
<td>地址</td>
<td><input type="text" name="address"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="添加"></td>
</tr>
</table>
</form>
</body>
</html>
4.6效果展示
让我们输入一串数据,因为id字段我们设置了自动增长,所以可以不填写
现在看一看所有学生界面
成功
五, 删除功能实现
5.1 Dao
dao接口
public interface StudentDao {
List<Map<String, Object>> findAllStudent() throws SQLException;
int addStudent(Student stu) throws SQLException;
int deleteStudent(int id,String name) throws SQLException; //通过名称和id删除
}
**dao实现类**
public class StudentDaoImpl extends BaseDao implements StudentDao {
@Override
public List<Map<String, Object>> findAllStudent() throws SQLException {
String sql = "select id, name, age ,gender,score,address from student";
return super.queryMapList(sql);
}
@Override
public int addStudent(Student stu) throws SQLException {
String sql = "insert into student(name, age, gender, score, address) VALUES (?, ?, ?, ?, ?)";
return super.update(sql, stu.getName(), stu.getAge(), stu.getGender(), stu.getScore(), stu.getAddress());
}
@Override
public int deleteStudent(int id,String name) throws SQLException {
String sql = "delete from student where id=? and name=?";
return super.update(sql, id, name); //工具类方法,返回影响的行数
}
5.2 Service
接口
public interface StudentService {
List<Map<String, Object>> findAllStudent();
boolean addStudent(Map<String, String[]> map);
boolean deleteStudent(int id,String name) throws SQLException, InvocationTargetException, IllegalAccessException;
}
实现类
public class StudentServiceImpl implements StudentService {
/**
* Service 需要操作 Dao 层进行数据库功能实现,需要提供给当前 Service 对应 Dao 的实例化对象
*/
private final StudentDao studentDao = new StudentDaoImpl();
@Override
public List<Map<String, Object>> findAllStudent() {
List<Map<String, Object>> allStudent = null;
try {
allStudent = studentDao.findAllStudent();
} catch (SQLException e) {
e.printStackTrace();
}
return allStudent;
}
@Override
public boolean addStudent(Map<String, String[]> map) {
Student student = new Student();
boolean flag = false;
try {
BeanUtils.populate(student, map);
flag = studentDao.addStudent(student) != 0;
} catch (IllegalAccessException | InvocationTargetException | SQLException e) {
e.printStackTrace();
}
return flag;
}
@Override
public boolean deleteStudent(int id, String name) throws SQLException, InvocationTargetException, IllegalAccessException {
boolean flag= studentDao.deleteStudent(id,name)!=0;
return flag;
}
}
5.3 controller层
@WebServlet("/deleteStudent")
public class DeleteStudentServlet extends HttpServlet {
private final StudentService studentService = new StudentServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String id = req.getParameter("id");
String name = req.getParameter("name"); //获取url上的指定值
System.out.println("id=" + id+" name=" + name);
try {
if (studentService.deleteStudent((int)Integer.valueOf(id),name)) { //req.getParameter方法获取的值都是字符串类型的,我们需要转型
resp.getWriter().append("删除成功
");
} else {
resp.getWriter().append("删除失败
");
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
5.4 删除功能前端界面
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>所有学生信息列表title>
<link rel="stylesheet" href="css/1.css">
head>
<body>
<div id="navbar">学生管理系统div>
<form action="deleteStudent" method="post"> //要和controller层请求地址一致
<table style="width: 800px">
<tr>
<th>idth>
<th>Nameth>
tr>
<tr>
<td><input type="text" name="id">td>
<td><input type="text" name="name">td>
<td>td>
<tr>
<td colspan="2"><input type="submit" value="删除">td>
tr>
tr>
table>
form>
body>
html>
5.5 测试
六,修改学生信息功能实现
6.1 dao层
dao层接口代码
public interface StudentDao {
List<Map<String, Object>> findAllStudent() throws SQLException;
int addStudent(Student stu) throws SQLException;
int deleteStudent(int id,String name) throws SQLException;
int updateStudent(int id, String name,int age,int gender,int score,String address);
}
dao层实现类代码
public class StudentDaoImpl extends BaseDao implements StudentDao {
@Override
public List<Map<String, Object>> findAllStudent() throws SQLException {
String sql = "select id, name, age ,gender,score,address from student";
return super.queryMapList(sql);
}
@Override
public int addStudent(Student stu) throws SQLException {
String sql = "insert into student(name, age, gender, score, address) VALUES (?, ?, ?, ?, ?)";
return super.update(sql, stu.getName(), stu.getAge(), stu.getGender(), stu.getScore(), stu.getAddress());
}
@Override
public int deleteStudent(int id,String name) throws SQLException {
String sql = "delete from student where id=? and name=?";
return super.update(sql, id, name);
}
@Override
public int updateStudent(int id, String name,int age,int gender,int score,String address) {
String sql = "update student set name=?,age=?,gender=?,score=?,address=? where id=?"; //通过id修改指定该学生,然后修改信息,注意这里sql和方法参数中id的顺序是不一样的
return super.update(sql, name, age,gender,score,address,id);
}
}
6.2 service层
接口代码
public interface StudentService {
List<Map<String, Object>> findAllStudent();
boolean addStudent(Map<String, String[]> map);
boolean deleteStudent(int id,String name) throws SQLException, InvocationTargetException, IllegalAccessException;
boolean updateStudent(int id, String name,int age,int gender,int score,String address);
}
实现类代码
public class StudentServiceImpl implements StudentService {
/**
* Service 需要操作 Dao 层进行数据库功能实现,需要提供给当前 Service 对应 Dao 的实例化对象
*/
private final StudentDao studentDao = new StudentDaoImpl();
@Override
public List<Map<String, Object>> findAllStudent() {
List<Map<String, Object>> allStudent = null;
try {
allStudent = studentDao.findAllStudent();
} catch (SQLException e) {
e.printStackTrace();
}
return allStudent;
}
@Override
public boolean addStudent(Map<String, String[]> map) {
Student student = new Student();
boolean flag = false;
try {
BeanUtils.populate(student, map);
flag = studentDao.addStudent(student) != 0;
} catch (IllegalAccessException | InvocationTargetException | SQLException e) {
e.printStackTrace();
}
return flag;
}
@Override
public boolean deleteStudent(int id, String name) throws SQLException, InvocationTargetException, IllegalAccessException {
boolean flag= studentDao.deleteStudent(id,name)!=0;
return flag;
}
@Override
public boolean updateStudent(int id, String name, int age, int gender, int score, String address) {
boolean flag= studentDao.updateStudent(id,name,age,gender,score,address)!=0;
return flag;
}
}
6.3controller层
在controller包下创建updateStudent类
@WebServlet("/updateStudent")
public class updateStudentServlet extends HttpServlet {
private final StudentService studentService = new StudentServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String id = req.getParameter("id");
String name = req.getParameter("name");
String age = req.getParameter("age");
String gender = req.getParameter("gender");
String score = req.getParameter("score");
String address = req.getParameter("address");
System.out.println(id + " " + name + " " + age + " " +gender+score+address);
if (studentService.updateStudent(Integer.valueOf(id), name, Integer.valueOf(age), Integer.valueOf(gender), Integer.valueOf(score), address)){
resp.getWriter().append("修改成功
");
} else {
resp.getWriter().append("修改失败,id可能不存在
");
}
}
}
6.4前端代码
在webapp包下创建updateStudent.html文件
@WebServlet("/updateStudent")
public class updateStudentServlet extends HttpServlet {
private final StudentService studentService = new StudentServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String id = req.getParameter("id");
String name = req.getParameter("name");
String age = req.getParameter("age");
String gender = req.getParameter("gender");
String score = req.getParameter("score");
String address = req.getParameter("address");
System.out.println(id + " " + name + " " + age + " " +gender+score+address);
if (studentService.updateStudent(Integer.valueOf(id), name, Integer.valueOf(age), Integer.valueOf(gender), Integer.valueOf(score), address)){
resp.getWriter().append("修改成功
");
} else {
resp.getWriter().append("修改失败,id可能不存在
");
}
}
}
6.5修改功能测试
七,模糊查询学生信息
模糊查询指的就是通过关键字查询,比如我想查询所有“关”字开头的学生
7.1 dao层
接口
public interface StudentDao {
List<Map<String, Object>> findAllStudent() throws SQLException;
int addStudent(Student stu) throws SQLException;
int deleteStudent(int id,String name) throws SQLException;
int updateStudent(int id, String name,int age,int gender,int score,String address);
List<Map<String, Object>> selectStudent(String name) throws SQLException;
}
实现类
public class StudentDaoImpl extends BaseDao implements StudentDao {
@Override
public List<Map<String, Object>> findAllStudent() throws SQLException {
String sql = "select id, name, age ,gender,score,address from student";
return super.queryMapList(sql);
}
@Override
public int addStudent(Student stu) throws SQLException {
String sql = "insert into student(name, age, gender, score, address) VALUES (?, ?, ?, ?, ?)";
return super.update(sql, stu.getName(), stu.getAge(), stu.getGender(), stu.getScore(), stu.getAddress());
}
@Override
public int deleteStudent(int id,String name) throws SQLException {
String sql = "delete from student where id=? and name=?";
return super.update(sql, id, name);
}
@Override
public int updateStudent(int id, String name,int age,int gender,int score,String address) {
String sql = "update student set name=?,age=?,gender=?,score=?,address=? where id=?";
return super.update(sql, name, age,gender,score,address,id);
}
@Override
public List<Map<String, Object>> selectStudent(String name) throws SQLException {
String sql = "select id, name, age from student where name like ?";
return super.queryMapList(sql,"%"+name+"%"); //这里使用了%,表示名字中带有指定字符串的都能查出来
}
}
7.2 service层
接口
public interface StudentService {
List<Map<String, Object>> findAllStudent();
boolean addStudent(Map<String, String[]> map);
boolean deleteStudent(int id,String name) throws SQLException, InvocationTargetException, IllegalAccessException;
boolean updateStudent(int id, String name,int age,int gender,int score,String address);
List<Map<String, Object>> selectStudent(String name);
}
实现类
public class StudentServiceImpl implements StudentService {
/**
* Service 需要操作 Dao 层进行数据库功能实现,需要提供给当前 Service 对应 Dao 的实例化对象
*/
private final StudentDao studentDao = new StudentDaoImpl();
@Override
public List<Map<String, Object>> findAllStudent() {
List<Map<String, Object>> allStudent = null;
try {
allStudent = studentDao.findAllStudent();
} catch (SQLException e) {
e.printStackTrace();
}
return allStudent;
}
@Override
public boolean addStudent(Map<String, String[]> map) {
Student student = new Student();
boolean flag = false;
try {
BeanUtils.populate(student, map);
flag = studentDao.addStudent(student) != 0;
} catch (IllegalAccessException | InvocationTargetException | SQLException e) {
e.printStackTrace();
}
return flag;
}
@Override
public boolean deleteStudent(int id, String name) throws SQLException, InvocationTargetException, IllegalAccessException {
boolean flag= studentDao.deleteStudent(id,name)!=0;
return flag;
}
@Override
public boolean updateStudent(int id, String name, int age, int gender, int score, String address) {
boolean flag= studentDao.updateStudent(id,name,age,gender,score,address)!=0;
return flag;
}
@Override
public List<Map<String, Object>> selectStudent(String name) {
List<Map<String, Object>> allStudent = null;
try {
allStudent = studentDao.selectStudent(name);
} catch (SQLException e) {
e.printStackTrace();
}
return allStudent;
}
}
7.3 controller层
创建selectStudentServlet类
@WebServlet("/selectStudent")
public class selectStudentServlet extends HttpServlet {
private final StudentService studentService = new StudentServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String name = req.getParameter("name");
List<Map<String, Object>> maps = studentService.selectStudent(name);
System.out.println(name);
String html = "" +
"" +
"" +
" " +
" 所有学生信息列表 " +
" " +
"" +
"" +
" "+
"" +
" " +
" ID " +
" Name " +
" Age " +
" ";
if (maps != null) {
for (Map<String, Object> map : maps) {
html += "" +
" " + map.get("id") + " " +
" " + map.get("name") + " " +
" " + map.get("age") + " " +
" ";
}
}
html += "
" +
"" +
"";
resp.getWriter().append(html);
}
}
这块和findAllStudent模块比较类似,只是加了一个条件参数name
7.4 前端代码
在webapp包下穿件selectStudent.xml文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>模糊查询</title>
<link rel="stylesheet" href="css/1.css">
</head>
<body>
<div style="text-align: center">
<div id="navbar" style="text-align: center">学生管理系统</div>
<form action="selectStudent" method="get">
<span >输入需要查询的姓名关键字</span>
<br>
<input type="text" name="name">
<br>
<input type="submit" value="查询">
</form>
</div>
</body>
</html>
7.5 测试
结语
增删改查,任何项目都离不开的功能,也是一切项目的基石,基石牢固了,房子才能盖得高,我们自己才能走得远。
你可能感兴趣的:(项目,java,servlet,学习,tomcat,数据库)