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
?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With