Python 官方文档:入门教程 => 点击学习
目录@Valid和@Validated@Valid和@Validated比较@Valid高级使用@Valid级联校验@Validated高级使用@Validated分组校验@Vali
@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);
}
@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;
}
@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<>();
@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);
}
到此这篇关于Java中的三种校验注解的使用(@Valid,@Validated和@PathVariable)的文章就介绍到这了,更多相关Java 校验注解内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Java中的三种校验注解的使用(@Valid,@Validated和@PathVariable)
本文链接: https://lsjlt.com/news/147509.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0