spring - difference between request.setAttribute and model.addAttribute? - spring

can any one tell me the difference between request.setAttribute and model.addAttribute in spring web app?

The difference is, that Model is an abstraction. You could use Spring with servlets, portlets or other frontend technologies and Model attributes will always be available in your respective views.
HttpServletRequest on the other hand is an object specific for Servlets. Spring will also make request attributes available in your views, just like model attributes, so from a user perspective there is not much difference.
Another aspect is that models are more lightweight and more convenient to work with (e.g iterating over all attributes in a model map is easier than in a request).

Request V/s Model
where request could get attributes through getAttribute("") method. normally it is used for getting information from defined attributes and used inside the method for performing the different operations. So Basically Request used for input.
Just like Request, the model provides addAttribute("","") method, Through this model, we could make the object and storing data inside model object and deploying it on result Server Page.Basically it used in storing input data which is provide by us and storing for some time.

Related

Do backend web service API's have a view as in MVC?

Lets's say I have a backend web API. It takes in a web request and returns some json. Other services then consume that json and do what they will with it.
My question is twofold:
1) Does this backend web API technically have a view (v in MVC)? My thinking is no, since it doesn't actually display any frontend to the user.
2) Does the JSON object returned represent a model (m in MVC)?
Thanks!
1) Does this backend web API technically have a view (v in MVC)? My
thinking is no, since it doesn't actually display any frontend to the
user.
You are correct, it doesn't really have a View.
The Web API itself is simply going to return some data that was requested or something to indicate to the user that a request was performed properly (e.g. a JSON-formatted object indicating that a user was created, a collection of user objects, etc.)
Although a front-end could call the API and then use that information to render something, the Web API on it's own isn't going to do anything like that.
2) Does the JSON object returned represent a model (m in MVC)?
It can.
Each component of the MVC pattern plays an important role :
Controller - Responsible for things like data access and possibly populating a model.
Model - Responsible for representing the data that was accessed or for some type of operation.
View - Responsible for taking the model that was passed along from the controller and serving it to the user.
In this case, when you hit your Controller, you will likely be accessing some type of data and building a model. This model might use some business logic that you have designed yourself, or it might simply be content that was returned from your data layer, either way, the model, regardless of how it was created merely represents some type of data.
The "Model" is this case can be any type of data that you might decide to pass along to a View. Regardless of how it is serialized, if it is consumable either by a View or some other mechanism, you can think of it as a model.

Spring best practice to separate model from view in controller and jsp?

Is it a good practice to use Spring Controller class(with #ModelAttribute) and the jsp to prepare model at the same time or the model has to be prepared only by Spring and the view from the jsp?
The idea comes from this topic . I have a Controller class:
#RequestMapping(value = {"", "/"}, method = RequestMethod.GET, params = "mode=create")
public ModelAndView showCreatePage(#ModelAttribute("createForm") ApplicationCreateForm form)
{
return customMethod("some string");
}
and in my jsp I have:
<jsp:useBean id="createForm" scope="request" class="com.example.ApplicationCreateForm"/>
I do not need to populate the form with the information to be present to the user all fields are empty.
So from what I uderstand I have been declared ApplicationCreateForm bean twice, with the same scope - request.
Is it a good design practice to use both at the same time? Is there a reason for that? Does the second declaration(in jsp) give me more power, for example to override the model or it is complete unnecessary? Does the second declaration overrides the first one when both are present?
There are many things wrong with this implementation.
Is it MVC?
If JSP know about Model, why do we need controller. Lets remove the routing engine and use JSP directly to consume Model. But then the application will be monolithic. I believe you do not want that. We have two major flavours of MVC. In both, controller is the front facing object. It receives the command, interprets it, works with data layer and gets Model. If required the Model gets converted into a viewModel and then this object is passed to the view.
Why viewModel?
Say we are implementing paging on screen. We are showing list of persons. Person is your model here but your view also need to know page number, page size etc. Your model thus may not fit directly in this case.
Say we need data from multiple tables to shown on screen. This data is related in some way. Now will you pass separate model objects to view and let it do all the business logic? Ideally no.
Should not the design support DTO or ViewModel or Commands and Queries?
We want our application to be designed properly. As stated above we need to send data to view or clients (REST) after processing. Processed data may not map to you domain until unless we are just creating a CRUD stuff. What if you want to implement CQS or CQRS?
Where is separation, where is SOLID?
If my view is performing business logic then where is 'S'? If view knows about model and need to be changed in slightest of changes in model then where is 'O'?What if I want to separate queries from command (CQS) and scale the two things separately?
To conclude I would say, yes you can do this but it is not good if you are developing a decent size application or you think it will eventually be one. I have seen people using model entities starting from ORM, to controller to view. It will work but the question is do you want a monolithic and tightly coupled application. As per my experience the presentation logic (view) has very different logic and need of data in comparison of controller and same goes for your data access layer.
I think you should prepare your model fully in spring controller. Then view should be as passive as possible, ie. only showing model attributes received from controller while having no further knowledge about application logic. This approach gives you clean separation of concerns and you view is as independent as possible and can be easily switched for different view technology - eg. thymeleaf or freemarker templates. The whole idea of MVC is to separate presentation layer and by leaking business logic to view you create unnecessary dependencies.
Your view should be as simple as possible, as the logic leaked to view makes it very hard to test and reuse. On the other hand, if your logic is nicely separated, you can test it easily and reuse it easily. Ideally, business logic should be completly independent on web environment.
By defining you are creating tight coupling between your view and class com.example.ApplicationCreateForm, using spring mvc you achive loose coupling between your controllers, view and model it might happen that you change you model name but you still have same properties in it which might be enough for view, in above case you will need to update your view but it won't be required in case you are using Spring MVC.
Since spring comes with the concept of making things loosely coupled to make your code more testable, you should always keep in mind that separation of concern is your priority. So it is always the best practice to prepare your model fully in Controller, not in views.
Keep thing simple , make your controller responsible for preparing your model, and keep your views to display the model only.
So, a big NO to your question. The second declaration isn't going to make you powerful, rather help you to be tied up.

Get POST data in controller or model

I am learning CodeIgniter. I am wondering which one is the best practice to get the form POST data when updating the database: from Controller or from Model?
If we get the POST data in the Controller, then we need to pass the data as arguments to the Model function, but the Model function can be used in other forms. If we get the POST data directly in the Model, then we can eliminate the argument passing step, but it's limited to some specific forms.
Which one is the best practice?
Thanks.
It is best practice to handle your view code (form responses, etc) in your controllers, and then pass anything you need as parameters to your models.
This allows for the most reuse, as your model (and it's methods) can be reused, if, for example, you have a different view and controller requiring that model which processes forms in different ways (e.g. an API).
The best practice would be to do all data processing in the Controller and the service layer, and then pass only the required data to either the Modal or the View. That way, you have a controlled flow of information and a clean separation between the concepts. The Model objects should only be used as data objects via ORM, and nothing more. The controller should contain all business logic.

On MVC, clarification on object responsibility needed

Suppose, as part of an iphone application, I need to show user a list of some of some objects.
The model
Represents actual objects to be shown
Brainless data, collection of getters and setters
The view
Displays the list, passes received actions to a controller
Presentation layer
The Controller
Interprets actions received from the view and takes actions on data
Sits between the view and data
In this picture, would be be controller's responsibility to persist model to disk, or, should it be a part of Model's logic? Request to do this will come from a controller, but, should the controller know how to save data to disk, or should data know how to save itself to disk?
This is wrong.
Model is responsible for all the business logic. Additionally model is not directly aware of database or any other data storage medium. When model is initialized it receives factory for creating DAOs or DataMappers which are the ones responsible for storing and retrieving the informations.
Controller interprets the received information from view , and changes the state of model and view.
View either receives information from a persistent model via observer pattern ( classical MVC ) or request data from models ( Model2 MVC ).
I can see this going both ways. I would think that this logic goes into the model this way the controller is a little cleaner. Also, if you're using this functionality across models and it's mostly consistent e.g $person->saveData(), $user->saveData() then you could possible extend the base model so it would be inherited by other models and save you from duplicate code.
If this logic is incorporated into the model it would probably be a good idea to make it flexible enough so that the controller can override the persisting of data. So maybe, pass an argument into the model function $person->save( false ) This false would prevent the model from persisting the data but on default would be true.

How to name the layer between Controller and Model codeigniter MVC

I wanna restrict model to calling to db only
while controller will call model, libraries or helpers.
I do not want to put logic in controller nor in the model to prepare data for views.
Now the logic for preparing all the arrays for views are done in controller. I am creating a library to separate this part as sometimes i feel it is overloading the controller
Hence, i want to create a library class and make controller build the view data before throwing it to the view. It is not exactly templating.
The thing is i do not know how to name it.. Any good suggestion ?
I am thinking view_builder, ui_builder, ui_components?
Cheers
Here's how I'd layer the app:
View
Controller
Service
Persistence
View is either desktop or browser or mobile-based.
Controller is tightly bound to view. It's responsible for validating and binding input to model objects, calling services to fulfill use cases, and routing the response to the next view.
Services fulfill use cases. They know about units of work, own transactions, and manage connections to resources like databases. They work with model objects, other services, and persistence objects. They're interface-based objects, but can be remoted or exposed as web services - RPC-XML, SOAP, REST or other.
Persistence is another interfaced-based object. The implementation can be relational or NoSQL; the important thing is that the interface expresses CRUD operations for model objects. If you use generics, it's possible to write one interface that works for all.
I wouldn't have model objects persist themselves. I'm aware of the "anemic domain model" pejorative, but I think more exciting behavior should center around the business purpose, not CRUD operations.
Good setup. I also sometimes use CI libraries to work out the kinks in a returned data array before passing it to a view. I also sometimes just use the model.
And good for you for thinking about names - I think all the ones you mention are fine; you could also think about naming your library something like data_structure or array_to_object - or something more specific to your own problem like friend_map or tag_cloud.
My advice: pick a name, and then don't be afraid to change it if something more descriptive comes along or the function of your library evolves into something else. Find+replace is your friend.

Resources