Implementation of Spring Boot Data Verification @ Valid + Unified Exception Handling

  • 2021-07-24 11:00:45
  • OfStack

1. First add the required annotations to the entity class you need to verify

In order to test, I wrote it simply myself. @ NotNull and @ NotBlank cannot be empty


 @Entity
 @Table(name = "User")
 @Data
 public class User implements Serializable {

 @Id
 @NotNull(message = "id Cannot be empty ")
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Integer id;

 @NonNull
 @NotBlank(message = " Name cannot be empty ")
 @Column(name = "name")
 private String name;

 public User() {
 }

 public User(Integer id,String name) {
  this.id=id;
  this.name = name;
 }


}

The following is the rule method for using all the parameter validation annotations I collected from other blogs

Empty check

@ Null Verify that the object is null

@ NotNull validates that the object is not null and cannot check a string of length 0

@ NotBlank checks whether the constraint string is Null and whether the length of Trim is greater than 0, only for strings, and the spaces before and after are removed.

@ NotEmpty checks whether the constraint element is NULL or EMPTY.

Booelan Check

@ AssertTrue Verify that the Boolean object is true

@ AssertFalse Verify that the Boolean object is false

Length check

@ Size (min=, max=) Verifies that the object (Array, Collection, Map, String) is within the given range

@Length(min=, max=) Validates that the annotated string is between min and max included.

Date check

@ Past verifies that the Date and Calendar objects are before the current time

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

@ Pattern validates that String objects conform to the rules of regular expressions

Numerical check

Recommended for Stirng, Integer type, not recommended for int type, because the form value of "" cannot be converted to int, but can be converted to Stirng to "", Integer to null

@ Min verifies that the Number and String objects are equal to or greater than the specified value

@ Max verifies that the Number and String objects are equal to or less than the specified value

@ DecimalMax must be marked with a value that is not greater than the maximum value specified in the constraint. The argument to this constraint is a string representation of the maximum value defined by BigDecimal. Decimal Existence Precision

@ DecimalMin must be marked with a value that is not less than the minimum value specified in the constraint. The argument to this constraint is a string representation of the minimum value defined by BigDecimal. Decimal has precision

@ Digits Verify that Number and String are made up legally

@ Digits (integer=, fraction=) verifies that the string is a number in the specified format, interger specifies integer precision, and 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") private BigDecimal wage;

@ Valid recursively verifies the associated object, if the associated object is a collection or array, then recursively verifies the elements in it, and if it is 1 map, then verifies the value part in it. (Whether to perform recursive verification)

@ CreditCardNumber credit card verification

@ Email verifies whether it is an email address. If it is null, it is verified without verification.

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

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

2. Add @ Valid annotation to controller layer

ServiceResult is an exception return class that I created myself

Method of adding user information


 @PostMapping("/saveUser")
 public ServiceResult addUsers(@Valid @RequestBody User user){
   return ServiceResult.success(userRepository.save(user));
 }

3. Create a class that handles exceptions in Uniform 1


@RestControllerAdvice
@ExceptionHandler( Write the type of exception you want to intercept )

These two annotations must be

The first method is to check the unified 1 processing of anomalies

The second is to prevent the processing of parameter type not 1

Of course, you can also handle other exceptions in it.


@RestControllerAdvice
public class BadRequestExceptionHandler {


 private static final Logger logger = LoggerFactory.getLogger(BadRequestExceptionHandler.class);

 /**
  *  Verification error interception processing 
  *
  * @param exception  Error message set 
  * @return  Error message 
  */
 @ExceptionHandler(MethodArgumentNotValidException.class)
 public ServiceResult validationBodyException(MethodArgumentNotValidException exception){

  BindingResult result = exception.getBindingResult();
  if (result.hasErrors()) {

   List<ObjectError> errors = result.getAllErrors();

   errors.forEach(p ->{

    FieldError fieldError = (FieldError) p;
    logger.error("Data check failure : object{"+fieldError.getObjectName()+"},field{"+fieldError.getField()+
      "},errorMessage{"+fieldError.getDefaultMessage()+"}");

   });

  }
  return ServiceResult.error(" Please fill in the correct information ");
 }

 /**
  *  Parameter type conversion error 
  *
  * @param exception  Errors 
  * @return  Error message 
  */
 @ExceptionHandler(HttpMessageConversionException.class)
 public ServiceResult parameterTypeException(HttpMessageConversionException exception){

  logger.error(exception.getCause().getLocalizedMessage());
  return ServiceResult.error(" Type conversion error ");

 }

}

Related articles: