spring boot 使用hibernate validator 验证service
不在controller中验证,而是在service中验证。
spring boot 默认使用的就是hibernate validator,存在于pom的spring-boot-starter-web中。
1、Validators
import java.util.List; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.StrUtil; /** * 通用验证方法 */ @Service public class Validators { @Autowired private Validator validator; public <T> String valid(T obj) { return this.valid(obj,null); } public <T> String valid(T obj,Class group) { Set<ConstraintViolation<T>> violations = null; if (group == null) { violations = validator.validate(obj); } else { violations = validator.validate(obj,group); } if (!violations.isEmpty()) { StringBuilder sb = new StringBuilder(); for (ConstraintViolation<T> constraintViolation : violations) { sb.append("[").append(constraintViolation.getPropertyPath().toString()).append("="); sb.append(constraintViolation.getInvalidValue()); sb.append(","); sb.append(constraintViolation.getMessage()); sb.append("]"); } return sb.toString(); } else { return null; } } public <T> String validList(List<T> objList) { return validList(objList,null); } public <T> String validList(List<T> objList,Class group) { if (CollUtil.isEmpty(objList) || objList.size()<=0) { return "对象空"; } StringBuilder sb = new StringBuilder(); String result = ""; for (int i = 0; i < objList.size(); i++) { if (group == null) { result = this.valid(objList.get(i)); } else { result = this.valid(objList.get(i),group); } if (!StrUtil.isBlank(result)) { sb.append(result); } } if (!StrUtil.isBlankIfStr(sb)) { return sb.toString(); } else { return null; } } }
2、entity注解
public class PrjDto extends BaseDtoAndApi { @JSONField(name = "name", ordinal = 11) @NotBlank(groups = PrjAddInfoReqChecker.class) private String name; @JSONField(name = "mem_list", ordinal = 24) @NotEmpty List<PrjMemberDto> memList; }
3、PrjAddInfoReqChecker
public interface PrjAddInfoReqChecker { }
4、service
@Autowired private Validators validators; @Transactional(readOnly=false) public ReMsg addPrj(PrjAddInfoReq prjAddInfoReq) { log.info("接收:{}",JSONObject.toJSONString(prjAddInfoReq,true)); ReMsg reMsg = null; Integer rs = null; String validResult = validators.valid(prjAddInfoReq,PrjAddInfoReqChecker.class); if (!StrUtil.isBlankIfStr(validResult)) { reMsg = new ReMsg("999",validResult); return reMsg; }
//验证集合中的对象 String validListResult1 = validators.validList(prjAddInfoReq.getMemList(),PrjAddInfoReqChecker.class); if (!StrUtil.isBlankIfStr(validListResult1)) { reMsg = new ReMsg("999",validResult); return reMsg; } ...... }