SpringMvcカスタムタイプ変換器

1649 ワード

まず、SpringMvcが構築した開発環境が必要です.
  • Convertインタフェースを実装クラス
  • public class DateConverter implements Converter<String, Date> {
     
    @Override
    public Date convert(String date) {
    if (date == null || date.length() < 8)
          return null;
     
        if (date.length() < 12)
          date += " 00:00:00";
     
        DateFormat df = DateFormat.getDateTimeInstance();
        try {
          return df.parse(date);
        } catch (ParseException e) {
          e.printStackTrace();
          return null;
        }
    }

    2.WebBindingInitializerインタフェースを実装したクラスを書く
        
    public class DateFormatBindingInitializer implements WebBindingInitializer {
    @Override
    public void initBinder(WebDataBinder binder, WebRequest request) {
    binder.registerCustomEditor(java.util.Date.class, 
    new CustomDateEditor(new JavaUtilDateFormater("yyyy-MM-dd HH24:mm:ss"), true));
    }
    }

    3.springMvc.xmlでの構成
    <mvc:annotation-driven conversion-service="conversionService" />
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="com.jockiller.convert.DateConverter" />
            </list>
        </property>
    </bean> 
     
     
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="webBindingInitializer">
            <bean class="com.jockiller.bind.DateFormatBindingInitializer" />
        </property>
    </bean>

    テストしてみよう..