Get the App
SLTechnology News&Howtos  ›  Development  › 

How to calibrate SpringBoot parameters

Shulou Source: shulou.com Published: 2022-05-31 17:25:47 10月03日 Update

This article mainly explains "how to check SpringBoot parameters". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to check SpringBoot parameters".

Disadvantages of using traditional methods: public String addUser (User user) {if (user = = null | | user.getId () = = null | | user.getAccount () = = null | | user.getPassword () = = null | | user.getEmail () = = null) {return "object or object field cannot be empty" } if (StringUtils.isEmpty (user.getAccount ()) | | StringUtils.isEmpty (user.getPassword ()) | | StringUtils.isEmpty (user.getEmail ()) {return "cannot enter an empty string";} if (user.getAccount (). Length ())

< 6 || user.getAccount().length() >

11) {return "account must be 6-11 characters long";} if (user.getPassword () .length ()

< 6 || user.getPassword().length() >

16) {return "password must be 6-16 characters long";} if (! Pattern.matches ("^ [a-zA-Z0-9 characters -] + @ [a-zA-Z0-9 characters -] + (\. [a-zA-Z0-9 characters -] +) + $", user.getEmail ()) {return "incorrect mailbox format" } / / after the parameter verification, write the business logic return "success";}

There is really nothing wrong with this, and the typesetting is neat, but the code is so cumbersome that if there are dozens of fields to check, this method will become very bloated and not elegant enough. Let's talk about how to use the most elegant way to solve the problem.

The introduction of dependent org.springframework.boot spring-boot-starter-validation annotations states that @ AssertFalse annotated elements must be false@AssertTrue annotated elements must be true@DecimalMax (value) annotated elements must be a number, and its value must be less than or equal to the specified maximum value @ DecimalMin (value) annotated elements must be a number Its value must be greater than or equal to the specified minimum value @ Digits (integer, fraction) annotated element must be a number, its value must be within the acceptable range @ Null annotated element must be empty @ NotNull annotated element must not be empty @ Min (value) annotated element must be a number, its value must be greater than or equal to the specified maximum value @ Max (value) annotated element must be a number Its value must be less than or equal to the specified maximum value @ Size (max, min) the length of the annotated element must be within the specified range @ Past annotated element must be a past date @ Future annotated element must be a future date @ Pattern (value) annotated element must conform to the specified regular expression

Let's use this to implement in the business.

1. Check the entity class 1. Entity@Datapublic class User {@ NotNull (message = "user id cannot be empty") private Long id; @ NotNull (message = "user account cannot be empty") @ Size (min = 6, max = 11, message = "account length must be 6-11 characters") private String account @ NotNull (message = "user password cannot be empty") @ Size (min = 6, max = 11, message = "password must be 6-16 characters long") private String password; @ NotNull (message = "user mailbox cannot be empty") @ Email (message = "incorrect mailbox format") private String email } 2, controller@RestControllerpublic class UserController {@ PostMapping ("/ addUser") public void addUser (@ RequestBody @ Valid User user) {/ / Business}} 3, write global unified exception handling 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 java.util.stream.Collectors / * @ author master * / @ RestControllerAdvicepublic class ExceptionConfig {/ * * Parameter is entity class * @ param e * @ return * / @ ExceptionHandler (value = MethodArgumentNotValidException.class) public String handleValidException (MethodArgumentNotValidException e) {/ / get the ObjectError object ObjectError objectError = e.getBindingResult () .getAllErrors () .get (0) from the exception object / / then extract the error message and return to return objectError.getDefaultMessage () } / * Parameter is a single parameter or multiple parameters * @ param e * @ return * / @ ExceptionHandler (value = ConstraintViolationException.class) public String handleConstraintViolationException (ConstraintViolationException e) {/ / get the ObjectError object return e.getConstraintViolations () .stream () .map (ConstraintViolation::getMessage) from the exception object ) .quit (Collectors.toList ()) .get (0) }}

Then we use apipost to test

Second, verify import org.springframework.validation.annotation.Validated;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RestController;import javax.validation.constraints.NotNull;@RestController@Validatedpublic class TestController {@ GetMapping ("/ test") public void test (@ NotNull (message = "id cannot be empty") Integer id) {}} against a single parameter.

Then we use apipost to test

Third, grouping verification

Scenario: when adding, we need id to be empty, but when we modify it, we need that id is not empty, so it is impossible to create two classes. At this time, the use of grouping verification comes.

1. Entityimport lombok.Data;import javax.validation.constraints.Email;import javax.validation.constraints.NotNull;import javax.validation.constraints.Size;@Datapublic class User {public interface Insert {} public interface Update {} @ NotNull (message = "user id cannot be empty", groups = Update.class) @ Null (message = "user id must be empty", groups = Integer.class) private Long id; private String account; private String password; private String email 2. Controller@PostMapping ("/ add") public void add (@ RequestBody @ Validated (User.Insert.class) User user) {}

Use User.Insert.class when adding and User.Update.class when modifying.

IV. Custom grouping check

Scenario: parameter an is required to be not empty when type is 1, and parameter b is required to be not empty when type is 2.

1. Entityimport com.example.demo.provider.CustomSequenceProvider;import lombok.Data;import org.hibernate.validator.group.GroupSequenceProvider;import javax.validation.constraints.NotEmpty;import javax.validation.constraints.Pattern;@Data@GroupSequenceProvider (value = CustomSequenceProvider.class) public class CustomGroup {/ * Type * / @ Pattern (regexp = "[A | B]", message = "Type does not have to be A | B") private String type / * * Parameter A * / @ NotEmpty (message = "Parameter A cannot be empty", groups = {WhenTypeIsA.class}) private String paramA; / * * Parameter B * / @ NotEmpty (message = "Parameter B cannot be null", groups = {WhenTypeIsB.class}) private String paramB / * * Group A * / public interface WhenTypeIsA {} / * * Group B * / public interface WhenTypeIsB {}} 2, CustomSequenceProviderimport com.example.demo.controller.CustomGroup;import org.hibernate.validator.spi.group.DefaultGroupSequenceProvider;import java.util.ArrayList;import java.util.List;public class CustomSequenceProvider implements DefaultGroupSequenceProvider {@ Override public List > defaultGroupSequence = new ArrayList (); defaultGroupSequence.add (CustomGroup.class) If (form! = null & & "A" .equals (form.getType () {defaultGroupSequence.add (CustomGroup.WhenTypeIsA.class);} if (form! = null & & "B" .equals (form.getType () {defaultGroupSequence.add (CustomGroup.WhenTypeIsB.class);} return defaultGroupSequence }} 3. Controller@PostMapping ("/ add") public void add (@ RequestBody @ Validated CustomGroup user) {} 5. Custom check

Although the official verification notes have met many situations, they still can not meet all the needs of our business, such as verifying mobile phone numbers. Let me take the verification of mobile phone numbers as an example.

1. Define the check annotation @ Target ({ElementType.FIELD}) @ Retention (RetentionPolicy.RUNTIME) @ Constraint (validatedBy = PhoneValidator.class) public @ interface Phone {String message () default "incorrect Mobile number format"; Class [] groups () default {}; Class

Tags: Comments parameters elements objects users numbers length grouping business characters maximum number field entity password mobile phone mobile number maximum format account number Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Microsoft Shulou Information vpn Huawei