Spring Validator参数校验
Spring Validator参数校验
Spring提供了Validator接口用于对Bean即一般的接口入参DTO做参数校验。
校验器需要实现Validator接口:
@Component //使校验器可以注入Controller类
public class FeedBackDtoValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return clazz.equals(FeedBackDto.class);
}
@Override
public void validate(Object target, Errors errors) {
FeedBackDto dto=(FeedBackDto)target;
if(null !=dto.getCourseFeedBackId() && StringUtils.isBlank(EnumCourseFeedStatus.getValue(dto.getCourseFeedBackId()))){
errors.reject("课堂反馈状态参数错误", "课堂反馈状态参数错误");
return;
}
if(StringUtils.isBlank(dto.getStartDate()) || StringUtils.isBlank(dto.getEndDate())){
errors.reject("开始和结束日期必须同时选中", "开始和结束日期必须同时选中");
return;
}
}
}
@InitBinder(value = "feedBackDto")
public void initBinderParameter(WebDataBinder binder) {
binder.addValidators(feedBackDtoValidator);
}
@InitBinder 注解
用于初始化WebDataBinder
WebDataBinder
将请求参数绑定到Java类(Java Bean)
@InitBinder
public void dataBinding(WebDataBinder binder) {
binder.addValidators(userValidator, emailValidator);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, "dob", new CustomDateEditor(dateFormat, true));
}
CustomDateEditor
转换请求参数格式的工具
registerCustomEditor()
注册请求参数格式转换工具
@ApiOperation(value = "查询课堂反馈列表")
@ResponseBody
@RequestMapping(value = "/feedbackList", method = { RequestMethod.POST, RequestMethod.GET })
public ResponseInfo<Criteria<OCourseFeedbackVO>> feedbackList(@Valid @ApiParam(value = "查询参数")@RequestBody FeedBackDto feedBackDto, BindingResult result, @RequestHeader("access-token") String token) throws Exception {
if (result.hasErrors()) {
throw new CustomExcetion(result.getAllErrors().get(0).getDefaultMessage().toString());
}
return buildSuccessRetunInfo();
}
@Valid
Hibernate-Valid 注解,表示开启入参校验
BindingResult
校验结果,如果校验不成功(result.hasErrors()),则返回校验失败。
[1]:Spring MVC 4 - Form validation example using Validator interface
[2]:SR 303 - Bean Validation 介绍及最佳实践
posted on 2018-11-21 10:41 ShoolyShooly 阅读(1046) 评论(0) 编辑 收藏 举报