A write parity based on the parameter hands under Spring Boot Framework assembly (JSR-303)

Foreword  

        Before participating in the new open platform development process, due to the different interfaces need to check into the different parameters, which relates to the common parameters check package, if not packaged, then the code will write out the check style is not uniform, check tools are inconsistent, maintaining higher risk of other factors, so I did a check of the package to its public, to the parameters you can achieve a unified verification by way of comment.

Problems encountered

                      In the package when he found a problem, we are an open platform, returned messages must be uniform style, which is similar to {code: 999, msg: "parameter check failed", data: null} this, but the native JSR303 does not support custom fields, so you need custom validation annotation. To address this issue I reference some of JSR303, and it was a custom extensions to achieve the developers do not need to capture the attention and package return information.

  

The traditional practice of parity 

        If an entity inside the following check hundreds of fields that need to check it, to maintain it is a very troublesome thing, and many can be unified verification process by way of comment jsr-303 without having to write a lot of if and else

IF (name == null ) { 
     // returns the error message 
 } the else IF (Age == null ) { 
     // return error 
}

 Based on a check after jsr-303 custom

  1. Define a custom non-empty comment
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { CorpNotEmptyValidator.class })
public @interface CorpNotEmpty {

    //自定义字段
    String field() default  "";
   //返回错误码
    String code() default  "0";
    //错误消息
    String message() default "{javax.validation.constraints.NotNull.message}"; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RUNTIME) @Documented @interface List { CorpNotEmpty[] value(); } }

   2. Define the annotation of the non-empty validators, initialize, and isValid action described as follows:

  •   initialize method is to initialize ReturnCodeModel, the parameter is not used when the verification by returning, ReturnCodeModel package which is mainly a return member, such as a code, message, etc.
  •        isValid mainly self-checking checker rule defined as follows is determined whether the air StringUtils.isEmpty method used, if the check does not pass through the set flag is false, then calls the base class isValid, the base class method determines flag whether it is false, false if it is not explained by
public class CorpNotEmptyValidator extends BaseCorpValidator<CorpNotEmpty,String> {


    @Override
    public void initialize(CorpNotEmpty constraintAnnotation) {
        model = new ReturnCodeModel();
        model.setCode(constraintAnnotation.code());
        model.setErrorMsg(constraintAnnotation.message());
        model.setField(constraintAnnotation.field());
    }
 
    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        System.out.println("1");
        if(StringUtils.isEmpty(s)){ model.setFlag(false); }else{ model.setFlag(true); } return super.isValid(s,constraintValidatorContext); } }

  3. Define a base class to implement ConstraintValidator, primarily because of the need to define an abstract method isValid this method to provide different validators, to avoid repeated to write other code verifier

public abstract class BaseCorpValidator<A extends Annotation,B> implements ConstraintValidator<A ,B> {
    protected ReturnCodeModel model = null;

    @Override
    public boolean isValid(B value, ConstraintValidatorContext context) {
        if(!model.getFlag()){
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(JSON.toJSONString(model)).addConstraintViolation();
            return false;
        }
        return true; } }

   4. Test Class

class public TestV1 { 
    
    static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory (); 
    static the Validator Validator = validatorFactory.getValidator (); 
    
    public static void main (String [] args) {  UserModel usermodel = new new UserModel ();  userModel.setName ( "AA" ); userModel.setDate ( "2011" ); the Set <ConstraintViolation <userModel >> constraintViolations = Validator.validate (usermodel); // determines whether constraintViolations is empty, not empty described verification is not passed, get inside the error ReturnCodeModel after the information is returned to the client IF (! constraintViolations.isEmpty ()) {for (ConstraintViolation <?> item : constraintViolations) { ReturnCodeModel codeModel = JSON.parseObject(item.getMessage(), ReturnCodeModel.class); System.out.println(JSON.toJSONString(codeModel)); } } } }

Voice-over: Consider the scene

  1. For example, name the field, to meet both can not be empty and only these two digital case, if the two calibration methods are written in the same validator is used when other developers will also affect, so the need for two annotation mode, a check is empty, a check is whether the digit, then there is after analysis of a sequence of questions, so for this scenario requires a custom sequence annotation.

  The following code, added @GroupSequence annotations on physical model to be verified, so that the bottom will help us validator sequentially processed in the order

// sequence annotation 
@GroupSequence ({ 
    First.class, 
    Two.class, 
    Three.class, 
    UserModel.class 
}) 
public class UserModel { 
	@CorpMustNumber (code = "- 2", Message = "must be a number", groups = Two. class) // in the implementation of digital check 
	@CorpNotEmpty (code = "- 1" , message = " name required", groups = First.class) // executed first non-empty 
	Private String name; 
	@CorpNotEmpty (code = "- 1 ", message =" required date ") 
	Private String dATE; 
	public String getName () { 
		return name; 
	} 
	public void the setName (String name) { 
		this.name = name; 
	} 
	public String getDate () { 
		return dATE;
	}
	public void setDate(String date) {
		this.date = date;
	}
	
	
}

  

First
Two

to sum up

    These are related to this blog all the technical points of the code, by customizing your own validator in order to meet the company's business scenario, it is for the development of a unified standard, unified style for future maintenance or expansion are very convenient. If you have a blog to help trouble spots followers or praise, thank you! 17:40:42

Guess you like

Origin www.cnblogs.com/zdd-java/p/12240929.html