用java代码示例springboot中修改密码的接口
时间: 2024-03-09 11:50:20 浏览: 24
好的,以下是一个简单的示例代码:
```java
@RestController
@RequestMapping("/api/user")
public class UserController {
@Autowired
private UserService userService;
@PutMapping("/{userId}/password")
public ResponseEntity<String> updatePassword(@PathVariable Long userId, @RequestBody PasswordUpdateRequest request) {
userService.updatePassword(userId, request.getOldPassword(), request.getNewPassword());
return ResponseEntity.ok("Password updated successfully.");
}
}
public class PasswordUpdateRequest {
private String oldPassword;
private String newPassword;
// getters and setters
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void updatePassword(Long userId, String oldPassword, String newPassword) {
User user = userRepository.findById(userId).orElseThrow(() -> new UserNotFoundException(userId));
if (!user.getPassword().equals(oldPassword)) {
throw new InvalidPasswordException("Old password is incorrect.");
}
user.setPassword(newPassword);
userRepository.save(user);
}
}
public class User {
private Long id;
private String username;
private String password;
// getters and setters
}
public interface UserRepository extends JpaRepository<User, Long> {}
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(Long userId) {
super("User not found with id: " + userId);
}
}
public class InvalidPasswordException extends RuntimeException {
public InvalidPasswordException(String message) {
super(message);
}
}
```
这个示例中,我们定义了一个 `UserController`,其中有一个 `updatePassword` 方法,用于修改用户的密码。在 `UserService` 中,我们实现了修改密码的逻辑,并在出现异常的情况下抛出自定义的异常。最后,我们使用 `UserRepository` 来与数据库进行交互,完成密码的修改。
相关推荐
![](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)
![](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)