spring中用户自定义的某个验证器/解析器

在spring中默认已经给我们提供了很多的从client到服务器的一些参数的验证器(可能也称解析器),但有些我们需要的还得自己扩展才能满足我们的需要,比如,我们通常需要解析从client端过来的字符串类型的日期格式,并且我们需要解析精确到时分秒,即 年月日时分秒的情况,这个怎么做呢,网很多了,我这里就写一下吧;

很简单,分两步:

1,解析的Java Bean类代码:

public class SystemWebBindingInitializer implements WebBindingInitializer{
	@Override
	public void initBinder(WebDataBinder webDataBinder, WebRequest request){
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
	    //format: "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd"
	    //binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); //save to below 
	    PropertyEditor propertyEditor = new CustomDateEditor(dateFormat, true ); //true=can empty
	    webDataBinder.registerCustomEditor(Date.class, propertyEditor);  
	    	    
	    //可以定义不同class类型的转换器,方法跟上面的相似的,定义propertyEditor,然后注册到webDataBinder中	    
	}
	
}


2,向Spring的配置文件 applicationContent.xml 配置这个Bean,目的是在spring启动时注入到其容器中,提供其它地方使用;

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" init-method="">
	<property name="webBindingInitializer">
		<bean class="com.xxx.kkk.validator.SystemWebBindingInitializer"></bean>
	</property> 
</bean>

就这么简单,方便吧,当然类存放在哪个包下自己修改路径即可,就这样可以解析client端发送过来符合 yyyy-MM-dd HH:mm:ss 格式的字符串解析成日期类型了,


怎么样,方便吧,呵呵,懒人计划大笑... 





猜你喜欢

转载自blog.csdn.net/shenzhennba/article/details/51759082