项目参考:详细参见:《Spring Boot 2精髓:从构建小系统到架构分布式大系统》 第三章 3.5.3节 自定义校验
项目结构
WorkTime
package com.archibladwitwicke.springboot2.chapter03.validated;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Constraint(validatedBy = { WorkTimeValidated.class })
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD})
public @interface WorkTime {
String message() default "工作时间不能超过8小时!";
int max() default 8;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
WorkTimeValidated
package com.archibladwitwicke.springboot2.chapter03.validated;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class WorkTimeValidated implements ConstraintValidator<WorkTime, Integer> {
private int max;
@Override
public void initialize(WorkTime work) {
max = work.max();
}
@Override
public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
Boolean flag = false;
if (value == null || value < max) {
flag = true;
}
return flag;
}
}
UserValidated
package com.archibladwitwicke.springboot2.chapter03.pojo;
import com.archibladwitwicke.springboot2.chapter03.validated.WorkTime;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
public class UserValidated {
public interface Add {
}
public interface Update {
}
@NotNull(groups = Update.class)
@Null(groups = Add.class)
private Long id;
@NotNull(message = "名字不能为空!")
private String name;
@NotNull(message = "年龄不能为空!")
@Max(value = 100, message = "年龄不能大于100岁!")
private String age;
@NotNull
@WorkTime(max = 5, message = "工作时间不能超过5小时!")
private Integer worktime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Integer getWorktime() {
return worktime;
}
public void setWorktime(Integer worktime) {
this.worktime = worktime;
}
}
ValidateController
package com.archibladwitwicke.springboot2.chapter03.controller;
import com.archibladwitwicke.springboot2.chapter03.pojo.UserValidated;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/validated")
public class ValidatedController {
@RequestMapping("/validateuser")
@ResponseBody
public String validateUser(@Validated UserValidated userValidated, BindingResult bindingResult) {
String result = null;
if (bindingResult.getErrorCount() == 0) {
result = "通过验证!";
}
List<ObjectError> allErrors = bindingResult.getAllErrors();
for (ObjectError error : allErrors) {
String defaultMessage = error.getDefaultMessage();
System.out.println(defaultMessage);
}
return result;
}
@RequestMapping("/validateusergroup")
@ResponseBody
public String validateUserByGroup(@Validated UserValidated userValidated, BindingResult bindingResult) {
String result = null;
if (bindingResult.getErrorCount() == 0) {
result = "通过验证!";
}
List<ObjectError> allErrors = bindingResult.getAllErrors();
for (ObjectError error : allErrors) {
String defaultMessage = error.getDefaultMessage();
System.out.println(defaultMessage);
}
return result;
}
}