spring技术手册阅读笔记(三) 使用CustomEditorConfigurer

本文介绍如何使用Spring框架中的CustomEditorConfigurer进行类型转换,特别是将字符串转换为日期类型,并展示了配置示例及Spring MVC中的使用方法。

CustomEditorConfigurer可以读取实现java.beans.PropertyEditor接口的类,将字符串转为指定的类型,更方便的使用PropertyEditorSupport.PropertyEditorSupport实现PropertyEditor,必须重新定义setAsText.
举个将字符串转为date的例子.
import java.util.Date;

public final class ValueRelationalOperand {

private Date _date;

public Date getValue() {
return _date;
}

public void setValue(Date date) {
_date = date;
}
}
配置文件
<bean id="configBean"
class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>

<entry key="java.util.Date">
<bean class="org.springframework.beans.propertyeditors.CustomDateEditor">
<constructor-arg index="0">
<bean class="java.text.SimpleDateFormat">
<constructor-arg>
<value>yyyy/MM/dd</value>
</constructor-arg>
</bean>
</constructor-arg>
<constructor-arg index="1">
<value>true</value>
</constructor-arg>
</bean>
</entry>
</map>
</property>
</bean>


<bean id="rightDateOperand" class="onlyfun.caterpillar.ValueRelationalOperand">
<property name="value" value="2001/15/01"/>
</bean>
测试例子
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public final class Main {

public static void main(final String[] args) {
ApplicationContext ctx = new FileSystemXmlApplicationContext(
"D:\\workspace\\springdemo\\src\\beans-config.xml");
ValueRelationalOperand op = (ValueRelationalOperand) ctx
.getBean("rightDateOperand");
System.out.println(op.getValue());
}
}
这只是用于ApplicationContext中,如果用于spring MVC中,要麻烦一些,必须注册property editor ,需要重载initBinder,然后调用binder.registerCustomEditor(Date.class, yourPropertyEditor),
代码:
protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Date.class,ValueRelationalOperand);
}

页面绑定
<spring:bind path="dateCommand.startDate">
<input type="text" id="startDateField" name="${status.expression}" value="<c:out value="${status.value}"/>"/>
<span class="fieldError">${status.errorMessage}</span>
</spring:bind>

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值