簡單的學生管理系統(適合新手理解學習)

首先看一下學生管理系統的體系(我這個系統作的比較簡單) 主要應用到了 MVC模式  JDBC  前端用到了 HTML5  CSS   JS等html

 後臺數據處理主要分爲:controller層  repository層  和service層  下面將每一層的代碼進行展現->>>前端

首先在entity包內進行類的建立   這個系統只實現了對 學生的 CRUD(增刪改查) 因此只須要建立一個學生類(Student):java

package com.xcl.entity;

public class Student {
    private  Integer id;
    private  String name;
    private  String password;
    private  Double money;

    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 String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    public Student(Integer id, String name, String password, Double money) {
        this.id = id;
        this.name = name;
        this.password = password;
        this.money = money;
    }

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

 學生類寫完以後 因爲這個系統簡單不須要進行業務邏輯處理   因此我選擇去寫 service層 mysql

 首先寫一個接口 在接口中定義 CRUD 的方法:
sql

package com.xcl.service;

import com.xcl.entity.Student;

import java.util.List;

public interface StudentService {
    public List<Student> findAll();
    public void deleteById(Integer id);
    public void update(Integer id,String name,String password,Double money);
    public Student findById(Integer id);
    public void add(String name,String password,Double money);
}

 再寫一個接口的實現類  實現接口中的 CRUD 方法:數據庫

package com.xcl.service.impl;

import com.xcl.entity.Student;
import com.xcl.repository.StudentRepository;
import com.xcl.repository.impl.StudentRepositoryImpl;
import com.xcl.service.StudentService;

import java.util.List;

public class StudentServiceImpl implements StudentService {

    private StudentRepository studentRepository = new StudentRepositoryImpl();

    @Override
    public List<Student> findAll() {
        return studentRepository.findAll();
    }

    @Override
    public void deleteById(Integer id) {
        studentRepository.deleteById(id);
    }

    @Override
    public void update(Integer id, String name, String password, Double money) {
        studentRepository.update(id, name, password, money);
    }

    @Override
    public Student findById(Integer id) {
         return studentRepository.findById(id);
    }

    @Override
    public void add(String name, String password, Double money) {
        studentRepository.add(name, password, money);
    }
}

 寫到這裏service層就算是寫完了後端

下面咱們進行 repository 和數據庫操做方面的代碼編寫   這裏會用到 JDBC 數據庫鏈接  因此提早寫一個 JDBC 鏈接數據庫的工具類:jsp

package com.xcl.Tools;

import java.sql.*;

public class JDBCTools {
    public static Connection getConnection(){
        Connection connection = null;
        try {
            //1.加載驅動
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.獲取鏈接
            String url = "jdbc:mysql://localhost:3306/user?serverTimezone=UTC";
            String user = "root";
            String password = "root";
            connection = DriverManager.getConnection(url,user,password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

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

 下面是 repository 層代碼的編寫  仍是老樣子  先寫一個接口   接口裏面寫好須要實現的 CRUD 方法:ide

package com.xcl.repository;

import com.xcl.entity.Student;

import java.util.List;

public interface StudentRepository {
    public List<Student> findAll();
    public void deleteById(Integer id);
    public void update(Integer id,String name,String password,Double money);
    public Student findById(Integer id);
    public void add(String name,String password,Double money);
}

再寫一個實現類 實現接口裏面定義的方法:工具

package com.xcl.repository.impl;

import com.xcl.Tools.JDBCTools;
import com.xcl.entity.Student;
import com.xcl.repository.StudentRepository;


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

public class StudentRepositoryImpl implements StudentRepository {
    /**
     * 查詢
     *
     * @return
     */
    @Override
    public List<Student> findAll() {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Student> list = new ArrayList<>();
        try {
            connection = JDBCTools.getConnection();
            String sql = "select * from stu";
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            Student student = null;
            while (resultSet.next()) {
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                String password = resultSet.getString(3);
                Double money = resultSet.getDouble(4);
                student = new Student(id, name, password, money);
                list.add(student);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCTools.release(connection, statement, resultSet);
        }
        return list;
    }

    /**
     *
     * 刪除
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = JDBCTools.getConnection();
            String sql = "delete from stu where id = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, id);
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCTools.release(connection, statement, null);
        }
    }

    /**
     *
     * 修改
     *
     * @param id
     * @param name
     * @param password
     * @param money
     */
    @Override
    public void update(Integer id, String name, String password, Double money) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = JDBCTools.getConnection();
            String sql = "update stu set name =?,password=?,money=? where id=?";
            statement = connection.prepareStatement(sql);
            statement.setString(1, name);
            statement.setString(2, password);
            statement.setDouble(3, money);
            statement.setInt(4, id);
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCTools.release(connection, statement, null);
        }
    }

    /**
     * @param id
     * @return
     */
    @Override
    public Student findById(Integer id) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        Student student = null;
        try {
            connection = JDBCTools.getConnection();
            String sql = "select * from stu where id=?";
            statement = connection.prepareStatement(sql);
            System.out.println(sql);
            statement.setInt(1, id);
            resultSet = statement.executeQuery();
            if (resultSet.next()) {
                id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                String password = resultSet.getString(3);
                Double money = resultSet.getDouble(4);
                student = new Student(id, name, password, money);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCTools.release(connection, statement, resultSet);
        }
        return student;
    }

    /**
     * 添加
     *
     *
     * @param name
     * @param password
     * @param money
     */
    @Override
    public void add(String name, String password, Double money) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = JDBCTools.getConnection();
            String sql = "insert into stu (name,password,money) values (?,?,?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1, name);
            statement.setString(2, password);
            statement.setDouble(3, money);
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCTools.release(connection, statement, null);
        }
    }
}

接下來就是要編寫先後端交互的代碼  也就是 controller 層的編寫

package com.xcl.controller;

import com.xcl.service.StudentService;
import com.xcl.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;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {

    private StudentService studentService = new StudentServiceImpl();
    private final static String USERNAME = "admin";
    private final static String PASSWORD = "123";


    @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 {
        req.setCharacterEncoding("UTF-8");
        String method = req.getParameter("method");
        if (method == null) method = "findAll";
        switch (method) {
            case "findAll":
                req.setAttribute("list", studentService.findAll());
                req.getRequestDispatcher("index.jsp").forward(req, resp);
                break;
            case "deleteById":
                String idStr = req.getParameter("id");
                Integer id = Integer.parseInt(idStr);
                studentService.deleteById(id);
                resp.sendRedirect("/student");
                break;
            case "findById":
                idStr = req.getParameter("id");
                id = Integer.parseInt(idStr);
                req.setAttribute("student", studentService.findById(id));
                req.getRequestDispatcher("update.jsp").forward(req, resp);
                break;
            case "add":
                String name = req.getParameter("name");
                String password = req.getParameter("password");
                String money1 = req.getParameter("money");
                Double money = Double.parseDouble(money1);
                studentService.add( name, password, money);
                resp.sendRedirect("/student");
                break;
            case "update":
                idStr = req.getParameter("id");
                id = Integer.parseInt(idStr);
                name = req.getParameter("name");
                password = req.getParameter("password");
                money1 = req.getParameter("money");
                money = Double.parseDouble(money1);
                studentService.update(id, name, password, money);
                resp.sendRedirect("/student");
                break;
            case "login":
                String username = req.getParameter("username");
                password = req.getParameter("password");
                if (username.equals(USERNAME) && password.equals(PASSWORD)) {
                    req.getSession().setAttribute("name", username);
                    resp.sendRedirect("/student");
                } else {
                    req.getRequestDispatcher("index.html").forward(req, resp);
                }
                break;
            case "logout":
                req.getSession().invalidate();
                req.getRequestDispatcher("index.html").forward(req, resp);
                break;
        }

    }
}
相關文章
相關標籤/搜索