When user decides to leave the field in the form empty the Apache Struts binds empty String as value for properties in the ActionForm. Is there any way to modify the behavior globally and opt for null instead of empty String?
I know that Spring MVC does exactly the same, but there is also StringTrimmerEditor that can be registered as property editor to trim strings to null.
A possible solution – one that will allow a single conversion entry point for all your String fields – would be to register a custom convertor, but not with Struts but with BeanUtils.
For mapping request parameters to form properties, Struts makes use of the populate method of its RequestUtils class. This class in turn uses a
BeanUtilsimplementation do do its work.A simplistic flow would be something of the likes of Struts’ RequestUtils > BeanUtils > BeanUtilsBean > ConvertUtils > ConvertUtilsBean > Converter.
The interesting thing is that there is also a StringConverter which converts from String to… aaaaaa… String!
The ConvertUtils class has a register method which you can use to register convertors, overwriting the existing ones. This means you could write yourself the custom String convertor which returns null for empty strings and then you could wait for your Struts application to load completely so that you have no surprises (i.e. make sure your converter is the last registered for type
String).After the application loads, you step in and overwrite the default String convertor with your own implementation. For example, you could do that using a ServletContextListener and call the
ConvertUtils.register(...)in thecontextInitializedmethod.You then configure the listener in
web.xmland you should be good to go.