赞
踩
@Data
public class User {
/**
* 用户名
*/
private String name;
}
@PostMapping("/user")
public Result addUser(@RequestBody User user) {
// 参数校验
if (StringUtils.isEmpty(user.getName())) {
throw new RuntimeException("用户姓名必须提交!");
}
return Result.buildSuccess(user);
}
@Data
public class User {
@NotBlank(message = "用户姓名必须提交!")
private String name;
}
@PostMapping("/user")
public Result addUser(@Valid @RequestBody User user) {
return Result.buildSuccess(user);
}
@PostMapping("/user")
public Result addUser(@Valid @RequestBody User user, BindingResult result) {
if (result.hasErrors()) {
Map<String, String> map = new HashMap<>();
result.getFieldErrors().forEach(item -> {
// 获取错误提示信息message
String message = item.getDefaultMessage();
// 获取发生错误的字段
String field = item.getField();
map.put(field, message);
System.out.println(field + ":" + message);
});
return Result.buildFailure(400, "参数错误", map);
}
return Result.buildSuccess(user);
}
public class MethodArgumentNotValidException extends Exception {
private final MethodParameter parameter;
private final BindingResult bindingResult;
public MethodArgumentNotValidException(MethodParameter parameter, BindingResult bindingResult) {
this.parameter = parameter;
this.bindingResult = bindingResult;
}
public MethodParameter getParameter() {
return this.parameter;
}
public BindingResult getBindingResult() {
return this.bindingResult;
}
}
@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result handValidationException(MethodArgumentNotValidException e) {
log.error(ErrorStatus.ILLEGAL_DATA.getMessage() + ":" + e.getMessage());
Map<String, Object> map = new HashMap<>();
// 获取异常输出信息
BindingResult bindingResult = e.getBindingResult();
bindingResult.getFieldErrors().forEach(fieldError -> {
String message = fieldError.getDefaultMessage();
String field = fieldError.getField();
map.put(field, message);
});
return Result.buildFailure(ErrorStatus.ILLEGAL_DATA.getCode(), String.valueOf(getFirstOrNull(map)), map);
}
private static Object getFirstOrNull(Map<String, Object> map) {
Object obj = null;
for (Map.Entry<String, Object> entry : map.entrySet()) {
obj = entry.getValue();
if (null != obj) {
break;
}
}
return obj;
}
}
@Data
public class Hair {
@NotBlank(message = "头发长度必须提交!")
private Double length;
@NotBlank(message = "头发颜色必须提交!")
private String color;
}
@Data
public class Person {
@NotBlank(message = "用户姓名必须提交!")
@Size(min=2, max=8)
private String userName;
// 添加@Valid注解实现嵌套检测
@Valid
@NotEmpty(message = "用户要有头发!")
private List<Hair> hairs;
}
@PostMapping("/person")
public Result addPerson(@Valid @RequestBody Person person) {
return Result.buildSuccess(person);
}
@Data
public class PersonGroup {
public interface AddGroup {}
public interface UpdateGroup {}
// @Validated注解value方法指定分组UpdateGroup.class时校验
@NotBlank(message = "用户ID必须提交!", groups = UpdateGroup.class)
private String id;
// @Validated注解value方法指定分组AddGroup.class或者分组UpdateGroup.class时校验
@NotBlank(message = "用户的姓名必须提交!", groups = {AddGroup.class, UpdateGroup.class})
private String name;
// @Validated注解value方法未指定分组时校验
@Range(min = 1, max = 200, message = "用户的年龄必须提交!")
private int age;
}
@RestController
@RequestMapping("/person")
public class PersonGroupController {
// 不指定分组时校验
@GetMapping("/person")
public Result getPerson(@Validated @RequestBody PersonGroup person) {
return Result.buildSuccess(person);
}
// 指定AddGroup分组校验
@PostMapping("/person")
public Result addPerson(@Validated(value = PersonGroup.AddGroup.class) @RequestBody PersonGroup person) {
return Result.buildSuccess(person);
}
// 指定UpdateGroup分组校验
@PutMapping("/person")
public Result updatePerson(@Validated(value = PersonGroup.updateGroup.class) @RequestBody PersonGroup person) {
return Result.buildSuccess(person);
}
}
@Data
public class UserGroupSequence {
public interface FirstGroup {}
public interface SecondGroup {}
// 使用GroupSequence定义分组校验顺序:按照FirstGroup,SecondGroup分组顺序进行校验
@GroupSequence({FirstGroup.class, SecondGroup.class})
public interface Group {}
@NotEmpty(message = "用户ID必须提交!", group = FirstGroup.class)
private String userId;
@NotEmpty(message = "用户姓名必须提交!", group = FirstGroup.class)
@Size(min = 2, max = 8, message = "用户姓名的长度在2~8之间", goup = Second.class)
private String userName;
}
@RestController
@RequestMapping("/user")
public class UserGroupSequenceController {
// 这里方法中@Validated注解value的值是Group.class
@PostMapping("/user")
public Result addGroup(@Validated(value = Group.class) @RequestBody UserGroupSequence user) {
return Result.buildSuccess(user);
}
}
@Validated
public class AnnotationController {
@GetMapping("/person")
public Result getAge(@Range(min = 2, max = 8, message = "年龄在3~8岁!") @RequestParam int age) {
return Result.buildSuccess(age);
}
}
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public Result resolveConstraintViolationException(ConstraintVilationException exception) {
Set<ConstraintVilation<?>> constraintVilations = exception.getConstraintVilations();
// 处理异常信息
if (!CollectionUtils.isEmpty(constraintVilations)) {
StringBuilder messageBuilder = new StringBuilder();
for (ConstraintVilation constraintViolation : constraintVilations) {
messageBuilder.append(constraintVilation.getMessage()).append(",");
}
String errorMessage = messageBuilder.toString();
if (errorMessage.length() > 1) {
errorMessage.substring(0, errorMessage.length() - 1);
}
return Result.builderFailure(ErrorStatus.ILLEGAL_DATA.getCode(), errorMessage);
}
return Result.builderFailure(ErrorStatus.ILLEGAL_DATA.getCode(), exception.getMessage())
}
// 请求路径中的id必须是数字,否则寻找不到这个路径404
@GetMapping("/user/{id:\\d+}")
public Result getId(@PathVariable(name="id") String userId) {
return Result.buildSuccess(userId);
}
@RestController
public class PathErrorController extends BasicErrorController {
@Autowired
public PathErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties, List<ErrorViewResolver> errorViewResolvers) {
super(errorAttributes, serverProperties.getError(), errorViewResolvers);
}
/**
* 处理html请求
*/
@Override
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
HttpStatus status = getStatus(request);
Map<String, Object> model = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML));
ModelAndView modelAndView = new ModelAndView("pathErrorPage", model, status);
return modelAndView;
}
/**
* 处理json请求
*/
@Override
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
Map<String, Object> responseBody = new HashMap<>(8);
responseBody.put("success", false);
responseBody.put("code", body.get("status"));
responseBody.put("message", body.get("error"));
return new ResponseEntity<>(responseBody, HttpStatus.OK);
}
}
@Documented
@Constraint(validateBy = {Show.ShowConstraintValidator.class})
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Rentation(RUNTIME)
public @interface Show {
String message() default "{com.oxford.annotation.Show.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int[] value();
class ShowConstraintValidator implements ConstraintValidator<Show, Integer> {
private Set<Integer> set = new HashSet<>();
/**
* 初始化操作
* 获取value属性指定的数字,保存到Set集合中
*/
@Override
public void initilize(Show constraintAnnotation) {
int[] value = constraintAnnotation.value();
for (int v : value) {
set.add(i);
}
}
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
return set.contains(value);
}
}
}
@Data
public class AnnotationQuery {
@Show(value = {0, 1}, message = "数值只能是0或者1")
private Integer isShow;
}
@PostMapping("/annotation")
public Result addAnnotation(@Validated @RequestBody AnnotationQuery annotation) {
return Result.buildSuccess(annotation);
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。