创建项目
创建spring-boot项目,这里我网络不好,就创建普通maven项目,通过依赖手动完成spring-boot项目创建。
添加注解
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.7.2</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<!-- 数据验证的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
常用注解说明
- @AssertFalse 校验false
- @AssertTrue 校验true
- @DecimalMax(value=,inclusive=) 小于等于value,inclusive=true,是小于等于
- @DecimalMin(value=,inclusive=) 与上类似
- @Max(value=) 小于等于value
- @Min(value=) 大于等于value
- @NotNull 检查Null
- @Past 检查日期
- @Pattern(regex=,flag=) 正则
- @Size(min=, max=) 字符串,集合,map限制大小
- @Validate 对po实体类进行校验
创建实体类
package com.hopeful.pojo;
import lombok.Data;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
@Data
public class User implements Serializable {
private Integer id;
@NotNull(message = "姓名不能为空")
private String name;
@NotNull
@Size(min = 6,message = "密码不能没空,且不能少于6位")
private String pwd;
}
创建controller
package com.hopeful;
import com.hopeful.pojo.User;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RequestMapping("/user")
@RestController
public class controller {
@RequestMapping("/hello")
public String hello() {
return "hello";
}
@PostMapping("/insertUser")
public String insert2(@Validated @RequestBody User user) {
System.out.println(user);
return "新增成功";
}
}
数据验证失败,会报错,需要处理
数据验证失败处理
方法一:controller处理
package com.hopeful;
import com.hopeful.pojo.User;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RequestMapping("/user")
@RestController
public class controller {
@RequestMapping("/hello")
public String hello() {
return "hello";
}
@GetMapping("/insertUser")
public User insert(@Validated User user) {
return user;
}
@PostMapping("/insertUser")
public String insert2(@Validated @RequestBody User user, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
String msg = "";
msg = getString(bindingResult, msg);
return msg;
}
System.out.println(user);
return "新增成功";
}
public static String getString(BindingResult bindingResult, String msg) {
List<FieldError> fieldErrors = bindingResult.getFieldErrors();
int size = fieldErrors.size();
for (int i = 0; i < size; i++) {
FieldError fieldError = fieldErrors.get(i);
if(fieldError != null) {
msg += fieldError.getDefaultMessage();
}
if(i < size - 1) {
msg += ";";
}
}
return msg;
}
}
方法二:全局异常处理
我们建议使用全局异常处理。
创建全局异常处理
package com.hopeful.pojo.common;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ControllerAdvice
@ResponseBody
public class globalException extends RuntimeException {
@ExceptionHandler(value = {BindException.class, ValidationException.class,MethodArgumentNotValidException.class})
public String MethodArgumentNotValidException(Exception e) {
String msg = "";
if (e instanceof MethodArgumentNotValidException) {
BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
// getFieldError获取的是第一个不合法的参数(P.S.如果有多个参数不合法的话)
//FieldError fieldError = bindingResult.getFieldError();
//if (fieldError != null) {
// msg = fieldError.getDefaultMessage();
//}
List<FieldError> fieldErrors = bindingResult.getFieldErrors();
int size = fieldErrors.size();
for (int i = 0; i < size; i++) {
FieldError fieldError = fieldErrors.get(i);
if(fieldError != null) {
msg += fieldError.getDefaultMessage();
}
if(i < size - 1) {
msg += ";";
}
}
} else if (e instanceof BindException) {
// getFieldError获取的是第一个不合法的参数(P.S.如果有多个参数不合法的话)
FieldError fieldError = ((BindException) e).getFieldError();
if (fieldError != null) {
msg = fieldError.getDefaultMessage();
}
} else if (e instanceof ConstraintViolationException) {
msg = e.getMessage();
if (msg != null) {
int lastIndex = msg.lastIndexOf(':');
if (lastIndex >= 0) {
msg = msg.substring(lastIndex + 1).trim();
}
}
/// ValidationException 的其它子类异常
} else {
msg = "处理参数时异常";
}
return msg;
}
}
##测试
结果如下:
到此这篇关于Springboot结合@validated优化代码验证的文章就介绍到这了,更多相关Springboot @validated内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!