Student Information Management System Case Summary

Take a recent study of knowledge (JDBC, Servlet, JSP) weekend to do a small case, originally weekend should organize your notes, but the play can not be delayed ah, so take advantage of the time to work today, do the next record.


Technical preparations

  1. Basic knowledge of Java, JavaEE base

    tomcat, servlet, jsp(EL + JSTL)

  2. Basic knowledge of web frontend

    html, css, javascript basis + Jquery basis

  3. Relational Database

    Use SpringJDBC operation mysql

  4. development tools

    IDEA, JDK8.0


demand analysis

  1. Use mysql to store student information
  2. Complete the page display student data, additions and deletions can be made to change the poor student information, and support previous, next operation, and student information queries.


achieve

A Table Design

  • Create a database: student

    Set the encoding utf-8, to facilitate access to Chinese

    drop database if exists student;
    create database student default charset=utf8;
  • Create a table: student

    create table student(
        id int unsigned primary key auto_increment not null,
        student_id varchar(20) not null unique COMMENT '学号',
        name varchar(20) not null,
        gender varchar(5),
        birthday date, 
        address varchar(50),
        qq varchar(20),
        email varchar(50)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    The reason is because the school setting student_id number may change, but the primary key id can not be modified.


II. Creating JavaEE project, import the jar package

Item structure is as follows:


III. Preparation front page (prototype)

In front of the project is html code, this step is also very important.

Home show student information in the form of a list of

Add and modify information pages, two pages should be long like

If the new and modified as a page, of a total of two pages -

Student Information List

Adding student page

Edit Student page


Four. Src directory hierarchy

Division code module:

  1. Entity classes: student (a student on the table, so the corresponding entity class has only one)
  2. Data Access Objects: dao (operating student objects StudentDao)
  3. Logic: Servlet (student information list display, add, modify, delete student information)
  4. Tools: JDBCDruidUtils (encapsulates SpringJDBC operation of the database)
  5. Unit testing: test

Create a hierarchy of code in the src directory:


V. specific code logic implemented

student entity class
package com.student.entity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Student {
    private int id;
    private String studentId;
    private String name;
    private String gender;
    private Date birthday;
    private String address;
    private String qq;

    // setter and getter ,  日期类型需要额外转换下
    
    public String getBirthday() {
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
        return formater.format(this.birthday);
    }

    public void setBirthday(String birthday) {
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = formater.parse(birthday);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        this.birthday = date;
    }
}


JDBCDruidUtils connection pool:
package com.student.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * JDBCDruidUtils 工具类
 */
public class JDBCDruidUtils {
    private static DataSource ds = null;

    static {
        try {
            // 加载配置文件
            Properties pro = new Properties();
            // 获取 src 路径下的文件 --> ClassLoader
            ClassLoader cl = JDBCDruidUtils.class.getClassLoader();
            InputStream is = cl.getResourceAsStream("druid.properties");
            pro.load(is);
            // 通过工厂函数 获取 数据库连接池 (传入配置文件)
            ds = DruidDataSourceFactory.createDataSource(pro);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取连接池对象
    public static DataSource getDataSource(){
        return ds;
    }

    // 获取连接对象
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
}


druid.properties profile
driverClassName=com.mysql.jdbc.Driver
# useUnicode表示允许使用自定义的Unicode
url=jdbc:mysql://192.168.0.115:3306/JDBC?useUnicode=true&characterEncoding=utf8
username=username
password=password
initialSize=5
maxActive=10
maxWait=3000


studentDao

DAO (Data Access Object) 数据库访问, 就是对数据库的操作进行封装, 让 servlet 里边看不到 JDBC 的代码

package com.student.dao;

import com.student.entity.Student;
import com.student.utils.JDBCDruidUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * student 对象相关的操作方法
 */
public class StudentDao {
    // 获取 JdbcTemplate 对象
    private static JdbcTemplate template = new JdbcTemplate(JDBCDruidUtils.getDataSource());

    /**
     * 获取 JdbcTemplate 对象, 将学生信息写入到数据库中
     */
    public static int createStudent(Student student){
        String createSql = "insert into student values(?,?,?,?,?,?,?,?);";
        int num = StudentDao.template.update(createSql, student.getId(), student.getStudentId(), student.getName(),
                student.getGender(), student.getBirthday(), student.getAddress(), student.getQq(), student.getEmail());
        return num;
    }

    /**
     * 通过id查询学生
     * @param id
     * @return
     */
    public static Student queryStudentById(String id){
        String querySql = "select * from student where id = ?";
        Student student = StudentDao.template.queryForObject(querySql, new BeanPropertyRowMapper<Student>(Student.class), id);
        return student;
    }


    /**
     * 更新 学生信息
     * @param student
     * @return
     */
    public static int updateStudent(Student student){
        String updateSql = "update student set gender = ?, birthday = ?, address = ?," +
                           "qq = ?, email = ? where id = ?;";
        int num = StudentDao.template.update(updateSql, student.getGender(), student.getBirthday(), student.getAddress(),
                student.getQq(), student.getEmail(), student.getId());
        return num;
    }

    /**
     * 删除学生信息
     * @param id
     * @return
     */
    public static int deleteStudentById(String id){
        String deleteSql = "delete from student where id = ?";
        int num = StudentDao.template.update(deleteSql, id);
        return num;
    }
}


学生列表展示
package com.student.servlet;

import com.student.utils.JDBCDruidUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/list")
public class ReadList extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 不用获取参数, 所以不用设置流的编码
            // 获取 JdbcTemplate 对象
        DataSource ds  = JDBCDruidUtils.getDataSource();
        JdbcTemplate template = new JdbcTemplate(ds);

        // 查询结果, 将结果集封装为 ReadList 集合
//        String querySql = "select * from student limit 0, 3";
        String querySql = "select * from student";
        java.util.List<Map<String, Object>> studentList = template.queryForList(querySql);
        // 将学生对象列表存储到 request 对象域中
        request.setAttribute("studentList", studentList);
        // 转发到 list 页面
        request.getRequestDispatcher("/list.jsp").forward(request, response);
    }
}


新增一条学生信息

先返回新增学生信息的 jsp 页面, 然后用户在键入信息之后, 提交表单到后端处理.

package com.student.servlet;

import com.student.dao.StudentDao;
import com.student.entity.Student;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/create")
public class Create extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数, 设置流的编码
        request.setCharacterEncoding("utf-8");
        // 将参数封装到 map 集合中 (使用JavaBeanUtils工具)
        Map<String, String[]> map = request.getParameterMap();
        Student student = StudentDao.mapToStudent(map);

        // 获取 JdbcTemplate 对象, 将学生信息写入到数据库中
        int num = StudentDao.create(student);
        // 重定向到 list 页面
        response.sendRedirect(request.getContextPath() + "/list");
    }
}


更新学生信息

get 方法中返回编辑学生信息的 jsp 页面, 填充当前学生的信息

post 方法对用户提交的 form 表单, 对学生信息进行更新

package com.student.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import com.student.dao.StudentDao;
import com.student.entity.Student;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/update")
public class Update extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数, 设置流的编码
        request.setCharacterEncoding("utf-8");
        // 将参数封装到 map 集合中 (使用JavaBeanUtils工具)
        Map<String, String[]> map = request.getParameterMap();
        Student student = new Student();
        try {
            BeanUtils.populate(student, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        // 获取 JdbcTemplate 对象, 将学生信息更新到数据库中
        int num = StudentDao.updateStudent(student);
        System.out.println("更新成功, num: " + num);
        // 重定向到 list 页面
        response.sendRedirect(request.getContextPath() + "/list");
    }

    // 返回带有 student 信息的修改页面
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取student的 id
        String id = request.getParameter("id");
        Student student = StudentDao.queryStudentById(id);
        // 将需要修改的学生信息放到 request 域对象中
        request.setAttribute("student", student);
        // 请求转发到 update.jsp 页面
        request.getRequestDispatcher("/update.jsp").forward(request, response);
    }
}


删除学生信息

写到这里, 删除的逻辑就非常简单了, 需要注意的是, 删除的时候, 需要给用户弹框确认, 这部分涉及到前端 js 的一个知识点.

function deleteStudent(id){
    //用户安全提示
    if(confirm("您确定要删除吗?")){                                                          location.href="${pageContext.request.contextPath}/delete?id="+id;                       location.submit();
    }
}
package com.student.servlet;

import com.student.dao.StudentDao;
import com.student.entity.Student;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/delete")
public class Delete extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取student的 id
        String id = request.getParameter("id");
        int num = StudentDao.deleteStudentById(id);
        System.out.println("删除学生信息, num: " + num);
        // 重定向到 list 页面
        response.sendRedirect(request.getContextPath() + "/list");
    }
}


案例总结

  1. 一共花了 6 个小时左右的时间, 后端的逻辑处理不算复杂, 知识点忘记了可以看下前边学习的笔记, 总的来说还算顺利.
  2. 前端的页面布局是资料里边找的模板, 然后改了一些, 能够配合后端的 api 进行数据交互, 然后运用 jsp 中的 EL 表达式和 JSTL 标签进行展示, 没有涉及到一些很难的内容.
  3. 这是一个前后端不分离的案例, 和之前学习的 python flask 项目里边的 jinja2 模板引擎非常的相似, 例如大胡子语法( {{}} ), 控制代码块( if else, for 循环 ), 过滤器, 模板继承等内容, 有之前的项目经验, 理解起来也比较的容易.


案例改进

写到这里, 还是一个非常粗糙的案例, 可以优化的点有:

  1. 新增, 修改学生信息时对参数进行校验,
  2. 按学号, 姓名, 性别进行检索,
  3. 分页查询,
  4. 批量删除,
  5. 登录功能,
  6. 权限管理 (分管理员, 普通用户等, 普通用户没有删除功能)

后边有时间再持续优化 ~ (也许就这么一说, haha)


最后, 附上github仓库地址: https://github.com/kaichenkai/StudentManagement


ending ~


Guess you like

Origin www.cnblogs.com/kaichenkai/p/11973555.html
Recommended