Controller
// 参数校验
// 需要在被校验的对象上添加@valid注解(设置在形参前)
@PutMapping("user02")
public Map<String,Object> updateUser02(@Valid User user){
Map<String,Object> map = new HashMap<>();
//调用service层添加方法,返回map对象
userService.updateUser(user);
return map;
}
Po
//数据校验 当校验不通过时,会抛出异常,被全局异常处理器所捕获(BindException)
public class User {
private Integer id;
@NotBlank(message = "用户名称不能为空")
private String userName;
@NotBlank(message = "密码不能为空")
@Length(min = 4,max = 10,message = "密码长度4至10位之间")
private String userPwd;
@Email //如果email值为空,则不校验;不为空要求,满足email格式
private String user
GlobalExceptionHandlerResolver
//处理数据校验的异常
@ExceptionHandler(value = BindException.class)
@ResponseBody
public Map<String,Object> exceptionHandler03(BindException b){
Map<String,Object> map = new HashMap<>();
map.put("code",500);
map.put("msg",b.getBindingResult().getFieldError().getDefaultMessage());
return map;
}