Set date format for an input text using Spring MVC

后端 未结 3 1418
既然无缘
既然无缘 2020-12-15 13:33

How can I set the format for a Date in a text field with Spring MVC?

I\'m using the Spring Form tag library and the input tag.

What I get now is

3条回答
  •  臣服心动
    2020-12-15 14:05

    If you want to format all your dates without having to repeat the same code in every Controller, you can create a global InitBinder in a class annotated with @ControllerAdvice annotation.

    Steps

    1. Create a DateEditor class that will format your dates, like this:

        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. Create a class annotated with @ControllerAdvice (I called it 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. In your Spring MVC configuration file (for example webmvc-config.xml) add the lines that allow Spring to scan the package in which you created your GlobalBindingInitializer class. For example, if you created GlobalBindingInitializer in the org.example.common package:

        
    

    Finished!

    Sources:

    • Keenformatics - How To create a global InitBinder in Spring with @ControllerAdvice (my blog)
    • Spring Framework 3.2.4 - Annotation Type ControllerAdvice
    • Spring Framework API 2.5 - Annotation Type InitBinder
    • Personal experience

提交回复
热议问题