Spring Validation data validation implementation

1. The role of Spring validation

1) Regarding Sql injection: it is to insert SQL commands into Web forms to submit or enter query strings for domain names or page requests, and finally trick the server into executing malicious SQL commands.

2) Prevent Sql injection: (1) Never trust the user's input. To verify the user's input, you can use regular expressions, or limit the length, convert single quotes and double "-", etc. (2) Never use dynamic assembled SQL, you can use parameterized SQL or directly use stored procedures for data query and access. (3) Never use a database connection with administrator privileges, use a separate database connection with limited privileges for each application. (4) Do not store confidential information in plain text, please encrypt or hash passwords and sensitive information. (5) The exception information of the application should give as few hints as possible. It is better to use custom error information to package the original error information and store the exception information in an independent table.

3) Therefore, Spring Validation is needed, and the main function of Spring Validation is to check the basic format of request parameters.

2. About checking request parameters

In development practice, whether it is a client-side project (such as a web front-end) or a server-side project, it is necessary to check the data filled in and selected by the user!

In fact, it is the server-side inspection that can finally ensure that the data is valid. Therefore, the server-side must check the request parameters, and only when the basic format of the data is valid can it perform related processing.

The client's inspection should not be the final guarantee. In the front-end and back-end separation mode, the server cannot guarantee that all clients have adopted unified and effective verification rules! Because the checking of the client may not be implemented, the version of the client software in the user equipment may not be upgraded, and even the client software may be forged or tampered with.

Even though the client's checks are not necessarily reliable, all clients should still check the request parameters, and if the basic format of the parameters does not meet the requirements, the request should not be submitted! After all, the client's inspection can intercept most errors (no low-level error requests will be sent to the server), so as to reduce the pressure on the server.

3. Add dependencies

In a Spring Boot project, the dependencies to use Spring Boot Validation are:

<!-- Spring Boot Validation:用于检查请求参数的基本格式 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

4. Basic use

In the method of the controller processing the request, add `@Valid` or `@Validated` annotations to the request parameters that need to be verified, indicating that this parameter needs to be checked by Spring Boot Validation, for example:

@PostMapping("/add-new")
public JsonResult addNew(@RequestBody @Valid BrandAddNewDTO brandAddNewDTO) {
    brandService.addNew(brandAddNewDTO);
    return JsonResult.ok();
}

In the POJO class that encapsulates the request parameters, before each attribute that needs to verify the format, add annotations to check the format to achieve format verification, for example:

@ApiModelProperty(value = "品牌名称", required = true, example = "华为")
@NotNull
private String name;

5. Notes on checking parameter format

@NotNull: `null` is not allowed, that is, the parameter corresponding to this name must be submitted

  Note: Works with primitive data types (Integer, Long, Double, etc.)

@NotEmpty: Empty strings (strings of length 0) are not allowed

 Note: Applicable to array or collection type attributes to determine that the current array or collection cannot be null and the length cannot be 0

@NotBlank: Blank is not allowed (the length of the string may be greater than 0, but it is entered by spaces, TABs, etc.)

 Note: Applies to parameters in string format

@Min: Set the minimum value of the numeric type

 Only for request parameters of numeric type

 Can be replaced by @Range

@Max: Set the maximum value of the numeric type

Only for request parameters of numeric type

Can be replaced by @Range

@Range: Set the value range of the data type, the minimum and maximum values ​​can be set

The min attribute of this annotation defaults to 0, and the max attribute defaults to the maximum value of the long type

Only for request parameters of numeric type

@Pattern: configure regular expressions

Cannot replace @NotNull annotation

In development practice, for request parameters of string type, `@NotNull` (if you think it must be submitted) and @Pattern should be used at the same time, while `@NotEmpty`, `@NotBlank` usually do not need to be used unless you are concerned There are not many requirements for the value of the string. For request parameters of numeric type, you should use `@NotNull` and `@Range` at the same time.

Note: For attributes of numeric type, if the submitted request parameters cannot be converted into numeric types, these annotations will not take effect and an error will be reported.

In addition, in development practice, the regular expressions used and the prompt text when an error occurs are usually encapsulated in a special class or interface, and each POJO type can be directly referenced.

Guess you like

Origin blog.csdn.net/qq_43780761/article/details/126771428