近日开发rsetapi 做数据校验的时候,多次接触 到hibernate.validator 的注解校验, hibernate.validator 主要有如下的的注解校验规则。
@AssertTrue //用于boolean字段,该字段只能为true
@AssertFalse //该字段的值只能为false
@CreditCardNumber //对信用卡号进行一个大致的验证
@DecimalMax //只能小于或等于该值
@DecimalMin //只能大于或等于该值
@Digits (integer= 2 ,fraction= 20 ) //检查是否是一种数字的整数、分数,小数位数的数字。
@Email //检查是否是一个有效的email地址
@Future //检查该字段的日期是否是属于将来的日期
@Length (min=,max=) //检查所属的字段的长度是否在min和max之间,只能用于字符串
@Max //该字段的值只能小于或等于该值
@Min //该字段的值只能大于或等于该值
@NotNull //不能为null
@NotBlank //不能为空,检查时会将空格忽略
@NotEmpty //不能为空,这里的空是指空字符串
@Null //检查该字段为空
@Past //检查该字段的日期是在过去
@Size (min=, max=) //检查该字段的size是否在min和max之间,可以是字符串、数组、集合、Map等
@URL (protocol=,host,port) //检查是否是一个有效的URL,如果提供了protocol,host等,则该URL还需满足提供的条件
@Valid //该注解只要用于字段为一个包含其他对象的集合或map或数组的字段,或该字段直接为一个其他对象的引用,
那能否自己也写一个校验呢
首先创建一个规则类 继承ConstraintValidator 重写 initialize(加在) isValid(验证) 方法
public class MyConstraintValidator implements ConstraintValidator<MyConstraint,Object>{
//注解加载的方法
public void initialize(MyConstraint arg0) {
System.out.println("MyConstraint int");
// TODO Auto-generated method stub
}
@Override
//验证方法
public boolean isValid(Object value, ConstraintValidatorContext content) {
// TODO Auto-generated method stub
System.out.println("反正就是不给过你能怎么办呢");
//true 验证通过 false 验证不通过
return false;
}
创建一个调用上述验证类的注解
//表示该注解可以放在方法或者字段上面
@Target({ElementType.METHOD,ElementType.FIELD})
//这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用
@Retention(RetentionPolicy.RUNTIME)
//之命校验的类
@Constraint(validatedBy=MyConstraintValidator.class)
public @interface MyConstraint {
String message() default "{哈哈你错了}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
下面写一个类测试
public class User {
private int id;
public interface UserSimpleView{};
public interface UserDetailView extends UserSimpleView {};
@MyConstraint(message="看见我了就代表成功了")
private String username;
@NotBlank(message="密码不能为空")
private String password;
private Date birthday;
@JsonView(UserSimpleView.class)
@Past(message="时间必须是过去的时间")
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@JsonView(UserSimpleView.class)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
@JsonView(UserSimpleView.class)
public void setUsername(String username) {
this.username = username;
}
@JsonView(UserDetailView.class)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
些一个单元测试 测试看看是否成功
@Test //put 请求做修改
public void whenUpdateSuccess() {
//传入后一年的时间
Date date=new Date(LocalDateTime.now().plusYears(1).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
String content="{\"username\":\"tom\",\"id\":1,\"birthday\":"+date.getTime()+"}";
try {
String result=mockMvc.perform(MockMvcRequestBuilders.put("/user/1")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(content))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1))
.andReturn().getResponse().getContentAsString();
System.out.println(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
运行单元测试
哒哒哒 成功了
文章地址:http://www.haha174.top/article/details/251105
源码地址:https://github.com/haha174/imooc-security.git