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

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
}
}

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.

Ways in which Controller (in Spring MVC) can provide the view name to DispatcherServlet?

I am working on a project, which is mainly using Spring framework.The views has been implemented using JSP and JSTLs.
Usually in various books / online tutorials which I read, the Controller class returns ModelAndView and based on what this object has, DispatcherServlet is able to return the correct view name.
Are there any other ways in which Controller (of Spring MVC) can specify the view name, for example returning a String?
Any pointer in this regards highly appreciated.
As Spring Documentation states:
All handler methods in the Spring Web MVC controllers must resolve to
a logical view name, either explicitly (e.g., by returning a String,
View, or ModelAndView) or implicitly (i.e., based on conventions)
So:
Is there any other way in which the Controller (in MVC part) can
specify the view name, for example returning a String?
Yes, you can just specify the view name as a String return value. Basically you can determine the view explicitly by returning:
A String representing the logical view name
An instance of ModelAndView
An instance of a View implementation, e.g. RedirectView

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.

View logic in spring MVC

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.

Spring MVC 2.5, JsonView, and ModelMap

I want many of my controllers to create and return ModelMaps and to have these ModelMaps subsequently sent to/processed by a JsonView. (These controllers will service AJAX requests.) I assume I need setup a ViewResolver; what is the best way to do this? Is there a better alternative to Spring-Json View?
EDIT:
How do I wire a view when my controller returns ModelMap objects rather than ModelAndView objects?
I'm not sure if it's a 'better' alternative to spring-json, but with Spring 3.0, you can just annotate some methods in your Controller, and it will return json or xml based on the HTTP Accept header.
See this blog post for more information.
What is the problem with using spring-json view?
This seems like the exact way you would want to handle something like this:
Your controller is ignorant of the view technology that will be used, it just returns a viewname and the data (model)
You configure a view resolver to transform this model into JSON (or HTML, or Excel, or whatever you would like)
/**
* Custom handler for displaying vets.
* Note that this handler returns a plain {#link ModelMap} object instead of
* a ModelAndView, thus leveraging convention-based model attribute names.
* It relies on the RequestToViewNameTranslator to determine the logical
* view name based on the request URL: "/vets.do" -> "vets".
* #return a ModelMap with the model attributes for the view
*/
#RequestMapping("/vets.do")
public ModelMap vetsHandler() {
return new ModelMap(this.clinic.getVets());
}
It relies on the RequestToViewNameTranslator to determine the logical view name.

Categories

Resources