spring validation的灵活使用

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

  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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值