今天受文章 http://www.jfinal.com/share/440 启发,尝试了一下,把经常用于spring项目的参数验证机制加入到jfinal项目中,运行正常。分享一下过程,直接上代码
public class ValidatorUtil { /** * 对象校验,默认group * @param t 待校验对象 */ public static <T> ValidateResult validatorObj(T t){ return validatorObj(t, Default.class); } /** * 对象校验 * @param t 待校验对象 * @param groups 组 * @return */ public static <T> ValidateResult validatorObj(T t, Class<?>...groups){ ValidateResult result = new ValidateResult(); Set<ConstraintViolation<T>> constraintViolations = Validation.buildDefaultValidatorFactory().getValidator().validate(t, groups); Iterator<ConstraintViolation<T>> iter = constraintViolations.iterator(); StringBuffer errorMsg = new StringBuffer(); String op = ""; while (iter.hasNext()) { result.setValid(false); String message = iter.next().getMessage(); errorMsg.append(op).append(message); op = ","; } result.setErrorInfo(errorMsg.toString()); return result; } } public class BaseController extends Controller { /** * 获取参数生成bean,并校验 * @param beanClass * @param <T> * @return * @throws */ public <T> T getValidatedBean(Class<T> beanClass) { T bean = super.getBean(beanClass,""); if(bean==null){ renderJson(new BaseResult(ErrorType.PARAM_ERROR,"参数不允许为空")); return null; } ValidateResult validateResult = ValidatorUtil.validatorObj(bean); if(!validateResult.isValid()){ renderJson(new BaseResult(ErrorType.PARAM_ERROR,validateResult.getErrorInfo())); return null; } return bean; } } public class UserRegisterParam { private String name; private String email; @NotNull(message = "请提供姓名") public String getName() { return name; } public void setName(String name) { this.name = name; } @Email(message = "请提供正确邮箱") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } public class UserController extends BaseController { public void reg(){ UserRegisterParam newUser = getValidatedBean(UserRegisterParam.class); if(newUser==null){ return;} } }
jdk1.7环境下引入jar包
<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.1.1.Final</version> </dependency>
针对restful api 测试结果
需要应用于render视图的可酌情修改