In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of Spring Boot how to achieve request parameter verification, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this Spring Boot article on how to achieve request parameter verification. Let's take a look.
JSR-303
Before we start hands-on practice, let's take a look at a standard specification that we will use next: JSR-303
What is JSR?
JSR is an acronym for Java Specification Requests, which means Java specification proposal. Is a formal request to JCP (Java Community Process) to add a standardized technical specification. Anyone can submit a JSR to add new API and services to the Java platform. JSR has become an important standard in the Java world.
What standard does JSR-303 define?
JSR-303 is a subspecification of JAVA EE 6, called Bean Validation,Hibernate Validator, which is a reference implementation of Bean Validation. Hibernate Validator provides an implementation of all the built-in constraint in the JSR 303 specification, in addition to some additional constraint.
Constraint built into Bean Validation
Constraint attached to Hibernate Validator
Under the JSR-303 standard, we can elegantly define the validation of each request parameter through the above annotations. More information about JSR can be found in the citations in the official documentation or Resources [1].
Hands-on practice
Now that we know about JSR-303, let's try how to implement parameter verification based on this specification!
Preparatory work
Readers can use any project built using Spring Boot 2.x to provide RESTful API as a basis. You can also use the Spring Boot 2.x basic tutorial: use the experimental project built in Swagger2 to build powerful API documents as a foundation, which you can get from the chapter2-2 directory in the warehouse below:
Github: https://github.com/dyc87112/SpringBoot-Learning/tree/2.x
Gitee: https://gitee.com/didispace/SpringBoot-Learning/tree/2.x
Of course, you can also build another one for review based on the previous article, which is no problem at all.
Getting started
Let's start with a simple example, such as defining that a field cannot be Null. It only takes two steps.
Step 1: add @ NotNull annotation to the field to be verified as follows:
@ Data@ApiModel (description= "user entity") public class User {@ ApiModelProperty ("user number") private Long id; @ NotNull @ ApiModelProperty ("user name") private String name; @ NotNull @ ApiModelProperty ("user age") private Integer age;}
Step 2: add @ Valid annotation before the parameter entity to be verified, as shown below:
@ PostMapping ("/") @ ApiOperation (value = "create user", notes = "create user from User object") public String postUser (@ Valid @ RequestBody User user) {users.put (user.getId (), user); return "success";}
After completing the above configuration, start the application and use the POST request to access the localhost:8080/users/ interface, and body uses an empty object, {}. You can use test tools such as Postman to initiate, or you can use curl to initiate, such as:
Curl-X POST\ http://localhost:8080/users/\-H 'Content-Type: application/json'\-H 'Postman-Token: 72745d04-caa5-44a1murbe84qba9c115f4dfb'\-H 'cache-control: no-cache'\-d' {}'
No surprise, you can get the following results:
{"timestamp": "2019-10-05T05:45:19.221+0000", "status": 400, "error": "Bad Request", "errors": [{"codes": ["NotNull.user.age", "NotNull.age", "NotNull.java.lang.Integer" "NotNull"], "arguments": [{"codes": ["user.age", "age"], "arguments": null "defaultMessage": "age", "code": "age"}], "defaultMessage": "cannot be null", "objectName": "user", "field": "age", "rejectedValue": null, "bindingFailure": false "code": "NotNull"}, {"codes": ["NotNull.user.name", "NotNull.name", "NotNull.java.lang.String", "NotNull"] "arguments": [{"codes": ["user.name", "name"], "arguments": null, "defaultMessage": "name" "code": "name"}], "defaultMessage": "cannot be null", "objectName": "user", "field": "name", "rejectedValue": null, "bindingFailure": false, "code": "NotNull"}] "message": "Validation failed for object='user'." Error count: 2 "," path ":" / users/ "}
The parameters of the returned content are as follows:
Timestamp: request time
The status code returned by status:HTTP. 400 is returned here, that is, the request is invalid and incorrect. Usually, the parameter verification fails.
The error description returned by error:HTTP, which corresponds to the error description of status: Bad Request
Errors: the specific cause of the error is an array type. Because there may be errors in multiple fields in error verification, for example, there are two error record messages here because two parameters cannot be Null.
Message: summary error message. It is easy to know in the returned content that the error here is caused by a failed validation of the user object, where the number of errors is 2, and the specific error message is defined in the errors array above.
Path: request path
After getting the standardized error message, the caller of the request can easily parse and take corresponding measures to complete its own business logic.
Try some other checks
After completing the above example, we can also add some verification rules, such as the length of the check string, the size of the check number, whether the format of the check string is a mailbox, and so on. Let's define some complex parity definitions, such as:
@ Data@ApiModel (description= "user entity") public class User {@ ApiModelProperty ("user number") private Long id; @ NotNull @ Size (min = 2, max = 5) @ ApiModelProperty ("user name") private String name; @ NotNull @ Max (10) @ ApiModelProperty ("user age") private Integer age; @ NotNull @ Email @ ApiModelProperty ("user email") private String email }
Initiate a request that fails the verification of name, age and email, as shown below:
Curl-X POST\ http://localhost:8080/users/\-H 'Content-Type: application/json'\-H 'Postman-Token: 114db0f0-bdce-4ba5-baf6-01e5104a68a3'\-H 'cache-control: no-cache'\-d' {"name": "abcdefg", "age": 8, "email": "aaaa"}'
We will get the following error return:
{"timestamp": "2019-10-05T06:24:30.518+0000", "status": 400, "error": "Bad Request", "errors": [{"codes": ["Size.user.name", "Size.name", "Size.java.lang.String" "Size"], "arguments": [{"codes": ["user.name", "name"], "arguments": null "defaultMessage": "name", "code": "name"}, 5,2], "defaultMessage": "number must be between 2 and 5", "objectName": "user", "field": "name" "rejectedValue": "abcdefg", "bindingFailure": false, "code": "Size"}, {"codes": ["Min.user.age", "Min.age", "Min.java.lang.Integer", "Min"] "arguments": [{"codes": ["user.age", "age"], "arguments": null, "defaultMessage": "age" "code": "age"}, 10], "defaultMessage": "minimum cannot be less than 10", "objectName": "user", "field": "age", "rejectedValue": 8, "bindingFailure": false "code": "Min"}, {"codes": ["Email.user.email", "Email.email", "Email.java.lang.String", "Email"] "arguments": [{"codes": ["user.email", "email"], "arguments": null, "defaultMessage": "email" "code": "email"}, [], {"defaultMessage": ". *", "codes": [. * "] "arguments": null}], "defaultMessage": "not a valid email address", "objectName": "user", "field": "email", "rejectedValue": "aaaa", "bindingFailure": false "code": "Email"}], "message": "Validation failed for object='user'." Error count: 3 "," path ":" / users/ "}
Knowing the defaultMessage of each field from the error details in the errors array, you can see a clear description of the error.
Embodiment in Swagger document
Some readers may ask, there are so many reservations in my interface. In the previous tutorial, I also taught you how to generate documents automatically, so how to describe the validation logic for parameters?
There are two situations here. Swagger itself has some support for JSR-303, but the support is not so perfect that it does not cover all the annotations.
For example, the annotations we used above can be generated automatically, start our experimental project above, and then visit http://localhost:8080/swagger-ui.html. In Models, we can see the content shown in the following figure:
Among them: the name and age fields have more instructions about verification than the documentation described in the previous tutorial, while the email field does not reflect the relevant verification instructions. Currently, Swagger supports the following annotations: @ NotNull, @ Max, @ Min, @ Size, @ Pattern. In the actual development process, we need to deal with it on a case-by-case basis. The automatically generated Swagger support can be generated using native support. If some fields cannot be generated, you can add the corresponding verification description in the description of the @ ApiModelProperty annotation to facilitate the user's view.
Foreigner: maybe you will have these questions
When there is an error message in the request parameter verification, can the error format be modified?
The answer is yes. The error messages here are actually uniformly organized and returned by Spring Boot's exception handling mechanism. We will explain in detail how Spring Boot uniformly handles exception returns and how we should schedule exception returns in later tutorials.
Is spring-boot-starter-validation necessary?
Some readers have asked before, seeing that many tutorials have been written, it is necessary to introduce spring-boot-starter-validation dependency. (not introduced in this article)
Org.springframework.boot spring-boot-starter-validation
In fact, you only need to take a closer look at what the spring-boot-starter-validation dependency is mainly about, and then judge it based on the version of Spring Boot you are currently using. In fact, the main purpose of spring-boot-starter-validation dependency is to introduce the following dependency:
Org.hibernate.validator hibernate-validator 6.0.14.Final compile
We can see if it is in the current project's dependencies, and we can determine whether additional introduction is needed. In Spring Boot 2.1, this still is actually included in spring-boot-starter-web dependencies and does not require additional introduction, so you will not find this step in this article.
This is the end of the article on "how to implement request parameter verification in Spring Boot". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to achieve request parameter verification in Spring Boot". If you want to learn more, 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.