java设计并完成一个数据驱动的管理系统

目录

一、运行环境

1、环境:

2、实现一个管理系统需要以下步骤:

二、创建项目

1.创建

2、选择依赖

3、项目结构

4、配置数据库

 三、代码

1、Model层

2、Repository层

3、Service层

3.1接口

3.2、实现

4、Controller层

5、视图层

5.1、index.html

5.2、new_student.html

5.3、test.html

5.4、update_student.html

四、运行结果


一、运行环境

1、环境:

IDE - IDEA

Spring Boot 3+

Spring Framework 6+

Maven

Java 17

Spring Data JPA ( Hibernate)

Thymeleaf

2、实现一个管理系统需要以下步骤:

  • 确定需求:首先需要了解管理系统的需求,包括功能模块和功能细节。
  • 设计数据库:根据管理系统的需求设计相应的数据库,包括表结构和表之间的关系。
  • 设计用户界面:为管理系统设计相应的用户界面,使用户操作方便。
  • 编写代码:根据设计的数据库和用户界面,使用 Java 编写管理系统的代码。
  • 测试与调试:对管理系统进行测试,检查代码是否有误,并对代码进行调试。
  • 发布与维护:将管理系统发布到相应的服务器上,并对管理系统进行维护。

二、创建项目

1.创建

2、选择依赖

3、项目结构

4、配置数据库

代码

spring.datasource.url=jdbc:mysql://localhost/testdb?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.username= root
spring.datasource.password= 123456

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# for Spring Boot 2
# spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect

# for Spring Boot 3
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQLDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update

#?????hibernate-sql
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE

 三、代码

1、Model层

import jakarta.persistence.*;
import lombok.Data;
@Data
@Entity
@Table(name = "students")
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "student_name")
    private String studentName;

    @Column(name = "student_age")
    private String studentAge;

    @Column(name = "counsellor")//辅导员
    private String counsellor;
}

2、Repository层

3、Service层

3.1接口

StudentService

import java.util.List;
import en.edu.lzzy.s05mvcemployee.model.Student;
import org.springframework.data.domain.Page;

public interface StudentService {

    //获取所有的学生
    List <Student> getAllStudents();

    //新增/更新一个学生
    void saveStudent(Student student);

    //获取指定ID的学生
    Student getStudentById(long id);

    //删除指定ID的学生
    void deleteStudentById(long id);


    //分页
    Page<Student> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection);
}
3.2、实现

StudentServiceImpl

import java.util.List;
import java.util.Optional;

import en.edu.lzzy.s05mvcemployee.model.Student;
import en.edu.lzzy.s05mvcemployee.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;


@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;

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

    @Override
    public void saveStudent(Student student) {
        this.studentRepository.save(student);
    }

    @Override
    public Student getStudentById(long id) {
        //调用数据访问层查找指定ID的学生,返回Optional对象
        Optional <Student> optional = studentRepository.findById(id);

        Student student = null;
        //如果存在指定id的学生
        if (optional.isPresent()) {
            //从Optional对象中获取学生对象
            student = optional.get();
        } else {
            //否则抛出运行时异常
            throw new RuntimeException(" 找不到学生ID :: " + id);
        }
        return student;
    }

    @Override
    public void deleteStudentById(long id) {
        this.studentRepository.deleteById(id);
    }

    @Override
    public Page<Student> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) {
        //设置排序参数,升序ASC/降序DESC?
        Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())
                    ? Sort.by(sortField).ascending()
                    : Sort.by(sortField).descending();

         //根据页号/每页记录数/排序依据返回某指定页面数据。
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
        return this.studentRepository.findAll(pageable);
    }
}

4、Controller层

代码

import en.edu.lzzy.s05mvcemployee.model.Student;
import en.edu.lzzy.s05mvcemployee.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

//     display list of employees
//    @GetMapping("/")
//    public String viewHomePage(Model model) {
//        model.addAttribute("listEmployees", employeeService.getAllEmployees());
//        return "index";
//    }
    @GetMapping("/")
    public String viewHomePage(Model model) {
        return findPaginated(1, "studentName", "asc", model);
    }

    @GetMapping("/showNewStudentForm")
    public String showNewStudentForm(Model model) {
        // create model attribute to bind form data
        Student student = new Student();
        model.addAttribute("student", student);
        return "new_student";
    }

    @PostMapping("/saveStudent")
    public String saveStudent(@ModelAttribute("student") Student student) {
        // save employee to database
        studentService.saveStudent(student);
        return "redirect:/";
    }

    @GetMapping("/showFormForUpdate/{id}")
    public String showFormForUpdate(@PathVariable(value = "id") long id, Model model) {

        // get employee from the service
        Student student = studentService.getStudentById(id);

        // set employee as a model attribute to pre-populate the form
        model.addAttribute("student", student);
        return "update_student";
    }

    @GetMapping("/deleteStudent/{id}")
    public String deleteStudent(@PathVariable(value = "id") long id) {

        // call delete employee method
        this.studentService.deleteStudentById(id);
        return "redirect:/";
    }

    //获取分页数据
    @GetMapping("/page/{pageNo}")
    public String findPaginated(@PathVariable (value = "pageNo") int pageNo,
                                @RequestParam("sortField") String sortField,
                                @RequestParam("sortDir") String sortDir,
                                Model model) {
        int pageSize = 5;

        Page<Student> page = studentService.findPaginated(pageNo, pageSize, sortField, sortDir);
        List<Student> listStudents = page.getContent();

        model.addAttribute("currentPage", pageNo);
        model.addAttribute("totalPages", page.getTotalPages());
        model.addAttribute("totalItems", page.getTotalElements());

        model.addAttribute("sortField", sortField);
        model.addAttribute("sortDir", sortDir);
        model.addAttribute("reverseSortDir", sortDir.equals("asc") ? "desc" : "asc");

        model.addAttribute("listStudents", listStudents);
        return "index";
    }
}

5、视图层

5.1、index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="ISO-8859-1">
    <title>Student Management System</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">

</head>
<body>

<div class="container my-2">
    <h1>Students List</h1>

    <a th:href = "@{/showNewStudentForm}" class="btn btn-primary btn-sm mb-3"> Add Student </a>

    <table border="1" class = "table table-striped table-responsive-md">
        <thead>
        <tr>
            <th>
                <a th:href="@{'/page/' + ${currentPage} + '?sortField=studentName&sortDir=' + ${reverseSortDir}}">
                    Student Name</a>
            </th>
            <th>
                <a th:href="@{'/page/' + ${currentPage} + '?sortField=studentAge&sortDir=' + ${reverseSortDir}}">
                    Student Age</a>
            </th>
            <th>
                <a th:href="@{'/page/' + ${currentPage} + '?sortField=counsellor&sortDir=' + ${reverseSortDir}}">
                    Student Counsellor</a>
            </th>
            <th> Actions </th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="student : ${listStudents}">
            <td th:text="${student.studentName}"></td>
            <td th:text="${student.studentAge}"></td>
            <td th:text="${student.counsellor}"></td>
            <td> <a th:href="@{/showFormForUpdate/{id}(id=${student.id})}" class="btn btn-primary">Update</a>
                <a th:href="@{/deleteStudent/{id}(id=${student.id})}" class="btn btn-danger">Delete</a>
            </td>
        </tr>
        </tbody>
    </table>

    <div th:if = "${totalPages > 1}">
        <div class = "row col-sm-10">
            <div class = "col-sm-3">
                Total Rows: [[${totalItems}]]
            </div>
            <div class = "col-sm-5">
					<span th:each="i: ${#numbers.sequence(1, totalPages)}">
						<a th:if="${currentPage != i}" th:href="@{'/page/' + ${i}+ '?sortField=' + ${sortField} + '&sortDir=' + ${sortDir}}">[[${i}]]</a>
						<span th:unless="${currentPage != i}">[[${i}]]</span>  &nbsp; &nbsp;
					</span>
            </div>
            <div class = "col-sm-1">
                <a th:if="${currentPage < totalPages}" th:href="@{'/page/' + ${currentPage + 1}+ '?sortField=' + ${sortField} + '&sortDir=' + ${sortDir}}">Next</a>
                <span th:unless="${currentPage < totalPages}">Next</span>
            </div>

            <div class="col-sm-1">
                <a th:if="${currentPage < totalPages}" th:href="@{'/page/' + ${totalPages}+ '?sortField=' + ${sortField} + '&sortDir=' + ${sortDir}}">Last</a>
                <span th:unless="${currentPage < totalPages}">Last</span>
            </div>
        </div>
    </div>
</div>
</body>
</html>
5.2、new_student.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="ISO-8859-1">
    <title>Student Management System</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
</head>

<body>
<div class="container">
    <h1>Student Management System</h1>
    <hr>
    <h2>Save Student</h2>

    <form action="#" th:action="@{/saveStudent}" th:object="${student}" method="POST">
        <input type="text" th:field="*{studentName}" placeholder="Student Name" class="form-control mb-4 col-4">

        <input type="text" th:field="*{studentAge}" placeholder="Student Age" class="form-control mb-4 col-4">

        <input type="text" th:field="*{counsellor}" placeholder="Student Counsellor" class="form-control mb-4 col-4">

        <button type="submit" class="btn btn-info col-2"> Save Student</button>
    </form>

    <hr>

    <a th:href="@{/}"> Back to Student List</a>
</div>
</body>

</html>
5.3、test.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col">
            1 of 2
        </div>
        <div class="col">
            2 of 2
        </div>
    </div>
    <div class="row">
        <div class="col">
            1 of 3
        </div>
        <div class="col">
            2 of 3
        </div>
        <div class="col">
            3 of 3
        </div>
        <div class="col">
            1 of 3
        </div>
        <div class="col">
            2 of 3
        </div>
        <div class="col">
            3 of 3
        </div>
    </div>
</div>
</body>
</html>
5.4、update_student.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="ISO-8859-1">
    <title>Student Management System</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">

   </head>

<body>
<div class="container">
    <h1>Student Management System</h1>
    <hr>
    <h2>Update Student</h2>

    <form action="#" th:action="@{/saveStudent}" th:object="${student}" method="POST">

        <!-- Add hidden form field to handle update -->
        <input type="hidden" th:field="*{id}" />

        <input type="text" th:field="*{studentName}" class="form-control mb-4 col-4">

        <input type="text" th:field="*{studentAge}" class="form-control mb-4 col-4">

        <input type="text" th:field="*{counsellor}" class="form-control mb-4 col-4">

        <button type="submit" class="btn btn-info col-2"> Update Student</button>
    </form>

    <hr>

    <a th:href="@{/}"> Back to Student List</a>
</div>
</body>

</html>

四、运行结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值