Set the date format for text input using Spring MVC

How to set date format in textbox using Spring MVC?

I am using Spring tag library and input tag.

Now I get something like this Mon May 28 11:09:28 CEST 2012 .

I want to show the date in dd/MM/yyyy format.

+7
source share
3 answers

register date editor in yr controller:

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

and then the data editor itself might look like this:

 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()); } } 

I use my own abstract utility class (Joda) for parsing dates, in fact LocalDates from the Joda Datetime library - it is recommended as standard java date / calendar - an abomination, IMHO. But you should get this idea. In addition, you can register a global editor, so you do not need to do this every controller (I do not remember how).

+7
source

Done! I just added this method to my controller class:

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

If you want to format all your dates without repeating the same code in each controller, you can create a global InitBinder in the class annotated with @ControllerAdvice .

Actions

1. Create a DateEditor class that will format your dates, for example:

  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 using @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 the Spring MVC configuration file (for example, webmvc-config.xml) add 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:

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

Done!

Sources:

+6
source

All Articles