springboot注解校验参数
实例
基本应用
引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
Controller 中需要校验的参数Bean前添加Validated
public ResultVO updateSysUser(@RequestBody @Validated(Groups.Update.class) SysUserIPt sysUserIPt) { String token = request.getHeader(CommonConstant.ACCESS_TOKEN); SysUser userInfo = (SysUser)redisService.get(CommonConstant.PREFIX_USER_INFO+token); SysUser sysUser = BeanConvertor.convertBean(sysUserIPt,SysUser.class); try { int count = sysUserService.updateSysUser(sysUser,userInfo); } catch (Exception e) { e.printStackTrace(); return ResultVO.vo(ResultCode.ERROR,e.getMessage()); } SysUserIPo sysUserIPo = BeanConvertor.convertBean(sysUser, SysUserIPo.class); return ResultVO.vo(sysUserIPo); }
给参数对象添加校验注解
/** * 用户ID */ @NotEmpty(message = "用户id不能为空" , groups = Groups.Update.class) private String userId; /** * 部门ID */ @NotEmpty(message = "部门ID不能为空",groups = Groups.Add.class) @NotEmpty(message = "部门ID不能为空",groups = Groups.Update.class) private String deptId; /** * 登录账号 */ @NotEmpty(message = "登录账号不能为空",groups = Groups.Add.class) @NotEmpty(message = "登录账号不能为空",groups = Groups.Update.class) private String loginName;
异常的统一处理
参数校验不通过时,会抛出 BingBindException 异常,可以在统一异常处理中,做统一处理。
/** * 方法参数错误异常 * @param e * @return */ @ExceptionHandler({MethodArgumentNotValidException.class,BindException.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) public ResultVO<Object> MethodArgumentNotValidExceptionHandler(Exception e) { log.error("参数异常"); BindingResult bindingResult = null; Map map = new HashMap<>(); if (e instanceof MethodArgumentNotValidException) { bindingResult = ((MethodArgumentNotValidException)e).getBindingResult(); } else if (e instanceof BindException) { bindingResult = ((BindException)e).getBindingResult(); } bindingResult.getFieldErrors().forEach((fieldError)-> map.put(fieldError.getField(),fieldError.getDefaultMessage()) ); return ResultVO.vo( ResultCode.VALIDATE_FAILED , map); }
然后加上分组校验
public class Groups {
public interface Add{}
public interface Update{}
}
就成功了