Difference b/w passing model and using request object at jsp/gsp - java

I have been working both on spring and grails (grails is built on spring).
We can pass our data from controller to view (jsp/gsp) via request object or via model.
Passing data via model is preferred because its easy.
Comparison of code :
Spring :
controller request.setAttribute("name","india");
view ${pageContext.request.getAttribute('name')}
controller ModelAndView("viewname",modelObject)
Grails
controller request.setAttribute("name","india")
view ${request.getAttribute("name")}
controller render(view:"viewName",model:[name:"india"])
I think request object does many functionalities other than this.
So my question is : If passing data from controller to view can be done with request object itself why java technology required to make a concept like model ?
necessity is mother of invention
I mean to say that there must be a task that can be implemented only via a model.

A few things come to mind, but they are speculation as to why.
Mainly, separation of concerns. Modifying the request, which is input, to hold output seems to be abusing this. The model is clearly ouput, and only output.
By clearly defining what constitutes output, using a model, frameworks such as Spring and Grails can then apply other processes to only the model. Grails filters come to mind, as an example.
That's my quick opinion.

That data which a controller gathers up and needs to make available to the view should be put in the model. That is kind of the definition of what the model is in this context. Never use request attributes for this.

Related

MVC pattern, no database, where to store objects?

I'm working on a school project and or task is to design a project management tool. We are allowed to use any design pattern as long as we can explain how it's good according to the GRASP principles.
I'll give a synopsis of the project tool:
CRUD-functionality for projects
CRUD-functionality for tasks (a project has tasks)
CRUD-functionality for users (a user is assigned to tasks)
A simple GUI
We decided to go with the MVC-pattern and we are not allowed to use a database. My question is: Where should I store objects?
Should I do this in the controller? Currently we do it like this:
public class ProjectController
{
private ArrayList<Project> projects;
public ProjectController(TaskController taskController)
{
projects = new ArrayList<Project>();
}
}
I have a feeling there is something wrong with keeping the objects in the controller but I can't explain why. Anyone that can explain what's the best practice according to the GRASP-principles?
EDIT:
Thank you, learned from everyone something but can only pick one answer.
For a very short answer : NO, don't put your store in the controller. This is a bad idea and it goes against the MVC principle.
Usually, the model is the only place responsible for your data BUT it is frequent that the M part is split into :
Fetching the data.
Storing the data in the application.
The interesting part in this is that, no one cares where your data come from. A database, a file, an API rest. whatever, it doesn't matter.
I'm not saying i have the best solution for you but here is how you could do this with an example.
You store your user data into a file.
You create a php class UserDataRepository that fetches the user data files, and sets the data into your UserModel class.
From the controller, you call your UserDataReposiroty and get back your UserModel.
This way your controller doesn't have any idea how you are fetching the data. He just asks a repository to fetch them and it returns the UserModel that the controller is allowed to manipulate.
I hope this will help you
Increase abstraction.. Create a model class. Create your arraylist (model objects) there. Your controller should still access/call model methods.
Tomorrow, you might want to dump that data into a file or into a DB, you will have one hell of a ride doing that with the current design. So separate your model from your controller and keep the design clean.
No. If you store data in the controller then you are not using MVC. You have to do it in the Model. You can store in memory or files, but always store data throw the model. For example, you could implement DAO pattern to manipulate data.
Maybe, not now, but then you will need a database. With DAO pattern, it won't be difficult to adapt your current persistence kind to a database.
In MVC pattern, M means models, V means view, C means controller. A common MVC application progress is that once a request is coming, controller get it and do necessary processing, retrieving results data, then pass the results data to view for rendering. After view layer is rendered, it displays to users via GUI.
So controller can be regarded as a commander, it controls process, but it is not good to handle data retrieving in controller. Model should be responsible for retrieving and organizing data. That means data objects should be stored in Model instead of Controller, Controller calls Model to retrieve data objects. Take Java application as example, usually these parts are needed:
ProjectController, it calls ProjectService.getAllProjects() method to retrieve result. Once retrieved, view layer use the result to render GUI for display. I suggest Controller layer should be thin.
ProjectService, it has method getAllProjects(), this method calls ProjectDAO.getAllProjects() method to retrieve projects data, and maybe other handling. Here business logic goes.
ProjectDAO, it has several methods which deal with Project objects, deal with data in this layer! But these methods should be independent with business logic(as business logic should be deal in ProjectService).
Project object.
Hope it helps.

Passing data back and forth from Spring MVC Controllers to Service layer

Could anyone suggest the best approach for sending data from controllers to service layer ?
I have UI <--> Controllers <--> Services <--> DAOs
I have models (or commands) to hold the data that user inputs in the UI to pass to controllers
I thought of creating models in controller layer , but don't want to pass them directly as service layer then depends on controller layer.
Do you suggest creating models in service layer and use them in controller layer ? But in this case these models will be used by jsps to serve data to the user ? is that ok ?
Could anyone suggest the best way in java to design the mvc layer shown above ?
Thanks
Ramesh
It's not necessarily wrong to serve domain model object directly to the UI layer, it's just that you tend quickly to run into a few common problems:
the view screen only needs a small subset of the model
certain fields like for example User.password you never want to send to the view layer
the domain model can contain loops, meaning object navigation paths in the object graph that go back to the initial object. This cannot be serialized correctly
lazy initialization exception on the domain model caused by detached objects
The common pattern to solve this is the DTO pattern, see here the description by Martin Fowler.
The common way to to it in larger applications is for the controller to send and received DTOs, and then do some mapping if needed to convert them into domain objects, this can be done for example with the Dozer mapping library.
On a smaller application this might not be justifiable, specially if you haven't encountered the problems mentioned above, although these tend to show up frequently.
Controllers take input from UIs and forward (hence the name Controller) the request to appropriate Model in tradional MVC pattern. But since you are using Spring MVC why not create your model objects in Spring context and use them is your service layer? You can use #Resource or #Autowired in service layer. Besides, if you want to reuse model objects you can easily do that because this way they are not locked into a particular layer. For eg., web service using your context.
Maybe others have a better way to do this.

Push vs Pull Model in MVC

What is the difference between the push & pull models of MVC?
Is Struts2, Spring MVC Pull based?
According to Struts2 Interview Questions and Answers
Struts2 is a Pull-MVC based architecture, in which all data is stored in Value Stack and retrieved by view layer for rendering.
Specifically:
In case of Push-MVC the data (Model) is constructed and given to the
view layer by the Controllers by putting it in the scoped variables
like request or session. Typical example is Spring MVC and Struts1.
Pull-MVC on the other hand puts the model data typically constructed
in Controllers are kept in a common place i.e. in actions, which then
gets rendered by view layer.
The concept of push and pull refers to what the server does in relation to the client. In a "push" application, a server is pushing or sending data to clients at it's own initiation. In a "pull" application, the server is pulling or waiting for and receiving messages initiated by clients.
A good explanation is given here mvc-pattern-its-importance-push-pull and here pull-vs-push-mvc-architecture
Struts1 and Spring both use Push MVC. This question might be helpful spring-mvc-complex-model-population-from-multiple-sources Struts2 uses Pull
Struts2, Play! and so on are all kinds of pull model implementations of the MVC pattern.
Terms "push" and "pull" refer directly to the type of implementation of the observer pattern used between View and Model. As stated in GoF Observer pattern explaination, we have:
At one extreme, which we call the push model, the subject sends observers detailed information about the change, whether they want it or not. At the other extreme is the pull model; the subject sends nothing but the most minimal notification, and observers ask for details explicitly thereafter.
This means that the implementation of push model requires that View and Model are implemented using the same language and they are executed in the the same environment. Good examples of this kind of implementation are Javascript single page applications, in which View and Model components execute inside the browser and a framework, i.e. Backbone, provides MVC (a.k.a. Observer) mechanism. Often, Model component interacts with some kind of server API, to persist and get persisted datas.
On the other hand, pull model lets you implement MVC using different technologies for View component, and Controller / Model components. In this kind of MVC, there is not an explicit use of the Observer pattern and View interacts exclusively with Controller. View component, which usually executes into the browser, sends to Controller component request of model's updates or model's state. Usually requestes are implemented using HTTP protocol. This kind of implementation requires the use of some type of "augmented HTML scripting language", such as JSP, which allows to create automatically the link between View and Controller.
Sorry .. I dont think that struts 1, struts 2 and spring MVC can be taken as PUSH MVC ..
as both of all frameworks use a front controller[Filer class for Struts , And Controller Listener for Spring ] defined in their respective deployment descriptor. Now both of all these frame work save the form data in their respective bean[Or model] object using that controller by reflection.
Now from our Action Controller we can receive the bean object and will get the values but in the front controller where the bean object[or model] is actually generated set the value in their resperctive field by using request.getParameter(param) or request.getParameterValues(param) methods internally.. So this can be considered as PULL.
So as per my thinking we can say that These framework can use two layers namely PULL layers used by end programmer and PUSH layers used by framework base classes.

Implementation of MVC

I am having some troubles understanding and implementing the MVC pattern.
I have a singleton "model" class which contains all the datas of the application and extends Observable. When those data are modified, I want to update the views, and when one of the views receives some input from the user, I want to update the model. In between stands a Controller (implements Observer) which has an instance of both the view and the model.
I think that to do this, the views must have an instance of the controller. Whenever it receives an event from a button or any component, it calls the correct controller's method, which transmit the informations to the model. The model is updated and notifies the observer which in turn will update every components of all the views, even if they are not linked to the particular data which has been modified, since the Controller can't know what has been modified in the model. I am not sure this is a good design.
I looked a bit upon the PropertyChangeListener class, which seems to correct this issue but I am not so sure that I understand everything. Is there any preferred way to do this ?
Thanks in advance !
There are a few issues with what you're suggesting.
First of all, you're describing MVVM, not MVC.
The second problem is that the terms model and controller aren't suppose to describe singletons. They are merely terms to help you separate concerns by organizing your logic into classes with well-defined responsibilities.
The MVC structure is as follows:
The Model
This is your application logic/business rules. This basically means that if your application is about a phone book, then all logic and data structures that have to do with providing a phone book API is implemented here.
The View
This layer is completely separate from the model, in that it doesn't care about data structures or logic, but only on presenting simple values. Strings, integers, collections, you name it. But it doesn't care about the model's API, it only depends on the controller's.
The Controller
This is where things come together. The controller is the mediator. It speaks the language of the model, and that of the view, and it can make them work together. User requests are routed to the controller.
For example, a request might want to list all numbers in the phone book. What happens is:
The controller receives the request
Asks the model for all numbers that exist in the phone book via the model's API
[Optionally] converts the data into a data structure which the view is intended to display
Passes the data to the view
One last remark before we finish:
If the controller doesn't convert data from the model into something simple, then allegedly the view is now tightly-coupled with the model. However, that doesn't always have to be the case. Even if the model's API changes, then the controller might still be able to adapt the new API into the old API, which the view already understands.

DTO vs Formbean

I'm developing spring MVC application and I used AirPortForm.java to get information in my airport.jsp. But I'm just wandering what is the standard method do I need to use AirPortDTO.java instead of AirPortForm.java kindly advice me.
Many thanks.
The Form suffix usually indicates that the object is meant to contain values coming from an HTML form (Spring calls these command objects).
The DTO suffix indicates that the object is a Data Transfer Object. A Data Transfer Object is an object, usually without much logic, which is used to carry information between the presentation layer and the service layer.
Use the appropriate suffix for you use-case, or use another one or not at all if your object is neither a form nor a DTO.
DTO use to transfer data between your database and application. Model View Controller (MVC) is one of the design pattern that separate your application with different layers. DTO is in model layer.In your application, you can use AirportFrom.java class only but it is not good practice.

Categories