Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting empty String to null Date object with Spring

I have a form field that should be converted to a Date object, as follows:

<form:input path="date" />

But I want to get a null value when this field is empty, instead of that I receive:

Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'date';
org.springframework.core.convert.ConversionFailedException: Unable to convert value "" from type 'java.lang.String' to type 'java.util.Date';

Is there an easy way to indicate that empty Strings should be converted to null? Or should I write my own PropertyEditor?

Thanks!

like image 430
Joaquín L. Robles Avatar asked Jan 26 '11 15:01

Joaquín L. Robles


People also ask

How can I pass an empty string value to a date field in Java?

Try setting the value of the date to 0000-00-00, this usually works (never tried it in this scenario but everywhere else it always worked for me). @AlonAlexander ah if only.

Can we inject null and empty string values in spring beans?

In Spring dependency injection, we can inject null and empty values. In XML configuration, null value is injected using <null> element.

How do you null a date in Java?

You can create a Date object with null value and can put a null check. Date date = new Date(); // Today's date and current time Date date2 = new Date(0); // Default date and time Date date3 = null; //Date object with null as value. if(null != date3) { // do your work. }

Can a string be null and empty?

The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.


2 Answers

Spring provides a PropertyEditor named CustomDateEditor which you can configure to convert an empty String to a null value. You typically have to register it in a @InitBinder method of your controller:

@InitBinder public void initBinder(WebDataBinder binder) {     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");     dateFormat.setLenient(false);      // true passed to CustomDateEditor constructor means convert empty String to null     binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); } 
like image 64
Chin Huang Avatar answered Oct 05 '22 13:10

Chin Huang


More recent versions of the Spring framework introduced conversion and formatting services to take care of these tasks, somehow leaving the property editors system behind. However, the issue reported is unfortunately still present: the default DateFormatter is unable to properly convert an empty string to a null Date object. What I find extremely irritating is that the Spring documentation contains a date formatter snippet example where the proper guard clauses are implemented for both conversions (to and from strings). This discrepancy between the framework implementation and the framework documentation really drives me insane, so much that I could even try to submit a patch as soon as I find some time to devote to the task.

In the meantime, my suggestion to everyone encountering this problem while using a modern version of the Spring framework is to subclass the default DateFormatter and override its parse method (its print method, too, if it's needed) so as to add a guard clause in the fashion of the one shown in the documentation.

package com.example.util;  import java.text.ParseException; import java.util.Date; import java.util.Locale;  public class DateFormatter extends org.springframework.format.datetime.DateFormatter {      @Override     public Date parse(String text, Locale locale) throws ParseException {         if (text != null && text.isEmpty()) {             return null;         }         return super.parse(text, locale);     }  } 

Then, some modifications must be applied to the XML Spring configuration: a conversion service bean must be defined, and the corresponding attribute in the annotation-driven element in the mvc namespace must be properly set.

<mvc:annotation-driven conversion-service="conversionService" /> <beans:bean     id="conversionService"     class="org.springframework.format.support.FormattingConversionServiceFactoryBean">     <beans:property name="formatters">         <beans:set>             <beans:bean class="com.example.util.DateFormatter" />         </beans:set>     </beans:property> </beans:bean> 

To provide a specific date format, the pattern property of the DateFormatter bean must be properly set.

<beans:bean class="com.example.util.DateFormatter">     <beans:property name="pattern" value="yyyy-MM-dd" /> </beans:bean> 
like image 29
Giulio Piancastelli Avatar answered Oct 05 '22 12:10

Giulio Piancastelli