请求入参的校验
1. 依赖
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
2. 接收前端传过来的参数的Dto类
import javax.validation.constraints.NotNull;
private class UserReqDto{
@NotNull(message = "用户名不能为空")
private String userName;
@NotNull(message = "密码不能为空")
private String password;
@NotNull(message = "联系地址不能为空")
private String address;
@NotNull(message = "电话号码不能为空")
private String phone;
...getter and setter...
}
3.控制层
@Controller
public class Test {
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test(@Valid @RequestBody UserReqDto userDto){
//service的逻辑...
}
这个时候如果直接发起请求,UserReqDto 其中一个字段为null,就会报错, 如果userName=null ...arguments []; default message [userName]]; default message [用户名不能为空]]
如果想要或者这个message信息,可以通过Spring的@ExceptionHandler和@ControllerAdvice
统一处理异常
参数校验失败,会经过spring的org.springframework.web.bind.MethodArgumentNotValidException
异常类抛出异常,我们处理这个异常类的信息就可以了
@ControllerAdvice
@ResponseBody
public class ExceptionHandle {
private static final Logger log = LoggerFactory.getLogger(ExceptionHandle.class);
public ExceptionHandle() {
}
@ExceptionHandler({MethodArgumentNotValidException.class})
public String handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
BindingResult result = e.getBindingResult();
FieldError error = result.getFieldError();
String field = error.getField();
String code = error.getDefaultMessage();
String message = String.format("%s:%s", field, code);
log.warn("参数验证失败:" + message);
return "参数验证失败:" + message;
}
}
弹出的显示信息:
2018-08-14 17:54:27.673 WARN com.zgd.exception.ExceptionHandle Line:124 - 参数验证失败:mchtName:mchtName不能为空
4. 其他的valid注解
hibernate除了JSR303的标准之外还额外提供了其他的验证注解。下表是JSR303支持的验证注解:
hibernate-validator附带的注解
5. group分组
比如name,password,age在登录的时候,需要name和password不为空, 在修改年龄的时候,仅需要age不为空, 所以在不同的需求中, 校验也不一样, 这个时候我们可以分组
@NotNull(message = "用户名不能为空", groups = GroupA.class)
private String userName;
@NotNull(message = "密码不能为空", groups = GroupB.class)
private String password;
这个时候我们需要自定义没有方法的接口:
public interface GroupA {
}
public interface GroupB {
}
然后在方法中指定我们需要哪个group的校验就可以了
public String test(@Validated(GroupA.class) @RequestBody UserReqDto dto){
}
这个时候将
{"userName":null,"password":null}
作为参数进行访问,只会报用户名不能为空