作业管理系统实现

2022-11-30 20:28:31 浏览数 (1)

2.6系统实现 2.6.1JavaEE 实现 —— MVC 模式 DBCP.java——数据库连接池

实现代码如下:

代码语言:javascript复制
package com.javaEE.code.class12;

import org.apache.commons.dbcp.BasicDataSource;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

// Database Connection Pool
public class DBCP {

    // 数据库连接池
    private static BasicDataSource dbcp;

    //为不同线程管理连接
    private static ThreadLocal<Connection> tl;

    //通过配置文件来获取数据库参数
    static {
        try {
            Properties properties = new Properties();

            InputStream inputStream = DBCP.class.getClassLoader().getResourceAsStream("com/javaEE/code/class12/Application.properties");

            properties.load(inputStream);
            inputStream.close();

            // 初始化连接池
            dbcp = new BasicDataSource();

            // 数据库驱动 (Class.forName())
            dbcp.setDriverClassName(properties.getProperty("driverName"));
            // 数据库url
            dbcp.setUrl(properties.getProperty("dbUrl"));
            // 数据库用户名
            dbcp.setUsername(properties.getProperty("userName"));
            // 数据库密码
            dbcp.setPassword(properties.getProperty("password"));
            // 初始化连接数量
            dbcp.setInitialSize(Integer.parseInt(properties.getProperty("initSize")));
            // 连接池允许的最大连接数
            dbcp.setMaxActive(Integer.parseInt(properties.getProperty("maxActive")));
            // 最大等待时间
            dbcp.setMaxWait(Integer.parseInt(properties.getProperty("maxWait")));
            // 最小空闲数
            dbcp.setMinIdle(Integer.parseInt(properties.getProperty("minIdle"))            );
            // 最大空闲数
            dbcp.setMaxIdle(Integer.parseInt(properties.getProperty("maxIdle")));
            // 初始化线程本地
            tl = new ThreadLocal<Connection>();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 通过连接池获取一个连接
    public static Connection getConnection() throws SQLException {
        Connection conn = dbcp.getConnection();
        tl.set(conn);
        return conn;
    }

    // 归还连接,未关闭
    public static void closeConnection() {
        try {
            Connection conn = tl.get();
            if (conn != null) {
                conn.close();
                tl.remove();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

2.6.2Model 层——实体类的实现 Homework.java 实现代码如下:

代码语言:javascript复制
package com.javaEE.code.class12.model;

import java.util.Date;

public class Homework {

    private Long id;

    private String homeworkTittle;

    private String homeworkContent;

    private Date createTime;

    private Date updateTime;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getHomeworkTittle() {
        return homeworkTittle;
    }

    public void setHomeworkTittle(String homeworkTittle) {
        this.homeworkTittle = homeworkTittle;
    }

    public String getHomeworkContent() {
        return homeworkContent;
    }

    public void setHomeworkContent(String homeworkContent) {
        this.homeworkContent = homeworkContent;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    @Override
    public String toString() {
        return "Homework{"  
                "id="   id  
                ", homeworkTittle='"   homeworkTittle   '''  
                ", homeworkContent='"   homeworkContent   '''  
                ", createTime="   createTime  
                ", updateTime="   updateTime  
                '}';
    }
}

Student.java
package com.javaEE.code.class12.model;

import java.util.Date;

public class Student {

    private Long id;

    private String name;

    private Date createTime;

    private Date updateTime;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    @Override
    public String toString() {
        return "Student{"  
                "id="   id  
                ", name='"   name   '''  
                ", createTime="   createTime  
                ", updateTime="   updateTime  
                '}';
    }
}

StudentHomework.java

代码语言:javascript复制
package com.javaEE.code.class12.model;

import java.util.Date;

public class StudentHomework {

    private Long id;

    private Long studentId;

    private Long homeworkId;

    private String homeworkTitle;

    private String homeworkContent;

    private Date createTime;

    private Date updateTime;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getStudentId() {
        return studentId;
    }

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

    public Long getHomeworkId() {
        return homeworkId;
    }

    public void setHomeworkId(Long homeworkId) {
        this.homeworkId = homeworkId;
    }

    public String getHomeworkTitle() {
        return homeworkTitle;
    }

    public void setHomeworkTitle(String homeworkTitle) {
        this.homeworkTitle = homeworkTitle;
    }

    public String getHomeworkContent() {
        return homeworkContent;
    }

    public void setHomeworkContent(String homeworkContent) {
        this.homeworkContent = homeworkContent;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    @Override
    public String toString() {
        return "StudentHomework{"  
                "id="   id  
                ", studentId="   studentId  
                ", homeworkId="   homeworkId  
                ", homeworkTitle='"   homeworkTitle   '''  
                ", homeworkContent='"   homeworkContent   '''  
                ", createTime="   createTime  
                ", updateTime="   updateTime  
                '}';
    }
}

Controller 层 ——对数据的操作 JDBC 类对数据进行直接操作 Servlet 类接收 Http 请求,对数据库进行相应操作,并返回结果集给 Viewer 层 StudentJDBC.java

代码语言:javascript复制
package com.javaEE.code.class12.jdbc;

import com.javaEE.code.class12.DBCP;
import com.javaEE.code.class12.model.Student;

import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class StudentJDBC {

    // 数据库连接
    private Connection connection = null;
    // 执行对象
    private PreparedStatement pstmt = null;

    // 查找所有记录
    public List<Student> selectAll() {
        // 定义 SQL 语句
        String sql = "SELECT * FROM s_student";
        System.out.println(sql);
        // 一条结果
        Student s = null;
        // 存储结果集
        List<Student> resultList = new ArrayList<>();
        try {
            // 获取连接
            connection = DBCP.getConnection();
            pstmt = connection.prepareStatement(sql);
            ResultSet resultSet = pstmt.executeQuery(sql);
            // 输出结果集
            while (resultSet.next()) {
                // 初始化一条结果
                s = new Student();
                s.setId(resultSet.getLong("id"));
                s.setName(resultSet.getString("name"));
                s.setCreateTime(resultSet.getTimestamp("create_time"));
                s.setUpdateTime(resultSet.getTimestamp("update_time"));
                resultList.add(s);
            }
            // 归还连接
            DBCP.closeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultList;
    }

    // 添加一条记录
    public void addStudent(Student s) {
        // 定义 SQL 语句
        // PreparedStatement
        String sql = "INSERT INTO s_student(id, name) VALUES (?, ?)";
        // 执行 SQL
        try {
            // 获取连接
            connection = DBCP.getConnection();
            pstmt = connection.prepareStatement(sql);
            pstmt.setLong(1, s.getId());
            pstmt.setString(2, s.getName());
            System.out.println(sql);
            pstmt.execute();
            // 归还连接
            DBCP.closeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 删除一条记录
    public void deleteStudent(Student s) {
        // 定义 SQL 语句
        // PreparedStatement
        String sql = "DELETE FROM s_student WHERE id=?";
        // 执行 SQL
        try {
            // 获取连接
            connection = DBCP.getConnection();
            pstmt = connection.prepareStatement(sql);
            pstmt.setLong(1, s.getId());
            System.out.println(sql);
            pstmt.execute();
            DBCP.closeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 更新一条记录
    public void updateStudent(Student s) {
        // 定义 SQL 语句
        // PreparedStatement
        String sql = "UPDATE s_student SET name=?, update_time=? WHERE id=?";
        //
        try {
            connection = DBCP.getConnection();
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, s.getName());
            pstmt.setTimestamp(2, new Timestamp(new Date().getTime()));
            pstmt.setLong(3, s.getId());
            System.out.println(sql);
            pstmt.execute();
            DBCP.closeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) {
//        StudentJDBC sJDBC = new StudentJDBC();
//        Student s = new Student();

    // To test addStudent(Student s)
//        s.setId(100L);
//        s.setName("ddd");
//        sJDBC.addStudent(s);

    // To test selectAll()
//        List<Student> list =  sJDBC.selectAll();
//        for(Student student : list)
//            System.out.println(student.getName());

    // To test deleteStudent(Student s)
//        s.setId(100L);
//        s.setName("ddd");
//        sJDBC.deleteStudent(s);

    // To test updateStudent(Student s)
//        s.setId(100L);
//        s.setName("dd");
//        sJDBC.updateStudent(s);

//        sJDBC.closeAll();
//    }
}

HomeworkJDBC.java

代码语言:javascript复制
package com.javaEE.code.class12.jdbc;

import com.javaEE.code.class12.DBCP;
import com.javaEE.code.class12.model.Homework;

import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class HomeworkJDBC {

    // 数据库连接
    private Connection connection = null;
    // 执行对象
    private PreparedStatement pstmt = null;

    // 查找所有记录
    public List<Homework> selectAll() {
        // 定义 SQL 语句
        String sql = "SELECT * FROM s_homework";
        System.out.println(sql);
        // 一条结果
        Homework h = null;
        // 存储结果集
        List<Homework> resultList = new ArrayList<>();
        try {
            // 获取连接
            connection = DBCP.getConnection();
            pstmt = connection.prepareStatement(sql);
            ResultSet resultSet = pstmt.executeQuery(sql);
            // 输出结果集
            while (resultSet.next()) {
                // 初始化一条结果
                h = new Homework();
                h.setId(resultSet.getLong("id"));
                h.setHomeworkTittle(resultSet.getString("title"));
                h.setHomeworkContent(resultSet.getString("content"));
                h.setCreateTime(resultSet.getTimestamp("create_time"));
                h.setUpdateTime(resultSet.getTimestamp("update_time"));
                resultList.add(h);
            }
            // 归还连接
            DBCP.closeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultList;
    }

    // 添加一条记录
    public void addHomework(Homework h) {
        // 定义 SQL 语句
        // PreparedStatement
        String sql = "INSERT INTO s_homework(title, content) VALUES (?, ?)";
        // 执行 SQL
        try {
            // 获取连接
            connection = DBCP.getConnection();
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, h.getHomeworkTittle());
            pstmt.setString(2, h.getHomeworkContent());
            System.out.println(sql);
            pstmt.execute();
            DBCP.closeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 删除一条记录
    public void deleteHomework(Homework h) {
        // 定义 SQL 语句
        // PreparedStatement
        String sql = "DELETE FROM s_homework WHERE id=?";
        // 执行 SQL
        try {
            // 获取连接
            connection = DBCP.getConnection();
            pstmt = connection.prepareStatement(sql);
            pstmt.setLong(1, h.getId());
            System.out.println(sql);
            pstmt.execute();
            // 归还连接
            DBCP.closeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 更新一条记录
    public void updateHomework(Homework h) {
        // 定义 SQL 语句
        // PreparedStatement
        String sql = "UPDATE s_homework SET title=?, content=?, update_time=? WHERE id=?";
        //
        try {
            // 获取连接
            connection = DBCP.getConnection();
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, h.getHomeworkTittle());
            pstmt.setString(2, h.getHomeworkContent());
            pstmt.setTimestamp(3, new Timestamp(new Date().getTime()));
            pstmt.setLong(4, h.getId());
            System.out.println(sql);
            pstmt.execute();
            // 归还连接
            DBCP.closeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) {
//        HomeworkJDBC hJDBC = new HomeworkJDBC();
//        Homework h = new Homework();

    // To test addHomework(Homework h)
//        h.setId(100L);
//        h.setHomeworkTittle("作业");
//        h.setHomeworkContent("www.github.com");
//        hJDBC.addHomework(h);

    // To test selectAll()
//        List<Homework> list = hJDBC.selectAll();
//        for (Homework homework : list)
//            System.out.println(homework.getHomeworkContent());

    // To test updateHomework(Homework h)
//        h.setId(100L);
//        h.setHomeworkTittle("测试作业");
//        h.setHomeworkContent("bjtu.edu.cn");
//        hJDBC.updateHomework(h);

    // To test deleteHomework(Homework h)
//        h.setId(100L);
//        hJDBC.deleteHomework(h);
//
//        hJDBC.closeAll();
//    }
}

StudentHomeworkJDBC.java

代码语言:javascript复制
package com.javaEE.code.class12.jdbc;

import com.javaEE.code.class12.DBCP;
import com.javaEE.code.class12.model.StudentHomework;

import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class StudentHomeworkJDBC {

    // 数据库连接
    private Connection connection = null;
    // 执行对象
    private PreparedStatement pstmt = null;

    // 查找所有记录
    public List<StudentHomework> selectAll() {

        // 定义 SQL 语句
        String sql = "SELECT * FROM s_student_homework";
        System.out.println(sql);
        // 一条结果
        StudentHomework sh = null;
        // 存储结果集
        List<StudentHomework> resultList = new ArrayList<>();
        try {
            // 获取连接
            connection = DBCP.getConnection();
            pstmt = connection.prepareStatement(sql);
            // 获取结果集
            ResultSet resultSet = pstmt.executeQuery(sql);
            // 输出结果集
            while (resultSet.next()) {
                // 初始化一条结果
                sh = new StudentHomework();
                sh.setId(resultSet.getLong("id"));
                sh.setStudentId(resultSet.getLong("student_id"));
                sh.setHomeworkId(resultSet.getLong("homework_id"));
                sh.setHomeworkTitle(resultSet.getString("homework_title"));
                sh.setHomeworkContent(resultSet.getString("homework_content"));
                sh.setCreateTime(resultSet.getTimestamp("create_time"));
                sh.setUpdateTime(resultSet.getTimestamp("update_time"));
                resultList.add(sh);
            }
            // 归还连接
            DBCP.closeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultList;
    }

    // 添加一条记录
    public void addStudentHomework(StudentHomework sh) {

        // 定义 SQL 语句
        // PreparedStatement
        String sql = "INSERT INTO s_student_homework(student_id, homework_id, homework_title, homework_content) VALUES (?, ?, ?, ?)";
        // 执行 SQL
        try {
            // 获取连接
            connection = DBCP.getConnection();
            pstmt = connection.prepareStatement(sql);
            pstmt.setLong(1, sh.getStudentId());
            pstmt.setLong(2, sh.getHomeworkId());
            pstmt.setString(3, sh.getHomeworkTitle());
            pstmt.setString(4, sh.getHomeworkContent());
            System.out.println(sql);
            pstmt.execute();
            // 归还连接
            DBCP.closeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 删除一条记录
    public void deleteStudentHomework(StudentHomework sh) {

        // 定义 SQL 语句
        // PreparedStatement
        String sql = "DELETE FROM s_student_homework WHERE id=?";
        // 执行 SQL
        try {
            // 获取连接
            connection = DBCP.getConnection();
            pstmt = connection.prepareStatement(sql);
            pstmt.setLong(1, sh.getId());
            System.out.println(sql);
            pstmt.execute();
            // 归还连接
            DBCP.closeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 更新一条记录
    public void updateStudentHomework(StudentHomework sh) {

        // 定义 SQL 语句
        // PreparedStatement
        String sql = "UPDATE s_student_homework SET student_id=?, homework_id=?, homework_title=?, homework_content=?, update_time=? WHERE id=?";
        //
        try {
            // 获取连接
            connection = DBCP.getConnection();
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setLong(1, sh.getStudentId());
            pstmt.setLong(2, sh.getHomeworkId());
            pstmt.setString(3, sh.getHomeworkTitle());
            pstmt.setString(4, sh.getHomeworkContent());
            pstmt.setTimestamp(5, new Timestamp(new Date().getTime()));
            pstmt.setLong(6, sh.getId());
            System.out.println(sql);
            pstmt.execute();
            // 归还连接
            DBCP.closeConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) {
//        StudentHomeworkJDBC shJDBC = new StudentHomeworkJDBC();
//        StudentHomework sh = new StudentHomework();

//         To test selectAll()
//        List<StudentHomework> list = shJDBC.selectAll();
//        for (StudentHomework sh : list)
//            System.out.println(sh.getHomeworkContent());

//         To test addStudentHomework(StudentHomework sh)
//        sh.setStudentId(104L);
//        sh.setHomeworkId(104L);
//        sh.setHomeworkTitle("作业");
//        sh.setHomeworkContent("www.google.com");
//        shJDBC.addStudentHomework(sh);

//         To test deleteStudentHomework(StudentHomework sh)
//        sh.setId(4L);
//        shJDBC.deleteStudentHomework(sh);

//         To test updateStudentHomework(StudentHomework sh)
//        sh.setId(11L);
//        sh.setHomeworkId(105L);
//        sh.setStudentId(105L);
//        sh.setHomeworkTitle("作业");
//        sh.setHomeworkContent("bjtu.edu.cn");
//        shJDBC.updateStudentHomework(sh);

//          shJDBC.closeAll();
//    }
}

HomeworkStudentServlet.java 学生看到的作业列表,仅可提交作业

代码语言:javascript复制
package com.javaEE.code.class12.servlet;

import com.javaEE.code.class12.jdbc.HomeworkJDBC;
import com.javaEE.code.class12.model.Homework;

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;

// 学生看到的作业列表,仅可提交作业
@WebServlet(name = "HomeworkStudentServlet", urlPatterns = "/HomeworkStudent")
public class HomeworkStudentServlet extends HttpServlet {
    private HomeworkJDBC homeworkJDBC = new HomeworkJDBC();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Homework> list = homeworkJDBC.selectAll();
        req.setAttribute("list",list);
        req.getRequestDispatcher("/jsp/homework-student.jsp").forward(req, resp);
    }
}

StudentServlet.java 学生列表

代码语言:javascript复制
package com.javaEE.code.class12.servlet;

import com.javaEE.code.class12.jdbc.StudentJDBC;
import com.javaEE.code.class12.model.Student;

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.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

// 教师看到学生列表
@WebServlet(name = "StudentServlet", urlPatterns = "/Student")
public class 锕 extends HttpServlet {
    private StudentJDBC studentJDBC= new StudentJDBC();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Student> studentList = studentJDBC.selectAll();
        req.setAttribute("studentList", studentList);

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

    // https://www.cnblogs.com/xiaochuan94/p/9184444.html
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        // 获取方法名
        String name = req.getParameter("method");

        if(name == null || name.isEmpty()){
            throw new RuntimeException("method parameter does not exist");
        }

        // 获得当前类的Class对象
        Class c = this.getClass();
        Method method = null;
        try {
            // 使用反射机制获取在本类中声明了的方法
            method =  getClass().getDeclaredMethod(name, HttpServletRequest.class, HttpServletResponse.class);
            // 反射调用方法
            method.invoke(this, req, resp);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    protected void addStudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        Student s = new Student();
        s.setId(Long.parseLong(req.getParameter("studentId")));
        s.setName(req.getParameter("studentName"));
        studentJDBC.addStudent(s);
        // 刷新页面
        resp.sendRedirect("Student");
    }

    protected void updateStudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        Student s = new Student();
        s.setId(Long.parseLong(req.getParameter("studentId")));
        s.setName(req.getParameter("studentName"));
        studentJDBC.updateStudent(s);
        // 刷新页面
        resp.sendRedirect("Student");
    }
}

HomeworkTeacherServlet.java 教师看到的作业列表,可进行添加和修改操作

代码语言:javascript复制
package com.javaEE.code.class12.servlet;

import com.javaEE.code.class12.jdbc.HomeworkJDBC;
import com.javaEE.code.class12.model.Homework;

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.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

// 教师看到的作业列表,可进行添加和修改操作
@WebServlet(name = "HomeworkTeacherServlet", urlPatterns = "/HomeworkTeacher")
public class HomeworkTeacherServlet extends HttpServlet {
    private HomeworkJDBC homeworkJDBC = new HomeworkJDBC();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Homework> list = homeworkJDBC.selectAll();
        req.setAttribute("list",list);
        req.getRequestDispatcher("/jsp/homework-teacher.jsp").forward(req, resp);
    }

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

        // 获取方法名
        String name = req.getParameter("method");

        if (name == null || name.isEmpty()) {
            throw new RuntimeException("method parameter does not exist");
        }

        // 获得当前类的Class对象
        Class c = this.getClass();
        Method method = null;
        try {
            // 使用反射机制获取在本类中声明了的方法
            method = getClass().getDeclaredMethod(name, HttpServletRequest.class, HttpServletResponse.class);
            // 反射调用方法
            method.invoke(this, req, resp);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    protected void addHomework(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Homework h = new Homework();
        h.setHomeworkTittle(req.getParameter("title"));
        h.setHomeworkContent(req.getParameter("content"));
        System.out.println(h.toString());
        homeworkJDBC.addHomework(h);
        // 刷新页面
        resp.sendRedirect("HomeworkTeacher");
    }

    protected void updateHomework(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Homework h = new Homework();
        h.setId(Long.parseLong(req.getParameter("homeworkId")));
        h.setHomeworkTittle(req.getParameter("title"));
        h.setHomeworkContent(req.getParameter("content"));
        homeworkJDBC.updateHomework(h);
        // 刷新页面
        resp.sendRedirect("HomeworkTeacher");
    }
}

StudentHomeworkServlet.java 学生提交的作业列表

代码语言:javascript复制
package com.javaEE.code.class12.servlet;

import com.javaEE.code.class12.jdbc.StudentHomeworkJDBC;
import com.javaEE.code.class12.model.StudentHomework;

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;

@WebServlet(name = "StudentHomeworkServlet", urlPatterns = "/StudentHomework")
public class StudentHomeworkServlet extends HttpServlet {
    private StudentHomeworkJDBC studentHomeworkJDBC = new StudentHomeworkJDBC();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<StudentHomework> list = studentHomeworkJDBC.selectAll();
        req.setAttribute("list",list);
        req.getRequestDispatcher("/jsp/studentHomework.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        StudentHomework sh = new StudentHomework();
        sh.setStudentId(Long.parseLong(req.getParameter("studentId")));
        sh.setHomeworkId(Long.parseLong(req.getParameter("homeworkId")));
        sh.setHomeworkTitle(req.getParameter("title"));
        sh.setHomeworkContent(req.getParameter("content"));
        System.out.println(sh.toString());
        studentHomeworkJDBC.addStudentHomework(sh);
        // 刷新页面
//        doGet(req, resp);
        resp.sendRedirect("HomeworkStudent");
    }
}

Viewer 层——界面 index.jsp 首页

代码语言:javascript复制
<%@ page import="com.javaEE.code.class12.model.StudentHomework" %>
<%@ page import="java.util.List" %>
<%@ page import="com.javaEE.code.class12.jdbc.StudentHomeworkJDBC" %>
<%--
  Created by IntelliJ IDEA.
  User: 
  Date: 2020/2/27
  Time: 15:04
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>JavaEE-01</title>
  <style>
    #div1 {
      height: 100%;
      width: 50%;
      /*float: none;*/
      /*border: black;*/
      margin: 0 auto;
      text-align: center;
    }
  </style>
</head>
<body>
<h2 align="center">基于 Java   Servlet   MySQL 的简易学生作业管理系统</h2>
<div id="div1" align="center">
  <fieldset>
    <legend align="left">学生作业管理系统</legend>
    <button οnclick="location.href='HomeworkStudent'" type="button">学生登录</button>
    &nbsp;&nbsp;&nbsp;&nbsp;
    <button οnclick="location.href='Student'" type="button">教师登录</button>
  </fieldset>
</div>
</button>
</body>
</html>

homework-student.jsp 学生查看作业列表,提交作业

代码语言:javascript复制
<%@ page import="com.javaEE.code.class12.model.StudentHomework" %>
<%@ page import="java.util.List" %>
<%@ page import="com.javaEE.code.class12.jdbc.StudentHomeworkJDBC" %>
<%@ page import="com.javaEE.code.class12.model.Homework" %>
<%--
  Created by IntelliJ IDEA.
  User: 
  Date: 2020/3/8
  Time: 20:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>student</title>
</head>
<body>
<h2 align="center">学生作业管理系统——学生端</h2>
<hr color="black">
<h3 align="center">作业列表</h3>
<div>
  <table align="center" width="960" border="1" cellpadding="1" cellspacing="1">
    <tr align="center" height="50" bgcolor="gray">
      <td>作业ID</td>
      <td>作业标题</td>
      <td>作业内容</td>
      <td>创建时间</td>
      <td>更新时间</td>
    </tr>
    <%
      // 通过网络请求获取结果
      List<Homework> list = (List<Homework>) request.getAttribute("list");
      // 通过HomeworkJDBC对象获取结果
//    HomeworkJDBC shJDBC = new HomeworkJDBC();
//    List<Homework> list = hJDBC.selectAll();
      for (Homework h : list) {
    %>
    <tr align="center" bgcolor="white" height="30">
      <td><%=h.getId()%>
      </td>
      <td><%=h.getHomeworkTittle()%>
      </td>
      <td><%=h.getHomeworkContent()%>
      </td>
      <td><%=h.getCreateTime()%>
      </td>
      <td><%=h.getUpdateTime()%>
      </td>
    </tr>
    <%
      }
    %>
  </table>
</div>
<h3 align="center">提交作业</h3>
<div align="center">
  <form action="StudentHomework" method="post" οnsubmit="location.reload()">
    <table>
      <tr>
        <td align="right">作业ID:&ensp;&ensp;</td>
        <td><input type="text" name="homeworkId"></td>
      </tr>
      <tr>
        <td align="right">学号:&ensp;&ensp;</td>
        <td><input type="text" name="studentId"></td>
      </tr>
      <tr>
        <td align="right">作业标题:&ensp;&ensp;</td>
        <td><input type="text" name="title"></td>
      </tr>
      <tr>
        <td valign="right">作业内容:&ensp;&ensp;</td>
        <td><input type="text" name="content"></td>
      </tr>
      <tr>
        <td><br></td>
        <td><br></td>
      </tr>
      <tr>
        <td><input type="button" name="Submit" οnclick="history.back();" value="返回上一页"></td>
        <td>
          &ensp;<button οnclick="location.href='index.jsp'" type="button">返回首页</button>&ensp;
          <input type="submit" value="提交作业"/>
        </td>
      </tr>
    </table>
  </form>
</div>
</body>
</html>

teacher.jsp 教师可查看学生列表,添加学生,修改学生信息

代码语言:javascript复制
<%@ page import="com.javaEE.code.class12.model.StudentHomework" %>
<%@ page import="java.util.List" %>
<%@ page import="com.javaEE.code.class12.jdbc.StudentHomeworkJDBC" %>
<%@ page import="com.javaEE.code.class12.model.Student" %>
<%--
  Created by IntelliJ IDEA.
  User: 
  Date: 2020/3/8
  Time: 20:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>teacher</title>
  <style>
    #div2, #div3 {
      width: 50%;
      float: left;
      /*border: black;*/
      text-align: center;
    }
  </style>
</head>
<body>
<h2 align="center">学生作业管理系统——教师端</h2>
<hr color="black">
<h3 align="center">学生列表</h3>
<div align="center">
  <div>
    <table align="center" width=70% border="1" cellpadding="1" cellspacing="1">
      <tr align="center" height="50" bgcolor="gray">
        <td>学生ID</td>
        <td>学生姓名</td>
        <td>创建时间</td>
        <td>更新时间</td>
      </tr>
      <%
        // 通过网络请求获取结果
        List<Student> list = (List<Student>) request.getAttribute("studentList");
        // 通过StudentHomeworkJDBC对象获取结果
//    StudentHomeworkJDBC shJDBC = new StudentHomeworkJDBC();
//    List<StudentHomework> list = shJDBC.selectAll();
        for (Student s : list) {
      %>
      <tr align="center" bgcolor="white" height="30">
        <td><%=s.getId()%>
        </td>
        <td><%=s.getName()%>
        </td>
        <td><%=s.getCreateTime()%>
        </td>
        <td><%=s.getUpdateTime()%>
        </td>
      </tr>
      <%
        }
      %>
    </table>
  </div>
  <div>
    <div id="div2">
      <h3>添加学生信息</h3>
      <form action="Student?method=addStudent" method="post" οnsubmit="location.reload()">
        <table align="center">
          <tr>
            <td align="right">学生ID:&ensp;&ensp;</td>
            <td><input type="text" name="studentId"></td>
          </tr>
          <tr>
            <td align="right">学生姓名:&ensp;&ensp;</td>
            <td><input type="text" name="studentName"></td>
          </tr>
          <tr>
            <td><br></td>
            <td><br></td>
          </tr>
          <tr>
            <td></td>
            <td>
              <input type="submit" value="添加学生信息"/>
            </td>
          </tr>
        </table>
      </form>
    </div>
    <div id="div3">
      <h3>更新学生信息</h3>
      <form action="Student?method=updateStudent" method="post" οnsubmit="location.reload()">
        <table align="center">
          <tr>
            <td align="right">学生ID:&ensp;&ensp;</td>
            <td><input type="text" name="studentId"></td>
          </tr>
          <tr>
            <td align="right">学生姓名:&ensp;&ensp;</td>
            <td><input type="text" name="studentName"></td>
          </tr>
          <tr>
            <td><br></td>
            <td><br></td>
          </tr>
          <tr>
            <td></td>
            <td>
              <input type="submit" value="更新学生信息"/>
            </td>
          </tr>
        </table>
      </form>
    </div>
  </div>
  <input type="button" name="Submit" οnclick="history.back();" value="返回上一页">&ensp;
  <button οnclick="location.href='index.jsp'" type="button">返回首页</button>&ensp;
  <button οnclick="location.href='StudentHomework'" type="button">查看作业提交列表</button>&ensp;
  <button οnclick="location.href='HomeworkTeacher'" type="button">查看作业发布列表</button>&ensp;
</div>
</body>
</html>

homework-teacher.jsp 教师可查看已发布的作业列表,发布作业和修改作业

代码语言:javascript复制
<%@ page import="com.javaEE.code.class12.model.StudentHomework" %>
<%@ page import="java.util.List" %>
<%@ page import="com.javaEE.code.class12.jdbc.StudentHomeworkJDBC" %>
<%@ page import="com.javaEE.code.class12.model.Homework" %>
<%--
  Created by IntelliJ IDEA.
  User: 
  Date: 2020/3/8
  Time: 20:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>student</title>
  <style>
    #div4, #div5 {
      width: 50%;
      float: left;
      /*border: black;*/
      text-align: center;
    }
  </style>
</head>
<body>
<h2 align="center">学生作业管理系统——教师端</h2>
<hr color="black">
<h3 align="center">作业列表</h3>
<div>
  <table align="center" width="960" border="1" cellpadding="1" cellspacing="1">
    <tr align="center" height="50" bgcolor="gray">
      <td>作业ID</td>
      <td>作业标题</td>
      <td>作业内容</td>
      <td>创建时间</td>
      <td>更新时间</td>
    </tr>
    <%
      // 通过网络请求获取结果
      List<Homework> list = (List<Homework>) request.getAttribute("list");
      // 通过HomeworkJDBC对象获取结果
//    HomeworkJDBC shJDBC = new HomeworkJDBC();
//    List<Homework> list = hJDBC.selectAll();
      for (Homework h : list) {
    %>
    <tr align="center" bgcolor="white" height="30">
      <td><%=h.getId()%>
      </td>
      <td><%=h.getHomeworkTittle()%>
      </td>
      <td><%=h.getHomeworkContent()%>
      </td>
      <td><%=h.getCreateTime()%>
      </td>
      <td><%=h.getUpdateTime()%>
      </td>
    </tr>
    <%
      }
    %>
  </table>
</div>
<div align="center">
  <div id="div4">
    <h3 align="center">添加作业</h3>
    <div align="center">
      <form action="HomeworkTeacher?method=addHomework" method="post" οnsubmit="location.reload()">
        <table>
          <tr>
            <td align="right">作业标题:&ensp;&ensp;</td>
            <td><input type="text" name="title"></td>
          </tr>
          <tr>
            <td valign="right">作业内容:&ensp;&ensp;</td>
            <td><input type="text" name="content"></td>
          </tr>
          <tr>
            <td><br></td>
            <td><br></td>
          </tr>
          <tr>
            <td></td>
            <td>
              <input type="button" name="Submit" οnclick="history.back();" value="返回上一页">&ensp;
              <input type="submit" value="发布作业"/>
            </td>
          </tr>
        </table>
      </form>
    </div>
  </div>
  <div id="div5">
    <h3 align="center">修改作业</h3>
    <div align="center">
      <form action="HomeworkTeacher?method=updateHomework" method="post" οnsubmit="location.reload()">
        <table>
          <tr>
            <td align="right">作业ID:&ensp;&ensp;</td>
            <td><input type="text" name="homeworkId"></td>
          </tr>
          <tr>
            <td align="right">作业标题:&ensp;&ensp;</td>
            <td><input type="text" name="title"></td>
          </tr>
          <tr>
            <td valign="right">作业内容:&ensp;&ensp;</td>
            <td><input type="text" name="content"></td>
          </tr>
          <tr>
            <td><br></td>
            <td><br></td>
          </tr>
          <tr>
            <td></td>
            <td>
              <input type="button" name="Submit" οnclick="history.back();" value="返回上一页">&nbsp;
              <input type="submit" value="修改作业"/>
            </td>
          </tr>
        </table>

      </form>
    </div>
  </div>
  <input type="button" name="Submit" οnclick="history.back();" value="返回上一页">&ensp;
  <button οnclick="location.href='index.jsp'" type="button">返回首页</button>&ensp;
  <button οnclick="location.href='StudentHomework'" type="button">查看作业提交列表</button>&ensp;
  <button οnclick="location.href='Student'" type="button">查看学生列表</button>&ensp;
</div>

</body>
</html>

StudentHomework.jsp 教师查看已提交的作业

代码语言:javascript复制
<%@ page import="com.javaEE.code.class12.model.StudentHomework" %>
<%@ page import="java.util.List" %>
<%@ page import="com.javaEE.code.class12.jdbc.StudentHomeworkJDBC" %>

<%--
  Created by IntelliJ IDEA.
  User: wkm
  Date: 2020/2/27
  Time: 09:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>My Homework</title>
</head>
<body>
<h2 align="center">学生作业管理系统——教师端</h2>
<hr color="black">
<h3 align="center">作业提交列表</h3>
<div align="center">
  <table align="center" width="960" border="1"
         bgcolor="black" cellpadding="1" cellspacing="1">
    <tr align="center" bgcolor="gray" height="50">
      <td>ID</td>
      <td>学生学号</td>
      <td>作业编号</td>
      <td>作业标题</td>
      <td>作业内容</td>
      <td>创建时间</td>
    </tr>
    <%
      StudentHomeworkJDBC studentHomeworkJDBC = new StudentHomeworkJDBC();
      List<StudentHomework> list = studentHomeworkJDBC.selectAll();
      for (StudentHomework sh : list) {
    %>
    <tr align="center" bgcolor="white" height="30">
      <td><%=sh.getId()%>
      </td>
      <td><%=sh.getStudentId()%>
      </td>
      <td><%=sh.getHomeworkId()%>
      </td>
      <td><%=sh.getHomeworkTitle()%>
      </td>
      <td><%=sh.getHomeworkContent()%>
      </td>
      <td><%=sh.getCreateTime()%>
      </td>
    </tr>
    <%
      }
    %>
  </table>
  <br>
  <input type="button" name="Submit" οnclick="history.back();" value="返回上一页">&ensp;
  <button οnclick="location.href='index.jsp'" type="button">返回首页</button>&ensp;
  <button οnclick="location.href='Student'" type="button">查看学生列表</button>&ensp;
  <button οnclick="location.href='HomeworkTeacher'" type="button">查看作业发布列表</button>&ensp;
</div>

</body>
</html>

0 人点赞