Java后端校验-使用hibernate-validator校验JavaBean
只进行前端校验及其不安全,规范的验证都是前后端都进行表单校验,下面介绍使用hibernate-validator进行后端校验。
1.添加相关依赖
<groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.1.Final</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.validation/validation-api --> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.0.0.GA</version> </dependency> <!-- https://mvnrepository.com/artifact/org.jboss.logging/jboss-logging --> <dependency> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging</artifactId> <version>3.1.0.CR2</version> </dependency>
2.定义公共验证类
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import org.hibernate.validator.HibernateValidator; /** * * @author Leave * */ public class ValidationUtils { /** * 使用hibernate的注解来进行验证 * */ private static Validator validator = Validation .byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator(); /** * * * Task: * @param obj * @return * date: 2018年7月5日 * @author pengLuo * */ public static <T> Map<String,Object> validate(T obj) { StringBuffer buffer = new StringBuffer(); //用于存储验证后的错误信息 Map<String,Object> map = new HashMap<String, Object>(); Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj); // 抛出检验异常 if (constraintViolations.size() > 0) { Iterator<ConstraintViolation<T>> iter = constraintViolations.iterator(); while (iter.hasNext()) { String message = iter.next().getMessage(); buffer.append(message); } map.put("isValid", false); map.put("msg", buffer.toString()); return map; } else { map.put("isValid", true); return map; } } }
3.在JavaBean中使用注解定义验证规则
@NotEmpty(message="姓名不能为空!") private String name; @Pattern(regexp = "\\d{3,4}-\\d{7,8}(-\\d{3,4})?", message = "电话号码格式错误") private String tel; @Pattern(regexp = "1[3|4|5|6|7|8|9]\\d{9}", message = "手机号码格式错误!") private String moble; @Pattern(regexp = "([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+", message = "邮箱格式错误!") private String email;
4.校验JavaBean,通过ValidationUtils的校验结果,可以详细的知道哪个字段验证失败,将结果返回给前端交互。
......//控制器或者服务中进行持久化之前校验
Map<String,Object> valMap = ValidationUtils.validate(addressBook); //封装返回参数,例如status,msg,code等 AliJson json = new AliJson(); if((Boolean)valMap.get("isValid")){ json = addressBookServices.saveAddressBook(addTxlUtils(request, addressBook)); }else{ json.getJsonFalse(json, valMap.get("msg").toString()); }
......
常用的注解大家可以自己百度,谢谢,本人很菜,不接受批评,哈哈哈。