Verify parameters and encapsulate global exception handling classes through spring-boot validation

Verify parameters and encapsulate global exception handling classes through spring-boot validation

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

import lombok.Data;
import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotBlank;
import java.io.Serializable;

/**
 *Author  wwk
 * Date  2023/6/29 22:55
 */

@Data
public class LoginRequest implements Serializable {
    
    
    private static final long serialVersionUID = 4001157484090646820L;

    @NotBlank(message = "用户名不能为空")
    @Length(min = 5,max = 15,message = "账号长度在5-15位之间")
    private String username;
    @NotBlank(message = "密码不能为空")
    @Length(min = 6,max = 15,message = "密码长度在6-15位之间")
    private String  password;
}

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

@ValidatedVerify the passed parameters through annotations

  @PostMapping("/login")
    public R doLogin(@RequestBody @Validated LoginRequest loginRequest) {
    
    
        if (StringUtils.isAnyBlank(loginRequest.getUsername(), loginRequest.getPassword())) {
    
    
            return R.error(Status.REGISTER_ERROR.getCode(),
                    Status.REGISTER_ERROR.getMessage(), null, "用户名或密码不能为空");
        }
        TokenResponse tokenResponse = memberService.doLogin(loginRequest);

        return R.success(tokenResponse);
    }

4. Encapsulate the global exception handling class

import com.wwk.zhenxuan.common.R;
import com.wwk.zhenxuan.common.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常类
 * @author wwk
 */
@RestControllerAdvice
@Slf4j
public class GlobalException {
    
    
    /**
     * 捕获管理用户抛出的异常
     *
     * @param e 错误信息
     * @return 响应类
     */
    @ExceptionHandler(IntegerRangeException.class)
    public R integerRangeException(IntegerRangeException e) {
    
    
        log.warn("{},状态码:{}---错误描述:{}", e.getMessage(), e.getCode(), e.getDetails());
        return R.error(e.getCode(), e.getMessage(), null, e.getDetails());
    }

    /**
     * 捕获用户验证抛出的异常
     */

    @ExceptionHandler(BindException.class)
    public R bindException(BindException bindException) {
    
    
        List<ObjectError> allErrors = bindException.getAllErrors();

        for (ObjectError allError : allErrors) {
    
    
            log.warn("参数校验错误信息,错误信息:{}", allError.getDefaultMessage());
        }
        return R.error(Status.PARAMS_VALIDATED_ERROR.getCode(), Status.PARAMS_VALIDATED_ERROR.getMessage(),
                null, allErrors.get(0).getDefaultMessage());
    }
}

5. Tool classes and enumeration classes that need to be used (modify according to requirements)

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/131471121