Through the spring-boot validation dependency, complete the parameter verification of the entity class

effect

This dependency is the Starter dependency used to enable the Validation functionality in Spring Boot applications.

The effect is as follows:

  1. Enable Validation: This dependency provides you with validation in Spring Boot. It contains the classes and configuration needed for authentication to perform authentication operations in the application.

  2. Support for JSR 303 validation specification: This dependency is based on the JSR 303 validation specification standardized by Java, and provides support for the Bean Validation (Bean Validation) function. You can use annotations (for example @NotNull, @Size, @Patternetc.) to verify the properties of the Java Bean to ensure the validity of the data.

  3. Integrated validator: This dependency also integrates commonly used validators (Validator), such as Hibernate Validator, to perform validation operations and detect validation failures.

By adding this dependency, you can easily use validation functions in Spring Boot applications, and use annotations for data validation in scenarios such as request parameter validation and form validation.

How to use

1. Introduce import dependencies through maven


  <!--  参数校验-->
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
  </dependency>

2. Add verification conditions to parameters by means of annotations

package com.wwk.usercenter.model.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotBlank;

/**
 *
 * @TableName user
 */
@TableName(value ="user")
@Data
public class User implements Serializable {
    
    
    /**
     * id
     */
    @TableId(type = IdType.AUTO)
    private Long id;

    /**
     * 昵称
     */
    private String nickname;

    /**
     * 用户名
     */
    @NotBlank(message = "用户名不能为空")
    @Length(min = 4,message = "用户名至少4位")
    private String username;

    /**
     * 密码
     */
    @NotBlank(message = "密码不能为空")
    @Length(min = 8,message = "密码至少8位")
    private String userPassword;


    /**
     * 确认密码(非数据库字段)
     */
    @TableField(exist = false)
    @NotBlank(message = "确认密码不能为空")
    @Length(min = 8,message = "确认密码至少8位")
    private String checkPassword;

    /**
     * 头像
     */
    private String avatarUrl;

    /**
     * 性别 0未知 1男 2女
     */
    private Integer gender;

    /**
     * 电话
     */
    private String phone;

    /**
     * 邮箱
     */
    @Email(message = "邮箱格式不正确")
    private String email;

    /**
     * 状态 0:正常 1:异常
     */
    private Integer userStatus;

    /**
     * 创建时间
     */
    private Date createTime;

    /**
     * 更新时间
     */
    private Date updateTime;

    /**
     * 是否删除
     */
    private Integer isDelete;

Notes and explanations for all validations

serial number annotation explain
1 @NotNull Validation object cannot be null.
2 @NotBlank The validation string cannot be null, an empty string, or contain only spaces.
3 @NotEmpty Validates that a string, collection or array cannot be null and must have elements.
4 @Size Validates that the size of a string, collection, or array must be within the specified range.
5 @Min The verification number must be greater than or equal to the specified minimum.
6 @Max The validation number must be less than or equal to the specified maximum value.
7 @DecimalMin The verification number must be greater than or equal to the specified minimum value, decimals are supported.
8 @DecimalMax The verification number must be less than or equal to the specified maximum value, decimals are supported.
9 @Pattern The validation string must match the specified regular expression.
10 @Email The verification string must be a valid email address.
11 @Length The length of the verification string must be within the specified range.
12 @Range The verification number must be within the specified range.
13 @Digits The verification number must be an integer or decimal with the specified number of digits.
14 @Positive Validation number must be positive.
15 @Negative Validation number must be negative.
16 @Past The verification date must be before the current time.
17 @Future Verification date must be after the current time.

3. Verify through the parameters received by the controller

import com.wwk.usercenter.model.entity.User;
import com.wwk.usercenter.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    
    

    @RequestMapping("/register")
    public R register(@RequestBody @Validated User user, BindingResult bindingResult) {
    
    
        Map<String, Object> map = new HashMap<>();

        // 检查绑定结果中是否存在字段错误
        if (bindingResult.getFieldErrors().size() > 0) {
    
    
            // 遍历每个字段错误,并将字段名和错误消息存储在map中
            bindingResult.getFieldErrors().forEach(fieldError -> {
    
    
                String field = fieldError.getField();
                String message = fieldError.getDefaultMessage();
                map.put(field, message);
            });

            // 记录错误消息
            map.forEach((field, message) -> {
    
    
                log.error("错误信息---->{}:{}", field, message);
            });

            // 收集错误消息并返回带有错误状态和消息的响应
            List<Object> errMessages = map.keySet().stream().map(key -> map.get(key)).collect(Collectors.toList());
            return R.error(444, "用户信息校验异常", errMessages);
        }

        // 没有字段错误,继续注册流程...
        System.out.println(user);
        return R.success("用户注册成功");
    }
};

4. Tool classes and enumeration classes that need to be used

1. R tool class


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class R<T> implements Serializable {
    
    
    private Integer code;
    private String msg;
    private Object data;

    public static R success(Object data){
    
    
        return new R(1,"OK", data);
    }

    public static R success(Status status,Object data){
    
    
        return new R(status.getCode(), status.getMessage(), data);
    }


    public static R success(){
    
    
        return new R(1,"OK",null);
    }


    //失败各有不同
    public static R error(Status status) {
    
    
        return new R(status.getCode(), status.getMessage(), null);
    }

    public static R error(String msg) {
    
    
        return new R(0,msg,null);
    }

    public static R error(Status status, Object obj) {
    
    
        return new R(status.getCode(), status.getMessage(), obj);
    }


    public static R error(Integer code, String msg, Object obj) {
    
    
        return  new R(code,msg,obj);
    }
}

2. The corresponding status code enumeration class Status


public enum Status {
    
    
    LOGIN_SUCCESS(1,"登录成功"),
    SUCCESS(1,"成功"),
    ERROR(0,"失败"),

    NOT_FIND_PATH(0,"没有找到路径"),

    STATUS_ERROR(0,"请先把状态改为停售再操作"),

    NOT_EXIST(0,"用户不存在"),

    PASS_ERROR(0,"密码错误"),
    ADMIN_DISABLE(0,"用户已禁用"),
    NOT_FIND_DATA(0,"没有找到该用户对应的数据")
    ;

    private Integer code;
    private String message;

    Status(Integer code, String message) {
    
    
        this.code = code;
        this.message = message;
    }

    public Integer getCode() {
    
    
        return code;
    }

    public String getMessage() {
    
    
        return message;
    }
}

Guess you like

Origin blog.csdn.net/m0_59757074/article/details/130876691