1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2.定义需要校验的对象
@Validated
public class TbDto implements Serializable {
@Min(message = "人数不得小于0", value = 0)
private int 人数;
@NotEmpty(message = "用户名不能为空")
@Size(message = "用户名长度 [1-3] ", min = 1, max = 3,groups = ValidateGroup.FirstGroup.class)
private String username;
@Min(message = "id不得小于0", value = 0)
private Integer id;
}
3.Controller中添加@Validated
@PostMapping("save")
public R<String> save(@RequestBody @Validated TbDto tbDto) {
......
}
@PostMapping("test3")
public User test3(@RequestBody @Validated({ FirstGroup.class }) User u) {
System.out.println(u);
return u;
}
4.常用注解
5.定义分组
用于分组校验。
使用场景,对同一个对象例如User(username , id) 在不同的接口时 需要的校验规则不同。
例如,访问一个接口需要 username 不为null且长度大于0 ,id>=0 ; 访问另一个接口 需要 username 参数的长度 在 [1,3]之间。
public class ValidateGroup {
public interface FirstGroup {
}
public interface SecondeGroup {
}
public interface ThirdGroup {
}
}
6.定义全局异常处理类
package com.itheima.reggie.common;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
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 java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;
/**
* 全局异常处理
*/
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
/**
* 异常处理方法
* @return
*/
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
log.error(ex.getMessage());
if(ex.getMessage().contains("Duplicate entry")){
String[] split = ex.getMessage().split(" ");
String msg = split[2] + "已存在";
return R.error(msg);
}
return R.error("未知错误");
}
/**
* 异常处理方法
* @return
*/
@ExceptionHandler(CustomException.class)
public R<String> exceptionHandler(CustomException ex){
log.error(ex.getMessage());
return R.error(ex.getMessage());
}
@ExceptionHandler(value = BindException.class)
public JsonResult exceptionHandle(BindException exception) {
BindingResult result = exception.getBindingResult();
StringBuilder errorMsg = new StringBuilder();
List<FieldError> fieldErrors = result.getFieldErrors();
fieldErrors.forEach(error -> {
log.error("field: " + error.getField() + ", msg:" + error.getDefaultMessage());
errorMsg.append(error.getDefaultMessage()).append("!");
});
return JsonResult.fail(errorMsg.toString());
}
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public JsonResult MyExceptionHandle(MethodArgumentNotValidException exception) {
BindingResult result = exception.getBindingResult();
StringBuilder errorMsg = new StringBuilder();
List<FieldError> fieldErrors = result.getFieldErrors();
fieldErrors.forEach(error -> {
log.error("field: " + error.getField() + ", msg:" + error.getDefaultMessage());
errorMsg.append(error.getDefaultMessage()).append("!");
});
return JsonResult.fail(errorMsg.toString());
}
}
7.定义json结果返回集
package com.itheima.reggie.common;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
/**
*@author wang
*@Date 2020-9-14
*
**/
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class JsonResult<T> {
/** 成功 */
public static final int SUCCESS=200;
/**内部服务器错误**/
public static final int FAIL=500;
/** 没有登录 */
public static final int NOT_LOGIN = 400;
/** 发生异常 */
public static final int EXCEPTION = 401;
/** 系统错误 */
public static final int SYS_ERROR = 402;
/** 参数错误 */
public static final int PARAMS_ERROR = 403;
/** 不支持或已经废弃 */
public static final int NOT_SUPPORTED = 410;
/** AuthCode错误 */
public static final int INVALID_AUTHCODE = 444;
/** 太频繁的调用 */
public static final int TOO_FREQUENT = 445;
/** 未知的错误 */
public static final int UNKNOWN_ERROR = 499;
private Integer code;
private String msg;
private T data;
public static JsonResult fail() {
return new JsonResult(FAIL, "请求处理失败",null);
}
public static JsonResult fail(String msg) {
return new JsonResult(FAIL, msg,null);
}
public static JsonResult fail(Integer code,String msg) {
return new JsonResult(code, msg,null);
}
public static JsonResult success() {
return new JsonResult(SUCCESS,"请求处理成功",null);
}
public static JsonResult success(String msg) {
return new JsonResult(SUCCESS,msg,null);
}
public static <T> JsonResult success(T data) {
return new JsonResult<T> (SUCCESS,"请求处理成功",data);
}
public static <T> JsonResult success(String msg,T data) {
return new JsonResult<T>(SUCCESS, msg,data);
}
public static JsonResult err() {
return build(EXCEPTION);
}
public static JsonResult err(String msg) {
return build(EXCEPTION, msg);
}
public JsonResult<T> code(int code) {
this.code = code;
return this;
}
public JsonResult<T> msg(String msg) {
this.msg = msg;
return this;
}
public JsonResult<T> data(T data) {
this.data = data;
return this;
}
public static JsonResult build() {
return new JsonResult();
}
public static JsonResult build(int code) {
return new JsonResult().code(code);
}
public static JsonResult build(int code, String msg) {
return new JsonResult<String>().code(code).msg(msg);
}
public static <T> JsonResult<T> build(int code, T data) {
return new JsonResult<T>().code(code).data(data);
}
public static <T> JsonResult<T> build(int code, String msg, T data) {
return new JsonResult<T>().code(code).msg(msg).data(data);
}
}