使用Spring MVC设置输入文本的日期格式

dav*_*ooh 7 java spring spring-mvc

如何Date使用Spring MVC在文本字段中设置a的格式?

我正在使用Spring Form标记库和input标记.

我现在得到的是这样的Mon May 28 11:09:28 CEST 2012.

我想以dd/MM/yyyy格式显示日期.

Nim*_*sky 8

在yr控制器中注册日期编辑器:

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(LocalDate.class, new LocalDateEditor());
}
Run Code Online (Sandbox Code Playgroud)

然后数据编辑器本身可能如下所示:

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());
 }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用我自己的抽象实用程序类(Joda)来解析日期,实际上来自Joda Datetime库的 LocalDates - 建议作为标准的java日期/日历是令人厌恶的,imho.但你应该明白这个想法.此外,您可以注册一个全局编辑器,因此您不必每个控制器都这样做(我不记得如何).


dav*_*ooh 8

完成!我刚刚将此方法添加到我的控制器类:

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


Kur*_*aki 7

如果要格式化所有日期而不必在每个Controller中重复相同的代码,则可以在使用@ControllerAdvice批注注释的类中创建全局InitBinder.

脚步

1.创建一个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;
    }
Run Code Online (Sandbox Code Playgroud)

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());
      }
    }
Run Code Online (Sandbox Code Playgroud)

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

    <context:component-scan base-package="org.example.common" />
Run Code Online (Sandbox Code Playgroud)

完了!

资料来源: