View logic in spring MVC - java

Spring MVC application with JPA
I have flow of my application like:
#Controller
Class
---> returning a view (JSP) page.
Before returning to view I would like to modify contents or before sending it to entity persistence service layer , would like some values to be altered.Where shall I introduce those classes?
EDIT :
I am clear about rendering the data from database and displaying to front view.
What I actually want to ask is like :
A a = aService.findXXX(aId);
//here i want some operations to be performed for specific view while converting it to dto and sending it to UI.
Where the class for doing the same would be introduced else my controller will have very large line of code sp. to what has to be displayed to sp. view?

As #chrylis said, it's not very clear what you are asking. But if I understood you correctly, this will help you.
The usual pattern is that your #Controller has a #Autowired service reference
#Autowired
private MyService myService;
and that #Service has a #Autowired reference to DAO class (annotated with #Repository). Service encapsulates business logic, and DAO layer is responsible for interaction with database.
In your case, you would call some service method from controller, service would alter the entity and pass it down to DAO, and controller then fills the necessary data to Model which is used for rendering appropriate view.

Related

Am I still using spring-mvc (MVC architecture) if my backend only returns a json response to the frontend

There are a lot of definitions on what MVC is, but most of them say that the user contacts the controller and then the controller changes the view and sends it to the user. If I am using React.js for my frontend and calling endpoints in my controller, am I still using MVC pattern or not?
Is the #Controller even the same thing as the controller in MVC because in the definitions it says that the controller handles the application logic which in my case it does not I have service classes for that. I am writing an essay and I don't even know what type of application I am creating. It is driving me nuts.
Yep, it's still MVC. In this case you have controller (Spring #Controller or #RestController and React) model (services) and view (html generated by React). There is no strict definition what is MVC.
In MVC controller should not contain logic themself, but communicate with model (your services), this is the correct layered backend architecture. Otherwise, the Single Responsibility Principle is violated.
Spring Controller i.e., #Controller is the responsible person to provide the view the user requested if you need only the view page, it can be anything .html,.JSP and many more. So, if the user requested for any page either by the react.js or anything like angular then it calls the dispatcher servlet of the spring front controller and calls the handler mapper to which controller the user have requested.
If you requested something from the client to provide or do some crud operation then Rest Controller comes into the picture where #RestController...#Service...#Repository is been used.
So indirectly, the spring provides the way where developers can define the user request in the model view and controller format in which it segerrate the things separately and provides more convenient way to organise the code it looks like and spring have assigned annotations where it marks the class the responsibility it should behave.

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?
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.
So let me make sure I understand ...
The user interacts with an interface to view or submit data. The user calls on the interface to view some data. That call (an HTTP Request) goes to the Dispatcher Servlet (DS).
The DS then consults the handler mapping to help it decide which Controller to use.
Once chosen, the DS passes the request onto the Controller which calls the appropriate service methods, based on GET or POST. The Service method may need to interact with a Repository, which can interact with non-volatile storage (database, XML file, text file, etc), to construct a model based on defined business logic. Once complete, the model data is returned to the DS.
The DS then consults the View Resolver on which view should be used. The View Resolver picks a defined view for the request.
The DS then forwards the request onto the View, which is presented to the user.

Why we use service classes in spring hibernate integration

I want to know the use of service classes in J2EE.
I have 2 projects.
One is in spring hibernate integration.That project contain DAO,MODEL,SERVICE and CONTROLLER.Within that The request is access by the controller and send to the values to the dao class through the service class.
2nd project contain only BEAN,CONTROLLER and DERIVED classes.Within that the request is access by the controller and send the values directly to the derived class.Query is written in this derived class.
I want to know the difference between these two projects. Why we use service class ?
in my experience, service class contains all business , calculate, logic
for example in login module :
base on MVC pattern
Model class (DAO,MODEL is call model) : User, UserDAO
Controller : UserController
View : LoginPage
That's doesn't mean we cannot create another class like Service
we can have UserBusinessthis class contain all method, logic realted to User like validateUserLogin ... etc
application may work like :
User access LoginPageinput value and submit => UserController=> UserBusiness=> UserDAO
we need divide to easy handle and maintain
In spring we have some annotation like
#Business
#Repository
#Controller
that is a maker spring will create a object , we no need to using "new" keyword.
Controllers: are used to just delegating the calls, meaning once the request arrive on controller it will forward it to relative service
Services: Service are develop to write the business logic in general.
Dao: Data transfer object, which intend to deal with the DTO's
So, Briefly, when Spring MVC receive a call. I will lend to controller, controller than redirects it to respective service. Service performs business login if any on the api call and than delegated data updation to DAO layer.

sending a form to a service

I have a Spring form which is called AddNewItemForm and contains the validation annotations.
This form is the parameter of my Spring RestController addNewItem() method and it will be validated, the results being stored in BindingResults.
From my controller I need to call the service. Here is my question. Is it ok to have a method inside my service with this signature
public Item add(AddNewItemForm form)
or is it better to have it like
public Item add(Item item)
I am thinking that the form is only needed for the controller validation but the service doesn't need to know about it. It just needs to know how to operate with entities.
I suppose that I should construct my Item in the controller, with all the data I have and then pass this item to the service add(item) method.
Am I right?
Think of it in terms of dependencies: your web layer always needs to know about your service module and by passing the AddNewItemForm (which I assume exists in your web module/package) back to your service you now have a circular dependency.
Dependencies should only flow downwards:
Repository > Service > Web
From my point of view the service should not know about your command object (AddNewItemForm) since they are totally independent.
I agree with your last suggestion, you have to construct your model object before calling your service. Basically in your controller or with the help of an utility class.

In a MVC architecture, can the `View` access the model?

I have to build a website in MVC pattern.
I have a "showuser.jsp" view, I can access the Model (DAO) in order to get all the users,
or my controller should pass this information to my view?
A typical sequence of MVC flow is as follows
User sends a page view request
Controller receives the request
Controller queries the Model for the data
Modelreturns the data (List of users in your case)
Controller passes this data to the selected View (showuser.jsp) (generally as request/session attribute)
The View is rendered and returned to the user.
This is nicely depicted in the following image:
I hope this answers your questions.
Normally controller fills model for the view (JSP).
You controller should call DAO (even better if you have Service layer where all the business logic is implemented. Then controller calls the Service which may have one or mode DAO). And store the info in model to be represented on the jsp.
This should be seamless. The view should not be aware of the model as such but it should be passed through the controller, a common technique in Spring MVC would be to pass a hibernate object through the controller which would then get converted to JSON.
The View would then render this JSON object and parse it appropriately. In your example your controller could pass to the view a list of User objects which you could then parse if it was an array of JSON objects.
Your view should call a controller, which would return the response from either the DAO or Service layer (depending on your business logic requirements).
In the MVC pattern the model and view should no be aware of each other. The model and view are bound together by a controller. So the controller should pass the model to the view.
To put it rather simply in code:
class View{}
class Model{}
class Controller{
View view = new View();
Model model = new Model();
public void controllerMethod(){
//pass model to view
}
}

Categories

Resources