创建一个学生信息管理系统,通过登录页面输入自己的姓名和密码后验证登录,成功跳转到指定页面并显示学生信息列表
时间: 2024-10-25 08:06:49 浏览: 40
创建一个简单的学生信息管理系统,我们可以使用Java Spring Boot框架,配合Thymeleaf模板引擎进行前端页面渲染。首先,我们需要设置数据库存储学生信息(例如MySQL),然后设计实体类(Student)、数据访问层(DAO)以及服务层(Service)来处理业务逻辑。
以下是一些关键步骤:
1. **Entity (实体类)**:
```java
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String password; // 密码通常在数据库中应加密存储
// Getters and Setters
}
```
2. **Repository (数据访问接口)**:
```java
public interface StudentRepository extends JpaRepository<Student, Long> {
Student findByUsername(String username);
}
```
3. **Service (服务类)**:
```java
@Service
public class UserService {
private final StudentRepository studentRepository;
public UserService(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
public boolean validateLogin(String username, String password) {
Student user = studentRepository.findByUsername(username);
if (user != null && BCrypt.checkpw(password, user.getPassword())) {
return true;
}
return false;
}
}
```
4. **Controller (控制器)**:
```java
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
if (userService.validateLogin(username, password)) {
return "Login successful. Redirecting to student details.";
} else {
return "Invalid credentials.";
}
}
@GetMapping("/students")
public String displayStudents() {
List<Student> students = studentRepository.findAll();
// 使用Thymeleaf将学生列表渲染到HTML模板中
return "redirect:/student-list.html?users=" + students;
}
}
```
5. **Thymeleaf模板** (`student-list.html`):
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<!-- ... -->
</head>
<body>
<h2>Student List</h2>
<table th:each="student : ${users}">
<tr>
<td th:text="${student.name}"></td>
<!-- 添加其他字段如ID或邮箱 -->
</tr>
</table>
<!-- ... -->
</body>
</html>
```
6. **登录页面**:
使用Spring Security或自定义表单提交请求到`/api/login` URL。
阅读全文