Spring 3 Type Conversion and Validation |

The Spring 3 final release is right around the corner, and it's going to be a great release. In this blog entry, I will take you through some of Spring 3's type conversion and validation enhancements. Whether you are developing a traditional web application, a desktop application, or a "next-generation" RIA, data binding, type conversion, and validation are important areas. As you'll see in this entry, Spring 3 gives you a significant upgrade in each of these areas while preserving backwards compatibility with previous releases.
New System Goals
Before I get into features, I'd first like to highlight the goals we had when we set out to improve Spring 3's data binding system:
- Provide a stateless, strongly-typed Type Converter SPI that supercedes JavaBean PropertyEditors
- Provide a unified Type Conversion API to use anywhere conversion is required, including Spring's DataBinder and Expression Language
- Allow for type conversion to be driven by Java Annotation metadata
- Simplify by registering sensible defaults and applying convention-over-configuration
As Spring 3 final approaches, I believe we have delivered on each of the goals. Read on and you be the judge of that.
Features
The first environment that takes full advantage of the new type conversion system is Spring MVC, which I'll pull from to demonstrate the new features. This starts with the new Spring MVC 3 configuration namespace:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven />
</beans>
The preceding minimal configuration causes Spring to automatically install default type converters that localize Number and Date fields, including full support for the popular Joda Time library if it is present on your classpath. In addition, Spring automatically enables annotation-driven declarative validation if a JSR-303 provider, such as Hibernate Validator, is present on your classpath.
Now when you bind to a field, that field will be printed and parsed for the user's locale using a sensible default format. To illustrate, consider the following model:
public class Account {
private Date activationDate = new Date(1258466400);
private BigDecimal balance = new BigDecimal("3000.25");
}
… printed on a form for users in the US and DE Locales:
| Locale.US | Locale.DE |
|---|---|
Overriding Defaults with Annotations
Often you need to format a field in a manner that differs from the default format. In the previous example, you probably want the activationDate field to be formatted using a short date format, and the balance field to be formatted using a currency format. In previous versions of Spring, you would register a custom PropertyEditor in your Controller to achieve this. In Spring 3, you simply annotate your fields:
private class Account {
@DateTimeFormat(style="S-")
private Date activationDate = new Date(1258466400);
@NumberFormat(style=Style.CURRENCY)
private BigDecimal balance = new BigDecimal("3000.25");
}
With the annotation overrides, the following is printed for the US and DE Locales:
| Locale.US | Locale.DE |
|---|---|
Parameter Annotations
Annotation-driven overrides can also be applied to method parameters. Consider the following Controller method that fetches upcoming appointments for a specific day, where the day is a URL path variable encoded in ISO date format:
@RequestMapping(value = "/appointments/{day}", method = RequestMethod.GET)
public String getAppointmentsForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day) {
...
}
Sending a GET request to /appointments/2009-11-17 fetches all Appointments on November 17th, 2009. Setting the @DateTimeFormat iso attribute to ISO.DATE instructs Spring to parse the incoming date string as an ISO Date (yyyy-mm-dd).
Validation
It is common to validate a model after binding user input to it. Spring 3 provides support for declarative validation with JSR-303. This support is enabled automatically if a JSR-303 provider, such as Hibernate Validator, is present on your classpath. When enabled, you can trigger validation simply by annotating a Controller method parameter with the @Valid annotation:
@RequestMapping(value = "/appointments", method = RequestMethod.POST)
public String add(@Valid AppointmentForm form, BindingResult result) {
....
}
static class AppointmentForm {
@NotNull @Future
private Date date;
}
After binding incoming POST parameters, the AppointmentForm will be validated; in this case, to verify the date field value is not null and occurs in the future.
Convention Over Configuration
Finally, consider how the principle of convention over configuration can be applied to type conversion. In a business application, you will often define your own custom field types. In previous versions of Spring, to format such types you would create a custom PropertyEditor implementation and register it in your Controller. With Spring 3, in most cases you simply can adhere to the following convention:
- Define a static valueOf(String) method or Constructor(String) to parse your value from its String representation
- Implement toString() to print your value for display
Consider a SocialSecurityNumber type that adheres to this convention:
public class SocialSecurityNumber {
@Size(9)
@Mask("###-##-####")
private String value;
public SocialSecurityNumber(String value) {
this.value = value;
}
public String toString() {
return this.value;
}
}
When a SocialSecurityNumber field is printed for display, toString() will be called; when a client value is parsed, the Constructor will be called. No separate Formatter or PropertyEditor implementation is required.
Summary
This entry has covered some of the new Spring 3 type conversion and validation features. To learn more, including how to implement your own type converters, checkout the Spring 3 Reference Guide. Also, watch for the release of the revised Petclinic 3 sample application in the coming weeks (this sample app demonstrates all the features highlighted here and is currently available for early access in our SVN repo here) .
I am excited about the foundation these new capabilities provide us moving forward! Please do let me know about your experiences applying and extending these features, and keep the feedback and ideas coming at jira.springframework.org.
Similar Posts
- MVC Simplifications in Spring 3.0
- XPath Support in Spring Web Services
- XML Syntax Sugar in Spring 2.0
- Integrating Spring MVC with jQuery for validation rules
- Customizing Annotation Configuration and Component Detection in Spring 2.1




Erwin says:
Added on November 17th, 2009 at 5:27 amKeith,
Could you elaborate a bit on why your stateless, strongly-typed Type Converter SPI is better than JavaBean PropertyEditors? What are the issues with the PropertyEditors system?
Erwin
Jose Noheda says:
Added on November 17th, 2009 at 5:45 amA fine feature to have no doubt. But for those used to DWR number and date converters are, well, bellow expectations. What about collections, maps, beans? Providing the converter interface and a constructor based approach is not enough IMO. Spring should handle at least JS/JSON objects (and probably XML if a suitable library is in the classpath) and parse them to their Java counterparts out-of-the-box.
Martin Vanek says:
Added on November 17th, 2009 at 5:51 amNice, I'm going to try this righ now! (Hmmm Locale example using $3,000.25 = €3.000,25 looks like quite silly idea)
Keith Donald (blog author) says:
Added on November 17th, 2009 at 9:12 amErwin,
Here are the issues with PropertyEditors as we see them:
- PropertyEditors are stateful objects, which means they cannot be shared between threads. This requires new instances to be created per request, rather than reused between requests.
- PropertyEditors are designed to convert from String to Object and back; they are not designed to convert between two arbitrary object types. Consider the requirement to coerse from one JDK Number type to another, or from a Long to a Date, or from one Collection type to another. PropertyEditors don't work well for these cases.
- PropertyEditors do not make available source and target field context during the type conversion process; such field context can be used to influence conversion based on field annotations, parameterized types, or other metadata.
- The PropertyEditor interface carries about eight additional operations that aren't used in the majority of cases. Extending from PropertyEditorSupport is generally required because of this.
- The PropertyEditor interface is not strongly typed; setValue(Object) can accept any Object, including objects not supported by a particular implementation.
With the new Converter-based SPIs, we set out to address these issues while preserving the support for PropertyEditors. The Converter interface provides a single-method, strongly-typed interface for converting from one type to another in a thread-safe manner. Additional SPI interfaces are provided for more specific cases, including "ranged converters" (ConverterFactory) and localized field formatting (Formatter and AnnotationFormatterFactory). Finally, in cases where source and target field context is rquired, for example, for annotation-driven conversion and collection/map conversion, an more complex interface can be implemented (GenericConverter) to obtain this context.
I think showing some side-by-side examples would be effective at comparing the PropertyEditor SPI with the new SPI. This comment is already getting long; instead of posting those examples here, I'll do a follow up entry. This is an important topic.
Thanks for your comment!
Keith
Xavier says:
Added on November 17th, 2009 at 9:31 amDo you plan to include a more sophisticated conversion service that could chain converter automatically? You could register [String -> Long] and [Long -> SocialSecurityNumber] so that the service could convert a String into a SSN without explicitly defining such a converter.
Oleg Zhurakousky (blog author) says:
Added on November 17th, 2009 at 10:26 am@Xavier
Yes, we are exploring this option and have couple of POC implementations already — see SPR-5794.
Oleg
Keith Donald (blog author) says:
Added on November 17th, 2009 at 10:36 amJose,
Collection, Map, and Bean mapping is fully supported, including full support for generic Collections. JSON and XML mapping is also fully supported. You make a great point that we should pre-register the JSON and XML support if the corresponding marshalling library (Jackson, JiBX, etc) is present on the classpath. This would be a nice default.
Thanks for your comment!
Keith
Ashish Jaiswal says:
Added on November 17th, 2009 at 1:22 pmDoes this release also include data binding support for nested objects including collections and maps (without the need for initializing nested object hierarchy)?
Keith Donald (blog author) says:
Added on November 17th, 2009 at 1:41 pmAshish,
Yes, full support for binding to nested object graphs is supported. This includes support for "auto growing" nested paths as required by the binding process. This alleviates the need to pre-initialize a nested object graph in many cases.
Best regards,
Keith
Byron says:
Added on November 17th, 2009 at 6:35 pmDo you have any examples of converting from String to a nested data structure?
For instance, how would you convert from a String to Map<String,List>, then bind it to a parameter in a Restful service?
Thanks
Lucas Teixeira says:
Added on November 17th, 2009 at 8:36 pmPlease guys, don't forget the imports in you snippets.
I know it is easy to find and that this is a simple example, but ppl looks here and several times goes directly into their IDEs to try it.
THanks
donny says:
Added on November 18th, 2009 at 6:14 amHi Keith,
Is the org.springframework.core.convert.support.DefaultConversionService the one used behind mvc namespace? and is it available to other beans if i use the namespace? Thanks.
Regards,
Donny
Keith Donald (blog author) says:
Added on November 18th, 2009 at 9:20 amDonny,
By default, the mvc annotation-driven element will setup a inner FormattingConversionServiceFactoryBean definition that creates a FormattingConversionService configured with the appropriate default converters. Since it's an inner bean, its not accessible to other beans. You can override this by explicitly referencing a ConversionService bean using the conversionService attribute.
Were you expecting the ConversionService instance setup by the namespace to be registered as a top-level bean? As a sidenote, yesterday another user opened a JIRA where they expected the default Validator that gets setup by the namespace to be registered as a top-level bean so they could inject it elsewhere.
Thanks!
Keith
donny says:
Added on November 18th, 2009 at 10:22 amHi Keith, Thanks for the reply. Yes I think it would be nice to have these default conversion service and validator accessible through setter injection.
Any plan to add the Jasypt encryptor as part of the default converter, maybe sometime in the future? I know i can add the encryptor easily.. but it would be nicer to see spring mvc to support this naturally… or should it be part of spring security?
Keith Donald (blog author) says:
Added on November 18th, 2009 at 12:07 pmDonny,
I encourage you to open a New Feature JIRA requesting integration of Jasypt into Spring MVC. Please let us know how you are using the library in the application, and how you think the integration should be implemented. If you have existing code to submit as an attachment, that's very helpful as well.
Keith
Andy Pemberton says:
Added on November 20th, 2009 at 10:21 amGreat work, guys. I recently wrote up a blog entry on the new Bean Validation and Portlet MVC features: http://blogs.captechventures.com/blog/andy-pemberton/spring-3-example-portlet-and-overview
In the example code, I actually used the older, 2.5 name spaces. Is the 'new mvc 3 configuration namespace' you mentioned part of RC2?
solid says:
Added on November 20th, 2009 at 10:22 pmI am getting a bizare exception when I try to use the app context config.
org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/mvc]
Offending resource: class path resource [ApplicationContext.xml]
What does this mean? I assume it means I am missing a jar.
Sam Brannen says:
Added on November 22nd, 2009 at 9:36 amAndy,
Yes, the new mvc namespace is available as of Spring 3.0.0.RC2.
– Sam
Roel says:
Added on December 1st, 2009 at 10:00 amCan you provide the JSP that produces the formatted numbers and dates (as in "With the annotation overrides, the following is printed for the US and DE Locales:"..) ?
Joel says:
Added on December 2nd, 2009 at 5:18 pmGreat stuff! Is it possible to use this in RC3 or do I need to wait for Spring 3 final?
Sam Brannen says:
Added on December 2nd, 2009 at 6:55 pmJoel, you can use this already in RC2 and RC3.
Sam Brannen says:
Added on December 2nd, 2009 at 7:03 pmRoel,
> Can you provide the JSP that produces the formatted
> numbers and dates (as in "With the annotation
> overrides, the following is printed for the US and DE
> Locales:"..) ?
In order to take advantage of this annotation-driven formatting support, you can use Spring's "form" tag library (e.g., ) to output the properties of the model object.
– Sam
Bojan says:
Added on January 3rd, 2010 at 10:57 amI have next situation: I use my domain objects also as form objects, for example, I have USERS table, mapped with Hibernate on User class (using hibernate and JPA annotations), and I am writing a controller to save new users. I will use my domain objects as form object (instance of User class will be used as form object – I think this is very common case in real world). So if I apply
@DateTimeFormat and @NumberFormat annotations on fields of class "User" I will have both hibernate and validation annotations in that class!? I think this is not nice!
Am I making some mistake? How should I do validation in such cases?
Marc says:
Added on January 15th, 2010 at 4:30 amIs there now a way to declaratively handle date conversion when the date may be an empty string?
Stevo Slavic says:
Added on January 20th, 2010 at 5:15 amLink to reference guide is broken. It should probably lead to http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/validation.html#core-convert
Adrian says:
Added on January 25th, 2010 at 3:14 amHi, thanks for the post.
As Marc mentioned above, there appears to be an issue binding empty form fields to Date properties in Spring 3. When doing so, an error such as the following is thrown:
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 5 errors
Field error in object 'shelf' on field 'asset.endOfLifeDate': rejected value []; codes [typeMismatch.shelf.asset.endOfLifeDate,typeMismatch.asset.endOfLifeDate,typeMismatch.endOfLifeDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [shelf.asset.endOfLifeDate,asset.endOfLifeDate]; arguments []; default message [asset.endOfLifeDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'asset.endOfLifeDate'; nested exception is java.lang.IllegalStateException: Cannot convert value of type to required type for property 'endOfLifeDate': no matching editors or conversion strategy found]
Is there some way to declaratively handle this in Spring 3 or are custom property editors still required for this?
Keith Donald (blog author) says:
Added on January 25th, 2010 at 3:23 amHi Adrian,
The best way to report a bug is to open a JIRA at http://jira.springframework.org with a small test case attached that helps the team to reproduce it.
I am not aware of any issues with binding empty fields to Date properties; at least the work I've done lately, this is working fine. I encourage you to file a JIRA and attach a small test case so we can reproduce things to match your environment as far as possible.
Thanks
Keith
Ha says:
Added on February 15th, 2010 at 6:06 pmHello,
We plan to build an application following the architecture in the Hotel Booking sample project (it uses Web Flow 2.0.8 and JSF 1.2). I wonder if we could use this feature in JSF?
Thanks,
-Ha
Michael Chang says:
Added on February 28th, 2010 at 12:40 amA previous poster (Lucas) has asked for the imports that you used. I, too, would like to know. I just tried using this new stuff and created a FooForm class to back my form. One of the fields in FooForm is a String with a @Length annotation. Neither me nor my IDE knew exactly which annotation to import (org.hibernate.validator.constraints.Length or org.springmodules.validation.bean.conf.loader.annotation.handler.Length). Unfortunately, neither annotation amounted to the correct behaviour when used in conjunction with Spring MVC's 'form' tag library (specifically the tag). When using the Spring Modules annotation, no validation is performed whatsoever, whereas when using Hibernate's import, it does the validation but no error messages are rendered (Hibernate's annotations don't support the 'message' and 'errorCode' parameters, which are what I assume are displayed in a form when validation fails).
Anyway, I LOVE the work you guys have done. But next time, more complete (and compilable, @Size(9) is invalid) examples would be appreciated.
Thanks
Michael
Andy says:
Added on February 28th, 2010 at 2:20 pmMichael:
One of this highlights in this article is the JSR303 Bean Validation integration. If you want to use the standard JSR303 features, you'd want to use: javax.validation.constraints.Size (ie: @Size(min=x, max=y)). There is no JSR303 @Length annotation for validation.
Hope this is helpful.
-Andy
Michael Chang says:
Added on February 28th, 2010 at 2:52 pmAndy,
I see. Then is it advisable from here on out to neither use nor refer to Spring's Bean Validation framework (from Spring Modules)? I guess I had looked at the wrong documentation initially (https://springmodules.dev.java.net/docs/reference/0.8/html_single/#d0e9699), where it says that @Size is only used for collections. Do you know if JSR-303 implementations (like Hibernate Validator) and Spring MVC's 'form' tags cooperate together?
Michael
Andy says:
Added on February 28th, 2010 at 3:17 pmWell, this is up for debate, but personally, yes: I'd prefer to use JSR303 Bean Validation annotations alone.
The Bean Validation @Size annotation can be used on:
* String (string length is evaluated)
* Collection (collection size is evaluated)
* Map (map size is evaluated)
* Array (array length is evaluated)
To your last question, yes. Specifically, you can use the new @Valid annotation (which is essentially like the older @ModelAttribute annotation, plus adding in validation to the binding lifecycle. This will add BindingResult errors which would then be displayed in spring form:errors tag(s).
I actually added a Maven-Eclipse project example with this code and dependencies worked out to a blog entry I wrote: http://blogs.captechventures.com/blog/andy-pemberton/spring-3-example-portlet-and-overview
Adrian says:
Added on February 28th, 2010 at 7:44 pmI have set up JSR303 validation annotations on my object model, however I am unable to use the @Valid annotation on my beans in the POST method signature, for this reason: at the point of binding the form to the bean, there are related objects which have @NotNull constraints on my beans and which have to be looked up and attached inside of the POST method. How would I programmatically invoke the same Validation cycle on the bean object inside my controller method after I have built the relationships?
Thanks!
andybe says:
Added on March 12th, 2010 at 7:21 pmI look around, read the spring documentation and fail in every part…
do you got an simple small project or something like that
——–
package de.kit.ksm.kalibweb.formatter;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface WebDateFormat {
}
——-
package de.kit.ksm.kalibweb.formatter;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.format.AnnotationFormatterFactory;
import org.springframework.format.Parser;
import org.springframework.format.Printer;
public final class WebDateFormatAnnotationFormatterFactory implements
AnnotationFormatterFactory {
Log log = LogFactory.getLog(getClass().getName());
private final Set<Class> fieldType;
public WebDateFormatAnnotationFormatterFactory() {
Set<Class> rawFieldTypes = new HashSet<Class>(1);
rawFieldTypes.add(Date.class);
log.debug("init");
this.fieldType = Collections.unmodifiableSet(rawFieldTypes);
}
@Override
public Set<Class> getFieldTypes() {
log.debug("set fieldtypes");
return this.fieldType;
}
@Override
public Parser getParser(WebDateFormat arannotation, Class fieldType) {
log.debug("get parser");
return new WebDateFormatter();
}
@Override
public Printer getPrinter(WebDateFormat annotation, Class fieldType) {
log.debug("get printer");
return new WebDateFormatter();
}
}
—-
package de.kit.ksm.kalibweb.formatter;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.support.FormattingConversionServiceFactoryBean;
public class WebDateFormatFormattingConversionServiceFactoryBean extends FormattingConversionServiceFactoryBean
{
@Override
protected void installFormatters(FormatterRegistry registry) {
super.installFormatters(registry);
registry.addFormatterForFieldAnnotation(new WebDateFormatAnnotationFormatterFactory());
}
}
——-
xml setup seams to be ok…but no go with annotation @WebDateFormat
andybe says:
Added on March 12th, 2010 at 7:26 pmwhere is my comment goes…i fail to setup a stub of my @WebFormatdate, is send you the code…
Grzegorz Borkowski says:
Added on March 30th, 2010 at 4:13 amKeith, is it possible to configure the Joda Time parser globally, to parse all the dates in common format? There is no documentation on it. I'd like to have it configured so that it parses all dates and times in valid ISO format (org.joda.time.format.ISODateTimeFormat.dateTimeParser() | dateParser() | dateOptionalTimeParser() | timeParser()). I was able to write my own converter to do it, but if Spring has JodaTime support built-in, than I'd expect to be able to do it without writing any code.
Grzegorz Borkowski says:
Added on March 31st, 2010 at 3:17 pmOne more thing make me puzzled: according to Hibernate Validator documentation, the JPA 2 provider (like Hibernate 3.5) will detect presence of validator implementation on classpath, and automatically validate @Entities during persist or merge calls. However, it doesn't work for me – the validation is not called, I must call it explicitly (as I can't use @Valid-marked controller inputs in my case). Why validation is not triggered by Hibernate? Is it something specific to Spring environment, perhaps it is disabled intentionally (e.g. to not duplicate validation after validating controller inputs)?
Keith Donald (blog author) says:
Added on April 16th, 2010 at 11:23 amHi Grzegorz,
Be sure to open JIRAs on these two items – it's the best way to ensure they stay tracked. In general, for Spring 3.1 we want to make sure we capture these types of common defaults, and we really depend on good community input to arrive at the right defaults.
Have a look at FormattingConversionServiceFactoryBean in 3.0.x for now, and it's use of the JodaTimeFormattingConfigurer. The latter has some custom options in this area you might could take advantage of. You'd need to extend FormattingConversionServiceFactoryBean to apply them, and we should definitely look to make this easier in a future release.
Grzegorz Borkowski says:
Added on April 22nd, 2010 at 2:51 pmKeith, I created JIRA tasks for this: SPR-7121 and SPR-7122.
film says:
Added on October 11th, 2010 at 6:42 pmThanks for the constructive feedback
regarding the Overworld limitations and linearity, I only felt it limited in the sense that you aren't truely able to 'explore' fully in the way that could in other Zelda games – remember the underground caverns you could once find? – and quite frankly I miss that and it is basically linear in the sense that your destination is already chosen, yes you are still exploring and in a wonderful new way but this Overworld 'Transport' also highlights the limitations of what Nintendo can do with a 3D Zelda game on the DS but what they 'have' achieved is still impressive and I do acknowledge that fully.
systec says:
Added on October 14th, 2010 at 12:24 amKeith, in Spring 2.5 I used a PropertyEditor to bind some request parameter to an entity object which was then available in my controller through the bound form.
A common and simple example as per the Spring docs is – http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/view.html#view-jsp-formtaglib-optionstag. In such a case I would use a PropertyEditor to get a Country object from the DAO layer using the posted country code and bind that to the form.
In Spring 3 I am trying something similar using a custom Formatter. All works well except when serving a jsp using the example select box. The Formatter is given all the options in the select box including the 'Please select' option which returns null and results in an exception.
I was wondering whether i should be using the Conversion SPI instead, but this only seems to do the conversion one way. Any ideas? Thanks
John says:
Added on November 17th, 2010 at 11:07 amHi, I was trying to implement custom Formatter. I have registered it using formatterRegistry.addFormatterForFieldType(). Unfortunately the formatter is not called for data binding. In Spring Docs 3.0.4 chapter 5.6.3 FormatterRegistry SPI it says: "Because this implemementation also implements ConversionService, it can be directly configured for use with Spring's DataBinder and the Spring Expression Language (SpEL)." This hints to me that some additional step might be required. Unfortunately there is no documentation example how to do that. How do you configure DataBinder to use the FormattingConversionService? Actually there is also no example how to configure DataBinder with any ConversionService.
Keith Donald (blog author) says:
Added on November 17th, 2010 at 11:34 amHave a look at section "5.6.4 Configuring Formatting in Spring MVC" and also the mvc-showcase sample project that shows plugging in a custom Formatter into Spring MVC.
Keith
John says:
Added on November 17th, 2010 at 11:40 amThanks, sometimes one is blind. I had the present, but the conversion-service="conversionService" attribute was missing.
Krishna says:
Added on February 19th, 2011 at 12:16 pmHI,
This is good feature in spring framework. Custom Spring Converters and Formatters adds more value to the spring framework.
Thanks,
Krishna
WQ says:
Added on May 25th, 2011 at 11:05 amKeith,
As you do,but url cannot be parsed!But while I exchange Date for String,everything is normal,why?
Thanks!
@RequestMapping(value = "/appointments/{day}", method = RequestMethod.GET)
public String getAppointmentsForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day) {
…
}
John says:
Added on August 29th, 2011 at 10:17 pmHow can I allow dates to be null when using the @DateTimeFormat
@DateTimeFormat(pattern = "MMM dd yyyy")
private Date arriveDate;
This does not let me have a null value for this field. How can I make it to allow null values also without removing the pattern.
Thank you much!
Claudia says:
Added on April 25th, 2012 at 5:52 pmKeith,
Thanks for the article, it is enlightening.
I do not know the @Mask annotation, can you refer me to some documentation?
Thanks,
Claudia
Rohit says:
Added on September 21st, 2012 at 12:49 amThe way you specify DateTimeFormat is just amazing, quite readable.