增删查改CURD实战(笔记ಥ_ಥ)

温故而知新,可以为师矣

主体

MySQL数据库:
Student表,存放Student信息,id为自增主键。
从左到右各字段分别是int,String,Float和Date。
增删查改CURD实战(笔记ಥ_ಥ)_第1张图片
实现功能:增删查改

需要导入的jar包:
增删查改CURD实战(笔记ಥ_ಥ)_第2张图片

Java包及其作用

包名 作用
entity 对象实体,用于实例化对象
servlet 接受请求,发出响应
repository 数据库操作
filter 过滤器,对servlet进行过滤操作(设置编码)
util 工具包,存放封装的方法

Java类及其作用
结构:
增删查改CURD实战(笔记ಥ_ಥ)_第3张图片
1.entity包
Student类:实例化Student对象,用于传递表信息。

package com.southwind.entity;

import java.util.Date;

public class Student {
    private Integer id;
    private String name;
    private Float score;
    private Date birthday;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", score=" + score +
                ", birthday=" + birthday +
                '}';
    }

    public Student(Integer id, String name, Float score, Date birthday) {
        this.id = id;
        this.name = name;
        this.score = score;
        this.birthday = birthday;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Float getScore() {
        return score;
    }

    public void setScore(Float score) {
        this.score = score;
    }

    public Date getBirthday() {
        return birthday;
    }

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

2.servlet包
StudentServlet类:处理客户端发来的请求以及发出响应,请求到来前首先会经过过滤器。

package com.southwind.servlet;

import com.southwind.entity.Student;
import com.southwind.repository.StudentRepository;

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("/student")
public class StudentServlet extends HttpServlet {

    StudentRepository studentRepository = new StudentRepository();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method == null){
            method = "findAll";
        }

        switch (method){
            case "findAll":
                List<Student> list = studentRepository.findAll();
                req.setAttribute("list",list);
                req.getRequestDispatcher("index.jsp").forward(req,resp);
                break;
            case "deleteById":
                //取出id
                String idStr = req.getParameter("id");
                Integer id = Integer.parseInt(idStr);
                studentRepository.delete(id);
                resp.sendRedirect("/student");
                //根据id删除
                break;
            case "findById":
                //取出id
                idStr = req.getParameter("id");
                id = Integer.parseInt(idStr);
                req.setAttribute("student",studentRepository.findById(id));

                req.getRequestDispatcher("update.jsp").forward(req,resp);
                break;
    }

    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");

        switch (method){
            case "update":
                String idStr = req.getParameter("id");
                Integer id = Integer.parseInt(idStr);
                String name = req.getParameter("name");
                String scoreStr = req.getParameter("score");
                Float score = Float.parseFloat(scoreStr);
                studentRepository.update(id,name,score);
                break;
            case "add":
                name = req.getParameter("name");
                scoreStr = req.getParameter("score");
                score = Float.parseFloat(scoreStr);
                studentRepository.add(name,score);

                break;
        }

        resp.sendRedirect("/student");
    }
}

3.filter包
CharacterFilter类:把servlet的请求过滤,处理请求的编码,使之传递中文不出现乱码

package com.southwind.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;


@WebFilter("/student")
public class CharaterFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("UTF-8");
        filterChain.doFilter(servletRequest,servletResponse);
    }
}

4.util包
JDBCUtil类:集中处理数据库的连接和关闭,减少代码重复。给StudentRepository方法调用。

package com.southwind.util;



import java.sql.*;

public class JDBCTools {
    private static Connection connection = null;
    private static String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";
    private static String user = "root";
    private static String password = "admin";

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static Connection getConnection() {
        try {
            connection = DriverManager.getConnection(url,user,password);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }


        return connection;
    }

    public static void release(Connection connection, Statement statement, ResultSet resultSet){
        if(connection != null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(statement != null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        getConnection();
        System.out.println(connection);
    }
}

5.repository包
StudentRepository类:处理增删查改操作,使用本类的方法前要实例化StudentRepository对象

package com.southwind.repository;

import com.southwind.entity.Student;
import com.southwind.util.JDBCTools;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentNavigableMap;

public class StudentRepository {
    //写关于Student的数据库操作

    public  List<Student> findAll(){
        List<Student> list = new ArrayList<>();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        //查询数据库,遍历对象
        connection = JDBCTools.getConnection();
        String sql = "select * from student";
        try {
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            Student student = null;
            while(resultSet.next()){
                Integer id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                Float score = resultSet.getFloat(3);
                Date birthday = resultSet.getDate(4);

                student = new Student(id,name,score,birthday);
                list.add(student);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCTools.release(connection,preparedStatement,resultSet);
        }


        return list;
    }


    public void delete(Integer id){
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        connection = JDBCTools.getConnection();
        String sql = "delete from student where id = ?";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,id);
            preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCTools.release(connection,preparedStatement,null);
        }

    }

    public Student findById(Integer id){
        Student student = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        connection = JDBCTools.getConnection();
        String sql = "select * from student where id = ?";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,id);
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                Integer id1 = resultSet.getInt(1);
                String name = resultSet.getString(2);
                Float score = resultSet.getFloat(3);
                Date birthday = resultSet.getDate(4);
                student = new Student(id1,name,score,birthday);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCTools.release(connection,preparedStatement,resultSet);
        }


        return student;
    }

    public void update(Integer id,String name,Float score){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        Student student = null;

        connection = JDBCTools.getConnection();
        String sql = "update student set name = ?,score = ? where id = ?";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,name);
            preparedStatement.setFloat(2,score);
            preparedStatement.setInt(3,id);
            preparedStatement.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCTools.release(connection,preparedStatement,null);
        }

    }

    public void add(String name,Float score){
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        connection = JDBCTools.getConnection();
        String sql = "insert into student(name,score,birthday) values(?,?,?)";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,name);
            preparedStatement.setFloat(2,score);
            preparedStatement.setDate(3,new java.sql.Date(System.currentTimeMillis()));

            preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCTools.release(connection,preparedStatement,null);
        }

    }




    public static void main(String[] args) {
        StudentRepository studentRepository = new StudentRepository();
        System.out.println(studentRepository.findAll());
        System.out.println(new java.sql.Date(System.currentTimeMillis()));
    }
}

前端jsp页面

1、index.jsp
作用:显示所有学生信息

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: shinelon
  Date: 2020/6/26
  Time: 23:09
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <h1>成绩管理系统</h1>
  <form action="/student" method="get">
    <input value="查询学生信息" type="submit" />
    <a href="add.jsp" >添加学生信息</a>
  </form>
    <table>
      <tr>
        <th>编号</th>
        <th>姓名</th>
        <th>成绩</th>
        <th>注册日期</th>
        <th>操作</th>
      </tr>
      <c:forEach items="${list}" var="student">
        <tr>
          <td>${student.id}</td>
          <td>${student.name}</td>
          <td>${student.score}</td>
          <td>${student.birthday}</td>
          <td>
            <a href="/student?method=deleteById&id=${student.id}">删除</a>
            <a href="/student?method=findById&id=${student.id}">修改</a>
          </td>
        </tr>


      </c:forEach>


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

显示:(单击查询学生信息后)
增删查改CURD实战(笔记ಥ_ಥ)_第4张图片

2、add.jsp
作用:添加学生信息

<%--
  Created by IntelliJ IDEA.
  User: shinelon
  Date: 2020/6/27
  Time: 11:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form method="post" action="/student">
        姓名:<input type="text" name="name" /><br/>
        成绩:<input type="text" name="score" /><br/>
        <input type="hidden" name="method" value="add" />
        <input type="submit" value="提交" />
    </form>
</body>
</html>

显示:(注意:功能简化,暂不支持提交Date)
增删查改CURD实战(笔记ಥ_ಥ)_第5张图片

3、update.jsp
作用:更新学生信息

<%--
  Created by IntelliJ IDEA.
  User: shinelon
  Date: 2020/6/27
  Time: 8:34
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/student" method="post">
        编号:<input type="text" name="id" value="${student.id}" readonly/><br/>
        姓名:<input type="text" name="name" value="${student.name}" /><br/>
        成绩:<input type="text" name="score" value="${student.score}" /><br/>
        日期:<input type="text" name="birthday" value="${student.birthday}" readonly/><br/>
        <input type="hidden" name="method" value="update" />
        <input type="submit" value="提交" />
    </form>
</body>
</html>

显示:(只允许修改姓名与成绩)
增删查改CURD实战(笔记ಥ_ಥ)_第6张图片

你可能感兴趣的:(增删查改CURD实战(笔记ಥ_ಥ))