前言
我們在寫接口的時候,需要對傳來的數據進行必要的校驗,先來看一段可以改造的代碼:
public String register(User user) {
if (StringUtils.isEmpty(user.getAccount()) || StringUtils.isEmpty(user.getPassword()) || StringUtils.isEmpty(user.getEmail())) {
return "不能輸入空字符串";
}
if (user.getAccount().length() < 6 || user.getAccount().length() > 11) {
return "賬號長度必須是6-11個字符";
}
if (user.getPassword().length() < 6 || user.getPassword().length() > 16) {
return "密碼長度必須是6-16個字符";
}
if (!Pattern.matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$", user.getEmail())) {
return "郵箱格式不正確";
}
// 註冊用戶邏輯
return "success";
}
方法中用於校驗數據格式的代碼很多,這種代碼可以改造。
首先,在實體類上標上註解:
@Data
public class User {
private Long id;
@NotNull(message = "用戶賬號不能爲空")
@Size(min = 6, max = 11, message = "賬號長度必須是6-11")
private String account;
@NotNull(message = "密碼不能爲空")
@Size(min = 6, max = 11, message = "密碼長度必須是6-16")
private String password;
@NotNull(message = "郵箱不能爲空")
@Email(message = "郵箱格式不正確")
private String email;
}
接着,在 controller 上加上 @Valid 註解
@PostMapping("/register")
public String register(@RequestBody @Valid User user) {
return userService.register(user);
}
請求時,參數傳 {}
,響應如下:
{
"status": 400,
"error": "Bad Request",
"errors": [
{
"codes": [
"NotNull.user.password",
"NotNull.password",
"NotNull.java.lang.String",
"NotNull"
],
"arguments": [
{
"codes": [
"user.password",
"password"
],
"arguments": null,
"defaultMessage": "password",
"code": "password"
}
],
"defaultMessage": "用戶密碼不能爲空",
"objectName": "user",
"field": "password",
"rejectedValue": null,
"bindingFailure": false,
"code": "NotNull"
}
],
"message": "Validation failed for object='user'. Error count: 4",
"path": "/user/register"
}
這種應該怎麼解決呢?
之前我們用過@ExceptionHandler
,現在加一個
@ControllerAdvice
@Slf4j
@ResponseBody
public class ExceptionHandlerAdvice {
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result<Object> handleArgsNotValidException(MethodArgumentNotValidException e) {
ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
return Result.err(objectError.getDefaultMessage());
}
}
最後的結果:
{
"code": 500,
"message": "用戶郵箱不能爲空",
"data": null
}