1.导入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency>
2.测试类
package com.jmj.gulimall.product.testC;import lombok.Data;import javax.validation.constraints.NotNull;@Data
public class Test {@NotNull(message = "id不能为空")private String id;@NotNull(message = "name不能为空")private String name;}
3.接口Controller
@GetMapping("/getTest")public Test getTest(@Validated Test test){return test;}
4.异常处理器
@ExceptionHandler(org.springframework.validation.BindException.class)public R handleValidException(org.springframework.validation.BindException e){System.out.println("进来了");BindingResult bindingResult = e.getBindingResult();List<FieldError> fieldErrors = bindingResult.getFieldErrors();HashMap<String, String> map = new HashMap<>();for (FieldError fieldError : fieldErrors) {String field = fieldError.getField();String defaultMessage = fieldError.getDefaultMessage();Object rejectedValue = fieldError.getRejectedValue();map.put(field,defaultMessage+":value="+rejectedValue);}return R.error(BizCodeEnum.RESOURCE_NOT_FOUND_EXCEPTION.getCode(),BizCodeEnum.RESOURCE_NOT_FOUND_EXCEPTION.getMsg()).put("data",map);}
5.访问 返回