springboot学生宿舍管理系统不同角色登录功能判断密码与角色类型代码
时间: 2023-12-08 16:05:40 浏览: 32
以下是一个简单的 Spring Boot 学生宿舍管理系统不同角色登录功能判断密码与角色类型代码的示例:
首先,需要定义一个用户实体类 User,包括 id、用户名、密码和角色类型等属性:
```java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String role;
// getter 和 setter 略
}
```
接下来,定义一个 UserService 类,用于处理用户相关的业务逻辑,包括用户登录验证和角色类型判断:
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User login(String username, String password) {
User user = userRepository.findByUsername(username);
if (user == null || !user.getPassword().equals(password)) {
throw new RuntimeException("用户名或密码错误");
}
return user;
}
public boolean hasRole(User user, String role) {
return user.getRole().equals(role);
}
}
```
其中,login() 方法用于验证用户登录,当用户名或密码错误时会抛出异常;hasRole() 方法用于判断用户的角色类型是否与指定的角色类型匹配。
最后,定义一个 LoginController 类,处理用户登录请求,并根据用户角色类型跳转到不同的页面:
```java
@Controller
public class LoginController {
@Autowired
private UserService userService;
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/login")
public String doLogin(String username, String password, Model model) {
try {
User user = userService.login(username, password);
if (userService.hasRole(user, "admin")) {
return "redirect:/admin/index";
} else if (userService.hasRole(user, "teacher")) {
return "redirect:/teacher/index";
} else if (userService.hasRole(user, "student")) {
return "redirect:/student/index";
} else {
throw new RuntimeException("未知的角色类型");
}
} catch (Exception e) {
model.addAttribute("error", e.getMessage());
return "login";
}
}
}
```
其中,login() 方法用于显示登录页面;doLogin() 方法用于处理用户登录请求,并根据用户角色类型跳转到不同的页面。当登录失败时,会将错误信息添加到模型中,再次显示登录页面并提示错误信息。
以上就是一个简单的 Spring Boot 学生宿舍管理系统不同角色登录功能判断密码与角色类型代码的示例。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)