基于spring的validation及hibernate validation
特点:
1、支持spring注入(没找到hibernate validation如何注入)
2、自定义注解验证(虽然hibernate validation也支持)
3、写了一个验证码校验,和验证引用的DIY注解(指向)
?
使用例子:
User entity
?
class="java" name="code">package org.kilobug.news.entity; import javax.validation.constraints.Min; import lombok.Data; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.Length; @Data public class User { private Long id; @Min(0) private Long roleId = 0L; @Email private String email; @Min(0) private Long mobile = 0L; private byte[] password; @Length(min=6, max=32) private String plainPassword; private byte[] salt; private String plainSalt; private Long creationTime; private Long creationIp; private Long lastLoginTime = 0L; private Long lastLoginIp = 0L; private Long statusId = 0L; }
?
?
UserAdd entity
?
package org.kilobug.news.service.entity; import lombok.Data; import org.hibernate.validator.constraints.NotBlank; import org.kilobug.news.entity.User; import org.kilobug.validator.constrains.BaseValidate; import org.kilobug.validator.constrains.Captcha; public @Data class UserAdd { @BaseValidate(value=User.class) // 根据User的email字段的规则验证 private String email; @BaseValidate(value=User.class) // 根据User的plainPassword字段的规则验证 private String plainPassword; @NotBlank @Captcha // 自定义注解验证器,支持注入 private String captcha; }
?
?
使用:
?
package org.kilobug.news.validator; import org.kilobug.news.entity.User; import org.kilobug.news.service.entity.UserAdd; import org.kilobug.validator.ValidatorUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; @Component public class UserAddValidator implements Validator { @Autowired private ValidatorUtil validator; @Override public boolean supports(Class<?> clazz) { return UserAdd.class.equals(clazz); } @Override public void validate(Object target, Errors errors) { if(validator.vaildate(target, errors) == false) return; UserAdd entity = (UserAdd) target; // :TODO 进一步自定义判断 } }
?
?
?