Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the parameter verification process of SpringBoot developed by java

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to achieve java development SpringBoot parameter verification process", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in-depth, together to study and learn "how to achieve java development SpringBoot parameter verification process" bar!

Why do you need parameter verification

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 verifying whether the user name and password is empty when logging in and verifying whether the format of email and mobile phone number is accurate when creating users. 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 during development 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.

The Validator verification framework follows the JSR-303 verification specification (parameter verification specification).

JSR is the abbreviation of Java Specification Requests.

Let's take a look at how to integrate the parameter verification framework in SpringbBoot.

The first step of integrated parameter verification in SpringBoot is to introduce dependent org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-validation

Note: starting from springboot-2.3, the check package is separated into a starter component, so validation and web need to be introduced.

Previous versions of springboot-2.3 only needed to introduce web dependencies.

The second step is to define the entity class @ Datapublic class ValidVO {private String id; @ Length (min = 6 mag max = 12 Magi message = "appId length must be between 6 and 12") private String appId; @ NotBlank (message = "name is required") private String name; @ Email (message = "Please fill in the correct email address") private String email; private String sex @ NotEmpty (message = "level cannot be empty") private String level;}

In the actual development, you need to set the corresponding business prompt, that is, the message attribute, for the fields that need to be verified.

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.

The third step is to define a check class to test @ RestController@Slf4j@Validatedpublic class ValidController {@ ApiOperation ("RequestBody check") @ PostMapping ("/ valid/test1") public String test1 (@ Validated @ RequestBody ValidVO validVO) {log.info ("validEntity is {}", validVO); return "test1 valid success" } @ ApiOperation ("Form check") @ PostMapping (value = "/ valid/test2") public String test2 (@ Validated ValidVO validVO) {log.info ("validEntity is {}", validVO); return "test2 valid success";} @ ApiOperation ("single parameter check") @ PostMapping (value = "/ valid/test3") public String test3 (@ Email String email) {log.info ("email is {}", email) Return "email valid success";}}

Here we first define three methods: test1,test2,test3,test1 uses the @ RequestBody annotation to accept json data sent by the front end, test2 simulates form submission, and test3 simulates single parameter submission. Note that when using single-parameter validation, you need to add the @ Validated annotation to the Controller, otherwise it will not take effect.

Step 4, experience the effect.

Call the test1 method

It indicates an org.springframework.web.bind.MethodArgumentNotValidException exception.

POST http://localhost:8080/valid/test1Content-Type: application/json {"id": 1, "level": "12", "email": "47693899", "appId": "ab1c"} {"status": 500, "message": "Validation failed for argument [0] in public java.lang.String com.jianzh6.blog.valid.ValidController.test1 (com.jianzh6.blog.valid.ValidVO) with 3 errors: [Field error in object 'validVO' on field' email': rejected value [47693899] Codes [Email.validVO.email,Email.email,Email.java.lang.String,Email]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [validVO.email,email]; arguments []; default message [email], [Ljavax.validation.constraints.Pattern$Flag;@26139123,.*]; default message [not a valid email address]]... "," data ": null," timestamp ": 1628239624332}

Call the test2 method

It indicates an org.springframework.validation.BindException exception.

POST http://localhost:8080/valid/test2Content-Type: application/x-www-form-urlencodedid=1&level=12&email=476938977&appId=ab1c {"status": 500, "message": "org.springframework.validation.BeanPropertyBindingResult: 3 errors\ nField error in object 'validVO' on field' name': rejected value [null]; codes [NotBlank.validVO.name,NotBlank.name,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [validVO.name,name]; arguments []; default message [name]] Default message [name is required]..., "data": null, "timestamp": 1628239301951}

Call the test3 method

It indicates a javax.validation.ConstraintViolationException exception.

POST http://localhost:8080/valid/test3Content-Type: application/x-www-form-urlencodedemail=476938977 {"status": 500, "message": "test3.email: not a valid email address", "data": null, "timestamp": 1628239281022}

By adding the Validator verification framework, we can help us to automatically verify the parameters.

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:

@ ExceptionHandler (value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class}) public ResponseEntity handleValidatedException (Exception e) {ResultData resp = null; if (e instanceof MethodArgumentNotValidException) {/ / BeanValidation exception MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e Resp = ResultData.fail (HttpStatus.BAD_REQUEST.value (), ex.getBindingResult (). GetAllErrors (). Stream () .map (ObjectError::getDefaultMessage) .map (Collectors.joining (";")) } else if (e instanceof ConstraintViolationException) {/ / BeanValidation GET simple param ConstraintViolationException ex = (ConstraintViolationException) e; resp = ResultData.fail (HttpStatus.BAD_REQUEST.value (), ex.getConstraintViolations (). Stream () .map (ConstraintViolation::getMessage) .map (Collectors.joining (";") } else if (e instanceof BindException) {/ / BeanValidation GET object param BindException ex = (BindException) e; resp = ResultData.fail (HttpStatus.BAD_REQUEST.value (), ex.getAllErrors (). Stream () .map (ObjectError::getDefaultMessage) .map (Collectors.joining (";") } return new ResponseEntity (resp,HttpStatus.BAD_REQUEST);}

Experience effect

POST http://localhost:8080/valid/test1Content-Type: application/json {"id": 1, "level": "12", "email": "47693899", "appId": "ab1c"} POST http://localhost:8080/valid/test1Content-Type: application/json {"id": 1, "level": "12", "email": "47693899", "appId": "ab1c"} {"status": 400 "message": "first name is required Is not a valid email address; appId length must be between 6 and 12 "," data ": null," timestamp ": 1628435116680}

Do you feel much more refreshed?

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 in the above entity class only allows the front end to pass on the two enumerated values of MMagi F, how to achieve it?

The first step is to create a custom annotation @ 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report