JAVA字段校验(validation)
在开发业务时,不可避免的需要处理⼀些校验, 如果是写if-el这种代码去校验, 那会有⼀⼤段这样的代码。不过还好有个校验插件:javax.validation.validation-api,不过⼀般会引⽤hibernate的校验组件:org.hibernate.hibernate-validator, 它已经引⽤了validation-api组件。
基础校验类型
JSR303 是⼀套JavaBean参数校验的标准,它定义了很多常⽤的校验注解,我们可以直接将这些注解加在我们JavaBean的属性上⾯,就可以在需要校验的时候进⾏校验了。注解如下:
Hibernate validator 在JSR303的基础上对校验注解进⾏了扩展,扩展注解如下:
写个DEMO看看
校验⼯具类:ValidatorUtils
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import ups.Default;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Created by saleson on 2017/10/13.
*/
public class ValidatorUtils {
private static Validator validator = Validation.buildDefaultValidatorFactory()
.getValidator();
public static <T> Map<String, String> validate(T obj) {
Map<String, StringBuilder> errorMap = new HashMap<>();
Set<ConstraintViolation<T>> t = validator.validate(obj, Default.class);
if (t != null && t.size() > 0) {
String property = null;
for (ConstraintViolation<T> cv : t) {
//这⾥循环获取错误信息,可以⾃定义格式
property = cv.getPropertyPath().toString();
if ((property) != null) {
<(property).append("," + cv.getMessage());
} el {
StringBuilder sb = new StringBuilder();
sb.Message());
errorMap.put(property, sb);
}
}
}
Set().stream().Map(k -> k.getKey(), v -> v.getValue().toString()));
}
}
DemoBean:
import xceptions.ApiException;
import org.straints.NotEmpty;
import com.fm.framework.api.ApiResultHelper;
import com.fm.framework.json.Json;
import com.fm.framework.utils.StringUtils;
import antauth.domain.ValidateResult;
import antauth.domain.dto.AuthorizationApplyDTO;
import antauth.utils.ValidatorUtils;
import org.junit.Test;
import javax.validation.Valid;
import java.util.Map;
/**
* Created by saleson on 2017/10/12.
*/
public class DataAuthValidator {
private static final Logger log = Logger(DataAuthValidator.class);
@Override
public ValidateResult validate(AuthorizationApplyDTO applyDTO) {
String json = ContractParams();
if (StringUtils.isEmpty(json)) {
throw new wParameterEmpty("contractParams字段不能为空"));
}
DataAuthContractParams params = Json.parObject(json, DataAuthContractParams.class);
Map<String, String> validMap = ValidatorUtils.validate(params);
if (!validMap.isEmpty()) {
log.String());
throw new wBusinessError(lackFieldMessage(validMap.keySet().toArray(new String[0])))); }
return new ValidateResult(true);
}
public static class DataAuthContractParams {
@NotEmpty
private String businessName;
@NotEmpty
private String dataProvider;
@NotEmpty
private String personalDataName;
@NotEmpty
private String dataDemander;
public String getBusinessName() {
return businessName;
}
public void tBusinessName(String businessName) {
this.businessName = businessName;
}
public String getDataProvider() {
return dataProvider;
}
public void tDataProvider(String dataProvider) {
this.dataProvider = dataProvider;
}
public String getPersonalDataName() {
return personalDataName;
}
public void tPersonalDataName(String personalDataName) {
this.personalDataName = personalDataName;
}
public String getDataDemander() {
return dataDemander;
}
public void tDataDemander(String dataDemander) {
this.dataDemander = dataDemander;
}
}
@Test
public void test() {
AuthorizationApplyDTO applyDTO = new AuthorizationApplyDTO();
DataAuthContractParams params = new DataAuthContractParams();
params.tBusinessName("f");
params.tDataDemander("f");
params.tDataProvider("");
params.tPersonalDataName("");
applyDTO.JSONString(params));
ValidateResult result = new DataAuthValidator().validate(applyDTO);
System.out.JSONString(result));
asrt result.isSeccess();
}
}
运⾏结果:
[main] WARN act.DataAuthValidator - {dataProvider=不能为空, personalDataName=不能为空} xceptions.ApiException:参数contractParams中缺少字段:dataProvider, personalDataName
⾃定义校验规则(Validator)
⾃定义注解:
package validation;
import validation.validator.NotEmptyValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
/**
* Created by saleson on 2017/5/31.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Documented
@Constraint(validatedBy = {NotEmptyValidator.class})
public @interface NotEmpty {
String message() default"参数不能为null或空字符串";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
校验器(validator):
package validation.validator;
import validation.NotEmpty;
import com.fm.framework.utils.StringUtils;
import s.collections.MapUtils;
import javax.validation.ConstraintValidatorContext;
import flect.Array;
import java.util.Collection;
import java.util.Map;
/**
* Created by saleson on 2017/5/27.
*/
public class NotEmptyValidator extends AbstractValidator<NotEmpty, Object> {
@Override
protected boolean validNull(ConstraintValidatorContext context) {
return fal;
}
@Override
protected boolean valid(Object value, ConstraintValidatorContext context) {
if (value instanceof String) {
return StringUtils.String());
} el if (value instanceof Collection) {
return !org.springframework.util.CollectionUtils.isEmpty((Collection) value);
} el if (value instanceof Map) {
return MapUtils.isNotEmpty((Map) value);
} el if (Class().isArray()) {
Length(value) > 0;
}
return true;
}
}
将上个demo中引⽤的org.straints.NotEmpty改为validation.NotEmpty即可。
运⾏结果:
WARN act.DataAuthValidator - {dataProvider=参数不能为null或空字符串, personalDataName=参数不能为null或xceptions.ApiException:参数contractParams中缺少字段:dataProvider, personalDataName
级联校验
校验的对象中包含另⼀个需要校验的对象时,则可以使⽤@javax.validation.Valid
import xceptions.ApiException;
import validation.NotEmpty;
import com.fm.framework.api.ApiResultHelper;
import com.fm.framework.json.Json;
import com.fm.framework.utils.StringUtils;
import antauth.domain.ValidateResult;
import antauth.domain.dto.AuthorizationApplyDTO;
import antauth.utils.ValidatorUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;