SpringBoot2.x 参数校验
Posted RtxTitanV
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot2.x 参数校验相关的知识,希望对你有一定的参考价值。
本文主要对SpringBoot2.x参数校验进行简单总结,其中SpringBoot使用的2.4.5
版本。
一、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- lombok插件 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
二、实体类
User类:
package com.rtxtitanv.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.*;
/**
* @author rtxtitanv
* @version 1.0.0
* @name com.rtxtitanv.model.User
* @description 用户实体类
* @date 2021/8/15 16:28
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
@NotNull(message = "id不能为空")
private Long id;
@Length(min = 6, max = 20, message = "用户名长度不小于6,不超过20")
@NotNull(message = "用户名不能为空")
private String username;
@Pattern(regexp = "^[A-Z][A-Za-z0-9_]{5,19}$", message = "密码以大写英文字母开头,只包含英文字母、数字、下划线,长度在6到20之间")
@NotNull(message = "密码不能为空")
private String password;
@Max(value = 60, message = "年龄最大为60")
@Min(value = 18, message = "年龄最小为18")
@NotNull(message = "年龄不能为空")
private Integer age;
@Email(message = "邮箱格式不正确")
@NotEmpty(message = "邮箱不能为空")
private String email;
private String rank;
}
通用响应类:
package com.rtxtitanv.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.http.HttpStatus;
import java.io.Serializable;
/**
* @author rtxtitanv
* @version 1.0.0
* @name com.rtxtitanv.model.CommonResult
* @description 通用响应类
* @date 2021/8/15 17:35
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class CommonResult<T> implements Serializable {
private static final long serialVersionUID = 5231430760082814286L;
private int code;
private String message;
private T data;
public static <T> CommonResult<T> ok(String message, T data) {
return new CommonResult<T>(HttpStatus.OK.value(), message, data);
}
public static <T> CommonResult<T> fail(int code, String message, T data) {
return new CommonResult<>(code, message, data);
}
}
三、常用的校验注解
这里对一些用于参数校验的常用注解进行总结:
@Null
:必须为null。@NotNull
:必须不为null。@AssertTrue
:必须为true。@AssertFalse
:必须为false。@Min(value)
:必须是一个大于等于指定值的数字。@Max(value)
:必须是一个小于等于指定值的数字。@DecimalMin(value)
:必须是一个大于等于指定值的数字。@DecimalMax(value)
:必须是一个小于等于指定值的数字。@Size(min=,max=)
:大小必须在指定的范围内。@Digits(integer, fraction)
:必须是一个数字,其值必须在可接受的范围内。@Past
:必须是一个过去的日期。@Future
:必须是一个将来的日期。@Pattern(regex=)
:必须符合指定的正则表达式。@Email
:必须是一个有效的email地址。@Length(min=,max=)
:字符串长度是否在指定范围内。@NotBlank
:必须非空且长度大于0。@NotEmpty
:必须不为null或空。@URL(protocol=,host,port)
:必须是一个有效的URL,如果提供了protocol,host等,则还需满足提供的条件。
四、校验Controller中的参数
1.校验请求体
创建UserController
,在需要校验的参数上添加@Valid
注解:
package com.rtxtitanv.controller;
import com.rtxtitanv.model.CommonResult;
import com.rtxtitanv.model.User;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
/**
* @author rtxtitanv
* @version 1.0.0
* @name com.rtxtitanv.controller.UserController
* @description UserController
* @date 2021/8/15 16:33
*/
@RequestMapping("/user")
@RestController
public class UserController {
@PostMapping("/save")
public CommonResult<User> saveUser(@RequestBody @Valid User user) {
return CommonResult.ok("保存用户成功", user);
}
}
启动项目,发送如下POST请求,请求地址为http://localhost:8080/user/save
:
如果验证失败会抛出MethodArgumentNotValidException
,默认情况下,Spring会将MethodArgumentNotValidException
异常转换为HTTP Status 400。查看控制台打印的日志发现抛出了MethodArgumentNotValidException
:
创建全局异常处理类捕获异常并进行处理:
package com.rtxtitanv.handler;
import com.rtxtitanv.model.CommonResult;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;
/**
* @author rtxtitanv
* @version 1.0.0
* @name com.rtxtitanv.handler.GlobalExceptionHandler
* @description 全局异常处理类
* @date 2021/8/15 16:36
*/
@RestControllerAdvice(annotations = {Controller.class, RestController.class})
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
public CommonResult<Map<String, String>> validateException(MethodArgumentNotValidException e) {
Map<String, String> errors = new HashMap<>(16);
e.getBindingResult().getAllErrors()
.forEach(error -> errors.put(((FieldError)error).getField(), error.getDefaultMessage()));
return CommonResult.fail(HttpStatus.BAD_REQUEST.value(), "无效的参数", errors);
}
}
重启项目后再次发送如下POST请求:
2.校验请求参数
UserController
上添加Validated
注解并新增以下方法:
@GetMapping("/get/{id}")
public CommonResult<User>
getUserById(@Valid @PathVariable(value = "id") @Min(value = 1, message = "id不能小于1") Long id) {
User user = new User(id, "ZhaoYun", "A123456sd", 20, "zhaoyun123@xxx.com", "黄金");
return CommonResult.ok("根据id查询用户成功", user);
}
@DeleteMapping("/delete")
public CommonResult<User> deleteByUsername(
@Valid @RequestParam(value = "username") @Size(min = 6, max = 20, message = "用户名长度不在指定范围内") String username) {
User user = new User(1L, username, "A123456sd", 20, "zhaoyun123@xxx.com", "黄金");
return CommonResult.ok("根据用户名删除用户成功", user);
}
全局异常处理类中新增以下方法:
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
public CommonResult<Map<String, String>> handleConstraintViolationException(ConstraintViolationException e) {
Map<String, String> errors = new HashMap<>(16);
e.getConstraintViolations().forEach(constraintViolation -> errors
.put(constraintViolation.getPropertyPath().toString(), constraintViolation.getMessage()));
return CommonResult.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), "无效的参数", errors);
}
发送如下GET请求,请求地址为http://localhost:8080/user/get/0
:
发送如下DELETE请求,请求地址为http://localhost:8080/user/delete?username=ZhaoZiLong_1896582826
:
五、校验Service中的参数
通过@Validated
和@Valid
注解组合使用不仅可以校验Controller中的参数,还可以校验任何Spring组件中的参数。
UserService
:
package com.rtxtitanv.service;
import com.rtxtitanv.model.CommonResult;
import com.rtxtitanv.model.User;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
/**
* @author rtxtitanv
* @version 1.0.0
* @name com.rtxtitanv.service.UserService
* @description UserService
* @date 2021/8/15 16:46
*/
@Validated
public interface UserService {
/**
* 更新用户
*
* @param user 用户参数
* @return CommonResult<User>
*/
CommonResult<User> updateUser(@Valid User user);
}
UserService
实现类:
package com.rtxtitanv.service.impl;
import com.rtxtitanv.model.CommonResult;
import com.rtxtitanv.model.User;
import com.rtxtitanv.service.UserService;
import org.springframework.stereotype.Service;
/**
* @author rtxtitanv
* @version 1.0.0
* @name com.rtxtitanv.service.impl.UserServiceImpl
* @description UserService实现类
* @date 2021/8/15 16:46
*/
@Service
public class UserServiceImpl implements UserService {
@Override
public CommonResult<User> updateUser(User user) {
return CommonResult.ok("更新用户成功", user);
}
}
UserController
中新增以下代码:
@Resource
private UserService userService;
@PutMapping("/update")
public CommonResult<User> updateUser(@RequestBody User user) {
return userService.updateUser(user);
}
发送如下PUT请求,请求地址为http://localhost:8080/user/update
:
六、编程式校验
通过Validator
实例可以手动进行参数校验。UserController
中新增以下代码:
@Resource
private Validator validator;
@PostMapping("/insert")
public CommonResult<User> insertUser(@RequestBody User user) {
if (!validator.validate(user).isEmpty()) {
throw new ConstraintViolationException(validator.validate(user));
}
return CommonResult.ok("添加用户成功", user);
}
发送如下POST请求,请求地址为http://localhost:8080/user/insert
:
七、自定义校验注解
如果自带的校验注解无法满足需求,还可以自定义校验注解。首先创建如下注解用于密码校验:
package com.rtxtitanv.annotation;
import com.rtxtitanv.validator.PasswordValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
/**
* @author rtxtitanv
* @version 1.0.0
* @name com.rtxtitanv.annotation.Password
* @description 自定义密码校验注解
* @date 2021/8/16 14:54
*/
@Documented
@Constraint(validatedBy = PasswordValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Password {
String message() default "无效密码";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
然后创建ConstraintValidator
接口的实现类并重写isValid
方法:
package com.rtxtitanv.validator;
import com.rtxtitanv.annotation.Password;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* @author rtxtitanv
* @version 1.0.0
* @name com.rtxtitanv.validator.PasswordValidator
* @description PasswordValidator
* @date 2021/8/16 15:01
*/
public class PasswordValidator implements ConstraintValidator<Password, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
// 密码必须以大写英文字母开头,只包含英文字母、数字、下划线,长度在6到20之间
return value.matches("^[A-Z][A-Za-z0-9_]{5,19}$");
}
}
创建如下注解用于密码校验:
package com.rtxtitanv.annotation;
import com.rtxtitanv.validator.RankValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
/**
* @author rtxtitanv
* @version 1.0.0
* @name com.rtxtitanv.annotation.Rank
* @description 自定义用户段位校验注解
* @date 2021/8/16 15:12
*/
@Documented
@Constraint(validatedBy = RankValidator.class)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface Rank {
String message() default "rank值无效";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
创建ConstraintValidator
接口的实现类并重写isValid
方法,:
package com<以上是关于SpringBoot2.x 参数校验的主要内容,如果未能解决你的问题,请参考以下文章