In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
In this issue, the editor will bring you the integrated parameter verification on how to carry out SpringBoot development. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.
For web services, in order to prevent illegal parameters from affecting the business, the parameters must be verified in the Controller layer!
Easy to use
1. To add parameter verification to a Springboot project, you must first add spring-boot-starter-validation dependencies.
Org.springframework.boot spring-boot-starter-validation
two。 Then add binding comments to the fields that need to be verified, such as we check the parameters of the entity class.
@ Data public class ValidEntity {private int id; @ NotBlank private String appId; @ NotBlank private String name; @ Email private String email;}
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 it is not null, the setting for true@DecimalMax 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 must not be less than this minimum @ NotNull cannot be null 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 "@ URL" and the value must be within the specified range. @ Range must be a URL.
Note: this table is only a simple description of the annotation function, and does not describe the attributes of each annotation; see the source code for details.
3. Add @ Validated annotations to the methods that require parameter verification in the Controller layer
Parameter validation is generally divided into two categories: when Controller uses the model to receive data, the @ Validated annotation can be placed directly in front of the model parameters.
PostMapping (value = "test1") public String test1 (@ Validated @ RequestBody ValidEntity validEntity) {return "test1 valid success";} @ PostMapping (value = "test3") public String test3 (@ Validated ValidEntity validEntity) {return "test3 valid success";}
When we use constraint annotations directly before the parameters in the Controller layer, @ Validated should be placed directly on the class
@ PostMapping (value = "test2") public String test2 (@ Email String email) {return "test2 valid success";}
At this point, you need to add @ Validated annotation to the main class.
@ Validated @ RestController @ RequestMapping ("/ demo/valid") public class ValidController {...}
In parameter verification, we can use either @ Validated or @ Valid annotations, most of which are similar in function.
The main differences are:
@ Valid belongs to javax, while @ Validated belongs to spring
@ Valid supports nested parity, but @ Validated does not, @ Validated supports grouping, and @ Valid does not.
Unified exception handling
If the parameter verification fails Spring, three types of exceptions will be thrown.
1. Org.springframework.web.bind.MethodArgumentNotValidException occurs when verifying the parameters required by @ RequestBody
Javax.validation.ConstraintViolationException occurs when verifying specific parameters directly, which is also a ValidationException exception.
Org.springframework.validation.BindException appears when you directly validate an object
Unified interception processing in SpringBoot only needs to add @ RestControllerAdvice annotation to the configuration class, and then specify the exception to be handled by @ ExceptionHandler in the specific method. The specific code is as follows:
@ RestControllerAdvice @ Slf4j public class GlobalExceptionHandler {public static final String ERROR_MSG = "system exception, please contact your administrator." ; @ ExceptionHandler (value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class}) public ResponseEntity handleValidatedException (Exception e) {Result resp = null; if (e instanceof MethodArgumentNotValidException) {/ / BeanValidation exception MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e Resp = new Result (Integer.toString (HttpStatus.BAD_REQUEST.value ()), ex.getBindingResult (). GetAllErrors (). Stream (). Map (ObjectError::getDefaultMessage). ObjectError::getDefaultMessage (Collectors.joining (",")), getStackTrace (ex);} else if (e instanceof ConstraintViolationException) {/ / BeanValidation GET simple param ConstraintViolationException ex = (ConstraintViolationException) e Resp = new Result (Integer.toString (HttpStatus.BAD_REQUEST.value ()), ex.getConstraintViolations (). Stream (). Map (ConstraintViolation::getMessage). Collectors.joining (","), getStackTrace (ex);} else if (e instanceof BindException) {/ / BeanValidation GET object param BindException ex = (BindException) e Resp = new Result (Integer.toString (HttpStatus.BAD_REQUEST.value ()), ex.getAllErrors (). Stream (). Map (ObjectError::getDefaultMessage) .Collectors.joining (","), getStackTrace (ex));} return new ResponseEntity (resp,HttpStatus.BAD_REQUEST) } private String getStackTrace (Exception e) {/ / print log switch, you can read boolean printStrackTrace = false; if (printStrackTrace) {StringWriter sw = new StringWriter (); e.printStackTrace (new PrintWriter (sw)); return sw.toString ();} else {return ERROR_MSG;}
The final results are as follows:
Parameter grouping
There is an entity class below, and we need to verify its parameters.
@ Data public class ValidEntity {private int id; @ NotBlank private String appId; @ NotBlank private String name; @ Email private String email;}
However, appId is required when the actual business is edited, and name is required when it is added. At this time, you can use the groups grouping feature to achieve: the same model can dynamically distinguish different fields in the verification model in different scenarios.
Mode of use
First, we define a packet interface ValidGroup, and then define several different operation types in the packet interface, Create,Update,Query,Delete.
Public interface ValidGroup extends Default {interface Crud extends ValidGroup {interface Create extends Crud {} interface Update extends Crud {} interface Query extends Crud {} interface Delete extends Crud {}
The ValidGroup here inherits the Default, of course, it doesn't have to be inherited, and we'll talk about the difference later.
Assign groups to check parameters in the model
Data @ ApiModel (value= "ValidEntity") public class ValidEntity {private int id; @ NotBlank (groups = ValidGroup.Crud.Update.class) private String appId; @ NotBlank (groups = ValidGroup.Crud.Create.class) private String name; @ Email private String email;}
Tips: the @ Email note here does not specify a grouping. By default, it belongs to the Default grouping. If appId and name specify a grouping, it will no longer belong to the Default grouping.
Specify the grouping through the value attribute when the parameter is checked
The specific grouping is specified through @ Validated (value = ValidGroup.Crud.Update.class). The difference between whether or not to inherit Default mentioned above is:
Parameters that are not grouped or grouped by Default are also verified if the annotations of Default,@Validated annotations are inherited, such as email
If you do not inherit Default, the parameters that are not grouped will not be verified. You need to add @ Validated (value = {ValidGroup.Crud.Update.class, Default.class}) to verify them.
Quick failure (Fali Fast)
By default, Spring Validation verifies all fields before throwing an exception when verifying the parameters. You can enable Fali Fast mode through configuration and return immediately if the verification fails.
@ Configuration public class ValidatedConfig {@ Bean public Validator validator () {ValidatorFactory validatorFactory = Validation.byProvider (HibernateValidator.class) .configure () / / Quick failure mode .failFast (true) .buildValidatorFactory (); return validatorFactory.getValidator () }} the above is the verification of the integration parameters of SpringBoot development shared by the editor. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
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.