JavaWeb实现简单对数据库的增删改查

文章目录

  • 写在前面
  • 一、效果图
  • 二、数据库实现
    • 1. 建立数据库表
    • 2. 数据库连接工具druid和dbutils
  • 三、jar包和架构解析
    • 1.常用jar包分析
    • 2.三层架构分析
  • 四、主体代码 - 实现简单增删改查
    • 1.dao层
    • 2.entity实体类
    • 3.service层
    • 4.web层(Servlet层)
    • 5.前端页面展示
      • 1.学生相关
      • 2.教职工相关
  • 总结


写在前面

小demo:用来练习和巩固所学到的知识
包含的知识点:Java基础、Http传输协议、MySQL、JDB C、Tomcat、html、css、js、Servlet、jsp、EL表达式、JSTL标签库
开发工具:IDEA 2019
数据库:MySQL
连接池:Druid连接池
Github仓库地址:点我
jar包下载:点我!提取码:y4ef
参考:Javaweb实现增删改查操作操作
JavaWeb实现简单对数据库的增删改查_第1张图片


用JavaWeb部分知识实现对数据库的增删改查
只展示Student和Teacher的相关代码

一、效果图

JavaWeb实现简单对数据库的增删改查_第2张图片

JavaWeb实现简单对数据库的增删改查_第3张图片
JavaWeb实现简单对数据库的增删改查_第4张图片
JavaWeb实现简单对数据库的增删改查_第5张图片

JavaWeb实现简单对数据库的增删改查_第6张图片
JavaWeb实现简单对数据库的增删改查_第7张图片

二、数据库实现

1. 建立数据库表

文件名:lms2.sql

/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`lms2` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `lms2`;

/*Table structure for table `course` */

DROP TABLE IF EXISTS `course`;

CREATE TABLE `course` (
  `id` varchar(10) NOT NULL COMMENT '课程号',
  `name` varchar(20) NOT NULL COMMENT '姓名',
  `teacherId` varchar(20) NOT NULL COMMENT '任课教师号',
  `creditHour` int(3) NOT NULL COMMENT '学时',
  `creditPoint` int(2) NOT NULL COMMENT '学分',
  `schoolTime` datetime NOT NULL COMMENT '上课时间',
  `classPlace` varchar(50) NOT NULL COMMENT '上课地点',
  `examTime` datetime NOT NULL COMMENT '考试时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `course` */

/*Table structure for table `department` */

DROP TABLE IF EXISTS `department`;

CREATE TABLE `department` (
  `depNo` varchar(20) NOT NULL COMMENT '系号',
  `name` varchar(20) NOT NULL COMMENT '系名称',
  `intro` varchar(128) DEFAULT NULL COMMENT '系的简介',
  PRIMARY KEY (`depNo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `department` */

/*Table structure for table `student` */

DROP TABLE IF EXISTS `student`;

CREATE TABLE `student` (
  `id` varchar(20) NOT NULL COMMENT '学号',
  `name` varchar(20) NOT NULL COMMENT '姓名',
  `sex` varchar(2) NOT NULL DEFAULT '男' COMMENT '性别',
  `bornDate` datetime DEFAULT NULL COMMENT '出生日期',
  `scores` int(3) DEFAULT NULL COMMENT '入学成绩',
  `depNo` varchar(20) NOT NULL COMMENT '所在系号',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `student` */

/*Table structure for table `teacher` */

DROP TABLE IF EXISTS `teacher`;

CREATE TABLE `teacher` (
  `id` varchar(20) NOT NULL COMMENT '职工号',
  `name` varchar(20) NOT NULL COMMENT '姓名',
  `sex` varchar(2) NOT NULL DEFAULT '男' COMMENT '性别',
  `bornDate` datetime DEFAULT NULL COMMENT '出生日期',
  `depNo` varchar(20) NOT NULL COMMENT '所在系号',
  `jobTitle` varchar(20) NOT NULL COMMENT '职称',
  `major` varchar(12) NOT NULL COMMENT '专业及教学方向',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `teacher` */

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

2. 数据库连接工具druid和dbutils

文件名:jdbc.properties
JavaWeb实现简单对数据库的增删改查_第8张图片
代码如下:

username=root
password=123456
url=jdbc:mysql://localhost:3306/lms2?useUnicode=true&characterEncoding=UTF8&useSSL=false
driverClassName=com.mysql.jdbc.Driver
initialSize=5
maxActive=10

JDBC工具类用来加载配置文件、创建数据库连接池、获取连接和关闭连接释放内存

代码如下:

文件名:JdbcUtils.java

package com.makonike.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * JDBC工具类 使用Druid连接池
 *
 * @author Makonike
 **/
public class JdbcUtils {

    /** 数据源 **/
    private static DruidDataSource dataSource = null;


    public static void main(String[] args) {

    }
    static {


        try{
            //加载配置文件
            Properties properties = new Properties();
            //使用ClassLoader加载配置文件,获取字节输入流in
            InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            properties.load(in);

            //创建数据库连接池,初始化连接池对象
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 获取连接Connection对象
     * @param
     * @return java.sql.Connection
     * @author Makonike
     * @date 2021/2/23 10:49
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 关闭连接,释放内存
     * @param conn
     * @return void
     * @author Makonike
     * @date 2021/2/23 10:50
     */

    public static void close(Connection conn){
        if(conn!=null){
            try{
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}



三、jar包和架构解析

1.常用jar包分析

jar包下载:点我!提取码:y4ef
JavaWeb实现简单对数据库的增删改查_第9张图片

2.三层架构分析

dao 数据持久化层,主要用于和数据库进行交互,返回和传递数据
service 处理业务逻辑层,完成其相关的业务逻辑的具体实现
servlet和jsp 前端页面展示和服务器运行程序,让用户能够直接看到现象
entity 实体类,这里特别注意 druid连接池中的查询实现需要属性名与数据库表的字段名一致
JavaWeb实现简单对数据库的增删改查_第10张图片

四、主体代码 - 实现简单增删改查

1.dao层

dao层实现数据的持久化操作,更多的是实现对数据的前后台交互,数据能够来回之间相互传递
JavaWeb实现简单对数据库的增删改查_第11张图片

接口层

文件名:StudentDao.java

package com.makonike.dao;

import com.makonike.entity.Student;

import java.util.List;

/**
 * 持久化接口 - Student
 *
 * @author Makonike
 * @date 2021-02-23 16:04
 **/
public interface StudentDao {

    /**
     * 显示所有学生
     * @param
     * @return java.util.List
     * @author Makonike
     * @date 2021/3/10 22:51
     */

    List<Student> findAllStudent();

    /**
     * 根据学号查询学生信息
     * @param id 需要查询的学号
     * @return 如果是null就没有找到,反之则找到,返回学生信息
     * @author Makonike
     * @date 2021/2/23 16:06
     */
    Student queryStudentById(String id);


    /**
     * 保存学生信息
     * @param student 新的student对象
     * @return int
     * @author Makonike
     * @date 2021/2/23 16:18
     */
    int saveStudent(Student student);

    /**
     * 根据id删除
     * @param id
     * @return boolean
     * @author Makonike
     * @date 2021/2/24 0:52
     */
    int deleteStudent(String id);

    /**
     * 根据id删除
     * @param student
     * @return boolean
     * @author Makonike
     * @date 2021/2/24 0:55
     */
    int updateStudent(Student student);
}

文件名:TeacherDao.java

package com.makonike.dao;

import com.makonike.entity.Teacher;

import java.util.List;

/**
 * 持久化接口 - Teacher
 *
 * @author Makonike
 * @date 2021-02-24 2:19
 **/
public interface TeacherDao {

    /**
     * 查询所有教师
     * @param
     * @return 返回一个Teacher的List集合
     * @author Makonike
     * @date 2021/3/12 19:08
     */

    List<Teacher> findAllTeacher();

    /**
     * 通过教职工工号查询教师信息
     * @param id
     * @return com.makonike.entity.Teacher
     * @author Makonike
     * @date 2021/3/13 10:27
     */

    Teacher queryTeacherById(String id);

    /**
     * 教师基本信息的输入
     * @param teacher
     * @return int
     * @author Makonike
     * @date 2021/2/24 2:23
     */
    int saveTeacher(Teacher teacher);

    /**
     * 教师基本信息的删除
     * @param id
     * @return int
     * @author Makonike
     * @date 2021/2/24 2:23
     */
    int deleteTeacher(String id);

    /**
     * 教师基本信息的修改
     * @param teacher
     * @return int
     * @author Makonike
     * @date 2021/2/24 2:23
     */
    int updateTeacher(Teacher teacher);

}


接口实现层

接口实现层:重点关注BaseDao.java
文件名:BaseDao.java
是所有dao实现类的超类

package com.makonike.dao.impl;

import com.makonike.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Dao持久层的超类
 *
 * @author Makonike
 * @date 2021-02-23 11:35
 **/
public abstract class BaseDao {

    private QueryRunner queryRunner = new QueryRunner();

    /**
     * 增、删、改
     * @param sql 数据库操作语句
     * @param args ?占位符 参数
     * @return int
     * @author Makonike
     * @date 2021/2/23 11:41
     */

    public int update(String sql, Object... args){
        Connection connection = null;
        try {
            connection = JdbcUtils.getConnection();
            return queryRunner.update(connection,sql,args);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(connection);
        }
        return -1;
    }

    /**
     * 查询返回一个javaBean的sql语句
     * @param type  返回的对象类型
     * @param sql   数据库操作语句
     * @param args  ?占位符 参数
     * @return   返回的类型的泛型
     * @author Makonike
     * @date 2021/2/23 15:51
     */

    public <T> T queryForOne(Class<T> type, String sql, Object...args){
        Connection con = null;
        try {
            con = JdbcUtils.getConnection();
            return queryRunner.query(con,sql,new BeanHandler<T>(type),args);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.close(con);
        }
        return  null;
    }

    /**
     * 查询返回多个javaBean的sql语句
     * @param type  返回的对象类型
     * @param sql   数据库操作语句
     * @param args  ?占位符 参数
     * @return   返回的类型的泛型
     * @author Makonike
     * @date 2021/2/23 15:51
     */
    public <T>List<T> queryForList(Class<T> type, String sql, Object... args){
        Connection con = null;
        try {
            con = JdbcUtils.getConnection();
            return queryRunner.query(con,sql, new BeanListHandler<T>(type),args);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.close(con);
        }
        return  null;
    }

文件名:StudentDaoImpl.java

package com.makonike.dao.impl;

import com.makonike.dao.StudentDao;
import com.makonike.entity.Student;

import java.util.List;

/**
 * 持久化dao接口的实现类 - Student
 *
 * @author Makonike
 * @date 2021-02-23 16:17
 **/
public class StudentDaoImpl extends BaseDao implements StudentDao {

    /**
     * 显示所有学生
     * @param
     * @return 返回一个学生List集合
     * @author Makonike
     * @date 2021/3/10 22:52
     */

    @Override
    public List<Student> findAllStudent() {
        //language=MySQL
        String sql = "select `id`, `name`, `sex`,`bornDate`, `scores`, `depNo` from lms2.student order by `id` asc ";
        return queryForList(Student.class, sql);
    }

    /**
     * 根据学号查询一个学生的信息
     * @param id
     * @return com.makonike.pojo.Student 找到则返回查找到的学生信息,若找不到则返回null
     * @author Makonike
     * @date 2021/2/23 16:37
     */

    @Override
    public Student queryStudentById(String id) {
        //language=MySQL
        String sql = "select `id`, `name`, `sex`, `bornDate`, `scores`, `depNo` from lms2.student where id = ?";
        return queryForOne(Student.class,sql,id);
    }

    /**
     * 录入/保存学生信息
     * @param student 需要录入的学生对象
     * @return int int>0表示录入成功,反之则录入失败
     * @author Makonike
     * @date 2021/2/23 16:51
     */
    @Override
    public int saveStudent(Student student) {
        //language=MySQL
        String sql = "insert into lms2.student(`id`, `name`, `sex`, `bornDate`, `scores`, `depNo`) value (?,?,?,?,?,?)";
        return update(sql,student.getId(),student.getName(),student.getSex(),student.getBornDate(),student.getScores(),student.getDepNo());
    }

    /**
     * 根据学号删除学生信息
     * @param id
     * @return int int>0表示删除成功,反之则删除失败
     * @author Makonike
     * @date 2021/2/24 1:33
     */
    @Override
    public int deleteStudent(String id) {
        //language=MySQL
        String sql = "delete from  lms2.student where `id`  = ?" ;
        return update(sql, id);
    }

    /**
     * 更改学生信息
     * @param student
     * @return int 返回值大于0表示更改成功,反之则更改失败
     * @author Makonike
     * @date 2021/2/24 1:33
     */
    @Override
    public int updateStudent(Student student) {
        //language=MySQL
        String sql = "update lms2.student set `id`=?,`name`=?,`sex`=?,`bornDate`=?,`scores`=?,`depNo`=? where `id` = ? ";
        return update(sql,student.getId(),student.getName(),student.getSex(),student.getBornDate(),student.getScores(),student.getDepNo(),student.getId());
    }


}

文件名:TeacherDaoImpl.java

package com.makonike.dao.impl;

import com.makonike.dao.TeacherDao;
import com.makonike.entity.Teacher;

import java.util.List;

/**
 * 持久化dao接口的实现类 - Teacher
 *
 * @author Makonike
 * @date 2021-02-24 2:24
 **/
public class TeacherDaoImpl extends BaseDao implements TeacherDao {


    /**
     * 显示所有教师
     * @param
     * @return 返回一个教师对象的List集合>
     * @author Makonike
     * @date 2021/3/12 19:08
     */

    @Override
    public List<Teacher> findAllTeacher() {
        //language=MySQL
        String sql = "select `id`, `name`, `sex`, `bornDate`, `depNo`, `jobTitle`, `major` from lms2.teacher order by `id` asc ";
        return queryForList(Teacher.class, sql);
    }


    /**
     * 通过教职工号查询教师信息
     * @param id
     * @return 如果存在则返回查询到的教师对象,若没有则返回null
     * @author Makonike
     * @date 2021/3/13 10:28
     */

    @Override
    public Teacher queryTeacherById(String id) {
        //language=MySQL
        String sql = "select `id`, `name`, `sex`, `bornDate`, `depNo`, `jobTitle`, `major` from lms2.teacher where id = ?";
        return queryForOne(Teacher.class,sql,id);
    }


    /**
     * 教职工信息的输入
     * @param teacher
     * @return int
     * @author Makonike
     * @date 2021/2/24 13:42
     */

    @Override
    public int saveTeacher(Teacher teacher) {
        //language=MySQL
        String sql = "insert into lms2.teacher(`id`, `name`, `sex`, `bornDate`, `depNo`, `jobTitle`, `major`) value (?,?,?,?,?,?,?)";
        return update(sql,teacher.getId(),teacher.getName(),teacher.getSex(),teacher.getBornDate(),teacher.getDepNo(),teacher.getJobTitle(),teacher.getMajor());
    }

    /**
     * 根据教职工号删除教职工的信息
     * @param id
     * @return int
     * @author Makonike
     * @date 2021/2/24 13:44
     */

    @Override
    public int deleteTeacher(String id) {
        //language=MySQL
        String sql = "delete from lms2.teacher where `id` = ?";
        return update(sql,id);
    }

    /**
     * 修改教职工信息
     * @param teacher
     * @return int
     * @author Makonike
     * @date 2021/2/24 14:03
     */

    @Override
    public int updateTeacher(Teacher teacher) {
        //language=MySQL
        String sql = "update lms2.teacher set `name`=?,`sex`=?,`bornDate`=?,`depNo`=?,`jobTitle`=?,`major`=?";
        return update(sql,teacher.getName(),teacher.getSex(),teacher.getBornDate(),teacher.getDepNo(),teacher.getJobTitle(),teacher.getMajor());
    }
}



2.entity实体类

entity 实体类,这里特别注意 druid连接池中的查询实现需要属性名与数据库表的字段名一致

文件名:Student.java

package com.makonike.entity;

import java.util.Date;

/**
 * 学生实体类
 *
 * @author Makonike
 * @date 2021-02-23 10:25
 **/
public class Student {
    private String id;
    private String name;
    private String sex;
    private Date bornDate;
    private int scores;
    private String depNo;

    public Student() {
    }

    public Student(String id, String name, String sex, Date bornDate, int scores, String depNo) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.bornDate = bornDate;
        this.scores = scores;
        this.depNo = depNo;
    }

    public String getId() {
        return id;
    }

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

    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 getBornDate() {
        return bornDate;
    }

    public void setBornDate(Date bornDate) {
        this.bornDate = bornDate;
    }

    public int getScores() {
        return scores;
    }

    public void setScores(int scores) {
        this.scores = scores;
    }

    public String getDepNo() {
        return depNo;
    }

    public void setDepNo(String depNo) {
        this.depNo = depNo;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", bornDate='" + bornDate + '\'' +
                ", scores=" + scores +
                ", dep_no='" + depNo + '\'' +
                '}';
    }
}

文件名:Teacher.java

package com.makonike.entity;

import java.util.Date;

/**
 * 教师实体类
 *
 * @author Makonike
 * @date 2021-02-23 10:31
 **/
public class Teacher {
    private String id;
    private String name;
    private String sex;
    private Date bornDate;
    private String depNo;
    private String jobTitle;
    private String major;

    public Teacher() {
    }

    public Teacher(String id, String name, String sex, Date bornDate, String depNo, String jobTitle, String major) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.bornDate = bornDate;
        this.depNo = depNo;
        this.jobTitle = jobTitle;
        this.major = major;
    }

    public String getId() {
        return id;
    }

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

    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 getBornDate() {
        return bornDate;
    }

    public void setBornDate(Date bornDate) {
        this.bornDate = bornDate;
    }

    public String getDepNo() {
        return depNo;
    }

    public void setDepNo(String depNo) {
        this.depNo = depNo;
    }

    public String getJobTitle() {
        return jobTitle;
    }

    public void setJobTitle(String jobTitle) {
        this.jobTitle = jobTitle;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", bornDate='" + bornDate + '\'' +
                ", dep_no='" + depNo + '\'' +
                ", job_title='" + jobTitle + '\'' +
                ", major='" + major + '\'' +
                '}';
    }
}



3.service层

业务逻辑处理层,可以更好地处理业务逻辑

接口层

文件名:StudentService.java

package com.makonike.service;

import com.makonike.entity.Student;

import java.util.List;

/**
 * 业务逻辑层接口层 - Student
 *
 * @author Makonike
 * @date 2021-02-24 0:42
 **/
public interface StudentService{

    /**
     * 显示所有学生
     * @param
     * @return 返回一个Student对象的List集合
     * @author Makonike
     * @date 2021/3/10 23:02
     */

    List<Student> findAllStudent();

    /**
     * 添加学生
     * @param student
     * @return void
     * @author Makonike
     * @date 2021/2/24 15:57
     */

    boolean addStudent(Student student);

    /**
     * 查找学生
     * @param id
     * @return com.makonike.pojo.Student
     * @author Makonike
     * @date 2021/2/24 15:59
     */

    Student seekStudent(String id);

    /**
     * 检查学生信息是否存在
     * @param id
     * @return boolean
     * @author Makonike
     * @date 2021/2/24 16:00
     */

    boolean isExist(String id);

    /**
     * 删除学生信息
     * @param id
     * @return boolean
     * @author Makonike
     * @date 2021/2/24 16:01
     */

    boolean deleteStudent(String id);

    /**
     * 修改学生信息
     * @param student
     * @return void
     * @author Makonike
     * @date 2021/2/24 16:32
     */

    boolean updateStudent(Student student);
}

文件名:TeacherService.java

package com.makonike.service;

import com.makonike.entity.Teacher;

import java.util.List;

/**
 * 业务逻辑层接口层 - Teacher
 *
 * @author Makonike
 * @date 2021-02-24 17:03
 **/
public interface TeacherService {

    /**
     * 查询教师
     * @param id
     * @return com.makonike.entity.Teacher
     * @author Makonike
     * @date 2021/3/13 10:31
     */

    Teacher seekTeacher(String id);

    /**
     * 显示所有教师
     * @param
     * @return 返回一个Teacher对象的List集合
     * @author Makonike
     * @date 2021/3/12 19:12
     */

    List<Teacher> findAllTeacher();

    /**
     * 添加教职工信息
     * @param teacher
     * @return boolean
     * @author Makonike
     * @date 2021/2/24 17:17
     */

    boolean addTeacher(Teacher teacher);

    /**
     * 删除教职工信息
     * @param id
     * @return boolean
     * @author Makonike
     * @date 2021/2/24 17:18
     */

    boolean deleteStudent(String id);

    /**
     * 修改教职工信息
     * @param teacher
     * @return void
     * @author Makonike
     * @date 2021/2/24 17:18
     */

    boolean updateTeacher(Teacher teacher);

    /**
     * 检查教职工信息是否存在
     * @param id
     * @return boolean
     * @author Makonike
     * @date 2021/3/13 10:33
     */

    boolean isExist(String id);

}


接口实现层

文件名:StudentServiceImpl.java

package com.makonike.service.impl;

import com.makonike.dao.StudentDao;
import com.makonike.dao.impl.StudentDaoImpl;
import com.makonike.entity.Student;
import com.makonike.service.StudentService;

import java.util.List;

/**
 * 业务逻辑实现层 - Student
 *
 * @author Makonike
 * @date 2021-02-24 16:03
 **/
public class StudentServiceImpl implements StudentService {
    private StudentDao dao = new StudentDaoImpl();

    /**
     * 显示所有学生
     * @param
     * @return 返回一个Student对象的List集合
     * @author Makonike
     * @date 2021/3/10 23:03
     */

    @Override
    public List<Student> findAllStudent() {
        return dao.findAllStudent();
    }

    /**
     * 添加学生信息
     * @param student
     * @return boolean 返回true说明添加成功 反之则添加失败
     * @author Makonike
     * @date 2021/2/24 16:24
     */
    @Override
    public boolean addStudent(Student student) {
        if(isExist(student.getId())){
            return false;
        }
        int i = dao.saveStudent(student);
        return i > 0;
    }

    /**
     * 通过学号查询学生信息
     * @param id
     * @return 返回null则说明不存在该学生,反之则返回该学生对象
     * @author Makonike
     * @date 2021/2/24 16:24
     */
    @Override
    public Student seekStudent(String id) {
        return dao.queryStudentById(id);
    }

    /**
     * 根据学号检查学生信息是否存在
     * @param id
     * @return boolean 返回true说明存在,反之则不存在
     * @author Makonike
     * @date 2021/2/24 16:27
     */
    @Override
    public boolean isExist(String id) {
        return dao.queryStudentById(id) != null;
    }

    /**
     * 删除学生信息
     * @param id
     * @return boolean 返回true说明删除成功,反之则删除失败
     * @author Makonike
     * @date 2021/2/24 16:29
     */
    @Override
    public boolean deleteStudent(String id) {
        if(isExist(id)){
            int i = dao.deleteStudent(id);
            return i > 0;
        }
        return false;
    }

    @Override
    public boolean updateStudent(Student student) {
        if(isExist(student.getId())){
            int i = dao.updateStudent(student);
            return i > 0;
        }
        return false;
    }
}

文件名:TeacherServiceImpl.java

package com.makonike.service.impl;

import com.makonike.dao.TeacherDao;
import com.makonike.dao.impl.TeacherDaoImpl;
import com.makonike.entity.Teacher;

import java.util.List;

/**
 * 业务逻辑实现层 - Teacher
 *
 * @author Makonike
 * @date 2021-02-24 17:20
 **/
public class TeacherServiceImpl implements com.makonike.service.TeacherService {
    private TeacherDao dao = new TeacherDaoImpl();

    /**
     * 通过教职工号查询教职工信息
     * @param id
     * @return com.makonike.entity.Teacher
     * @author Makonike
     * @date 2021/3/13 10:31
     */

    @Override
    public Teacher seekTeacher(String id) {
        return dao.queryTeacherById(id);
    }

    /**
     * 显示所有教师
     * @param
     * @return 返回一个Teacher对象的List集合
     * @author Makonike
     * @date 2021/3/12 19:13
     */

    @Override
    public List<Teacher> findAllTeacher() {
        return dao.findAllTeacher();
    }

    @Override
    public boolean addTeacher(Teacher teacher) {
        if(isExist(teacher.getId())){
            return false;
        }
        int i = dao.saveTeacher(teacher);
        return i > 0;
    }

    @Override
    public boolean deleteStudent(String id) {
        if(isExist(id)){
            int i = dao.deleteTeacher(id);
            return i > 0;
        }
        return false;
    }

    @Override
    public boolean updateTeacher(Teacher teacher) {
        if(isExist(teacher.getId())){
            int i = dao.updateTeacher(teacher);
            return i > 0;
        }
        return false;
    }

    @Override
    public boolean isExist(String id) {
        return dao.queryTeacherById(id) != null;
    }
}



4.web层(Servlet层)

用于前端界面与后台交互

文件名:BaseServlet.java
通过反射获取类的方法减少代码冗余、作为servlet层的超类
相关链接:
web开发之BaseServlet的使用
个人关于BaseServlet的见解

package com.makonike.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 请求与分发处理的超类
 * 用方法名通过反射调用方法
 * @author Makonike
 * @date 2021-02-25 10:27
 **/
public abstract class BaseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=utf-8");
        req.setCharacterEncoding("UTF-8");
        //获取参数method
        //识别客户端想要请求的方法
        String methodName = req.getParameter("method");

        if(methodName == null || methodName.trim().isEmpty()){
            throw new RuntimeException("获取的参数为空!");
        }
        Method method = null;
        try {
            // this指继承自BaseServlet的、与所请求的url相匹配的Servlet
            method = this.getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            //调用method方法
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
//            throw new RuntimeException("你要调用的方法" + methodName +"不存在");
            PrintWriter out=resp.getWriter();
            out.print("");
        }
    }
}

文件名:StudentServlet.java

package com.makonike.web;

import com.alibaba.druid.util.DruidWebUtils;
import com.makonike.entity.Student;
import com.makonike.service.StudentService;
import com.makonike.service.impl.StudentServiceImpl;

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.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author Makonike
 **/
@WebServlet(name = "StudentServlet",value = "/studentServlet")
public class StudentServlet extends BaseServlet {

    private StudentService studentService = new StudentServiceImpl();

    protected void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Student> allStudent = studentService.findAllStudent();
        req.setAttribute("allStudent", allStudent);
        req.getRequestDispatcher(  "/showAllStudent.jsp").forward(req,resp);
    }

    protected void seek(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Student student = studentService.seekStudent(id);
        if(student==null){
       		 //警告提示框
            PrintWriter out=resp.getWriter();
            out.print("");
        }else{
            //将查到的对象放入请求域中,并跳转至相应页面展示
            req.setAttribute("oneStudent",student);
            req.getRequestDispatcher("/showOneStudent.jsp").forward(req,resp);
        }
    }

    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String bornDate = req.getParameter("bornDate");
        String depNo = req.getParameter("depNo");
        int scores = Integer.parseInt(req.getParameter("scores"));
        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");

        Date date = null;
        try {
            date = (Date)sdf.parse(bornDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Student student = new Student();
        student.setId(id);
        student.setName(name);
        student.setSex(sex);
        student.setBornDate(date);
        student.setScores(scores);
        student.setDepNo(depNo);

        boolean b = studentService.addStudent(student);
        if(b){
        	//警告提示框
            PrintWriter out=resp.getWriter();
            out.print("");
        }else{
            PrintWriter out=resp.getWriter();
            out.print("");
        }
    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        boolean b = studentService.deleteStudent(id);
        if(b){
            PrintWriter out=resp.getWriter();
            out.print("");
        }else{
            PrintWriter out=resp.getWriter();
            out.print("");
        }
    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String bornDate = req.getParameter("bornDate");
        String depNo = req.getParameter("depNo");
        int scores = Integer.parseInt(req.getParameter("scores"));
        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");

        Date date = null;
        try {
            date = (Date)sdf.parse(bornDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Student student = new Student();
        student.setId(id);
        student.setName(name);
        student.setSex(sex);
        student.setBornDate(date);
        student.setScores(scores);
        student.setDepNo(depNo);

        boolean b = studentService.updateStudent(student);
        if(b){
            PrintWriter out=resp.getWriter();
            out.print("");
        }else{
            PrintWriter out=resp.getWriter();
            out.print("");
        }
    }

}

文件名:TeacherServlet.java

package com.makonike.web;

import com.makonike.entity.Teacher;
import com.makonike.service.TeacherService;
import com.makonike.service.impl.TeacherServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author Makonike
 **/
@WebServlet(name = "TeacherServlet",value = "/teacherServlet")
public class TeacherServlet extends BaseServlet{

    private TeacherService teacherService = new TeacherServiceImpl();

    protected void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Teacher> allTeacher = teacherService.findAllTeacher();
        req.setAttribute("allTeacher", allTeacher);
        req.getRequestDispatcher("/showAllTeacher.jsp").forward(req,resp);
    }

    protected void seek(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Teacher teacher = teacherService.seekTeacher(id);
        if(teacher==null){
            PrintWriter out=resp.getWriter();
            out.print("");
        }else{
            req.setAttribute("oneTeacher",teacher);
            req.getRequestDispatcher("/showOneTeacher.jsp").forward(req,resp);
        }
    }

    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String bornDate = req.getParameter("bornDate");
        String depNo = req.getParameter("depNo");
        String jobTitle = req.getParameter("jobTitle");
        String major = req.getParameter("major");
        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");

        Date date = null;
        try {
            date = (Date)sdf.parse(bornDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Teacher teacher = new Teacher();
        teacher.setId(id);
        teacher.setName(name);
        teacher.setSex(sex);
        teacher.setBornDate(date);
        teacher.setDepNo(depNo);
        teacher.setJobTitle(jobTitle);
        teacher.setMajor(major);
        boolean b = teacherService.addTeacher(teacher);
        if(b){
            PrintWriter out=resp.getWriter();
            out.print("");
        }else{
            PrintWriter out=resp.getWriter();
            out.print("");
        }
    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        boolean b = teacherService.deleteStudent(id);
        if(b){
            PrintWriter out=resp.getWriter();
            out.print("");
        }else{
            PrintWriter out=resp.getWriter();
            out.print("");
        }
    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String bornDate = req.getParameter("bornDate");
        String depNo = req.getParameter("depNo");
        String jobTitle = req.getParameter("jobTitle");
        String major = req.getParameter("major");
        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");

        Date date = null;
        try {
            date = (Date)sdf.parse(bornDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Teacher teacher = new Teacher();
        teacher.setId(id);
        teacher.setName(name);
        teacher.setSex(sex);
        teacher.setBornDate(date);
        teacher.setDepNo(depNo);
        teacher.setJobTitle(jobTitle);
        teacher.setMajor(major);
        boolean b = teacherService.updateTeacher(teacher);
        if(b){
            PrintWriter out=resp.getWriter();
            out.print("");
        }else{
            PrintWriter out=resp.getWriter();
            out.print("");
        }
    }
}



5.前端页面展示

JavaWeb实现简单对数据库的增删改查_第12张图片

文件名:index.jsp
引导页

<%--
  Created by IntelliJ IDEA.
  User: Makonike
  Date: 2021/2/23
  Time: 10:18
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>LMStitle>
  head>
  <body>
<br/>
  <h1 align="center"> 欢迎来到教学管理系统 h1>
<br/>
<table align="center" height="400">

  <tr>
    <td align="center">>>  <a href="./student.jsp"> 学生 a>  <<td>
  tr>

  <tr>
    <td align="center">>>  <a href="./teacher.jsp"> 教职工 a>  <<td>
  tr>

  <tr>
    <td align="center">>>  <a href="https://www.csdn.net/"> 课程 a>  <<td>
  tr>

  <tr>
    <td align="center">>>  <a href="https://www.csdn.net/">a>  <<td>
  tr>


table>



  body>
html>



1.学生相关

文件名:student.jsp
内嵌套showAllStudent.jsp页面

<%--
  Created by IntelliJ IDEA.
  User: Makonike
  Date: 2021/3/10
  Time: 22:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>学生title>
head>
<body>
<br/>
<h1 align="center"> 欢迎来到学生界面 h1>
<form action="./studentServlet?method=seek" method="post">
    <p align="center">
        查询:<input type="text" name="id" align="right">
        <input type="submit">
    p>
form>

<table align="center">
    <tr>
        <td>
            <iframe src="./studentServlet?method=findAll" align="middle" width="500" height="250" frameborder="0">iframe>
        td>
    tr>
table>

<table align="center" height="100">

    <tr>
        <td align="center">>>  <a href="./addStudent.jsp"> 增加 a>  <<td>
        <td align="center">>>  <a href="./deleteStudent.jsp"> 删除 a>  <<td>
        <td align="center">>>  <a href="./updateStudent.jsp"> 修改 a>  <<td>
    tr>
    <tr>
        <td>td>
        <td align="center">>>  <a href="./index.jsp"> 返回 a>  <<td>
        <td>td>
    tr>

table>

body>
html>

文件名:addStudent.jsp
增加页面 具体表现为表单和三个按钮

<%--
  Created by IntelliJ IDEA.
  User: Makonike
  Date: 2021/3/9
  Time: 23:14
  To change this template use File | Settings | File Templates.
--%>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加操作title>

    <script type="text/javascript">
        //把表单的action改为student.jsp
        function jumpBack() {
            document.add.action = "student.jsp";
            document.add.submit();
        }
    script>

head>
<body>
<br/>
<h1 align="center">添加学生h1>
<br/>
<form action="${pageContext.request.contextPath}/studentServlet?method=add" method="post" name="add">
    <table align="center" height="350">
        <tr>
            <td>学号:td>
            <td><label><input type="text" name="id" placeholder="请输入学生的学号">label>td>
        tr>
        <tr>
            <td>姓名:td>
            <td><label><input type="text" name="name" placeholder="请输入学生的姓名">label>td>
        tr>

        <tr>
            <td>性别:td>
            <td>
                <label><input type="radio" name="sex" value=""/>label>
                <label><input type="radio" name="sex" value=""/>label>
            td>
        tr>

        <tr>
            <td>入学成绩:td>
            <td><label><input type="text" name="scores" placeholder="请输入学生的入学成绩">label>td>
        tr>

        <tr>
            <td>出生日期:td>
            <td><label><input type="date" name="bornDate">label>td>
        tr>

        <tr>
            <td>所在系号:td>
            <td><label><input type="text" name="depNo" placeholder="请输入学生所在系号">label>td>
        tr>
        <tr>
            <label>
                <td>
                     <input type="submit" value="提交">
                td>
                <td>
                          <input type="reset" value="重置">
                             
                    <input type="button" value="返回" onclick="jumpBack()"/>
                td>
            label>
        tr>
    table>

form>
body>
html>

文件名:deleteStudent.jsp
删除页面 、 通过输入学号来调用相关删除方法

<%--
  Created by IntelliJ IDEA.
  User: Makonike
  Date: 2021/3/11
  Time: 23:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>删除学生title>
head>
<body>
<br/>
<br/>
<h1 align="center">删除学生h1>
<br/>
<br/>
<br/>

<form action="${pageContext.request.contextPath}/studentServlet?method=delete" method="post" name="delete">
    <table align="center" height="50">
        <tr>
            <td><label>学号:<input type="text" name="id" placeholder="请输入学生的学号">label>td>
            <td><input type="submit" value="提交" onclick="">td>
        tr>
    table>

form>
<p align="center">
    <a href="./student.jsp"><button>返回button>a>
p>


body>
html>

文件名:showAllStudent.jsp
从数据库获取所有学生信息并展示

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%--
  Created by IntelliJ IDEA.
  User: Makonike
  Date: 2021/3/11
  Time: 12:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>显示所有学生title>
head>
<body>
        <table align="center" height="100" width="450" border="1">
                <tr align="center">
                    <td><font color="red">学号font>td>
                    <td><font color="red">姓名font>td>
                    <td><font color="red">性别font>td>
                    <td><font color="red">出生日期font>td>
                    <td><font color="red">入学成绩font>td>
                    <td><font color="red">所在系号font>td>
                tr>
        <%-- 遍历输出获取到的学生List集合 --%>
        <c:forEach items="${ allStudent }" var="i">
        <tr align="center">
        <td>${ i.id }td>
        <td>${ i.name }td>
        <td>${ i.sex }td>
        <td>
            <%-- 将bornDate转换为YY-HH-DD的形式输出 --%>
        <fmt:formatDate value="${i.bornDate}" type="date" dateStyle="medium"/>
        td>
        <td>${ i.scores }td>
        <td>${ i.depNo }td>
        tr>
            c:forEach>
    table>
body>
html>

文件名:showOneStudent.jsp
展示通过学号查询获取到的学生信息

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%--
  Created by IntelliJ IDEA.
  User: Makonike
  Date: 2021/3/11
  Time: 12:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>显示查询到的学生title>
head>
<body>
<br/>
<br/>
<br/>
<br/>
<br/>
    <table align="center" height="100" width="450" border="1">

        <tr align="center">
            <td><font color="red">学号font>td>
            <td><font color="red">姓名font>td>
            <td><font color="red">性别font>td>
            <td><font color="red">出生日期font>td>
            <td><font color="red">入学成绩font>td>
            <td><font color="red">所在系号font>td>
        tr>
        <%-- 遍历输出获取到的学生List集合 --%>
        <tr align="center">
        <td>${ oneStudent.id }td>
        <td>${ oneStudent.name }td>
        <td>${ oneStudent.sex }td>
        <td>
            <%-- 将bornDate转换为YY-HH-DD的形式输出 --%>
        <fmt:formatDate value="${oneStudent.bornDate}" type="date" dateStyle="medium"/>
        td>
        <td>${ oneStudent.scores }td>
        <td>${ oneStudent.depNo }td>
        tr>
    table>
<br/>
<br/>
<center>
    <a href="./student.jsp"><button>返回button>a>
center>

body>
html>

文件名:updateStudent.jsp
修改学生信息、

<%--
  Created by IntelliJ IDEA.
  User: Makonike
  Date: 2021/3/9
  Time: 23:14
  To change this template use File | Settings | File Templates.
--%>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改操作title>

    <script type="text/javascript">
        //把表单的action改为student.jsp
        function jumpBack() {
            document.update.action = "student.jsp";
            document.update.submit();
        }
    script>

head>
<body>
<br/>
<h1 align="center">修改学生信息h1>
<br/>
<form action="${pageContext.request.contextPath}/studentServlet?method=update" method="post" name="update">
    <table align="center" height="350">
        <tr>
            <td>学号:td>
            <td><label><input type="text" name="id" placeholder="请输入学生的学号">label>td>
        tr>
        <tr>
            <td>姓名:td>
            <td><label><input type="text" name="name" placeholder="请输入学生的姓名">label>td>
        tr>

        <tr>
            <td>性别:td>
            <td>
                <label><input type="radio" name="sex" value=""/>label>
                <label><input type="radio" name="sex" value=""/>label>
            td>
        tr>

        <tr>
            <td>入学成绩:td>
            <td><label><input type="text" name="scores" placeholder="请输入学生的入学成绩">label>td>
        tr>

        <tr>
            <td>出生日期:td>
            <td><label><input type="date" name="bornDate">label>td>
        tr>

        <tr>
            <td>所在系号:td>
            <td><label><input type="text" name="depNo" placeholder="请输入学生所在系号">label>td>
        tr>
        <tr>
            <label>
                <td>
                     <input type="submit" value="提交">
                td>
                <td>
                          <input type="reset" value="重置">
                             
                    <input type="button" value="返回" onclick="jumpBack()"/>
                td>
            label>
        tr>
    table>

form>
body>
html>




2.教职工相关

文件名:teacher.jsp
内部嵌套showAllTeacher.jsp页面、

<%--
  Created by IntelliJ IDEA.
  User: Makonike
  Date: 2021/3/10
  Time: 22:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>教职工title>
head>
<body>
<br/>
<h1 align="center"> 欢迎来到教职工界面 h1>
<form action="./teacherServlet?method=seek" method="post">
    <p align="center">
        查询:<input type="text" name="id" align="right">
        <input type="submit">
    p>
form>

<table align="center">
    <tr>
        <td>
            <iframe src="./teacherServlet?method=findAll" align="middle" width="550" height="250" frameborder="0">iframe>
        td>
    tr>
table>

<table align="center" height="100">

    <tr>
        <td align="center">>>  <a href="./addTeacher.jsp"> 增加 a>  <<td>
        <td align="center">>>  <a href="./deleteTeacher.jsp"> 删除 a>  <<td>
        <td align="center">>>  <a href="./updateTeacher.jsp"> 修改 a>  <<td>
    tr>
    <tr>
        <td>td>
        <td align="center">>>  <a href="./index.jsp"> 返回 a>  <<td>
        <td>td>
    tr>

table>
body>
html>

文件名:addTeacher.jsp
添加页面、具体表现为一个表单和三个有特定功能的按钮

<%--
  Created by IntelliJ IDEA.
  User: Makonike
  Date: 2021/3/9
  Time: 23:14
  To change this template use File | Settings | File Templates.
--%>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加操作title>

    <script type="text/javascript">
        //把表单的action改为teacher.jsp
        function jumpBack() {
            document.add.action = "teacher.jsp";
            document.add.submit();
        }
    script>

head>
<body>
<br/>
<h1 align="center">添加教职工h1>
<br/>
<form action="${pageContext.request.contextPath}/teacherServlet?method=add" method="post" name="add">
    <table align="center" height="350">
        <tr>
            <td>教职工号:td>
            <td><label><input type="text" name="id" placeholder="请输入教职工号">label>td>
        tr>
        <tr>
            <td>姓名:td>
            <td><label><input type="text" name="name" placeholder="请输入姓名">label>td>
        tr>

        <tr>
            <td>性别:td>
            <td>
                <label><input type="radio" name="sex" value=""/>label>
                <label><input type="radio" name="sex" value=""/>label>
            td>
        tr>

        <tr>
            <td>出生日期:td>
            <td><label><input type="date" name="bornDate">label>td>
        tr>

        <tr>
            <td>所在系号:td>
            <td><label><input type="text" name="depNo" placeholder="请输入所在系号">label>td>
        tr>

        <tr>
            <td>职称:td>
            <td><label><input type="text" name="jobTitle" placeholder="请输入职称">label>td>
        tr>

        <tr>
            <td>专业及教学方向:td>
            <td><label><input type="text" name="major" placeholder="请输入专业及教学方向">label>td>
        tr>

        <tr>
            <label>
                <td>
                     <input type="submit" value="提交">
                td>
                <td>
                    <input type="reset" value="重置">
                                   
                    <input type="button" value="返回" onclick="jumpBack()"/>
                td>
            label>
        tr>
    table>

form>
body>
html>

文件名:deleteTeacher.jsp
通过输入学号删除教职工信息

<%--
  Created by IntelliJ IDEA.
  User: Makonike
  Date: 2021/3/11
  Time: 23:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>删除操作title>
head>
<body>
<br/>
<br/>
<h1 align="center">删除教职工信息h1>
<br/>
<br/>
<br/>

<form action="${pageContext.request.contextPath}/teacherServlet?method=delete" method="post" name="delete">
    <table align="center" height="50">
        <tr>
            <td><label>教职工号:<input type="text" name="id" placeholder="请输入教职工号">label>td>
            <td><input type="submit" value="提交" onclick="">td>
        tr>
    table>

form>
<p align="center">
    <a href="./teacher.jsp"><button>返回button>a>
p>
body>
html>

文件名:showAllTeacher.jsp
从数据库获取教师信息并展示、

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%--
  Created by IntelliJ IDEA.
  User: Makonike
  Date: 2021/3/11
  Time: 12:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>显示所有学生title>
head>
<body>
        <table align="center" height="50" width="500" border="1">
                <tr align="center">
                    <td><font color="red">学号font>td>
                    <td><font color="red">姓名font>td>
                    <td><font color="red">性别font>td>
                    <td><font color="red">出生日期font>td>
                    <td><font color="red">所在系号font>td>
                    <td><font color="red">职称font>td>
                    <td><font color="red">专业及教学方向font>td>
                tr>
        <%-- 遍历输出获取到的学生List集合 --%>
        <c:forEach items="${ allTeacher }" var="i">
        <tr align="center">
        <td>${ i.id }td>
        <td>${ i.name }td>
        <td>${ i.sex }td>
        <td>
            <%-- 将bornDate转换为YY-HH-DD的形式输出 --%>
        <fmt:formatDate value="${i.bornDate}" type="date" dateStyle="medium"/>
        td>
        <td>${ i.depNo }td>
        <td>${ i.jobTitle }td>
        <td>${ i.major }td>
        tr>
            c:forEach>
    table>
body>
html>

文件名:showOneTeacher.jsp
展示通过教职工号搜索获取到的教职工信息

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%--
  Created by IntelliJ IDEA.
  User: Makonike
  Date: 2021/3/11
  Time: 12:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>显示查询到的教职工title>
head>
<body>
<br/>
<br/>
<br/>
<br/>
<br/>
    <table align="center" height="100" width="450" border="1">

        <tr align="center">
            <td><font color="red">学号font>td>
            <td><font color="red">姓名font>td>
            <td><font color="red">性别font>td>
            <td><font color="red">出生日期font>td>
            <td><font color="red">所在系号font>td>
            <td><font color="red">职称font>td>
            <td><font color="red">专业及教学方向font>td>
        tr>
        <%-- 遍历输出获取到的学生List集合 --%>
        <tr align="center">
        <td>${ oneTeacher.id }td>
        <td>${ oneTeacher.name }td>
        <td>${ oneTeacher.sex }td>
        <td>
            <%-- 将bornDate转换为YY-HH-DD的形式输出 --%>
        <fmt:formatDate value="${oneTeacher.bornDate}" type="date" dateStyle="medium"/>
        td>
        <td>${ oneTeacher.depNo }td>
        <td>${ oneTeacher.jobTitle }td>
        <td>${ oneTeacher.major }td>
        tr>
    table>
<br/>
<br/>
<center>
    <a href="./teacher.jsp"><button>返回button>a>
center>

body>
html>


文件名:updateTeacher.jsp
修改教职工信息

<%--
  Created by IntelliJ IDEA.
  User: Makonike
  Date: 2021/3/9
  Time: 23:14
  To change this template use File | Settings | File Templates.
--%>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改操作title>

    <script type="text/javascript">
        //把表单的action改为teacher.jsp
        function jumpBack() {
            document.update.action = "teacher.jsp";
            document.update.submit();
        }
    script>

head>
<body>
<br/>
<h1 align="center">修改教职工信息h1>
<br/><form action="${pageContext.request.contextPath}/teacherServlet?method=update" method="post" name="update">
    <table align="center" height="350">
        <tr>
            <td>教职工号:td>
            <td><label><input type="text" name="id" placeholder="请输入教职工号">label>td>
        tr>
        <tr>
            <td>姓名:td>
            <td><label><input type="text" name="name" placeholder="请输入姓名">label>td>
        tr>

        <tr>
            <td>性别:td>
            <td>
                <label><input type="radio" name="sex" value=""/>label>
                <label><input type="radio" name="sex" value=""/>label>
            td>
        tr>

        <tr>
            <td>出生日期:td>
            <td><label><input type="date" name="bornDate">label>td>
        tr>

        <tr>
            <td>所在系号:td>
            <td><label><input type="text" name="depNo" placeholder="请输入所在系号">label>td>
        tr>

        <tr>
            <td>职称:td>
            <td><label><input type="text" name="jobTitle" placeholder="请输入职称">label>td>
        tr>

        <tr>
            <td>专业及教学方向:td>
            <td><label><input type="text" name="major" placeholder="请输入专业及教学方向">label>td>
        tr>
        <tr>
            <label>
                <td>
                     <input type="submit" value="提交">
                td>
                <td>
                    <input type="reset" value="重置">
                                   
                    <input type="button" value="返回" onclick="jumpBack()"/>
                td>
            label>
        tr>
    table>

form>
body>
html>



总结

工作室考核期间做的一个小demo
简单实现了用JavaWeb部分知识对数据库进行增删改查操作,
以下是遇到的问题和相关反思

  • 通过sql查询得到的日期bornDate需要转化为YY-HH-MM形式
<fmt:formatDate value="${i.bornDate}" type="date" dateStyle="medium"/>
  • 重定向次数过多

呃开始写的时候还没想明白,不小心弄成两个页面相互跳转

  • form表单中按钮返回链接设置(一个form表单中有两个跳转链接)

更改sumit提交的链接

  • 遍历得到的List集合(存于request域中)

合理运用JSTL标签库

  • form表单提交返回页面alert弹窗提示

用到js的相关知识


以下是不足和有待改进的地方
  • 查询结果没有分页
  • Servlet层部分代码冗余,可以封装成beanUtils中
  • 各代码层耦合度过高、独立性很差

你可能感兴趣的:(JavaWeb,demo,java,javaweb,jdbc,mysql)