spring validation的灵活使用

论坛 期权论坛 脚本     
匿名技术用户   2021-1-2 17:33   15   0

首先看下这位网友的文章。

http://haohaoxuexi.iteye.com/blog/1812584

如上所述,spring支持的校验框架,一种是自己实现org.springframework.validation.Validator接口,一种是JSR303标准并采用hibernate的实现。相比之下,前者需要为每个被校验对象进行实现,而后者基于注解,虽然学习曲线稍多一些,但熟练后效率高得多。

两者都是通过controller方法声明中的@Valid注解表明该对象需要校验,并用紧随其后的BindingResult对象获取校验结果。

有时候,我可能需要在controller之外的地方进行校验,同时想利用JSR303的注解规则。

首先先注册相应的validator实现

<bean id="validator"
  class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
</bean>

然后定义messageSource.这在使用JSR303注解时可以更灵活地指定报错message,同时支持国际化

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
              <property name="basenames">
                     <list>
                            <value>conf.properties.msg.messages</value>
                     </list>
              </property>
 </bean>

然后定义一个工具类,工具类的作用是手动调用validator,并完成message code到具体message的转化。下述代码中根据校验结果的code,通过messageSource进行了动态的获取。API的详细说明可参考http://blog.csdn.net/qyf_5445/article/details/8124306

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

@Component
public class ModelValidator {
@Resource
private  Validator validator;
@Resource
private MessageSource messageSource;

public <T> List<String>  validate(T object){
 Set<ConstraintViolation<T>> results=validator.validate(object);
 List<String> errorMsg=new ArrayList<String>(); 
 for(ConstraintViolation<T> result :results){
  errorMsg.add(result.getPropertyPath().toString()+":"+messageSource.getMessage(result.getMessage(), new Object[0], Locale.CHINA));
 }
 return errorMsg;
}


}

于是,在需要进行校验的地方,调用该工具类,对使用了JSR303注解的对象进行校验,便可获得校验报错的信息列表。(若无错则列表为空).

该工具类只是个演示,包括动态参数和动态字符集的支持并未写入其中,请各位自己完善。

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP