我们在写接口的时候,需要对传来的数据进行必要的校验,先来看一段可以改造的代码:
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
}