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.
Related
In simple terms, why do we need 'a bean to bean mapping service' (like Dozer) in a web-application.
Suppose I'm working on a web-service.
I'm receiving an XML in request.
I fetch the the values from XML elements.
Perform the required operation on the fetched values.
Prepare the response XML.
Send the response XML as response
Why should I add one more steps of mapping XML elements to own custom elements.
I'm not able to convince myself, probably because I'm not able to think of a better situation/reason.
Please suggest, with example if possible.
It helps to reduce coupling between the presentation (i.e. the XML schema) and the business logic. For example in case of schema changes you don't have to touch the business logic, just the mapping between the objects.
In simple cases it might not be worth the additional complexity. But if the objects are used extensively in the business logic component you should consider it.
Just as a quick answer, the case you described is not the only one :).
Suppose you are working with an internal library providing some POJO / entity / other beans. You want to abstract from the internal representation (for a reason or anohter), you then want to map those bean to yours. It works :
for ejb client, or somehting like that,
when you don't want to expose internal entities (Business Object vs Presentation object) (see #Henry's reply)
you have beans that don't inherit from the same parent (and can't for any reason, even leacy) and you want to tarnsfert value from on to another
There are plenty of (other) reasons :)
As an advice see also orika
and this post :
any tool for java object to object mapping?
Short answer for me as henry said it helps reduce coupling between what you expose or consume and your core data model.
It is one way build Hexagonal Architecture. You can freely modify your core model without impacting the exposed model. In hexagonal architecture, it is used to expose only a small relevant part of the core model.
It is also a very goog way to handle services and model versionning since multiple versions can be mapped to the core model.
When working with XML services I tend to build contract first application so, I first write the XMLSchema then generate Jaxbeans and I realy don't want my business code to be polluted by JAxb annotations.
If you know that your exposed model will always be the same and that your application does not fall in the previously mentionned cases, so you realy don't need to use DTO.
Last, I would recommend using a framework with strong compile time checking like Selma instead of Dozer or Orika because they are evaluating the mapping only at runtime which is weak typing and sensible to refactoring.
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.
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.
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'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.