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 格式的字符串解析成日期类型了,


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





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值