Original address Original address

preface

One of the annoying things about web development is that you have to validate parameters. Basically, every interface has to validate parameters. For example, some format validation and non-null validation are necessary. IF you have a small number of arguments, it’s easy to handle. But IF you have a large number of arguments, your code will have a lot of IF and ELSE arguments like this:

This example just validates the null argument. If you need to validate email and phone numbers, there’s a lot more code, so here’s how the Validator annotates parameters.

What is a Validator

Bean Validation, a set of annotation-based data Validation specifications defined in Java, has been upgraded from JSR 303 version 1.0 to JSR 349 version 1.1 to JSR 380 version 2.0 (2.0 completed in 2017.08). SpringBoot is already integrated into the starter-Web, so there is no need to add additional dependencies.

Annotation is introduced

Validator has built-in annotations

annotations

The detailed information

@Null

The annotated element must benull

@NotNull

The annotated element must not benull

@AssertTrue

The annotated element must betrue

@AssertFalse

The annotated element must befalse

@Min(value)

The annotated element must be a number whose value must be greater than or equal to the specified minimum
@Max(value)

The annotated element must be a number whose value must be less than or equal to the specified maximum
@DecimalMin(value)

The annotated element must be a number whose value must be greater than or equal to the specified minimum
@DecimalMax(value)

The annotated element must be a number whose value must be less than or equal to the specified maximum
@Size(max, min)

The size of the annotated element must be within the specified range

@Digits (integer, fraction) The annotated element must be a number and its value must be within an acceptable range

@Past

The annotated element must be a past date

@Future

The annotated element must be a future date

@Pattern(value)

The annotated element must conform to the specified regular expression

Hibernate Validator has additional constraints

annotations The detailed information

@Email

The annotated element must be an E-mail address

@Length

The size of the annotated string must be within the specified range
@NotEmpty

The value of the annotated string must be non-empty

@Range

The annotated element must be in the appropriate scope

@NotBlank

Verify that the string is not null and must be greater than 0 in length

Note:

  • @notnull applies to any type of annotated element that must not be NULL
  • @notempTY applies to String maps or arrays that cannot be Null and must have a length greater than zero
  • @notBlank can only be used on strings and cannot be null. After trim() is called, the length must be greater than 0

use

It’s also very simple to use, so I’ll skip creating the project

Making address:

Mock user registration encapsulates a UserDTO

When submitting data, you need to add annotations IF you use an IF ELSE argument with the validator.

For example, non-null check:

And then you need to add @Validated to the controller method body so the verification doesn’t work if you don’t add @Validated

Then request the request interface and set the Email parameter to null

Parameters:

{
    "userName":"luomengsun",
    "mobileNo":"11111111111",
    "sex":1,
    "age":21,
    "email":""
}Copy the code

Return result:

Background Throw exception

This works, but the problem is that the return parameters are not ideal, and it’s not easy for the front end to handle the return parameters, so let’s add global exception handling, and then add global uniform return parameters to make it more standardized.

Adding a global exception

Create a GlobalExceptionHandler class, add the @RestControllerAdvice annotation above the class and add the following code:

Method parameters calibration * / / * * * @ ExceptionHandler (MethodArgumentNotValidException. Class) public ReturnVO handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { log.error(e.getMessage(), e); return new ReturnVO().error(e.getBindingResult().getFieldError().getDefaultMessage()); }Copy the code

This method is mainly to capture MethodArgumentNotValidException exception then encapsulate the abnormal results, if you need to add other exception handling on its own.

When we look at the result, the call interface returns:

{" code ":" 9999 ", "desc" : "email can't for empty", "data" : null}Copy the code

OK has handled the exception.

Check the format

It’s also easy to verify email format or mobile phone number.

Check your email

@notblank (message = "mailbox can not be empty ") @notnull (message =" mailbox can not be empty ") @email (message = "mailbox format error ") private String Email;Copy the code

Verify the mobile phone number using the re

Check the phone number is checked using the re and then limits the number of digits

/** * phone number */ @notnull (message = "phone number cannot be empty ") @notBlank (message =" phone number cannot be empty ") @pattern (regexp) ^ = "[1] [3,4,5,6,7,8,9] [0-9] {9} $". Message = "Mobile phone number format error ") @max (value = 11,message =" mobile phone number only {Max} bit ") @min (value = 11,message = "Mobile phone number only {Min} bit ") private String mobileNo;Copy the code

Take a look at the results

Passing in parameters:

{
    "userName":"luomengsun",
    "mobileNo":"111111a",
    "sex":1,
    "age":21,
    "email":"1212121"
}Copy the code

Return result:

{" code ":" 9999 ", "desc" : "email format error", "data" : null}Copy the code

I will not verify the mobile phone number example here

Custom annotations

There are only so many annotations above. If there are special Validator parameters, we can use custom annotations to validate them

Let’s start by creating an IdCard annotation class

@Documented @Target({ElementType.PARAMETER, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = IdCardValidator.class) public @interface IdCard {String message() default "ID number is invalid "; Class<? >[] groups() default {}; Class<? extends Payload>[] payload() default {}; }Copy the code

This can be verified by adding @idcard annotation to UserDTO, which is triggered at runtime. This article won’t explain custom annotations too much, but the next article will cover custom annotations

  • Message Prompt message
  • Groups are grouped
  • Payload refers to the Bean

And then I add the IdCardValidator to do the validation logic

Call the is18ByteIdCardComplex method, pass in the phone number, verify the id rule itself.

Then use the

@notnull (message = "id id NotNull ") @idcard (message =" id id NotNull ") private String IdCard number;Copy the code

grouping

For example, what if we want to take the parameter in UserDTO defined above?

Redefining a class and annotating its parameters?

Validator provides a grouping method that is perfect for DTO taking

Now we register the interface to modify the rule, only the user name can not be empty other parameters are not checked

Create an interface for the group first

public interface Create  extends Default {
}Copy the code

We just need to add group parameters to the annotation. For example:

/** * usernames */ @notblank (message = "usernames cannot be blank ",groups = create.class) @notnull (message =" usernames cannot be blank ",groups = create.class) @notnull (message = "usernames cannot be blank ",groups = create.class) private String userName; @notblank (message = "mailboxes cannot be empty ",groups = update.class) @email (message =" groups = update.class ") @notnull (message = "mailboxes cannot be empty ",groups = update.class) @email (message = Class) private String email;Copy the code

And then modify Controller at @Validated and pass create. class

    @PostMapping("/user")
    public ReturnVO userRegistra(@RequestBody @Validated(Create.class) UserDTO userDTO){
        ReturnVO returnVO = userService.userRegistra(userDTO);
        return returnVO ;
    }Copy the code

Then call the passed argument:

{
    "userName":"",
}Copy the code

Return parameters:

{" code ":" 9999 ", "desc" : "user name cannot be empty", "data" : null}Copy the code

OK now validates only Create and not Updata groups. Block validations can be used if dtos need to be reused

Verifying a single parameter

You must have encountered a single parameter in your development, so just add a comment in front of the parameter

@postmapping ("/get") public ReturnVO getUserInfo(@requestparam ("userId") @notnull (message = "userId cannot be empty ") String userId){PostMapping("/get") public ReturnVO getUserInfo(@requestparam ("userId") @notnull (message = "userId cannot be empty ") String userId){ return new ReturnVO().success(); }Copy the code

Then add the @ “Validated” annotation to the Controller class, not before the parameter.