Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 977
java123999 Avatar asked Feb 26 '16 00:02

java123999


2 Answers

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

like image 66
Ken Bekov Avatar answered Nov 15 '22 09:11

Ken Bekov


A controller accepts HTTP requests and often loads or save some data (from a service or DAO), and return an HTTP response. This response could be a redirect, or a view, or some JSON or a binary file.

A controller can use services, but should avoid having much logic of its own. It can also directly use data access objects, if there's no service logic required.

The model is whatever info a view needs to do its job. It is not necessarily related to a database. For example, you could have a model in a registration form, with email address and confirmEmailAddress fields. You don't store a confirmEmailAddress field in your db, so they there is not a 1-to-1 relationship between db tables and models. Also, your model could be data for a simple calculation that is not persisted.

like image 40
Neil McGuigan Avatar answered Nov 15 '22 08:11

Neil McGuigan