Announcement Announcement Module
Collapse
No announcement yet.
Formatting for dates/numbers Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Formatting for dates/numbers

    Hi

    I'm moving my project to Spring 3, and trying to use its resources extensively. Now I'm trying to set up Date and BigDecimal formatters. Using 2.5, I created an initBinder and registered a custom editor on every controller, and used <fmt> on every field on JSP. I really dislike that solution, is too much intrusive, IMHO.

    I'm trying to keep it simple and flexible, but so far no good. I wish to use annotations configurations (like @DateTimeFormat on Date fields, setting properties as needed - usually "S-") to keep it flexible, but avoid repetition (repeating the format everywhere). Using this annotation, my command field is being incorrectly parsed and incorrectly displayed back on the interface. Guess this should be because I need to set a locale, so I tried setting a FixedLocaleResolver like this:

    Code:
    	<bean id="localeResolver" class="org.springframework.web.servlet.i18n.FixedLocaleResolver">
    		<property name="defaultLocale" value="xx_YY"/>
    	</bean>
    It didn't worked (need to inject it somewhere? I couldn't find it). Guess I could use a pattern for the annotation, but I prefer something simpler and more flexible if someday my app becomes multilanguage. What am I missing to make the annotation work as expected?

    Also, I noticed that using style="S-" is formatting the year as 2 digits, and I want 4 digits for all my dates system-wide. If in my locale the year is also 2 digit, can I tweak it to 4 digit somehow in a simple way?
    Similarly, when dealing with numbers (BigDecimal), I'll want to parse and print numbers without grouping separator on input fields, despite the locale format probably including the separator, as I believe they may lead to confusion (some folks using grouping separator as digit separator).

    So, can I do these tasks with standard Spring annotation, or maybe I'll need to create my own formatter annotations?

    Thanks!

  • #2
    I did some further testing, and the FixedLocaleResolver is working nicely with the code above, but still I haven't got the result I want.

    In my locale, if I use style "S-" for dates, I get two letter year, instead of four letter. And for BigDecimal, it uses grouping separators, and I'll need them out.

    So, except for defining a pattern for every @DateTimeFormat/@NumberFormat, what is the most flexible solution? Is there some XML config that I can add or I'll a custom annotation?

    Thanks!

    Comment


    • #3
      if you only want to display date, you can use the tag <fmt:formatDate type="date" value="${command.property}"/>

      but I don't know how to display a date in an input field correctly. In my case, all date displayed in form are unformatted.
      I tried spring:bind but it doesn't work out.

      I am trying spring:eval.... Hope I can get some good news..

      Comment


      • #4
        My old code used <fmt:formatDate>, but it's cumbersome, plus annotation String annotation formatters do the job two-way (parse and format), so I'd like to just tweak it a little to fit my needs.
        Anyone?

        About your issue, if you want to keep using <fmt> tags, you can apply them to input fields as well. If your problem is that you can't insert the <fmt:formatDate> tag inside the <form:input>, save the formatted result to a variable with the 'var' attribute, then just use it for the input tag value with ${variableNameHere}.
        That's how I did for my old code... it was a crappy code, so it may be a bad way to do it.

        But I suggest you to use formatter annotations on the fields.

        Comment


        • #5
          A good reference for DateTimeFormat:
          http://forum.springsource.org/showthread.php?t=83220

          Comment


          • #6
            Thanks. I will try that.
            I am using Spring Webflow 2.2.1.In the reference, they claim that SWF "uses the type conversion and formatting system introduced in Spring 3 for nearly all type conversion needs." But I just cannot get the datetimeformat annotation work.

            Originally posted by mdrg View Post
            My old code used <fmt:formatDate>, but it's cumbersome, plus annotation String annotation formatters do the job two-way (parse and format), so I'd like to just tweak it a little to fit my needs.
            Anyone?

            About your issue, if you want to keep using <fmt> tags, you can apply them to input fields as well. If your problem is that you can't insert the <fmt:formatDate> tag inside the <form:input>, save the formatted result to a variable with the 'var' attribute, then just use it for the input tag value with ${variableNameHere}.
            That's how I did for my old code... it was a crappy code, so it may be a bad way to do it.

            But I suggest you to use formatter annotations on the fields.

            Comment


            • #7
              Thanks for the link, good reading.

              But I don't use Webflow, and my formatters are working, except that I need a bit more customization on them.

              Still waiting for some clarifying help!
              Thanks!

              Comment


              • #8
                Have you tried pattern or ISO date formats?
                @DateTimeFormat(pattern="yyyy-MM-dd")
                or
                @DateTimeFormat(iso=ISO.DATE)

                Originally posted by mdrg View Post
                Hi

                I'm moving my project to Spring 3, and trying to use its resources extensively. Now I'm trying to set up Date and BigDecimal formatters. Using 2.5, I created an initBinder and registered a custom editor on every controller, and used <fmt> on every field on JSP. I really dislike that solution, is too much intrusive, IMHO.

                I'm trying to keep it simple and flexible, but so far no good. I wish to use annotations configurations (like @DateTimeFormat on Date fields, setting properties as needed - usually "S-") to keep it flexible, but avoid repetition (repeating the format everywhere). Using this annotation, my command field is being incorrectly parsed and incorrectly displayed back on the interface. Guess this should be because I need to set a locale, so I tried setting a FixedLocaleResolver like this:

                Code:
                	<bean id="localeResolver" class="org.springframework.web.servlet.i18n.FixedLocaleResolver">
                		<property name="defaultLocale" value="xx_YY"/>
                	</bean>
                It didn't worked (need to inject it somewhere? I couldn't find it). Guess I could use a pattern for the annotation, but I prefer something simpler and more flexible if someday my app becomes multilanguage. What am I missing to make the annotation work as expected?

                Also, I noticed that using style="S-" is formatting the year as 2 digits, and I want 4 digits for all my dates system-wide. If in my locale the year is also 2 digit, can I tweak it to 4 digit somehow in a simple way?
                Similarly, when dealing with numbers (BigDecimal), I'll want to parse and print numbers without grouping separator on input fields, despite the locale format probably including the separator, as I believe they may lead to confusion (some folks using grouping separator as digit separator).

                So, can I do these tasks with standard Spring annotation, or maybe I'll need to create my own formatter annotations?

                Thanks!

                Comment


                • #9
                  ISO is not suitable, it is intended for standard visual representation, and as said in the topic, I specifically do not want to use a pattern, because I'll have to repeat it everywhere, and because it is not multi-locale-friendly (every locale would need a different pattern).

                  Comment


                  • #10
                    What are your requirements exactly?

                    Are you saying you'd like the default String<->Date formatting rule to be yyyy-mm-dd (adjusting the pattern for the current locale)? This is definitely possible. Would you expect this rule to be enforced only when using @DateTimeFormat, or would you view the annotation as entirely optional? You have the ability for conversion to be driven by annotation or by type only (e.g. String to Date, String to BigDecimal).

                    If you can be very specific about what you're trying to achieve, I can show you how to do it with the current system. It's a pretty flexible system.

                    Keith
                    Last edited by Keith Donald; Dec 8th, 2010, 09:26 PM.

                    Comment


                    • #11
                      Ok, let's be more specific (not summarized, I guess).

                      I use formatter/validator annotations, and want the @DateTimeFormat to do the job for dates, enforcing the correct format when parsing, and printing the very same format when populating inputs, without the boring task of setting <fmt:formatDate> for each field. The same applies to BigDecimal fields.

                      My app have no multilanguage support right now, but it may be added someday, so I'd like to keep it flexible enough to avoid rework in the furure. So I don't want to hardcode date/number patterns everywhere in my code. I want to keep formatting/parsing up to the locale, so that new formats can be supported instantly.
                      The question is that my locale uses dd/mm/yy as date format and I need dd/mm/yyyy, and numbers are 0.000,0 , and I need 0,00 (no group separators, two decimal digits if monetary).

                      That's what I need, and I don't know how to do it. I don't mind "overriding" the default patterns used by my locale (with custom classes and/or XML config), if that's the way to go... as long as this fix reflects everywhere.

                      Thanks, Keith!
                      Last edited by mdrg; Dec 8th, 2010, 10:23 PM.

                      Comment


                      • #12
                        When using @DateTimeFormat("S-"), the "S-" is interpreted as a Joda DateTime "style code" -- we simply delegate to Joda's printing and parsing behavior for that code. You could change what "S-" means, but you'd need to plug in a custom DateTimeFormatAnnotationFormatterFactory to do this. You might consider instead registering a custom Formatter<Date> and Formatter<BigDecimal> that applies to all Dates and BigDecimal fields (so conversion would be driven by type, not annotation, and no field annotation would be required then). To register a custom Formatter, you need to subclass FormattingConversionServiceFactoryBean, override the installFormatters(FormatterRegistry) hook, register your customizaitons, and finally inject the ConversionService produced by this FactoryBean into your mvc:annotation-driven element. You might find it helpful to review the super implementation which installs the default Joda-based @DateTimeFormat support, as well as the default @NumberFormat support.

                        I also recommending reading the reference documentation in this area and reviewing the mvc-showcase, which has working examples of customizing the registered set of Converters/Formatters.

                        Hope this gets you going.

                        Keith
                        Last edited by Keith Donald; Dec 8th, 2010, 10:36 PM.

                        Comment


                        • #13
                          Thanks for the tips. In the other topic about the Trimmed annotation I've seen how to implement formatters, but I prefer a per-field definition. I'll try a new DateTimeFormatAnnotationFormatterFactory and NumberFormatAnnotationFormatterFactory tonight and see if it does the trick.

                          Just one question: registering my custom formatter factory, like AnnotationFormatterFactory<NumberFormat>, would simply replace the default Spring implementation, or how would it behave? The docs do not mention this.

                          Once again, many many thanks, Keith!

                          Comment


                          • #14
                            AnnotationFormatterFactory<A> is a simple interface, so I'd try implementing your own that meets your needs. You would then replace the default implementations with your own. Alternatively, if you believe you can patch the default implementations to allow them to be customized to meet your needs, that'd be cool, too. But you might want to start first with just implementing your own, it's a good exercise to go through.

                            Keith

                            Comment


                            • #15
                              I can't find DateTimeFormatAnnotationFormatterFactory in spring 3.0.5 code?
                              Is that changed to JodaDateTimeFormatAnnotationFormatterFactory?

                              Comment

                              Working...
                              X