对参数进行验证,可以在Model进行验证注解的地方定制提示信息,比如:
@NotBlank(message = "用户名不能为空")
private String userName;
@NotBlank(message = "密码不能为空")
private String password;
private String id;
@Past(message = "生日必须是过去的时间")
private Date birthday;
获取一年后的时间的方法:
//1年以后的时间
Date date = new Date(LocalDateTime.now().plusYears(1).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
对于校验时使用BindingResult erros时,有两点需要注意:
1. 有了这个定义,代码会正常执行,所以返回的类型不是4xx,而是200(.isOK());
@Test
public void whenUpdateUserCurrent() throws Exception {
Date currentDate = new Date();
updateUser(currentDate);
}
@Test
public void whenUpdateUserAfterYear() throws Exception {
//1年以后的时间
Date date = new Date(LocalDateTime.now().plusYears(1).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
updateUser(date);
}
private void updateUser(Date birthday) throws Exception {
User u = new User();
u.setUserName("chen123");
u.setPassword("123456");
u.setBirthday(birthday);
String content = JSONObject.toJSONString(u);
String result = mockMvc.perform((put("/user/1")).contentType(MediaType.APPLICATION_JSON_UTF8)
.content(content))
.andExpect(status().isOk()) //這裡不變
.andExpect(jsonPath("$.id").value("1"))
.andReturn().getResponse().getContentAsString();
System.out.println(result);
}
2. BindingResult erros 要緊挨着要驗證的參數,否則不起作用,如果把BindingResult erros与路径参数ID换了为在,就不会有验证的输出。
@PutMapping("/user/{id:\\d+}")
public User updateUser(@Valid @RequestBody User u, BindingResult erros, @PathVariable String id) {
if (erros.hasErrors()) {
//如果验证有错误则进行输出
erros.getAllErrors().stream().forEach(error->{
// FieldError fieldError = (FieldError) error;
// String errorMessage = fieldError.getField() + " " + error.getDefaultMessage();
String errorMessage = error.getDefaultMessage();
System.out.println(errorMessage);
});
}
u.setId(id);
return u;
}