<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-validationartifactId>
dependency>
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;
}
所有验证的注解 及解释
序号 | 注解 | 解释 |
---|---|---|
1 | @NotNull |
验证对象不能为null。 |
2 | @NotBlank |
验证字符串不能为null、空字符串或只包含空格。 |
3 | @NotEmpty |
验证字符串、集合或数组不能为null且必须有元素。 |
4 | @Size |
验证字符串、集合或数组的大小必须在指定范围内。 |
5 | @Min |
验证数字必须大于等于指定的最小值。 |
6 | @Max |
验证数字必须小于等于指定的最大值。 |
7 | @DecimalMin |
验证数字必须大于等于指定的最小值,支持小数。 |
8 | @DecimalMax |
验证数字必须小于等于指定的最大值,支持小数。 |
9 | @Pattern |
验证字符串必须匹配指定的正则表达式。 |
10 | @Email |
验证字符串必须是一个有效的电子邮件地址。 |
11 | @Length |
验证字符串的长度必须在指定范围内。 |
12 | @Range |
验证数字必须在指定范围内。 |
13 | @Digits |
验证数字必须是指定位数的整数或小数。 |
14 | @Positive |
验证数字必须为正数。 |
15 | @Negative |
验证数字必须为负数。 |
16 | @Past |
验证日期必须在当前时间之前。 |
17 | @Future |
验证日期必须在当前时间之后。 |
通过@Validated
注解对传来的参数进行校验
@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);
}
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());
}
}
1.R工具类
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.对应的状态码枚举类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;
}
}