Friday, September 26, 2008

The Domain Model and Struts 2.x

A couple of months ago I had a new requirement where I had to display the look (ui) of only a few of my components in my Struts 2.x application. Specifically, I had to display some dates as date-time while others had to remain the same. I started to hold down for a minute and decided to think how best to tackle the problem. I hate to touch a lot of code for no reason and as many know, changing the domain model code is typically not a good idea.

Struts2 MVC and Converters

In the good old days of Struts 1.x, one would have to register a special Converter object and register it so that BeanUtils can use it when ActionForms are populate via the ActionServlet (wao, I can't believe I had to learn all that). This was a good way to provide good conversion across all your application, however this approach forces the Converter to be applied in all objects of the same type.

As an MVC implementation, the controller should be able to have a way to know what conversion process to use in each action mapping processing session. Struts 2.x provides a way to do this in a clean way with the use of the StrutsTypeConverter class. After creating your own converter class, you can register your converter globally (in a file that must be named xwork-conversion.properties). Alternatively, you can create a -conversion.properties file at the same package level where your model object resides and now you can have custom conversion per property. The latter approach is a powerful feature as it allows you to define a properties file with key,value pair listings. Each key represents the name of the java property of the model object and its value is the fully qualified converter class name. This approach for conversion is very appealing for the following reasons:

  1. Does not mix Struts2 code with Domain Object model code (not even annotations), thus offering a non-intrusive approach to the rendering of the object.

  2. It encourages a development environment where this file can be generated, overriden or even replaced at build time. This scenario is very appealing for companies that do customizations of a product thus encouraging a "configuration management" approach in the presentation tier.

  3. It allows you to provide a different converter per property, leaving the model type unchanged.

I was able to successfully display each property as needed and progressively move each component that was required.

No comments: