views:

915

answers:

2

Spring's form controller (such as SimpleFormController or BaseCommandController) uses commands to pass data between the HTML form and controller. My question is, is it common practice to use the backing model as the command itself? Or is it common to create a separate command with correspond attributes to those in the backing model.

My issue is that to use the backing model as the command, property editors are necessary for conversion of non-string attributes. Imagine a data model with many non-string strongly typed custom field types. On a form submission, property editor does the conversion before the validator is called. If the type conversion is not possible (user input error), then the validator never gets a chance to provide a detailed error message. All that's displayed on the HTML form is a generic error message. See my related Stackoverflow question.

The alternative is to create a separate command that duplicates each field in the backing model, but as a string. In this way the validator can validate the string representation of each field. The controller's onSubmit is then responsible for converting the text-based command to the backing model. From my research of Spring this appears to be intended usage. My hesitation to go down this path is the cumbersome manner in which a separate command needs to be created for each data model. Then there's the added work having to marshal between the command and the data model. It's so much more convenient to have the form directly edit the backing model and use property editors to do the conversion. The problem then is validation.

So I'm curious how others approach the issue of form-based editing of models that contain custom typed non-string fields.

+2  A: 

I'd recommend that you look into the Spring binding and validation API. Bind the form elements into the objects that the service layer needs and have the controller pass them along.

My preference is to bind directly to business objects and not create DTOs just for the sake of the web tier. I don't like parallel hierarchies.

duffymo
A: 

IMHO this boils down to how you want to design your domain classes. I prefer to design 'em qiute strict by not even allowing setting inapropriate values etc. This does not combine very well with the way Spring handles binding and validation.

As I want to avoid weakening my domain model I tend to use DTOs as command objects as typically the presentation gets a slightly different view on the domain objects anyway. The classic example is a User domain class that carries a password. In the presentation layer you typically would want to let the actual user the password twice and compare those values in validation step. Only if they match correctly the data would be bound to the domain class.

Might introduce a little overhead but allows to cleanly separate domain/application layer from the view.

Oliver Gierke