2012-05-28 97 views

回答

7

登记岁控制器的日期编辑:

@InitBinder 
protected void initBinder(WebDataBinder binder) { 
    binder.registerCustomEditor(LocalDate.class, new LocalDateEditor()); 
} 

,然后将数据编辑器本身可以是这样的:

public class LocalDateEditor extends PropertyEditorSupport{ 

@Override 
public void setAsText(String text) throws IllegalArgumentException{ 
    setValue(Joda.getLocalDateFromddMMMyyyy(text)); 
} 

@Override 
public String getAsText() throws IllegalArgumentException { 
    return Joda.getStringFromLocalDate((LocalDate) getValue()); 
} 
} 

我用我自己的抽象工具类(乔达)解析日期,其实LocalDates从Joda Datetime library - 建议作为标准的java日期/日历是一种可憎的,恕我直言。但你应该明白这个主意。此外,你可以注册一个全局编辑器,所以你不必每个控制器都做(我不记得是如何的)。

+0

谢谢!这绝对比我的解决方案更好。 – davioooh

+0

@davioooh Spring 3.0 +?这是我认为相关章节http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html“使用propertyregistars”显示如何在全球范围内执行 – NimChimpsky

+0

是的,我使用Spring 3.1,但我还是对它不熟悉...(以及对Spring Framework的总体...) – davioooh

8

完成!我只是说这个方法我的控制器类:

@InitBinder 
protected void initBinder(WebDataBinder binder) { 
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); 
    binder.registerCustomEditor(Date.class, new CustomDateEditor(
      dateFormat, false)); 
} 
6

如果您希望将所有日期格式,而无需重复相同的代码在每一个控制器,可以与@ControllerAdvice注释的类创建全球InitBinder注解。

步骤

创建DateEditor类,将格式化您的日期,就像这样:

public class DateEditor extends PropertyEditorSupport { 

    public void setAsText(String value) { 
     try { 
     setValue(new SimpleDateFormat("dd/MM/yyyy").parse(value)); 
     } catch(ParseException e) { 
     setValue(null); 
     } 
    } 

    public String getAsText() { 
     String s = ""; 
     if (getValue() != null) { 
     s = new SimpleDateFormat("dd/MM/yyyy").format((Date) getValue()); 
     } 
     return s; 
    } 

2.创建@ControllerAdvice注释的类(我把它叫做GlobalBindingInitializer) :

@ControllerAdvice 
    public class GlobalBindingInitializer { 

    /* Initialize a global InitBinder for dates instead of cloning its code in every Controller */ 

     @InitBinder 
     public void binder(WebDataBinder binder) { 
     binder.registerCustomEditor(Date.class, new DateEditor()); 
     } 
    } 

3.在您的Spring MVC配置文件(例如webmvc-config.xml)中添加允许Spring扫描您在其中创建GlobalBindingInitializer类的包的行。例如,如果您在org.example.common包中创建了GlobalBindingInitializer:

<context:component-scan base-package="org.example.common" /> 

完成!

来源:

相关问题