Reputation: 281
Could anyone suggest the best approach for sending data from controllers to service layer ?
I have UI <--> Controllers <--> Services <--> DAOs
I have models (or commands) to hold the data that user inputs in the UI to pass to controllers
I thought of creating models in controller layer , but don't want to pass them directly as service layer then depends on controller layer.
Do you suggest creating models in service layer and use them in controller layer ? But in this case these models will be used by jsps to serve data to the user ? is that ok ?
Could anyone suggest the best way in java to design the mvc layer shown above ?
Thanks Ramesh
Upvotes: 1
Views: 3659
Reputation: 43087
It's not necessarily wrong to serve domain model object directly to the UI layer, it's just that you tend quickly to run into a few common problems:
User.password
you never want to send to the view layerloops
, meaning object navigation paths in the object graph that go back to the initial object. This cannot be serialized correctlyThe common pattern to solve this is the DTO pattern, see here the description by Martin Fowler.
The common way to to it in larger applications is for the controller to send and received DTOs, and then do some mapping if needed to convert them into domain objects, this can be done for example with the Dozer mapping library.
On a smaller application this might not be justifiable, specially if you haven't encountered the problems mentioned above, although these tend to show up frequently.
Upvotes: 3
Reputation: 769
Controllers take input from UIs and forward (hence the name Controller) the request to appropriate Model in tradional MVC pattern. But since you are using Spring MVC why not create your model objects in Spring context and use them is your service layer? You can use @Resource or @Autowired in service layer. Besides, if you want to reuse model objects you can easily do that because this way they are not locked into a particular layer. For eg., web service using your context. Maybe others have a better way to do this.
Upvotes: 0