springboot创建学生管理系统
时间: 2023-09-04 11:15:31 浏览: 43
好的,下面是一个简单的示例,演示如何使用Spring Boot创建一个学生管理系统。
1. 创建Spring Boot项目
使用Spring Initializr创建一个新的Spring Boot项目。在“Dependencies”中选择“Spring Web”和“Thymeleaf”以进行Web开发和页面渲染。
2. 创建学生实体类
创建一个名为“Student”的Java类,表示学生实体。它应该包含学生的id、姓名、年龄和班级等属性。
```java
public class Student {
private Long id;
private String name;
private int age;
private String className;
// getters and setters
}
```
3. 创建学生控制器
创建一个名为“StudentController”的Java类,它将处理与学生相关的HTTP请求。例如,可以使用它来显示学生列表、添加新学生、删除学生等。
```java
@Controller
public class StudentController {
private List<Student> students = new ArrayList<>();
@GetMapping("/")
public String index(Model model) {
model.addAttribute("students", students);
return "index";
}
@GetMapping("/add")
public String add(Model model) {
model.addAttribute("student", new Student());
return "add";
}
@PostMapping("/save")
public String save(Student student) {
students.add(student);
return "redirect:/";
}
@GetMapping("/delete/{id}")
public String delete(@PathVariable Long id) {
students.removeIf(student -> student.getId().equals(id));
return "redirect:/";
}
}
```
4. 创建页面模板
创建两个名为“index.html”和“add.html”的HTML文件,用于渲染学生列表和添加学生表单。
index.html:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Student Management System</title>
</head>
<body>
<h1>Student List</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Class</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr th:each="student : ${students}">
<td th:text="${student.id}"></td>
<td th:text="${student.name}"></td>
<td th:text="${student.age}"></td>
<td th:text="${student.className}"></td>
<td>
<a th:href="@{'/delete/' + ${student.id}}">Delete</a>
</td>
</tr>
</tbody>
</table>
<a th:href="@{/add}">Add Student</a>
</body>
</html>
```
add.html:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Add Student</title>
</head>
<body>
<h1>Add Student</h1>
<form method="post" th:object="${student}" th:action="@{/save}">
<label>ID: <input type="text" th:field="*{id}" /></label><br/>
<label>Name: <input type="text" th:field="*{name}" /></label><br/>
<label>Age: <input type="text" th:field="*{age}" /></label><br/>
<label>Class: <input type="text" th:field="*{className}" /></label><br/>
<input type="submit" value="Save" />
</form>
</body>
</html>
```
5. 运行应用程序
启动应用程序并访问http://localhost:8080,您应该能够看到学生列表。单击“Add Student”链接以添加新学生。添加后,学生列表应该会更新。
这就是使用Spring Boot创建学生管理系统的基本过程。当然,这只是一个简单示例,您可以根据自己的需求进行扩展和定制。