java自带的和hibernate validation有一些常规的校验,但是实际工作中可能不够用。。。
一,参考的资料和别人博客:
其中本人遇到的报错:
javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'
解决方案:
javax.el javax.el-api 2.2.4 org.glassfish.web javax.el 2.2.4
二、以自定义枚举校验器为例
1,定义枚举
package com.joindata.bss.model.ad;/** * Created by lijunhao on 2017/2/8. */public enum AdType { /**订单详情*/ ORDER_DETAIL, /**支付成功*/ PAY_SUCCESS, /**portal页*/ PORTAL, /**成功页*/ SUCCESS}
2,定义方法:EnumValidation
这个就是在bean属性上注释的名称,这里定义注释名称上的属性值,我在这里加的是Class<?> value(); 为了在校验器里的value中输入枚举类(class)
@Target( { METHOD, FIELD, ANNOTATION_TYPE }) @Retention(RUNTIME) @Constraint(validatedBy = EnumValidator.class) @Documented 以上几项的说明参考开头的资料
package com.joindata.bss.validation;import static java.lang.annotation.ElementType.*;import static java.lang.annotation.RetentionPolicy.*;import java.lang.annotation.Documented;import java.lang.annotation.Retention;import java.lang.annotation.Target;import javax.validation.Constraint;import javax.validation.Payload;/** * Created by lijunhao on 2017/2/9. */@Target( { METHOD, FIELD, ANNOTATION_TYPE })@Retention(RUNTIME)@Constraint(validatedBy = EnumValidator.class)@Documentedpublic @interface EnumValidation { String message() default "{请输入正确的类型}"; Class [] groups() default {}; Class [] payload() default {}; //自己定义的 Class value();}
3,书写校验器
- 在定义的方法中指定校验类 此校验类实现接口ConstraintValidator<EnumValidation, String>,其中第一个参数为第2步命名的方法,第2个是bean中所要校验的值,此接口有2个方法,源码如下:
-
第一个initialize方法是对输入东西的做校验前的处理
-
第二个isValid方法是做校验 返回的是布尔值(Boolean),true的话是校验通过,false的话是校验失败。校验失败返回的就是步骤2中的message信息(messagr可以覆盖默认的值)
具体实现方式,参考下面的代码
package com.joindata.bss.validation;import org.apache.commons.lang.StringUtils;import javax.validation.ConstraintValidator;import javax.validation.ConstraintValidatorContext;import java.util.ArrayList;import java.util.List;/** * Created by lijunhao on 2017/2/9. */public class EnumValidator implements ConstraintValidator{ private List objects; @Override public void initialize(EnumValidation constraintAnnotation) { Class value = (Class ) constraintAnnotation.value(); Enum[] enumConstants = value.getEnumConstants(); objects = new ArrayList<>(); for (Enum enumConstant : enumConstants) { objects.add(enumConstant.name()); } } @Override public boolean isValid(String value, ConstraintValidatorContext context) { if(StringUtils.isBlank(value)||objects.contains(value)){ return true; } return false; }}
4,测试方法:
bean中:
package com.joindata.bss.vo.invo;import com.joindata.bss.model.ad.AdType;import com.joindata.bss.validation.EnumValidation;import org.hibernate.validator.constraints.NotBlank;import java.io.Serializable;/** * Created by lijunhao on 2017/1/18. */public class CheckSendCodeInvo implements Serializable{ @EnumValidation(value = AdType.class,message = "请输入正确的广告类型") private String macRecondId; public String getMacRecondId() { return macRecondId; } public void setMacRecondId(String macRecondId) { this.macRecondId = macRecondId; }}
Main:
package com.joindata.bss.service;import com.joindata.bss.vo.invo.CheckSendCodeInvo;import javax.validation.ConstraintViolation;import javax.validation.Validation;import javax.validation.Validator;import javax.validation.ValidatorFactory;import java.util.ArrayList;import java.util.List;import java.util.Set;/** * Created by lijunhao on 2017/2/9. */public class Test { public static void main(String[] args) { CheckSendCodeInvo checkSendCodeInvo = new CheckSendCodeInvo(); checkSendCodeInvo.setCode("dsds"); checkSendCodeInvo.setMacRecondId("ORD_DETAIL"); checkSendCodeInvo.setPhone("dsdsdsd"); ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); Validator validator = validatorFactory.getValidator(); Set> validate = validator.validate(checkSendCodeInvo); List messageList = new ArrayList<>(); for (ConstraintViolation constraintViolation : validate) { messageList.add(constraintViolation.getMessage()); } messageList.stream().forEach(System.out::println); }}
结果:
大功告成!!!