引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
待校驗實體類User
更多參數(shù)校驗注解百度,只做示例
@Setter
@Getter
@NoArgsConstructor
public class User {
// @Size 注解表示一個字符串的長度或者一個集合的大小,必須在某一個范圍中
@Size(min = 5, max = 10, message = "用戶名長度介于5-10個字符之間")
private String name;
// @NotEmpty 注解表示該字段不能為空
@NotEmpty(message = "用戶地址不為空")
private String address;
// @DecimalMin 注解表示對應屬性值的下限
@DecimalMin(value = "1", message = "年齡輸入最小為1歲")
// @DecimalMax 注解表示對應屬性值的上限
@DecimalMax(value = "200", message = "年齡輸入最大為200")
private Integer age;
// @Email 注解表示對應屬性格式是一個 Email
@Email(message = "郵箱格式輸入不正確")
// @NotNull 注解表示該字段不能為null
@NotNull(message = "郵箱不能為空")
private String email;
}
Controller
- 實體上添加@Valid注解
- 實體上添加@RequestBody注解(不添加這個報BindException異常而且校驗結果有問題,添加之后報正確異常MethodArgumentNotValidException)
@RestController
public class TestController {
@PostMapping("/user")
public String addUser(@Valid @RequestBody User user) {
return "success";
}
}
異常處理
可以自定義異常返回格式
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 參數(shù)校驗全局異常處理
* @param e
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String,Object> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
Map<String,Object> map=new HashMap<>();
List<String> errors=new ArrayList<>();
if (!e.getBindingResult().getAllErrors().isEmpty()){
//循環(huán)獲取異常信息
for (ObjectError error:e.getBindingResult().getAllErrors()){
errors.add(error.getDefaultMessage());
}
}
map.put("code","1");
map.put("msg",errors);
return map;
}
}
使用postman測試
輸入:

輸入
返回結果:400 Bad Request

返回結果
具體返回錯誤信息:

返回信息