“This is the third day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.”

preface

Hi, everyone. I believe that you often write background interface in the development process. When the front end calls the background interface, it is necessary to verify the validity and validity of the parameters entered by the front end. There are several ways to validate data. This article introduces the validation of parameters based on the @valid annotation. I hope I can help you. Let’s get to the point.

The initial

The @VALID annotation validation is based on the standard JSR-303 specification. The @VALID annotation can be used on class methods, constructors, method arguments, and member attributes (fields). After the parameters are entered, the system verifies the validity of the parameters. If the parameters are abnormal, the system directly returns an exception message. Of course, using the @VALID annotation in a project requires the introduction of related dependencies. According to the Spring Boot version, the following POM dependency files are introduced. You can import dependent files based on the version of Spring Boot you are using. Spring Boot versions are as follows:

<version>2.3. 0.RELEASE</version>
Copy the code
      <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.22</version>
        </dependency>
Copy the code

Quick start

I’m sure you’ve already introduced response dependencies, so let’s start with annotations.

Defines the interface

The following is a common interface, where the request mode is: POST. In the request parameter, the parameter body OrderDto is annotated with @valid. When OrderDto is accessed as a parameter, it is automatically validated against the annotations of the properties in OrderDto. If the conditions are not met, message is returned.

 @PostMapping("/V1/save")
    public String addInfo(HttpServletRequest request, @Valid @RequestBody OrderDto orderDto) {

        log.info("Info new interface, request parameter is: {}".JSON.toJSONString(orderDto));
        try {
            return JSON.toJSONString(orderDto);
        } catch (Exception e) {
            log.error("Info new interface, request parameter is: {}, exception cause:".JSON.toJSONString(orderDto), e);
            return "Push interface failed. The reasons for failure are:"+ e.getMessage(); }}Copy the code

@Null

Description: Elements annotated with @NULL must be Null.

Parameter type: Accepts any type of parameter.

Where to use: methods, properties, comment types, constructors, parameters

“Message” : user-defined returned exception information.

Example:

    @Null(message = "Id must be null")
    private String id;
Copy the code

@NotNull

Description: Elements annotated @notnull must not be NULL.

Parameter type: Accepts any type of parameter.

Where to use: methods, properties, comment types, constructors, parameters

“Message” : user-defined returned exception information.

Example:

    @NotNull(message = "Name cannot be empty.")
    private String name;
Copy the code

@AssertFalse

Description: Elements annotated with AssertFalse must be false

Parameter type: The supported types are Boolean and Boolean

Where to use: methods, properties, comment types, constructors, parameters

“Message” : user-defined returned exception information.

Example:

    @AssertFalse
    private boolean bf;
Copy the code

@AssertTrue

Description: Elements annotated @assertTrue must be true.

Parameter type: The supported types are Boolean and Boolean

Where to use: methods, properties, comment types, constructors, parameters

“Message” : user-defined returned exception information.

Example:

    @AssertTrue
    private boolean bt;
Copy the code

@AssertTrue

Description: Elements annotated @assertTrue must be true.

Parameter type: The supported types are Boolean and Boolean

Where to use: methods, properties, comment types, constructors, parameters

“Message” : user-defined returned exception information.

Example:

    @AssertTrue
    private boolean bt;
Copy the code

@AssertTrue

Description: Elements annotated @assertTrue must be true.

Parameter type: The supported types are Boolean and Boolean

Where to use: methods, properties, comment types, constructors, parameters

“Message” : user-defined returned exception information.

Example:

    @AssertTrue
    private boolean bt;
Copy the code

@DecimalMax

Description: the value of an element annotated with @decimalmax must be less than or equal to the number equal to the maximum specified.

Parameter types: BigDecimal BigInteger CharSequence and base types: Byte Short int Long and wrapper types for these base types

Parameter types not supported: Double and float are not supported due to rounding errors

Where to use: methods, properties, comment types, constructors, parameters

A null value is considered valid.

Value: The value of the element must be less than or equal to

Inclusive: Specifies whether the maximum value is included. By default, it is included.

“Message” : user-defined returned exception information.

Example:

    @DecimalMax(value = "100.00")
    private BigDecimal bdMax;
Copy the code

@DecimalMin

Description: the value of an element annotated with @decimalmin must be greater than or equal to the number equal to the specified minimum.

Parameter types: BigDecimal BigInteger CharSequence and base types: Byte Short int Long and wrapper types for these base types

Parameter types not supported: Double and float are not supported due to rounding errors

Where to use: methods, properties, comment types, constructors, parameters

A null value is considered valid.

Value: The value of the element must be greater than or equal to

Inclusive: Whether the specified minimum value is included. By default, it is included.

“Message” : user-defined returned exception information.

Example:

    @DecimalMin(value = "60.00")
    private BigDecimal dmMin;
Copy the code

@Digits

Introduction: the @digits limit must be a decimal, and the number of Digits in the integer part must not exceed integer, the number of Digits in the decimal part must not exceed fraction, and the annotated element must be a number within the acceptable range.

Parameter types: BigDecimal BigInteger CharSequence and base types: Byte Short int Long and wrapper types for these base types

A null value is considered valid.

Where to use: methods, properties, comment types, constructors, parameters

“Message” : user-defined returned exception information.

Example:

   @Digits(integer = 100,fraction = 100)
    private double aDouble;
Copy the code

@Future

Description: The @Future annotated element must be a Future flash, date, or time.

Parameter type: Date; The Calendar; Instant; LocalDate; LocalDateTime; The LocalTime; MonthDay. OffsetDateTime; OffsetTime; Year; YearMonth; ZonedDateTime; HijrahDate; JapaneseDate; MinguoDate; ThaiBuddhistDate;

Where to use: methods, properties, comment types, constructors, parameters

A null value is considered valid.

“Message” : user-defined returned exception information.

Example:

    @Future
    private Date futureDate;
Copy the code

@Max

Description: The @max annotated element value must be less than or equal to the specified maximum value.

Parameter types: BigDecimal BigInteger Byte Short int Long and the wrapper types for these base types

Parameter types not supported: Double and float are not supported

A null value is considered valid.

Where to use: methods, properties, comment types, constructors, parameters

“Message” : user-defined returned exception information.

Example:

    @Max(value = 1000)
    private Long maxInfo;
Copy the code

@Min

Description: The @min-annotated element value must be greater than or equal to the specified minimum.

Parameter types: BigDecimal BigInteger Byte Short int Long and the wrapper types for these base types

Parameter types not supported: Double and float are not supported

A null value is considered valid.

Where to use: methods, properties, comment types, constructors, parameters

“Message” : user-defined returned exception information.

Example:

    @Min(value = 1)
    private Long minInfo;
Copy the code

@Past

Introduction: The @past annotated element must be a Past moment, date, or time. This is now defined by default as the current time of the VIRTUAL machine.

Parameter type: Date; The Calendar; Instant; LocalDate; LocalDateTime; The LocalTime; MonthDay. OffsetDateTime; OffsetTime; Year; YearMonth; ZonedDateTime; HijrahDate; JapaneseDate; MinguoDate; ThaiBuddhistDate;

Where to use: methods, properties, comment types, constructors, parameters

A null value is considered valid.

“Message” : user-defined returned exception information.

Example:

    @Past
    private Date pastDate;
Copy the code

@Pattern

Description: The @pattern annotation must match the specified regular expression.

Parameter types: Regular expression Follows Java regular expression conventions

Where to use: methods, properties, comment types, constructors, parameters

Regexp: indicates a regular expression

Flags: enumeration of whether regular expressions are enabled

“Message” : user-defined returned exception information.

Example:

     @Pattern(regexp = "^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$",
            flags = Pattern.Flag.CASE_INSENSITIVE)
    private String patternInfo;
Copy the code

@Size

Description: Elements annotated with @size must be between the specified boundaries (inclusive).

Parameter type: CharSequence Computes the length of a character sequence; Collection calculates the size of the Collection. Map The mapping size has been calculated. Array Calculates the length of an Array.

The null element is considered valid; Min minimum value, default is 0. Max Maximum value. The default value is 0x7ffFFFFf.

Where to use: methods, properties, comment types, constructors, parameters

“Message” : user-defined returned exception information.

Example:

    @Size(min = 0,max = 100)
    private int sizeInfo;
Copy the code

@NotEmpty

Description: Elements annotated @notempty cannot be null or null

Parameter type: CharSequence Computes the length of a character sequence; Collection calculates the size of the Collection. Map The mapping size has been calculated. Array Calculates the length of an Array.

Where to use: methods, properties, comment types, constructors, parameters

“Message” : user-defined returned exception information.

Example:

    @NotEmpty
    private String phone;
Copy the code

@NotBlank

Introduction: Verify that the element value of an annotation is not null (not null, length 0 after removing the first whitespace). Unlike @notempty, @notBlank applies only to strings and removes whitespace from strings when comparing. Annotated elements cannot be NULL and must contain at least one non-whitespace character.

Parameter type: Object

Where to use: methods, properties, comment types, constructors, parameters

“Message” : user-defined returned exception information.

Example:

   @NotBlank
    private String nickName;
Copy the code

@Email

Description: The string must be a well-formed email address. The exact semantics that make up valid data

Parameter type: Basic type CharSequence

Where to use: methods, properties, comment types, constructors, parameters

The null element is considered valid.

Regexp: indicates a regular expression

Flags: Used in combination to specify regular expressions

“Message” : user-defined returned exception information.

Example:

    @Email
    private String email;
Copy the code

conclusion

The above is the Spring Boot integration @valid annotation details, you can also consult the interface documentation to understand.

Well, thank you for reading, I hope you like it, if it is helpful to you, welcome to like collection. If there are shortcomings, welcome comments and corrections. See you next time.

About the author: [Little Ajie] a love tinkering with the program ape, JAVA developers and enthusiasts. Public number [Java full stack architect] maintainer, welcome to pay attention to reading communication.