gene b.
gene b.

Reputation: 12034

Spring MVC Different CustomDateEditor Binders for Various Fields

In my Controller I bind a main Date Custom editor that works for most fields, but not all: yyyy-MM-dd:

@InitBinder      
public void initBinder(WebDataBinder binder) 
{  
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
    binder.registerCustomEditor(Date.class, editor);
}   

I also have some GUI fields that map to a Date in my domain object, but they are different. Some are in yyyy format (Year only). They require a customized Date binder.

Is it possible to define other CustomDateEditors that bind to specific fields, rather than a one-for-all Type binder?

Upvotes: 0

Views: 213

Answers (1)

Ralph
Ralph

Reputation: 120851

An other way is to use Spring Formatter instead PropertyEditors. The good thing is, that Spring has already formatters for Date (@DateTimeFormat) and the next good thing is, that they are configured per attribute, by annotation.

For example

   @DateTimeFormat(pattern="yyyy")
   private Date yearOnly;

   @DateTimeFormat(pattern="yyyy-MM-dd")
   private Date dayMonthYear;

Upvotes: 2

Related Questions