SpringBoot uses jsr303 verification

Dependency addition

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Some older versions of SpringBoot need to add related dependencies. The 2.1.4 distribution I use does not need this operation.

Verify that the parameters are received using the object

public class PointDeductSetRequest {
 private Long id;
 @NotBlank(message = "tenant id Empty")
 private String tenantId;
 private Integer status;
 @NotNull
 private Integer pointValue;
 @NotNull
 private Integer deductValue;
 @NotBlank(message = "operator id Empty")
 private String operator;
}

First, add verification annotation above the corresponding field of the object to be verified. The following are some common annotations:
@Null restriction can only be null
@NotNull restriction must not be null
@AssertFalse restriction must be false
@AssertTrue restriction must be true
@The DecimalMax(value) limit must be a number no greater than the specified value
@The DecimalMin(value) limit must be a number not less than the specified value
@Digits(integer,fraction) must be limited to one decimal, and the number of digits in the integer part cannot exceed integer and the number of digits in the decimal part cannot exceed fraction
@The Future limit must be a Future date
@The Max(value) limit must be a number no greater than the specified value
@The Min(value) limit must be a number not less than the specified value
@Past limit must be a past date
@The Pattern(value) restriction must conform to the specified regular expression
@Size(max,min) the limit character length must be between min and max
@The element value (date type) of the Past validation annotation is earlier than the current time
@The element value of NotEmpty validation annotation is not null and empty (string length is not 0, collection size is not 0)
@NotBlank verifies that the element value of the annotation is not empty (it is not null, and the length is 0 after removing the first space). Unlike @ NotEmpty, @ NotBlank is only applied to strings, and spaces in strings are removed during comparison
@The element value of Email verification annotation is Email. You can also specify a custom Email format through regular expression and flag

@RequestMapping(value = "/deduct", method = RequestMethod.POST)
public BusinessResponse setPointDeduct(@RequestBody @Valid PointDeductSetRequest request){
    pointDeductService.setPointDeductRule(request);
    return new BusinessResponse(ResponseEnum.OK);
}

Then add @ Valid annotation before the object parameter of the controller method.

Verify acceptance using a single parameter

@RequestMapping(value = "/deduct", method = RequestMethod.GET)
public PageResponse<TPointDeduct> getPointDeductList(@RequestParam(value = "page", required = false) Integer page,
 @RequestParam(value = "pageSize", required = false) Integer pageSize,
 @RequestParam(value = "tenantId", required = false) @NotBlank(message = "tenant id Empty") String tenantId,
 @RequestParam(value = "status", required = false) Integer status){
    PageResponse<TPointDeduct> response = pointDeductService.getPointDeductList(page, pageSize, tenantId, status);
 response.setCodeMsg(ResponseEnum.OK);
 return response;
}

First, you need to add the @ Validated annotation on the controller class, and then add the corresponding validation annotation before the parameters to be verified in the method.

Capture of exceptions generated by verification

Define the global exception handling class and mark it with @ ControllerAdvice. Because the exception types generated by object and single parameter verification are different, they need to be handled separately.

When the object is used as the front-end request, the exception type generated by the verification is MethodArgumentNotValidException. The example method is as follows:

/**
 * Capture 303 for object field verification in body
 * @param e
 * @param request
 * @return
 */@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
ResponseEntity<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request){
   List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
 if (fieldErrors != null && !fieldErrors.isEmpty()){
      String message = fieldErrors.get(0).getDefaultMessage();
 log.error(message, e);
 }
   HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
 HttpHeaders headers = new HttpHeaders();
 Response response = new Response();
 response.setCode(ResponseEnum.FORMAT_ERROR.code());
 response.setMessage(ResponseEnum.FORMAT_ERROR.message());
 return new ResponseEntity<>(response, headers, httpStatus);
}

For accepting the front-end request with a single parameter, the exception class generated by verification is ConstraintViolationException. The example method is as follows:

/**
 * Capture 303 the verification of a single parameter of request param
 * @param e
 * @param request
 * @return
 */@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
ResponseEntity<Object> handleConstraintViolationException(ConstraintViolationException e, HttpServletRequest request){
   HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
 HttpHeaders headers = new HttpHeaders();
 Response response = new Response();
 response.setCode(ResponseEnum.FORMAT_ERROR.code());
 response.setMessage(ResponseEnum.FORMAT_ERROR.message());
 return new ResponseEntity<>(response, headers, httpStatus);
}

Tags: Java Spring Boot

Posted by spartan789 on Mon, 09 May 2022 23:25:48 +0300