Conversions in Struts Form Population

Posted on August 31, 2004 by Scott Leberknight

Ran across a nasty little detail using DynaActionForms in Struts today. When Struts populates an ActionForm from the request it uses the Jakarata Commons BeanUtils to accomplish this feat. BeanUtils, in turn, uses ConvertUtils, which converts String values to a specified class. (Actually BeanUtils uses BeanUtilsBean to do the actual population and ConvertUtils uses ConvertUtilsBean but that is another nasty little detail that is not important to this discussion.)

Anyway, in the DynaActionForm there was one property, which was a simple domain object (e.g. User) with several properties one of which was the id defined as a Long. This way you can define your form properties using dot notation, e.g. the HTML form property "" translates to user.setId(Long id). For entering a new User the HTML form has a "" property which contains no value, e.g. value="". When the form is submitted an interesting thing happens - the empty string gets converted by ConverUtils during the Struts form bean population process to a Long with the value zero, e.g. the equivalent code would be new Long(0). I dug through mounds of Struts and Commons code to find out why. It turns out the default converter for the Long type is in fact zero! In fact the default value for all numbers is zero. I am not sure if this is a bad thing or not. Should an empty string be converted by default to zero? That seems odd to me. I expected it to end up as null in the User object embedded in the DynaActionForm, but it instead ended up as zero. That caused me about 10 minutes of scratching my head at work and now has chewed up an hour looking at code and writing this entry on it. All in all a somewhat annoying "feature", but at least I'll never forget it again!

Post a Comment:
Comments are closed for this entry.