Intent of Spring form command - java

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.

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.

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.

Related

DTO vs Formbean

I'm developing spring MVC application and I used AirPortForm.java to get information in my airport.jsp. But I'm just wandering what is the standard method do I need to use AirPortDTO.java instead of AirPortForm.java kindly advice me.
Many thanks.
The Form suffix usually indicates that the object is meant to contain values coming from an HTML form (Spring calls these command objects).
The DTO suffix indicates that the object is a Data Transfer Object. A Data Transfer Object is an object, usually without much logic, which is used to carry information between the presentation layer and the service layer.
Use the appropriate suffix for you use-case, or use another one or not at all if your object is neither a form nor a DTO.
DTO use to transfer data between your database and application. Model View Controller (MVC) is one of the design pattern that separate your application with different layers. DTO is in model layer.In your application, you can use AirportFrom.java class only but it is not good practice.

Web form frameworks in Java

What are commonly used ways to build web forms in Java and Groovy?
Spring and Grails provide corresponding taglibs, but I am wondering whether there are form frameworks, which allow to create forms as sets of objects, dynamically manipulate the elements, embed sub-forms, populate and validate, and render.
For example, if I have a group of fields common for a number of forms, I would like to reuse the code. Furthermore, such a group of elements, in turn, may be a part of another group. I also would like to dynamically reorder the elements, change field names and other input field attributes, and so on without altering any HTML code.
You can try open-source Formio library. It can be used in many environments/frameworks and with various template frameworks.
With Formio, you can manipulate forms using objects: Create form definitions - mappings, definitions of form fields and nested mappings (for nested objects like person's address or list of addresses). Both mappings and form fields can be defined as reusable (immutable) objects and composed together. You can use nested mappings to model reusable "groups" of form fields (and to nest them into another groups).
Formio supports binding of data from Java object to form definition that can be then passed to a template and rendered. Data from the request can be validated (using bean validation API) and bound back to the Java object (to newly created instance or to provided one). Binding of basic Java types, nested object types, collections or arrays (of primitives or complex objects) is supported. Immutable classes can be used.
Form definition can be prepopulated with data (before passing to the template) and filled back with (validated) data from the request. Automatic bidirectional data binding is implemented in "fill" and "bind" methods on the form definition object.
Formio is server-centric library, but can be combined with existing client-side libraries. Rendering is left to the template system. For example, using JSP you can prepare your own reusable tags to render form definition populated with data and its parts (nested mappings, various types of form fields) which already contain all neccessary data to render, including flags like visible, enabled, readonly, required. You can define your own custom field attributes and use them in reusable tags/template snippets so the HTML code need not to be altered in most cases.
Note: I am author of the library, you can find the sources on the GitHub and make your fork. Check the documentation for further details.
What you need is a templating/layout framework which will allow you to reuse snippets of code.
In the java web dev space, Tiles is the de facto framework for layouts. Both Grails and Spring MVC support Tiles.
I haven't come across an MVC framework that would expose a complete interface to handling form data as objects, in both ways. There is always some manual coding that is required to translate form data into objects, and back.
There are alternative frameworks, like Echo (http://echo.nextapp.com/site/) that completely isolate the application from dealings with requests and responses, they may be more suited for the kind of abstraction you are looking for.

POJO or DTO approach

I am developing a new web application with Struts2, Spring and Hibernate as its core building blocks.
We have created POJO classes with respect to hibernate mapping files.There will be some inputs from users which needs to be updated in to the underlying database
e.g registration or updation.
We have few option like creating new POJO/DTO for action classes which will be filled by the Struts2 and than we can transfer them to the service layer where we can convert those DTO to the respected hibernate POJO else we can expose same POJO to struts2 so that the framework can fill them with the user input and we need not to do the work for conversion and creating extra set of classes.
Application will be not big in size and will have a medium size application tag.
My question is what is the best way to transfer this user input to underlying hibernate layer to perform data base specific work.
Thanks in advance
I'd prefer the "DTO" approach in this case since you then can validate the input first and trigger updates only when wanted.
However, you could use detached entities as DTOs and reattach them when you want to create or update them. If you don't want the web part of your application to depend on Hibernate and/or JPA you might need to create another set of classes (unless you don't use a single annotation).
You'll get both answers on this.
With Struts 2 I tend to use normal S2 action properties to gather form values/etc. and use BeanUtils to copy them to the Hibernate objects. The problem with exposing the Hibernate objects to the form, like with ModelDriven etc. is that you need to define whitelists/blacklists if you have columns that should not be set directly by the user. (Or handle the problem in a different way.)
That said, I'm not fundamentally opposed to the idea like a lot of people are, and they're arguably correct.

Spring MVC: should service layer be returning operation specific DTO's?

In my Spring MVC application I am using DTO in the presentation layer in order to encapsulate the domain model in the service layer. The DTO's are being used as the spring form backing objects.
hence my services look something like this:
userService.storeUser(NewUserRequestDTO req);
The service layer will translate DTO -> Domain object and do the rest of the work.
Now my problem is that when I want to retrieve a DTO from the service to perform say an Update or Display I can't seem to find a better way to do it then to have multiple methods for the lookup that return different DTO's like...
EditUserRequestDTO userService.loadUserForEdit(int id);
DisplayUserDTO userService.loadUserForDisplay(int id);
but something does not feel right about this approach. Perhaps the service should not return things like EditUserRequestDTO and the controller should be responsible of assembling a requestDTO from a dedicated form object and vice versa.
The reason do have separate DTO's is that DisplayUserDTO is strongly typed to be read only and also there are many properties of user that are entities from a lookup table in the db (like city and state) so the DisplayUserDTO would have the string description of the properties while the EditUserRequestDTO will have the id's that will back the select drop down lists in the forms.
What do you think?
thanks
I like the stripped down display objects. It's more efficient than building the whole domain object just to display a few fields of it. I have used a similar pattern with one difference. Instead of using an edit version of a DTO, I just used the domain object in the view. It significantly reduced the work of copying data back and forth between objects. I haven't decided if I want to do that now, since I'm using the annotations for JPA and the Bean Validation Framework and mixing the annotations looks messy. But I'm not fond of using DTOs for the sole purpose of keeping domain objects out of the MVC layer. It seems like a lot of work for not much benefit. Also, it might be useful to read Fowler's take on anemic objects. It may not apply exactly, but it's worth thinking about.
1st Edit: reply to below comment.
Yes, I like to use the actual domain objects for all the pages that operate on a single object at a time: edit, view, create, etc.
You said you are taking an existing object and copying the fields you need into a DTO and then passing the DTO as part of the model to your templating engine for a view page (or vice-versa for a create). What does that buy you? The ref to the DTO doesn't weigh any less than the ref to the full domain object, and you have all the extra attribute copying to do. There's no rule that says your templating engine has to use every method on your object.
I would use a small partial domain object if it improves efficiency (no relationship graphs to build), especially for the results of a search. But if the object already exists don't worry about how big or complex it is when you are sticking it in the model to render a page. It doesn't move the object around in memory. It doesn't cause the templating engine stress. It just accesses the methods it needs and ignores the rest.
2nd edit:
Good point. There are situations where you would want a limited set of properties available to the view (ie. different front-end and back-end developers). I should read more carefully before replying. If I were going to do what you want I would probably put separate methods on User (or whatever class) of the form forEdit() and forDisplay(). That way you could just get User from the service layer and tell User to give you the use limited copies of itself. I think maybe that's what I was reaching for with the anemic objects comment.
You should use a DTO and never an ORM in the MVC layer! There are a number of really good questions already asked on this, such as the following: Why should I isolate my domain entities from my presentation layer?
But to add to that question, you should separate them to help prevent the ORM being bound on a post as the potential is there for someone to add an extra field and cause all kinds of mayhem requiring unnecessary extra validation.

Spring formBackingObject, Business Object Creation, and Factories

Design question for using Business Objects as formBackingObjects in a Spring SimpleFormController.
Our controller's responsibility is to allow an End User to add a new Business Object to our web application.
So we are passing our Business Object though the formBackingObject(HttpServletRequest request) method. However, we've run into a conundrum.
The factory that we are using to create our new Business Object enforces the business rules that some of the attributes cannot be null. But since we don't know what the End User wants to enter we've been passing in "reasonable defaults" like "Please enter the name you want", but that seems hackie/icky at best.
What is a developer to do? I feel as though this is the classic chicken/egg problem.
All our Business Object are based off of Interfaces, should we create a Stub that represents the Business Object, pass the Stub as the formBackingObject, and then pass the Stub to the Factory on a Form submit? Or should we not pass anything in the formBackingObject and then manually gather the submitted information from the request?
Any other reasonable ideas/patterns?
Thank you for your time.
I definitely wouldn't choose the option of not using a formBackingObject and gathering the information manually -- that would eliminate a lot of the power that makes Spring MVC worthwhile in the first place.
If I were you, I would just make a new factory, or factory method, that is designed specifically to create an "uninitialized" business object, and use that as your formBackingObject.
Another approach that is widely used is not to use a business object as your formBackingObject at all, but create a separate transport object whose only purpose is to be the formBackingObject (and then add a factory method for your business object that lets you initialize it from the transport object). One of the big advantages of this is if your business object has a deep tree of other objects inside it, this can make it a pain to use as a formBackingObject. If you create a separate transport object just for use as a formBackingObject, you can give it a much flatter structure.
Use a command object (a dead simple POJO) to represent the user's input to your controller. Then you can use the validation built-in to Spring MVC to make sure that all of the required fields are supplied in the command object. If the command passes validation, then you can map it to a your "Business Object" programatically (or using a bean mapping library like Dozer).
This way you can handle validation, incomplete user submissions, etc., without touching or modifying any existing business logic / rules / service classes. This allows you to keep the web layer separate from these existing layers.
For reference, see the MVC tutorial, which touches on validation and command objects in Part 4.

Categories