用户信息修改和删除
本节类容
- 常用的验证注解
- 自定义消息
- 自定义校验注解
常用的验证注解
自己官网或则百度吧。
官网文档
http://hibernate.org/validator/documentation/
https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/
编写update测试用例
@Test
public void whenUpdateSuccess() throws Exception {
// jdk8的时间处理类;使用LocalDateTime必须传递时区
// 给定一个一年后的时间
// long birthday = LocalDateTime.now().plusYears(1).atZone(ZoneId.systemDefault()).toEpochSecond();
// 注意这里的api不要传错了。是毫秒不是秒
long birthday = LocalDateTime.now().plusYears(1).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
String content = "{\"username\":\"mrcode\",\"password\":null,\"birthday\":" + birthday + "}";
String contentAsString = mockMvc.perform(put("/user/1")
.contentType(APPLICATION_JSON_UTF8)
.content(content)
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value("1"))
.andReturn().getResponse().getContentAsString();
System.out.println(contentAsString);
}
编写update api
@PutMapping("/{id:\\d+}")
public User update(@PathVariable() String id, @Valid @RequestBody User user, BindingResult errors) {
if (errors.hasErrors()) {
errors.getAllErrors().stream().forEach(err -> {
FieldError fieldError = (FieldError) err;
System.out.println(fieldError.getField() + " : " + err.getDefaultMessage());
});
}
System.out.println(ReflectionToStringBuilder.toString(user, ToStringStyle.MULTI_LINE_STYLE));
user.setId(id);
return user;
}
同样需要对user对象的生日添加过去时注解
@Past // 必须是过去时间
@JsonView(UserSimpleView.class)
private Date birthday;
运行测试用例输出
password : must not be blank
birthday : must be a past date
com.example.demo.dto.User@1980a3f[
id=<null>
username=mrcode
password=<null>
birthday=Fri Aug 02 11:41:59 GMT+08:00 2019
]
{"id":"1","username":"mrcode","password":null,"birthday":"2019-08-02 11:41:59"}
这里的错误信息是英文,下面自定义错误信息
自定义验证信息
@NotBlank(message = "密码不能为空")
private String password;
@Past(message = "生日必须是过去时间") // 必须是过去时间
@JsonView(UserSimpleView.class)
private Date birthday;
------ 就能让错误信息变成自定义的了 -----
password : 密码不能为空
birthday : 生日必须是过去时间
自定义校验注解
自定义注解
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
/**
* <pre>
* 自定义注解8
* </pre>
* @author zhuqiang
* @version 1.0.0
* @date 2018/8/2 12:33
* @since 1.0.0
*/
@Target({METHOD, FIELD})
@Retention(RetentionPolicy.RUNTIME) // 注释信息保留在运行时
@Constraint(validatedBy = MyConstraintValidator.class) // 用于什么类来校验这个注解,也就是有该注解的时候执行什么逻辑
public @interface MyConstraint {
// 下面三个属性是必须的,要使用hibernate.validator这个引擎来使用的话
// 具体的可以去深入
// 这里可以随意仿照一个 之前用到的注解中的源码,就能看到都有下面三个属性
String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
自定义注解逻辑
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* 自定义注解
* @author zhuqiang
* @version 1.0.1 2018/8/2 12:32
* @date 2018/8/2 12:32
* @since 1.0
*/
// 绑定一个注解类型,用于验证的值是什么
// 如果Object换成String,那么则只能把注解放在String类型上
public class MyConstraintValidator implements ConstraintValidator<MyConstraint, Object> {
// 实现ConstraintValidator接口后,会被spring扫描管理,所以可以直接使用注入服务
// 在idea 2017.3.2 版本中,可以看到该行代码前面有被管理到的一个标志图标
// @Autowired
// private UserController userController;
@Override
public void initialize(MyConstraint constraintAnnotation) {
System.out.println("初始化信息");
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
// 校验逻辑
System.out.println(value + " : " + context);
return false; // 返回false 表示验证不通过
}
}
使用自定义注解
@MyConstraint(message = "自定义注解演示使用")
private String username;
只要一个有验证信息的方法,运行测试用例查看信息
初始化信息
mrcode : org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl@664e848c
password : 密码不能为空
username : 自定义注解演示使用
birthday : 生日必须是过去时间
这里可以看到注入的上下文(ConstraintValidatorContext)是hibernate的一个类,也证明了我们使用的javax 的注解,但是还是hibernate框架实现的校验逻辑
删除服务
没有特别的要讲解的
@Test
public void whenDeleteSuccess() throws Exception {
mockMvc.perform(delete("/user/1")
.contentType(APPLICATION_JSON_UTF8)
)
.andExpect(status().isOk());
}
@DeleteMapping("/{id:\\d+}")
public void delete(@PathVariable String id) {
System.out.println("id:" + id);
}