Search code examples
javaspringspring-mvcmodel-view-controllerservice

How does Spring MVC relate to Service, Controller and Data Access layers in a web application?


I understand the MVC Pattern and also how Spring MVC implements it.

However, how do the Rest controller, Data Access Layer and Service Layer fit into this pattern?

Is it:

  • Model = Database (e.g. Oracle/MySQL) and Repositories classes

  • Controller = Service (buisness logic) and Rest Controller classes

  • View = JSP / FreeMarker?


Solution

  • Model - is not a Database, is not a Repositories, is not an Entity. Model is abstraction, that contains all data, that is needed to be displayed. And every View has it's own model. You can consider Model as container for data between Controller and View.

    In Spring model is ModelMap parameter of method of controller.

    Controller - prepares Model, to pass it to View. If model is quite simple, Controller can do it by itself.

    But most of models contains a lot of data. This can be multiple Entities from database, data from configuration etc. In this case Controller use lower level tier: Service, Repository. They all help the Сontroller to build model for View.

    upd: It is a purpose of Controller to connect View and Model. Controller creates and fills the Model, then chooses View and pass this created Model to the View. That's how Model and View get connection.

    In Spring controllers are Controller and RestController.

    View - is final point where data from Model (passed by Controller) will be displayed to user. But another role of View is get commands from user, and pass it to Controller.

    In Spring this may be view of any view-engine: JSP,Freemaker,Thymeleaf.


    Note: usually, Controller does not use Repository directly. Traditionally, Controller works with Service, and Service uses Repository to get data from database. So relations are following: View<-Controller->Service->Repository