您的位置:首页 > 编程语言 > Java开发

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

2006-09-25 15:03 323 查看
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>

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息