@PathVariable 验证并提示
时间: 2023-12-02 12:42:59 浏览: 26
@PathVariable注解用于从URL中获取参数值,通常用于RESTful API中。如果参数值不符合要求,可以使用@PathVariable进行验证并提示用户。
以下是一个使用@PathVariable验证并提示的例子:
```java
@GetMapping("/users/{id}")
public User getUserById(@PathVariable Long id) {
User user = userRepository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
return user;
}
@ExceptionHandler(UserNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleUserNotFoundException(UserNotFoundException ex) {
return ex.getMessage();
}
```
在上面的例子中,getUserById方法使用@PathVariable注解从URL中获取id参数值,并使用userRepository查找对应的用户。如果找不到用户,将抛出UserNotFoundException异常。
handleUserNotFoundException方法使用@ExceptionHandler注解处理UserNotFoundException异常,并返回异常信息给用户。