1:在pom.xml添加依赖
<!--spring boot 版本 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 引用validation包 -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
</dependencies>
2: 在Dto类里面添加验证规则,验证规则根据不同需求添加
@Data
public class UserUpdatePasswordDto implements Serializable {
private String userId;
@NotNull(message = "旧密码不能为空")
private String oldPassword;
@NotNull(message = "新密码不能为空")
private String newPassword;
private String againPassword;
}
3:在Controller中配置入参,在方法前添加@Validated注解,使验证规则生效
@RequestMapping("/update")
public String updateUserPassword(@Validated UserUpdatePasswordDto dto){
return "success";
}
4:使用postman测试结果
5:为了统一异常处理,采用全局异常处理
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 实体类验证异常捕获
* @param e
* @return
*/
@ExceptionHandler(BindException.class)
public String handleBindException(BindException e){
List<ObjectError> errors = e.getAllErrors();
for (ObjectError error : errors){
System.out.println(error.getDefaultMessage());
}
return JSON.toJSONString(ReponseResult.error(e.getBindingResult().getFieldError().getDefaultMessage()));
}
/**
* 单个参数异常捕获
* @param e
* @return
*/
@ExceptionHandler(ConstraintViolationException.class)
public String handleConstraintViolationException(ConstraintViolationException e){
List<String> errorList = new ArrayList<>();
Set<ConstraintViolation<?>> errorSet = e.getConstraintViolations();
for (ConstraintViolation c : errorSet){
errorList.add(c.getMessage());
}
return JSON.toJSONString(ReponseResult.error(String.join(",",errorList)));
}
}
@Data
public class ReponseResult implements Serializable {
private Integer code;
private Boolean success;
private String message;
private Object data ;
public ReponseResult(Boolean success, String message) {
this.success = success;
this.message = message;
}
public static ReponseResult error(String message) {
ReponseResult reponseResult = new ReponseResult(false,message);
return reponseResult;
}
}
再次请求结果
6:单个参数请求
类上添加注解@Validated ,方法上添加验证规则
@RestController
@RequestMapping("/web")
@Validated
public class WebController {
@RequestMapping("/getPhone")
public String getUserPhone(@NotNull(message = "员工工号不能为空") String userId) {
return "success";
}
}