学生班级(双表)管理系统-增删改查—拓展—>网上书店项目的实现

学生班级(双表)管理系统 (参考版:以前文博客代码为基础)

1.1 标准思路:

在这里插入图片描述

1.2 代码目录:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

1.3 标准代码:

创建表:

#创建班级表
create table classInfo
(
    classId int primary key auto_increment,
    className varchar(20)
)

    insert into classInfo
(className)
select 'AAA01' UNION
select 'AAA02' UNION
select 'AAA03'

    insert into classInfo
(className)
select 'AAA04' UNION
select 'AAA05' UNION
select 'AAA06' UNION
select 'AAA07'

select * from classInfo

drop table studentInfo

    #创建学生信息表
create table studentInfo
(
    studentId int primary key auto_increment,
    name varchar(20),
    sex char(1),
    birthday date,
    tall decimal(3,2),
    classId int
)

    insert into studentInfo
(name,sex,birthday,tall,classId)
select '张三','男','2001-01-01',1.7,1 union
select '李四','女','2002-01-01',1.7,2

select * from studentInfo

BaseDAO:

package com.util;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseDAO {

	//四大金刚
	//驱动类
	private static final String DRIVER="com.mysql.cj.jdbc.Driver";
	//连接地址
	private static final String URL="jdbc:mysql://localhost:3306/0801_db?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
	//用户名
	private static final String USER="root";
	//密码
	private static final String PASSWORD="123456";

	//获取连接
	public static Connection getConnection(){

		Connection con = null;

		try{
			//加载驱动类
			Class.forName(DRIVER);
			//获取连接
			con = DriverManager.getConnection(URL,USER,PASSWORD);
			
		}catch(Exception ex){
			ex.printStackTrace();
		}

		return con;
	}

	//关闭数据库对象
	public static void closeAll(Connection con,Statement st,ResultSet rs){
		
		if(rs!=null){
			try{
				rs.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

		if(st!=null){

			try{
				st.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

		if(con!=null){
			try{
				con.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

	}


	//通用设置参数方法
	public static void setParams(PreparedStatement pst,Object[] params){

		if(params==null){
			return;
		}

		for(int i=0;i<params.length;i++){
			try{
				pst.setObject(i+1,params[i]);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
	}


	//通用增删改
	public static int executeUpdate(String sql,Object[] params){

		Connection con = null;
		PreparedStatement pst = null;
		
		int res = -1;
		
		try{

			//获取连接
			con = getConnection();
			//创建预编译命令执行对象
			pst = con.prepareStatement(sql);
			//设置参数
			setParams(pst,params);
			//执行
			res = pst.executeUpdate();

		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			closeAll(con,pst,null);
		}
		
		return res;
	}


	//通用查询
	public static List<Map<String,Object>> executeQuery(String sql,Object[] params) {

		List<Map<String,Object>> rows = new ArrayList<>();

		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;

		try{
			//获取连接	
			con = getConnection();			
			//获取命令对象
			pst = con.prepareStatement(sql);
			//设置参数
			setParams(pst,params);
			//执行查询
			rs = pst.executeQuery();

			//通过rs获取结果集的结构信息
			ResultSetMetaData rsmd =  rs.getMetaData();
			//获取结果集的列数
			int colCount = rsmd.getColumnCount();

			//遍历查询结果,并封装到List<Map>中
			while(rs.next()){
				//用Map存储当前行的各个列数据
				Map<String,Object> map = new HashMap<>();
				//循环获取每一列的信息
				for(int i=1;i<=colCount;i++){
					//获取列名(使用rsmd)
					String colName = rsmd.getColumnLabel(i);
					//获取列值(使用rs)
					Object colVal = rs.getObject(i);
					//将当前列存储到map中
					map.put(colName,colVal);								
				}
				
				//将遍历的当前行的数据存储到List中
				rows.add(map);
							
			}


		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			closeAll(con,pst,rs);
		}
		
		return rows;

	}

}

StudentInfo:

package com.entity;

import java.util.Date;

/**
 * @author: hy
 * @create: 2022-08-01 10:01:14
 */
public class StudentInfo {
    private Integer studentId;
    private String name;
    private String sex;
    private Date birthday;
    private Double tall;

    public StudentInfo() {
    }

    public StudentInfo(Integer studentId, String name, String sex, Date birthday, Double tall) {
        this.studentId = studentId;
        this.name = name;
        this.sex = sex;
        this.birthday = birthday;
        this.tall = tall;
    }

    public StudentInfo(String name, String sex, Date birthday, Double tall) {
        this.name = name;
        this.sex = sex;
        this.birthday = birthday;
        this.tall = tall;
    }

    public Integer getStudentId() {
        return studentId;
    }

    public void setStudentId(Integer studentId) {
        this.studentId = studentId;
    }

    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 Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Double getTall() {
        return tall;
    }

    public void setTall(Double tall) {
        this.tall = tall;
    }

    @Override
    public String toString() {
        return "StudentInfo{" +
                "studentId=" + studentId +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", birthday=" + birthday +
                ", tall=" + tall +
                '}';
    }
}

ClassInfo:

package com.entity;

/**
 * @author: hy
 * @create: 2022-08-01 10:52:43
 */
public class ClassInfo {
    private Integer classId;
    private String className;

    public ClassInfo() {
    }

    public ClassInfo(Integer classId, String className) {
        this.classId = classId;
        this.className = className;
    }

    public ClassInfo(String className) {
        this.className = className;
    }

    public Integer getClassId() {
        return classId;
    }

    public void setClassId(Integer classId) {
        this.classId = classId;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    @Override
    public String toString() {
        return "ClassInfo{" +
                "classId=" + classId +
                ", className='" + className + '\'' +
                '}';
    }
}

IStudentInfoDAO:

package com.dao;

import java.util.List;
import java.util.Map;

/**
 * 数据访问层接口
 */
public interface IStudentInfoDAO {
    List<Map<String,Object>> listAll();
}

StudentInfoDAOImpl:

package com.dao.impl;

import com.dao.IStudentInfoDAO;
import com.util.BaseDAO;

import java.util.List;
import java.util.Map;

/**
 * 数据访问层实现类
 * @author: hy
 * @create: 2022-08-01 10:03:24
 */
public class StudentInfoDAOImpl implements IStudentInfoDAO {
    /**
     * 数据查询
     * @return
     */
    @Override
    public List<Map<String, Object>> listAll() {
        String sql = "select studentId,name,sex,birthday,tall " +
                "     from studentInfo ";
        return BaseDAO.executeQuery(sql,null);
    }
}

IClassInfoDAO:

package com.dao;

import com.entity.ClassInfo;

import java.util.List;
import java.util.Map;

public interface IClassInfoDAO {
    /**
     * 查询所有
     * @return
     */
    List<Map<String,Object>> listAll();
    ClassInfo getByClassId(Integer classId);

    int insert(ClassInfo classInfo);
    int update(ClassInfo classInfo);
    int delete(Integer classId);
}

ClassInfoDAOImpl:

package com.dao.impl;

import com.dao.IClassInfoDAO;
import com.entity.ClassInfo;
import com.util.BaseDAO;

import java.util.List;
import java.util.Map;

/**
 * @author: hy
 * @create: 2022-08-01 10:54:26
 */
public class ClassInfoDAOImpl implements IClassInfoDAO {
    @Override
    public List<Map<String, Object>> listAll() {
        String sql ="select classId,className from classInfo ";
        return BaseDAO.executeQuery(sql,null);
    }

    /**
     * 根据编号查询数据对象
     * @param classId
     * @return
     */
    @Override
    public ClassInfo getByClassId(Integer classId) {
        String sql ="select classId,className from classInfo " +
                "    where classId = ? ";
        Object[] params = {classId};
        List<Map<String,Object>> rows = BaseDAO.executeQuery(sql,params);
        if(rows.size()>0){
            Map<String,Object> map = rows.get(0);
            ClassInfo c = new ClassInfo(
                    (Integer)map.get("classId"),
                    (String)map.get("className")
            );
            System.out.println(c);
            return c;
        }
        return null;
    }

    @Override
    public int insert(ClassInfo classInfo) {
        String sql = "insert into classInfo" +
                "     (className)" +
                "     values" +
                "     (?)";
        Object[] params = {classInfo.getClassName()};
        return BaseDAO.executeUpdate(sql,params);
    }

    @Override
    public int update(ClassInfo classInfo) {
        String sql = "update classInfo " +
                "     set className = ? " +
                "     where classId = ? ";
        Object[] params = {
                classInfo.getClassName(),
                classInfo.getClassId()
        };
        return BaseDAO.executeUpdate(sql,params);
    }

    @Override
    public int delete(Integer classId) {
        String sql = "delete from classInfo where classId = ? ";
        Object[] params = {classId};
        return BaseDAO.executeUpdate(sql,params);
    }
}

IStudentInfoService:

package com.service;

import java.util.List;
import java.util.Map;

/**
 * 业务层接口
 */
public interface IStudentInfoService {
    /**
     * 查询所有数据
     * @return
     */
    List<Map<String,Object>> listAll();
}

StudentInfoServiceImpl:

package com.service.impl;

import com.dao.IStudentInfoDAO;
import com.dao.impl.StudentInfoDAOImpl;
import com.service.IStudentInfoService;

import java.util.List;
import java.util.Map;

/**
 * 业务层实现类
 * @author: hy
 * @create: 2022-08-01 10:06:56
 */
public class StudentInfoServiceImpl implements IStudentInfoService {
    /**
     * 创建数据访问层对象
     */
    private IStudentInfoDAO studentInfoDAO = new StudentInfoDAOImpl();
    /**
     * 查询实现方法
     * @return
     */
    @Override
    public List<Map<String, Object>> listAll() {
        return studentInfoDAO.listAll();
    }
}

IClassInfoService:

package com.service;

import com.entity.ClassInfo;

import java.util.List;
import java.util.Map;

public interface IClassInfoService {
    //查询所有班级数据
    List<Map<String,Object>> listAll();
    //根据编号查询班级对象
    ClassInfo getByClassId(Integer classId);
    int insert(ClassInfo classInfo);
    int update(ClassInfo classInfo);
    int delete(Integer classId);
}

ClassInfoServiceImpl:

package com.service.impl;

import com.dao.IClassInfoDAO;
import com.dao.impl.ClassInfoDAOImpl;
import com.entity.ClassInfo;
import com.service.IClassInfoService;

import java.util.List;
import java.util.Map;

/**
 * @author: hy
 * @create: 2022-08-01 10:55:41
 */
public class ClassInfoServiceImpl implements IClassInfoService {
    //数据访问层对象
    private IClassInfoDAO classInfoDAO = new ClassInfoDAOImpl();
    @Override
    public List<Map<String, Object>> listAll() {
        return classInfoDAO.listAll();
    }

    @Override
    public ClassInfo getByClassId(Integer classId) {
        return classInfoDAO.getByClassId(classId);
    }

    @Override
    public int insert(ClassInfo classInfo) {
        return classInfoDAO.insert(classInfo);
    }

    @Override
    public int update(ClassInfo classInfo) {
        return classInfoDAO.update(classInfo);
    }

    @Override
    public int delete(Integer classId) {
        return classInfoDAO.delete(classId);
    }
}

StudentInfoServlet:

package com.servlet;

import com.service.impl.StudentInfoServiceImpl;
import com.service.IStudentInfoService;

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 java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author: hy
 * @create: 2022-08-01 10:09:19
 */
@WebServlet(urlPatterns = "/StudentInfoServlet")
public class StudentInfoServlet extends HttpServlet {

    //定义业务对象
    IStudentInfoService studentInfoService = new StudentInfoServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //查询数据
        List<Map<String,Object>> studentList = studentInfoService.listAll();
        //设置数据
        req.setAttribute("studentList",studentList);
        //转发到页面
        req.getRequestDispatcher("/studentList.jsp").forward(req,resp);

    }
}

ClassInfoServlet:

package com.servlet;

import com.entity.ClassInfo;
import com.service.IClassInfoService;
import com.service.impl.ClassInfoServiceImpl;

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 java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author: hy
 * @create: 2022-08-01 10:57:07
 */
@WebServlet(urlPatterns = "/ClassInfoServlet/*")
public class ClassInfoServlet extends HttpServlet {
    //定义业务层对象
    IClassInfoService classInfoService = new ClassInfoServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求和响应对象的编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //获取请求路径,截取请求处理的字符串
        //  uri: /lesson0801_crud/ClassInfoServlet/query
        String uri = req.getRequestURI();
        // process: query
        String process = uri.substring(uri.lastIndexOf("/")+1);

        //针对增删改查的请求做处理
        switch (process){
            case "query":
                this.query(req,resp); //查询处理
                break;
            case "toAdd":
                this.toAdd(req,resp); //跳转到添加
                break;
            case "add":
                this.add(req,resp); //添加处理
                break;
            case "toUpdate":
                this.toUpdate(req,resp);//跳转到修改
                break;
            case "update":
                this.update(req,resp);//修改处理
                break;
            case "delete":
                this.delete(req,resp); //删除处理
                break;
        }


    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取班级编号
        Integer classId = Integer.parseInt(req.getParameter("classId"));
        int count = classInfoService.delete(classId);
        if(count==1){
            //删除成功,重新显示
            this.query(req,resp);
        }else{
            //失败,跳转到失败页面
        }
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取提交的表单数据
        Integer classId = Integer.parseInt(req.getParameter("classId"));
        String className = req.getParameter("className");
        ClassInfo classInfo = new ClassInfo(classId,className);
        //调用修改
        int count = classInfoService.update(classInfo);
        if(count==1){
            //修改成功,则重新显示
            this.query(req,resp);
        }else{
            //跳转到失败
        }

    }

    private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取要修改的编号:如果此时没有获取到编号,会爆出数字格式异常
        System.out.println("classId:"+req.getParameter("classId"));
        Integer classId = Integer.parseInt(req.getParameter("classId"));
        //根据编号,查询要修改的班级对象
        ClassInfo classInfo =  classInfoService.getByClassId(classId);
        //将要修改的班级对象,存储到request中,带到页面上,呈现出来
        req.setAttribute("classInfo",classInfo);
        //跳转到修改页面
        req.getRequestDispatcher("/classUpdate.jsp").forward(req,resp);
    }

    /**
     * 添加班级数据
     * @param req
     * @param resp
     */
    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取添加页面提交的数据
        String className = req.getParameter("className");
        ClassInfo ci = new ClassInfo(className);
        //构建班级对象
        int count = classInfoService.insert(ci);

        if(count==1){
            //添加成功,跳转到查询页面
            //resp.sendRedirect(req.getContextPath()+"/ClassInfoServlet/query");
            //直接调用查询逻辑
            this.query(req,resp);
        }else{
            //跳转到失败页面
            System.out.println("添加记录不等于1,失败了......");
        }
    }

    /**
     * 跳转到添加页面
     * @param req
     * @param resp
     */
    private void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/classAdd.jsp").forward(req,resp);
    }

    /**
     * 查询处理
     * @param req
     * @param resp
     */
    private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Map<String,Object>> classInfoList = classInfoService.listAll();
        req.setAttribute("classInfoList",classInfoList);
        req.getRequestDispatcher("/classList.jsp").forward(req,resp);
    }
}

studentList.jsp:

<%--
  Created by IntelliJ IDEA.
  User: henry
  Date: 2022/8/1
  Time: 10:13
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    el:只负责数据的显示
    jstl: 分支,循环<br/>
    ${studentList}
    <hr/>
    <table border="1" align="center">
        <tr>
            <th>学号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>生日</th>
            <th>身高</th>
        </tr>
        <!--items:数据集合
            注意:items关联的一定是个对象集合(el表达式),不是纯粹的字符串
            var:用于定义变量名字,临时存储遍历集合中的某个对象
        -->
        <c:forEach items="${studentList}" var="stu">
        <tr>
            <td>${stu.studentId}</td>
            <td>${stu.name}</td>
            <td>${stu.sex}</td>
            <td>${stu.birthday}</td>
            <td>${stu.tall}</td>
        </tr>
        </c:forEach>


    </table>
</body>
</html>

index.jsp:

<%--
  Created by IntelliJ IDEA.
  User: henry
  Date: 2022/8/1
  Time: 9:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <a href="${pageContext.request.contextPath}/StudentInfoServlet">学生信息</a>
    <a href="${pageContext.request.contextPath}/ClassInfoServlet/query">班级信息</a>
  </body>
</html>

classList.jsp:

<%--
  Created by IntelliJ IDEA.
  User: henry
  Date: 2022/8/1
  Time: 10:58
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    班级数据:${classInfoList}
    <hr/>
    <table border="1" align="center">
        <tr>
            <td colspan="3">
                <a href="${pageContext.request.contextPath}/ClassInfoServlet/toAdd">添加</a>
            </td>
        </tr>
        <tr>
            <th>班级编号</th>
            <th>班级名称</th>
            <th>操作</th>
        </tr>
        <!--items:数据集合
            注意:items关联的一定是个对象集合(el表达式),不是纯粹的字符串
            var:用于定义变量名字,临时存储遍历集合中的某个对象
        -->
        <c:forEach items="${classInfoList}" var="c">
            <tr>
                <td>${c.classId}</td>
                <td>${c.className}</td>
                <td>
                    <a href="${pageContext.request.contextPath}/ClassInfoServlet/toUpdate?classId=${c.classId}">修改</a>
                    <a href="${pageContext.request.contextPath}/ClassInfoServlet/delete?classId=${c.classId}"
                       onclick="return confirm('确定要删除么?')">
                        删除
                    </a>
                </td>
            </tr>
        </c:forEach>
    </table>

</body>
</html>

classAdd.jsp:

<%--
  Created by IntelliJ IDEA.
  User: henry
  Date: 2022/8/1
  Time: 11:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form method="post" action="${pageContext.request.contextPath}/ClassInfoServlet/add">
        <table border="1" align="center">
            <tr>
                <td>班级名称</td>
                <td>
                    <input type="text" name="className"/>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="添加"/>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

classUpdate.jsp:

<%--
  Created by IntelliJ IDEA.
  User: henry
  Date: 2022/8/1
  Time: 11:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    ${classInfo}
    <hr/>
    <form method="post" action="${pageContext.request.contextPath}/ClassInfoServlet/update">
        <table border="1" align="center">
            <!--type=hidden : 隐藏文本框-->
            <input type="hidden" name="classId" value="${classInfo.classId}"/>
            <tr>
                <td>班级名称</td>
                <td>
                    <input type="text" name="className" value="${classInfo.className}"/>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="修改"/>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

学生班级(双表)管理系统 (完整版)

标准思路:

在这里插入图片描述

创建数据库:

在这里插入图片描述

创建数据表:

在这里插入图片描述

页面实现效果:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

控制台结果展示:

在这里插入图片描述

导包(略,后面会写一个完整的博文)

在这里插入图片描述

代码目录整体布局:

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

代码部分:

创建数据库:

#创建数据库
create database 70730_db
default character set utf8mb4 #设置字符集
default collate utf8mb4_general_ci #设置排序规则 

创建数据表:

#创建学生表
create table student
(
	stuId int primary key auto_increment,
	stuName varchar(20),
	stuSex varchar(2),
	stuBirthday date,
	stuTall int
);


select * from student;

insert into student
(stuName,stuSex,stuBirthday,stuTall)
values
('张三','男','1998-09-09',170),
('李四','女','2008-08-08',180);

#创建班级表
create table class
(
	classId int primary key auto_increment,
	className varchar(20)
);

insert into class
(className)
values 
('菜鸟1班'),
('菜鸟2班');

select * from class;

BaseDAO:

package com.util;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseDAO {

	//四大金刚
	//驱动类
	private static final String DRIVER="com.mysql.cj.jdbc.Driver";
	//连接地址
	private static final String URL="jdbc:mysql://localhost:3306/70730_db?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
	//用户名
	private static final String USER="root";
	//密码
	private static final String PASSWORD="123456";

	//获取连接
	public static Connection getConnection(){

		Connection con = null;

		try{
			//加载驱动类
			Class.forName(DRIVER);
			//获取连接
			con = DriverManager.getConnection(URL,USER,PASSWORD);
			
		}catch(Exception ex){
			ex.printStackTrace();
		}

		return con;
	}

	//关闭数据库对象
	public static void closeAll(Connection con,Statement st,ResultSet rs){
		
		if(rs!=null){
			try{
				rs.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

		if(st!=null){

			try{
				st.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

		if(con!=null){
			try{
				con.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

	}


	//通用设置参数方法
	public static void setParams(PreparedStatement pst,Object[] params){

		if(params==null){
			return;
		}

		for(int i=0;i<params.length;i++){
			try{
				pst.setObject(i+1,params[i]);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
	}


	//通用增删改
	public static int executeUpdate(String sql,Object[] params){

		Connection con = null;
		PreparedStatement pst = null;
		
		int res = -1;
		
		try{

			//获取连接
			con = getConnection();
			//创建预编译命令执行对象
			pst = con.prepareStatement(sql);
			//设置参数
			setParams(pst,params);
			//执行
			res = pst.executeUpdate();

		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			closeAll(con,pst,null);
		}
		
		return res;
	}


	//通用查询
	public static List<Map<String,Object>> executeQuery(String sql,Object[] params) {

		List<Map<String,Object>> rows = new ArrayList<>();

		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;

		try{
			//获取连接	
			con = getConnection();			
			//获取命令对象
			pst = con.prepareStatement(sql);
			//设置参数
			setParams(pst,params);
			//执行查询
			rs = pst.executeQuery();

			//通过rs获取结果集的结构信息
			ResultSetMetaData rsmd =  rs.getMetaData();
			//获取结果集的列数
			int colCount = rsmd.getColumnCount();

			//遍历查询结果,并封装到List<Map>中
			while(rs.next()){
				//用Map存储当前行的各个列数据
				Map<String,Object> map = new HashMap<>();
				//循环获取每一列的信息
				for(int i=1;i<=colCount;i++){
					//获取列名(使用rsmd)
					String colName = rsmd.getColumnLabel(i);
					//获取列值(使用rs)
					Object colVal = rs.getObject(i);
					//将当前列存储到map中
					map.put(colName,colVal);								
				}
				
				//将遍历的当前行的数据存储到List中
				rows.add(map);
							
			}


		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			closeAll(con,pst,rs);
		}
		
		return rows;

	}

}

Student:

package com.entity;

import java.util.Date;

public class Student {
    private Integer stuId;
    private String stuName;
    private String stuSex;
    private Date stuBirthday;
    private Integer stuTall;
//    stuId,stuName,stuSex,stuBirthday,stuTall

    public Student() {
    }

    public Student(Integer stuId, String stuName, String stuSex, Date stuBirthday, Integer stuTall) {
        this.stuId = stuId;
        this.stuName = stuName;
        this.stuSex = stuSex;
        this.stuBirthday = stuBirthday;
        this.stuTall = stuTall;
    }

    public Student(String stuName, String stuSex, Date stuBirthday, Integer stuTall) {
        this.stuName = stuName;
        this.stuSex = stuSex;
        this.stuBirthday = stuBirthday;
        this.stuTall = stuTall;
    }

    public Integer getStuId() {
        return stuId;
    }

    public void setStuId(Integer stuId) {
        this.stuId = stuId;
    }

    public String getStuName() {
        return stuName;
    }

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

    public String getStuSex() {
        return stuSex;
    }

    public void setStuSex(String stuSex) {
        this.stuSex = stuSex;
    }

    public Date getStuBirthday() {
        return stuBirthday;
    }

    public void setStuBirthday(Date stuBirthday) {
        this.stuBirthday = stuBirthday;
    }

    public Integer getStuTall() {
        return stuTall;
    }

    public void setStuTall(Integer stuTall) {
        this.stuTall = stuTall;
    }

    @Override
    public String toString() {
        return "Student{" +
                "stuId=" + stuId +
                ", stuName='" + stuName + '\'' +
                ", stuSex='" + stuSex + '\'' +
                ", stuBirthday=" + stuBirthday +
                ", stuTall=" + stuTall +
                '}';
    }
}

ClassInfo:

package com.entity;

public class ClassInfo {
    private Integer classId;
    private String className;

    public ClassInfo() {
    }

    public ClassInfo(String className) {
        this.className = className;
    }

    public ClassInfo(Integer classId, String className) {
        this.classId = classId;
        this.className = className;
    }

    public Integer getClassId() {
        return classId;
    }

    public void setClassId(Integer classId) {
        this.classId = classId;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    @Override
    public String toString() {
        return "Class{" +
                "classId=" + classId +
                ", className='" + className + '\'' +
                '}';
    }
}

IStudentsDAO:

package com.dao;

import java.util.List;
import java.util.Map;

public interface IStudentsDAO {
    List<Map<String,Object>> listAll();
}

StudentsDAOImpl:

package com.dao.impl;

import com.dao.IStudentsDAO;
import com.util.BaseDAO;

import java.util.List;
import java.util.Map;

public class StudentsDAOImpl implements IStudentsDAO {
    @Override
    public List<Map<String, Object>> listAll() {
        String sql="select * from student";
        return BaseDAO.executeQuery(sql,null);
    }
}

IClassDAO:

package com.dao;

import com.entity.ClassInfo;

import java.util.List;
import java.util.Map;

public interface IClassDAO {
    List<Map<String,Object>> listAll();
    ClassInfo getByClassId(Integer classId);

    int insert(ClassInfo classInfo);
    int update(ClassInfo classInfo);
    int delete(Integer classId);
}

ClassDAOImpl:

package com.dao.impl;

import com.dao.IClassDAO;
import com.entity.ClassInfo;
import com.util.BaseDAO;

import java.util.List;
import java.util.Map;

public class ClassDAOImpl implements IClassDAO {
    @Override
    public ClassInfo getByClassId(Integer classId) {
        String sql="select classId,className from class"+
                "   where classId=?";
        Object[] params={classId};
        List<Map<String,Object>> rows = BaseDAO.executeQuery(sql,params);
        if(rows.size()>0){
            Map<String,Object> map= rows.get(0);

            ClassInfo classInfo=new ClassInfo(
                    (Integer) map.get("classId"), //注意强转化 get得到的是Object类型(鼠标放在get上看)
                    (String) map.get("className")
            );
            System.out.println(classInfo);
            return classInfo;
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> listAll() {
        String sql="select * from class";
        return BaseDAO.executeQuery(sql,null);
    }

    @Override
    public int insert(ClassInfo classInfo) {
        String sql="insert into class"+
                "   (className)"+
                "   values"+
                "   (?)";
        Object[] params={classInfo.getClassName()};
        return BaseDAO.executeUpdate(sql,params);
    }

    @Override
    public int update(ClassInfo classInfo) {
        String sql="update class"+
                "   set className=?"+
                "   where classId=?";
        Object[] params={
                classInfo.getClassName(),
                classInfo.getClassId()
        };
        return BaseDAO.executeUpdate(sql,params);
    }

    @Override
    public int delete(Integer classId) {
        String sql="delete from class"+  //注意delete写法
                "   where classId=?";
        Object[] params={classId};
        return BaseDAO.executeUpdate(sql,params);
    }
}

IStudentsService:

package com.service;

import java.util.List;
import java.util.Map;

public interface IStudentsService {
    List<Map<String,Object>> listAll();
}

StudentsServiceImpl:

package com.service.impl;

import com.dao.IStudentsDAO;
import com.dao.impl.StudentsDAOImpl;
import com.service.IStudentsService;

import java.util.List;
import java.util.Map;

public class StudentsServiceImpl implements IStudentsService {
    IStudentsDAO studentsDAO=new StudentsDAOImpl();
    @Override
    public List<Map<String, Object>> listAll() {
        return studentsDAO.listAll();
    }
}

IClassService:

package com.service;

import com.entity.ClassInfo;

import java.util.List;
import java.util.Map;

public interface IClassService {
    List<Map<String,Object>> listAll();
    ClassInfo getByClassId(Integer classId);

    int insert(ClassInfo classInfo);
    int update(ClassInfo classInfo);
    int delete(Integer classId);
}

ClassServiceImpl:

package com.service.impl;

import com.dao.IClassDAO;
import com.dao.impl.ClassDAOImpl;
import com.entity.ClassInfo;
import com.service.IClassService;

import java.util.List;
import java.util.Map;

public class ClassServiceImpl implements IClassService {
    IClassDAO classDAO=new ClassDAOImpl();

    @Override
    public ClassInfo getByClassId(Integer classId) {
        return classDAO.getByClassId(classId);
    }

    @Override
    public List<Map<String, Object>> listAll() {
        return classDAO.listAll();
    }

    @Override
    public int insert(ClassInfo classInfo) {
        return classDAO.insert(classInfo);
    }

    @Override
    public int update(ClassInfo classInfo) {
        return classDAO.update(classInfo);
    }

    @Override
    public int delete(Integer classId) {
        return classDAO.delete(classId);
    }
}

StudentInfoServlet:

package com.servlet;

import com.service.IStudentsService;
import com.service.impl.StudentsServiceImpl;

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 java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/StudentInfoServlet")
public class StudentInfoServlet extends HttpServlet {
    IStudentsService studentsService=new StudentsServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        List<Map<String,Object>> studentsList=studentsService.listAll();
        req.setAttribute("studentsList",studentsList);
        req.getRequestDispatcher("/studentsList.jsp").forward(req,resp);
    }
}

ClassInfoServlet:

package com.servlet;

import com.entity.ClassInfo;
import com.service.IClassService;
import com.service.impl.ClassServiceImpl;

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 java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/ClassInfoServlet/*")
public class ClassInfoServlet extends HttpServlet {
    IClassService classService=new ClassServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        String uri=req.getRequestURI();
        String process=uri.substring(uri.lastIndexOf("/")+1);
        System.out.println("截取字段:"+process);

        switch (process){
            case "query":
                this.query(req,resp);
                break;
            case "toAdd":
                this.toAdd(req,resp);
                break;
            case "add":
                this.add(req,resp);
                break;
            case "toUpdate":
                this.toUpdate(req,resp);
                break;
            case "update":
                this.update(req,resp);
                break;
            case "delete":
                this.delete(req,resp);
                break;
        }
    }

    private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Map<String,Object>> classList=classService.listAll();

        req.setAttribute("classList",classList);
        req.getRequestDispatcher("/classList.jsp").forward(req,resp);
    }

    private void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/classAdd.jsp").forward(req,resp);
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String className=req.getParameter("className"); //注意 设置值关键字 从输入框获取值的关键字
        ClassInfo ci=new ClassInfo(className);

        int count=classService.insert(ci);

        if(count==1){
            System.out.println("插入成功!");
            this.query(req,resp);
        }else{
            System.out.println("插入失败!");
        }
    }

    private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer classId = Integer.parseInt(req.getParameter("classId"));
        //根据编号,查询要修改的班级对象
        ClassInfo classInfo =  classService.getByClassId(classId);
        //将要修改的班级对象,存储到request中,带到页面上,呈现出来
        req.setAttribute("classInfo",classInfo);
        //跳转到修改页面
        req.getRequestDispatcher("/classUpdate.jsp").forward(req,resp);

        req.setAttribute("classInfo",classInfo);
        req.getRequestDispatcher("/classUpdate.jsp").forward(req,resp);
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer classId = Integer.parseInt(req.getParameter("classId"));
        String className = req.getParameter("className");
        ClassInfo classInfo = new ClassInfo(classId,className);
        //调用修改
        int count = classService.update(classInfo);
        if(count==1){
            //修改成功,则重新显示
            this.query(req,resp);
        }else{
            //跳转到失败
        }

    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer classId= Integer.parseInt(req.getParameter("classId"));
        int count =classService.delete(classId);
        if(count==1){
            System.out.println("删除成功!");
            this.query(req,resp);
        }else{
            System.out.println("删除失败!");
        }
    }



}

index.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 33154
  Date: 2022/8/1
  Time: 20:26
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  $END$
  <a href="${pageContext.request.contextPath}/StudentInfoServlet ">学生信息</a>
  <a href="${pageContext.request.contextPath}/ClassInfoServlet/query">班级信息</a>
 
  </body>
</html>

studentsList.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 33154
  Date: 2022/8/1
  Time: 20:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
    <%=request.getAttribute("studentsList")%>
    <hr/>
</head>
<body>
    ${studentsList}
    <table border="1" align="center">
        <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>生日</th>
            <th>身高</th>
        </tr>
        <c:forEach items="${studentsList}" var="stu">
            <tr>
                <td>${stu.stuId}</td>
                <td>${stu.stuName}</td>
                <td>${stu.stuSex}</td>
                <td>${stu.stuBirthday}</td>
                <td>${stu.stuTall}</td>
            </tr>
        </c:forEach>
    </table>

</body>
</html>

classList.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 33154
  Date: 2022/8/2
  Time: 1:18
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
    <%=request.getAttribute("classList")%>
</head>
<body>
    班级数据:${classList}
    <hr/>
    <table border="1" align="center">
        <tr>
            <td colspan="3">
                <a href="${pageContext.request.contextPath}/ClassInfoServlet/toAdd">添加</a>
            </td>
        </tr>
        <tr>
            <th>班级编号</th>
            <th>班级名称</th>
            <th>操作</th>
        </tr>
        <c:forEach items="${classList}" var="clas">
            <tr>
                <td>${clas.classId}</td>
                <td>${clas.className}</td>
                <td>
                    <a href="${pageContext.request.contextPath}/ClassInfoServlet/toUpdate?classId=${clas.classId}">修改</a>
                    <a href="${pageContext.request.contextPath}/ClassInfoServlet/delete?classId=${clas.classId}"
                    onclick="return confirm('你确定要删除吗?')">
                        删除
                    </a>
                </td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

classAdd.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 33154
  Date: 2022/8/2
  Time: 2:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/ClassInfoServlet/add" method="post">
        <table border="1" align="center">
            <tr>
                <td>班级名称</td>
                <td>
                    <input type="text" name="className"/>
                </td>
                <td>
                    <input type="submit" value="添加"/>
                </td>
            </tr>
        </table>
    </form>

</body>
</html>

classUpdate.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 33154
  Date: 2022/8/2
  Time: 2:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    ${classInfo}
    <hr/>

    <form method="post" action="${pageContext.request.contextPath}/ClassInfoServlet/update">
        <table border="1" align="center">
            <input type="hidden" name="classId" value="${classInfo.classId}" />
            <tr>
                <td>班级名称</td>
                <td>
                    <input type="text" name="className" value="${classInfo.className}" />
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="修改"/>
                </td>
            </tr>

        </table>

    </form>

    <from method>

    </from>

</body>
</html>

// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值