java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java 校验注解

Java中的三种校验注解的使用(@Valid,@Validated和@PathVariable)

作者:攻城狮Chova

本文主要介绍了Java中的三种校验注解的使用(@Valid,@Validated和@PathVariable),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

@Valid和@Validated

@Valid和@Validated比较

@Valid高级使用

@Valid级联校验

@Validated高级使用

@Validated分组校验

@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);
	}
}

@Validated分组校验顺序

@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非实体类校验

@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())
}

@PathVariable

正则表达式校验

// 请求路径中的id必须是数字,否则寻找不到这个路径404
@GetMapping("/user/{id:\\d+}")
public Result getId(@PathVariable(name="id") String userId) {
	return Result.buildSuccess(userId);
}

继承BasicErrorController类

@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);
}

到此这篇关于Java中的三种校验注解的使用(@Valid,@Validated和@PathVariable)的文章就介绍到这了,更多相关Java 校验注解内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文