Jaiwo99
Jaiwo99

Reputation: 10017

How to configure locale based date format support in spring

Does someone had this problem:

I need to configure spring to recognize locale based date and number format, i.e. the following user behavior should be valid:

  1. User select language to EN, then the number format 1.23 should be valid, spring mvc will accept this format and no valid error triggered. User can also change the date with date format MM/dd/yyyy and no valid error raised, user can post this form.
  2. User select language to DE, then the number format 1,23 should bevalid, spring mvc will accept this format and no valid error triggered. User can also change the date with date format dd.MM.yyyy and no valid error triggerd. User can post this form.

I'v tried to use @DateTimeFormat(pattern="#{messageSource['date_format']}"),(I have date_format defined in messages_(locale).properties) but seems spring doesn't support this yet, see JIRA ISSUE

Does someone has the similar problem and got a solution.

Does it help to write my own converter, and register it in org.springframework.format.support.FormattingConversionServiceFactoryBean? I need some kind of request based converter

Upvotes: 5

Views: 4744

Answers (1)

Jaiwo99
Jaiwo99

Reputation: 10017

Since nobody answers my question, I just post one of my solution to solve this problem, it could help others:

  1. I had a request scoped bean, which resolves locale using: RequestContextUtils.getLocale(request); request can be autowired to the request scoped class(NOTICE, it works only with field injection, not with construction or setter). In this class I get locale based date/number format.
  2. In my controller (we have actually a abstractController). I have code like this:

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

formatHelper is the request scoped bean. LocalizedDateEditor looks like this:

public class LocalizedDateEditor extends CustomDateEditor {

    public LocalizedDateEditor(FormatHelper formatHelper) {
        super(new SimpleDateFormat(formatHelper.getDefaultDateFormat()), true);
    }
}

It just tell spring to use my dateFormat.

That's all.

Upvotes: 8

Related Questions