javaweb 服务端需要对请求数据进行校验,不过编写校验代码繁琐费时重复劳动。发现可以使用Bean Validation框架进行数据校验,在此整理了一个快速使用教程。
pom文件添加:
<dependency> <artifactId>hibernate-validator</artifactId> <groupId>org.hibernate</groupId> <version>6.0.16.Final</version> </dependency>javaBean代码:
public class User { private Integer userId; @NotEmpty(message = "用户名称不能为空") @Size(min=4,max = 16,message = "用户名称长度在4-16字符之间") private String userName; @NotNull(message = "城市不能为空") private Integer cityId; @NotEmpty(message = "手机号不能为空") @Pattern(regexp = "\\d{8,14}",message = "手机号格式不对") private String phone; //get and set }多层对象校验, 在成员变量使用注解@Valid
public class UserInfo{ @Valid private User user; //get set }校验:
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); Validator validator = validatorFactory.getValidator(); //装载校验对象并进行校验 Set<ConstraintViolation<T>> resultSet = validator.validate(user); for (ConstraintViolation<T> violation : resultSet) { logger.error(violation.getMessage()); }spring mvc整合使用校验
@PostMapping("userAdd") public String userAdd(@Valid User user,@Valid UserInfo userInfo,BindingResult result) throws Exception { //校验结果封装在 BindingResult对象里 if (result != null && result.hasErrors()) { return result.getAllErrors().stream().findFirst().get().getDefaultMessage(); } //........ return "ok"; }
有时候新增和修改需要校验不同的字段,需要使用分组校验功能。并且在使用中需要进行自定义的顺序校验
定义分组接口和顺序:
@GroupSequence({ValidateGroups.A.class, ValidateGroups.B.class, ValidateGroups.C.class, ValidateGroups.D.class, ValidateGroups.E.class}) public interface ValidateGroups { public interface A{ } public interface B{ } public interface C{ } public interface D{ } public interface E{ } }javaBean 代码改造:
public class User { private Integer userId; @NotEmpty(message = "用户名称不能为空",groups = ValidateGroups.A.class) @Size(min=4,max = 16,message = "用户名称长度在4-16字符之间",groups = ValidateGroups.A.class) private String userName; @NotNull(message = "城市不能为空",groups = ValidateGroups.C.class) private Integer cityId; @NotEmpty(message = "手机号不能为空",groups = ValidateGroups.D.class) @Pattern(regexp = "\\d{8,14}",message = "手机号格式不对",groups = ValidateGroups.D.class) private String phone; //get and set }spring mvc controller 改成用@Validated注解进行校验,并指定分组名称
@PostMapping("userAdd") public String userAdd(@Validated({ValidateGroups.class}) User user, BindingResult result) throws Exception { if (result != null && result.hasErrors()) { return result.getAllErrors().stream().findFirst().get().getDefaultMessage(); } //........ return "ok"; }