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 check SpringBoot parameters

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

In this article, the editor introduces in detail "how to check the SpringBoot parameters", the content is detailed, the steps are clear, and the details are handled properly. I hope this "how to check the SpringBoot parameters" article can help you solve your doubts.

I. Preface

In Web development, it is often necessary to check the parameters transmitted from the front end, such as format check, non-empty check and so on. Almost every interface needs to be checked. If you use conventional IF ELSE for verification, with more and more parameters, the redundancy of the verification logic becomes higher and higher, resulting in poor maintainability. A set of annotation-based data verification specification Bean Validation is defined in Java, which can complete the necessary logical verification through some simple annotations, which is relatively convenient. Bean Validation is only a specification, and there is no specific implementation. Hibernate provides a specific implementation, that is, Hibernate Validator, which is also a widely used validator at present.

II. Introduction of notes

Validator built-in comments

@ Null the annotated element must be null

@ NotNull the annotated element must not be null

@ AssertTrue the annotated element must be true

@ AssertFalse the annotated element must be false

@ Min (value) the annotated element must be a number whose value must be greater than or equal to the specified minimum value

@ Max (value) the annotated element must be a number whose value must be less than or equal to the specified maximum value

@ DecimalMin (value) the annotated element must be a number whose value must be greater than or equal to the specified minimum value

@ DecimalMax (value) the annotated element must be a number whose value must be less than or equal to the specified maximum value

@ Size (max, min) the size of the annotated element must be within the specified range

@ Digits (integer, fraction) the annotated element must be a number and its value must be within an acceptable range

@ Past the annotated element must be a past date

@ Future the annotated element must be a future date

@ Pattern (value) the annotated element must conform to the specified regular expression

Constraint attached to Hibernate Validator

@ Email the annotated element must be an email address

@ Length the size of the annotated string must be within the specified range

@ NotEmpty the commented string must be non-empty

@ Range the annotated element must be within the appropriate scope

@ NotBlank verify that the string is not null and must be greater than 0 in length

Be careful

@ NotNull is used to verify whether the object is not null and cannot detect a string of length 0

@ NotEmpty for String, Map or array collection type cannot be null and the length must be greater than 0

@ NotBlank can only be used for String, not null, and the length must be greater than 0 after calling trim ()

To verify whether the string is empty, use @ NotNull. It will be detected only if the parameter is not passed. A null value (such as an empty string) can still pass the verification, so @ NotBlank should be used.

Add dependencies

In SpringBoot, Bean Validation is already integrated into starter-web, so there is no need to add dependencies. However, my actual test found that it does not seem to work directly, so I added the following dependencies:

Org.springframework.boot spring-boot-starter-validation IV. Create entity classes for verification

Create a validator directory and create a UserDTO class in it

Originally, I wanted to reuse the entity class created earlier, but then I thought about it. Entity is used to establish the mapping relationship of the database, and the fields are one-to-one corresponding to the data table, while the validator here is used to verify the parameters passed by the front end, and the fields correspond to the parameters passed by the front end, so it cannot be reused. You need to write a separate validator class.

By the way, using self-defined objects in RestController requires methods such as setter, getter, or the @ Data annotation of lombok. If you don't add it, you will report an error:

No converter found for return value of type: class validator.UserDTO

Use the getter and setter methods as follows:

Public class UserDTO {private String username; private Integer age; public String getUsername () {return username;} public void setUsername (String username) {this.username = username;} public Integer getAge () {return age } public void setAge (Integer age) {this.age = age;}}

The @ Data annotation using lombok is as follows, and the code is equivalent to the above:

@ Datapublic class UserDTO {private String username; private Integer age;} 5. Write an interface for testing

Add a POST interface, get the parameters from the request body, and return to the past intact (mainly used to test parameter verification, where the interface logic is not important)

@ PostMapping ("validateUser") public UserDTO userValidate (@ RequestBody UserDTO userDTO) {return userDTO;} VI. Add comments to the entity class

Add comments to the parameters that need to be verified:

@ Datapublic class UserDTO {@ NotBlank (message = "user name cannot be empty") private String username; @ NotBlank (message = "phone number cannot be empty") private String mobile; @ NotNull (message = "gender cannot be empty") private Integer sex; @ NotNull (message = "age cannot be empty") private Integer age @ NotBlank (message = "mailbox cannot be empty") @ Email (message = "mailbox format error") private String email;} 7. Add a Validated annotation to the controller method

Then you need to add @ Validated to the body of the controller method, and it won't work without the @ Validated check.

Test it with the following data:

{"username": "," mobile ":" 2333 "," sex ": 0," age ": 0," email ":" 233@dby.com "}

You can see that the verification is successful, but an exception is thrown at the background:

Validation failed for argument [0] in public validator.UserDTO com.hhlnyfz.hhlnyfz.HelloController.userValidate (validator.UserDTO): [Field error in object 'userDTO' on field' username': rejected value []; codes [NotBlank.userDTO.username,NotBlank.username,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [userDTO.username,username]; arguments []; default message [username]]; default message [user name cannot be empty]

Then the return parameters are not ideal, and the front end is not easy to deal with the return parameters.

Add global exception handling

The above situation requires the addition of global exception handling, which is more standardized. Create a GlobalExceptionHandler class, add the @ RestControllerAdvice annotation on top of the class, and then add the following code:

/ * Global exception handling class * / @ RestControllerAdvicepublic class GlobalExceptionHandler {/ / catch MethodArgumentNotValidException exception @ ExceptionHandler (value = MethodArgumentNotValidException.class) public HashMap handleMethodArgumentNotValidException (MethodArgumentNotValidException e, HttpServletRequest request) {HashMap map = new HashMap (); map.put ("code", 400); map.put ("msg", e.getMessage ()); map.put ("url", request.getRequestURL ()); return map } / / other exception handling methods}

The MethodArgumentNotValidException.class in the @ ExceptionHandler annotation here is used to catch request parameter exceptions. If it is Exception.class, all exceptions are caught. Instead of using one method to handle all exceptions, one method handles one exception. If you need to handle other exceptions, you can add methods below.

Using the test case just now, the exception was caught this time

You can see that e.getMessage () prints out the entire error stack, but we just need to return the last default message to the front end, so we use e.getBindingResult (). GetFieldError (). GetDefaultMessage (), and IDE gives a hint:

Method invocation 'getDefaultMessage' may produce' NullPointerException'

That is, e.getBindingResult (). GetFieldError () may be a null pointer null, so wrap it in Objects.requireNonNull as prompted by IDE, and the final code is as follows:

/ * Global exception handling class * / @ RestControllerAdvicepublic class GlobalExceptionHandler {/ / catch MethodArgumentNotValidException exception @ ExceptionHandler (value = MethodArgumentNotValidException.class) public HashMap handleMethodArgumentNotValidException (MethodArgumentNotValidException e, HttpServletRequest request) {HashMap map = new HashMap (); map.put ("code", 400); map.put ("msg", Objects.requireNonNull (e.getBindingResult (). GetFieldError ()). GetDefaultMessage ()) Map.put ("url", request.getRequestURL ()); return map;} / / other exception handling methods}

Of course, there are still some irregularities here, and there is no return with the unified response body. How to encapsulate the unified response body will be described later.

IX. Grouping check

Both @ Valid and @ Validated annotations can be verified, and the previous function is also possible with @ Valid, but @ Validated is more powerful and can implement group verification. What is packet check? packet check actually implements the reuse of entity classes, and sometimes you do not want to verify all parameters, such as the following case:

@ Datapublic class Route {@ NotNull (message = "origin province id cannot be empty") private Integer startProvinceId; @ NotNull (message = "destination province id cannot be empty") private Integer endProvinceId; @ NotBlank (message = "detailed address cannot be empty") private String address;}

If you only want to check startProvinceId and address in one interface and only endProvinceId and address in another interface, you can use packet check. You can define an interface:

Public interface ValidateGroup {interface RouteValidStart {} interface RouteValidEnd {}}

Then add a grouping to the entity class:

@ Datapublic class Route {@ NotNull (groups = {RouteValidStart.class}, message = "Origin province id cannot be empty") private Integer startProvinceId; @ NotNull (groups = {RouteValidEnd.class}, message = "destination province id cannot be empty") private Integer endProvinceId; @ NotBlank (groups = {RouteValidStart.class, RouteValidEnd.class}, message = "detailed address cannot be empty") private String address;}

Then, when verifying, you only need to pass the packet into @ Validate to verify the specified parameters:

RequestMapping ("addRoute") public ServerResponse addRoute (@ RequestBody @ Validated ({RouteValidStart.class}) Route route) {/ /. Return ServerResponse.success ();} X. single parameter verification

Just add a note before the parameter:

@ PostMapping ("/ get") public ReturnVO getUserInfo (@ RequestParam ("userId") @ NotNull (message = "user ID cannot be empty") String userId) {return new ReturnVO () .success ();}

Then add the @ Validated annotation to the Controller class, not in front of the parameter.

After reading this, the article "how to calibrate SpringBoot parameters" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, 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.

Share To

Development

Wechat

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

12
Report