一.依赖架包:
validation-api-1.0.0.GA.jar
hibernate-validator-4.3.1.final-1.0.0.jar
二.校验工具类
public class ValidationUtils {
private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
public static <T> ValidationResult validateEntity(T obj) {
ValidationResult result = new ValidationResult();
Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
if (CollectionUtils.isNotEmpty(set)) {
result.setHasErrors(true);
Map<String, String> errorMsg = new HashMap < String, String>();
for (ConstraintViolation<T> cv : set) {
errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());
}
result.setErrorMsg(errorMsg);
}
return result;
}
public static <T> ValidationResult validateProperty(T obj, String propertyName) {
ValidationResult result = new ValidationResult();
Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, Default.class);
if (CollectionUtils.isNotEmpty(set)) {
result.setHasErrors(true);
Map<String, String> errorMsg = new HashMap< String, String>();
for (ConstraintViolation<T> cv : set) {
errorMsg.put(propertyName, cv.getMessage());
}
result.setErrorMsg(errorMsg);
}
return result;
}
}
三、校验返回对象
package com.framework.loippi.utils.vali;
import java.util.Map;
public class ValidationResult {
//校验结果是否有错
private boolean hasErrors;
//校验错误信息
private Map<String, String> errorMsg;
public boolean getHasErrors() {
return hasErrors;
}
public void setHasErrors(boolean hasErrors) {
this.hasErrors = hasErrors;
}
public Map<String, String> getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(Map<String, String> errorMsg) {
this.errorMsg = errorMsg;
}
}
四.自定义注解
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = PasswordValidator.class)
@Documented
public @interface Password {
String message() default"{密码必须是5~10位数字和字母组合}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
五、自定义密码校验类
public class PasswordValidator implements ConstraintValidator<Password, String>{
//5~10位的数字与字母组合
privatestatic Pattern pattern = Pattern.compile("(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{5,10}");
public void initialize(Password constraintAnnotation){
//do nothing
}
public boolean isValid(String value, ConstraintValidatorContext context){
if( value==null ){
returnfalse;
}
Matcher m = pattern.matcher(value);
return m.matches();
}
}
Constraint |
详细信息 |
@Null |
被注释的元素必须为 null |
@NotNull |
被注释的元素必须不为 null |
@AssertTrue |
被注释的元素必须为 true |
@AssertFalse |
被注释的元素必须为 false |
@Min(value) |
被注释的元素必须是一个数字,其值必须大于等于指定的最小值 |
@Max(value) |
被注释的元素必须是一个数字,其值必须小于等于指定的最大值 |
@DecimalMin(value) |
被注释的元素必须是一个数字,其值必须大于等于指定的最小值 |
@DecimalMax(value) |
被注释的元素必须是一个数字,其值必须小于等于指定的最大值 |
@Size(max, min) |
被注释的元素的大小必须在指定的范围内 |
@Digits (integer, fraction) |
被注释的元素必须是一个数字,其值必须在可接受的范围内 |
@Past |
被注释的元素必须是一个过去的日期 |
@Future |
被注释的元素必须是一个将来的日期 |
@Pattern(value) |
被注释的元素必须符合指定的正则表达式 |
标准实现者如hibernate-validater提供的约束如下:
Constraint |
详细信息 |
@Email |
被注释的元素必须是电子邮箱地址 |
@Length |
被注释的字符串的大小必须在指定的范围内 |
@NotEmpty |
被注释的字符串的必须非空 |
@Range |
被注释的元素必须在合适的范围内 |
应用部分
6.Result类编辑
import com.alibaba.fastjson.JSON;
import lombok.Data;
@Data
public class Result<T> {
private boolean success;
private String message;
private T data;
public Result() {
this.success = true;
this.message = "success";
}
public Result(boolean success, String message, T data) {
this.success = success;
this.message = message;
this.data = data;
}
public Result(boolean success, String message) {
this.success = success;
this.message = message;
}
/**
* 是否有错误
* @return
*/
public boolean hasError() {
return !success;
}
}
7.公共校验类
import com.framework.loippi.utils.result.Result;
import com.framework.loippi.utils.vali.ValidationResult;
import com.framework.loippi.utils.vali.ValidationUtils;
/**
* 验证器
*/
public class Validator {
public Result check() {
ValidationResult result = ValidationUtils.validateEntity(this);
if (result.getHasErrors()) {
for (String key : result.getErrorMsg().keySet()) {
return new Result(false, result.getErrorMsg().get(key));
}
}
return new Result(true, "ok");
}
}
8.要提交的表单实体extends 公共校验器 Validator
import com.alibaba.fastjson.JSON;
import com.framework.loippi.entity.*;
import com.framework.loippi.entity.supplier.LicenceForm;
import com.framework.loippi.entity.validator.Validator;
import com.framework.loippi.utils.CosUrlUtils;
import com.framework.loippi.utils.StringUtil;
import com.framework.loippi.utils.result.Result;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@Data
@NoArgsConstructor
public class GoodsForm extends Validator{
// 商品编号
@NotBlank(message = "商品编号不能为空")
private String bn;
// 条形码
@NotBlank(message = "条形码不能为空")
private String barCode;
// 标题
@NotBlank(message = "商品名称不能为空")
private String title;
}
9.controller 校验
@ResponseBody
@RequestMapping(value = "/save", method = RequestMethod.POST)
public Result save( GoodsForm goodsForm) {
// 检查
Result check = goodsForm.check();
if (!check.isSuccess()) {
return check;
}
return new Result(true, "OK");
}
网友评论