In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains "how to check the parameters of SpringBoot". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to check parameters in SpringBoot".
Introduction
In daily interface development, in order to prevent illegal parameters from affecting the business, it is often necessary to verify the parameters of the interface, such as checking whether the user name and password are empty when logging in. When adding users, verify whether the user's email address and mobile phone number format is correct. It is too tedious to check the interface parameters one by one by code, and the readability of the code is very poor.
Validator framework is to solve the problem that developers write less code when developing and improve development efficiency; Validator is specially used for interface parameter verification, such as common required check, email format check, user name must be between 6 and 12, and so on.
Let's take a look at how to integrate the parameter verification framework in SpringbBoot.
Integrated Parameter check 1.1 in 1.SpringBoot introduces dependency org.springframework.boot spring-boot-starter-validation1.2 to define parameter entity class package com.didiplus.modules.sys.domain;import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiModelProperty;import lombok.Data;import javax.validation.constraints.Email;import javax.validation.constraints.NotBlank;import javax.validation.constraints.NotEmpty / * Author: didiplus * Email: 972479352@qq.com * CreateTime: 2022-4-25 * Desc: dictionary type domain model * / @ Data@ApiModel (value = "dictionary type") public class SysDictType {@ ApiModelProperty ("ID") private String id; @ NotBlank (message = "dictionary name required") @ ApiModelProperty (value = "dictionary name", example = "user ID") private String typeName @ NotBlank (message = "dictionary encoding cannot be empty") @ ApiModelProperty (value = "dictionary encoding") private String typeCode; @ Email (message = "Please fill in the correct email address") @ ApiModelProperty (value = "dictionary encoding") private String email; @ ApiModelProperty (value = "dictionary description") private String description @ NotBlank (message = "dictionary status cannot be empty") @ ApiModelProperty (value = "dictionary status") private String enable;}
Common constraint annotations are as follows:
The annotation function @ AssertFalse can be null, or false@AssertTrue can be null if it is not null. If not for null, the true@DecimalMax setting must not exceed the maximum value @ DecimalMin setting must not exceed the minimum value @ Digits setting must be numeric and the number of digits of integers and decimals must be within the specified range @ Future date must be in the future of the current date @ Past date must be in the past of the current date @ Max maximum @ Min maximum @ NotNull can not be less than this minimum Can be empty @ Null must be null@Pattern must satisfy the specified regular expression @ Size collection, array, map, etc. Size () value must be within the specified range @ Email must be email format @ Length length must be within the specified range @ NotBlank string cannot be null, string trim () cannot be equal to "@ NotEmpty cannot be null, set, array, map, etc. Size () cannot be 0 The string trim () can be equal to "@ Range" and the value must be within the specified range. @ URL must be a URL1.3 definition check class to test package com.didiplus.modules.sys.controller;import com.didiplus.modules.sys.domain.SysDictType;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import io.swagger.v3.oas.annotations.parameters.RequestBody;import org.springframework.validation.annotation.Validated;import org.springframework.web.bind.annotation.PostMapping. Import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController / * Author: didiplus * Email: 972479352@qq.com * CreateTime: 2022-4-25 * Desc: data dictionary controller * / @ RestController@Api (tags = "data dictionary") @ RequestMapping ("/ api/sys/dictType") public class SysDictTypeController {@ ApiOperation ("dictionary add") @ PostMapping ("/ add") public SysDictType add (@ Validated @ RequestBody SysDictType sysDictType) {return sysDictType } @ ApiOperation ("dictionary modification") @ PutMapping ("/ edit") public SysDictType edit (@ Validated @ RequestBody SysDictType sysDictType) {return sysDictType;}}
Here we first define two methods add,edit, both of which use the @ RequestBody annotation to accept the json data sent by the front end.
1.4 Open the interface document to simulate the submission data
From the interface document, you can see that the first three fields are required.
The email was blocked because of the incorrect format, and the prompt was due to the wrong email address.
two。 Parameter exception is added to the global exception handler
Although we defined the global exception interceptor before and saw that the interceptor does work, the error prompt returned by the Validator verification framework is too bloated to be easy to read, and we need to simplify it in order to facilitate the front-end prompt.
Directly modify the previously defined RestExceptionHandler, and separately intercept the three exceptions of parameter verification:
Javax.validation.ConstraintViolationException
Org.springframework.validation.BindException
Org.springframework.web.bind.MethodArgumentNotValidException
The code is as follows:
Package com.didiplus.common.web.response.Handler;import com.didiplus.common.web.response.Result;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.validation.BindException;import org.springframework.validation.ObjectError;import org.springframework.web.bind.MethodArgumentNotValidException;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RestControllerAdvice;import javax.validation.ConstraintViolation;import javax.validation.ConstraintViolationException;import javax.validation.ValidationException;import java.util.stream.Collectors / * Author: didiplus * Email: 972479352@qq.com * CreateTime: 2022-4-24 * Desc: default global exception handling. * / @ RestControllerAdvicepublic class RestExceptionHandler {/ * default global exception handling. * @ param e the e * @ return ResultData * / @ ExceptionHandler (value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class}) public ResponseEntity handleValidatedException (Exception e) {Result result = null; if (e instanceof MethodArgumentNotValidException) {MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e Result = Result.failure (HttpStatus.BAD_REQUEST.value (), ex.getBindingResult (). GetAllErrors (). Stream () .map (ObjectError::getDefaultMessage) .map (Collectors.joining (";")) } else if (e instanceof ConstraintViolationException) {ConstraintViolationException ex = (ConstraintViolationException) e Result = Result.failure (HttpStatus.BAD_REQUEST.value (), ex.getConstraintViolations (). Stream () .map (ConstraintViolation::getMessage) .map (Collectors.joining (" ));} else if (e instanceof BindException) {BindException ex = (BindException) e Result = Result.failure (HttpStatus.BAD_REQUEST.value (), ex.getAllErrors (). Stream () .map (ObjectError::getDefaultMessage) .map (Collectors.joining (" ));} return new ResponseEntity (result,HttpStatus.BAD_REQUEST);}}
The error message is more friendly after beautification.
3. Custom parameter check
Although the annotations provided by Spring Validation are basically sufficient, in the face of complex definitions, we still need to define the relevant annotations ourselves to achieve automatic verification.
For example, the sex gender attribute added in the above entity class only allows the front end to pass on the two enumerated values of Mforce F, how to achieve it?
3.1 create a custom annotation package com.didiplus.common.annotation;import javax.validation.Constraint;import javax.validation.Payload;import java.lang.annotation.Documented;import java.lang.annotation.Repeatable;import java.lang.annotation.Retention;import java.lang.annotation.Target;import static java.lang.annotation.ElementType.*;import static java.lang.annotation.RetentionPolicy.RUNTIME / * Author: didiplus * Email: 972479352@qq.com * CreateTime: 2022-4-26 * Desc: * / @ Target ({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE}) @ Retention (RUNTIME) @ Repeatable (EnumString.List.class) @ Documented@Constraint (validatedBy = EnumStringValidator.class) / / indicate which class executes the verification logic public @ interface EnumString {String message () default "value not in enum values."; Class [] groups () default {}; Class
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.