对实体类字段的校验

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping(value = "/kafka")
public class KafkaController {

   //import javax.validation.Validator;
    @Autowired
    private Validator validator;

    @RequestMapping(value = "/msg")
    public Map<String,String> ty(){
        KafkaMsg kafka = new KafkaMsg();
        kafka.setUuid(null);
        kafka.setUsername("jksjasiisijwijddiwjdiwjdijwi");
        kafka.setSexhj("100000");
        Set<ConstraintViolation<KafkaMsg>> validate = validator.validate(kafka);
        Map<String, String> errors = getErrors(validate);
        return errors;
    }

    private<T>Map<String,String> getErrors(Set<ConstraintViolation<KafkaMsg>> set){
       Map<String,String> map = new HashMap<>();
       for (ConstraintViolation<?> item : set){
         map.put(item.getPropertyPath().toString(),item.getMessage());
       }
       return map;
    }
}
import lombok.Data;
import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotBlank;
import java.io.Serializable;

@Data
public class KafkaMsg implements Serializable {

    @NotBlank
    @Length(max = 5,message = "长度不能超过:{max}")
    private String uuid;


    @Length(max = 5,message = "长度不能超过:{max}")
    private String username;

    @Length(max = 2,message = "长度不能超过:{max}")
    private String sexhj;

  //删除时间  yyyy-MM-dd HH:mm:ss 时间
    @Pattern(regexp = "^((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29))\\s+([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$",message = "时间的数据格式不正确")
    private String delDate;

}

delDate 这个存储的时候可以为null,也不会出问题

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页