简体   繁体   中英

Passing data back and forth from Spring MVC Controllers to Service layer

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

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:

  • the view screen only needs a small subset of the model
  • certain fields like for example User.password you never want to send to the view layer
  • the domain model can contain loops , meaning object navigation paths in the object graph that go back to the initial object. This cannot be serialized correctly
  • lazy initialization exception on the domain model caused by detached objects

The 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM