Sprboot project usage (2) -- javax.validation

Keywords: Java Hibernate less

In the last article, we integrated swagger ui and built a restful-style interface. When doing logic processing, we must first do parameter verification. This article describes the use of javax.validation for parameter verification.

1. Create a new entity class with the annotation of javax.validation

import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.Range;

public class Student {

    @Range(min = 18, max = 60, message = "Age inappropriate")
    private int age;

    @NotBlank(message = "Schools cannot be empty")
    private String school;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }   

}

2. Make the following modifications in controller

@ApiImplicitParam(name = "student", value = "Ordinary users", required = true, dataType = "Student")
@RequestMapping(value = "/second", method = RequestMethod.POST)
public Result test2(@RequestBody @Valid Student student, BindingResult bindingResult){

    //Here, we determine whether the parameters pass the check.
    if (bindingResult.hasErrors()) {
        String message = bindingResult.getFieldError().getDefaultMessage();
        //Custom return and return error information
        return Result.error(message);
    }
    
    return Result.commonSuccess();
}

Annotations available for javax.validation

Empty check

Null verifies that the object is null

NotNull verifies that the object is not null and that a string of length 0 cannot be checked

NotBlank checks whether the constrained string is Null and whether the length of the Trim is greater than 0, only for the string, and removes the front and back spaces.

NotEmpty checks whether the constraint element is NULL or EMPTY.

Booelan check

AssertTrue verifies that the Boolean object is true

AssertFalse verifies that the Boolean object is false

Length check

Size(min=, max=) verifies that the length of the object (Array,Collection,Map,String) is within a given range

@Length(min=, max=)
Verify that the length of the string is within a given range, including both ends

Date check

Past verifies that Date and Calendar objects are prior to the current time

Future verifies that Date and Calendar objects are after the current time

Pattern s verify that String objects conform to regular expression rules

NUMERICAL CHECKING: It is recommended to use the Stirng,Integer type instead of the int type because the form value cannot be converted to int when it is ", but it can be converted to Stirng as", and Integer as null.

Min verifies that Number and String objects are large equal to the specified value

Max verifies that Number and String objects are small or equal to the specified value

The value of @DecimalMax must not be greater than the maximum specified in the constraint. The parameter of this constraint is a string representation of the maximum defined by BigDecimal. The decimal has precision.

The @DecimalMin tagged value must be no less than the minimum specified in the constraint. The parameter of the constraint is a string representation of the minimum defined by BigDecimal. The decimal has precision.

Digits verifies that Number and String are legitimate

Digits(integer=,fraction=) verifies that the string is a number in the specified format, interger specifies integer precision, fraction specifies decimal precision.

@Range(min=, max=) Checks whether the annotated value lies between (inclusive) the specified minimum and maximum.

@Range(min=10000,max=50000,message="range.bean.wage")
private BigDecimal wage;

Valid recursively checks the associated objects. If the associated objects are a collection or an array, then the elements are checked recursively. If it is a map, the value part is checked recursively.

CreditCardNumber Credit Card Verification

Whether the @Email verification is an email address, if it is null, it will pass the verification if it is not validated.

@ScriptAssert(lang= ,script=, alias=)

@URL(protocol=,host=, port=,regexp=, flags=)

3. Of course, sometimes we need some custom checks.

Write custom validation annotations

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target( {ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })  
@Retention(RetentionPolicy.RUNTIME)  
@Constraint(validatedBy = MyCheckImpl.class)  
public @interface MyCheck {

    String message() default "unknown error";  

    Class<?>[] groups() default {};  

    Class<? extends Payload>[] payload() default {}; 

}

Implementation class

import java.lang.annotation.Annotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class MyCheckImpl implements ConstraintValidator<Annotation, String>{

    public void initialize(Annotation arg0) {
    
    }

    public boolean isValid(String arg0, ConstraintValidatorContext arg1) {
        
        // Specific verification methods
        if("male".equals(arg0)||"female".equals(arg0)){
            return true;
        }
    
        return false;

    }

}

Use our custom validation in previous entity classes

Enterprise Wechat Screen _15263948059898.png

4. Test the effect:
Enterprise Wechat Screen _15263950374943.png

[Picture upload....... (Enterprise Wechat screenshot _15263952481263. png-f7b8ab-15263953239-0)]
Enterprise Wechat Screen _15263952481263.png
Enterprise Wechat Screen _15263952657919.png

Posted by ceanth on Tue, 08 Jan 2019 22:33:09 -0800