Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

spring

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

like image 478
k.elkourchi Avatar asked Feb 29 '12 10:02

k.elkourchi


People also ask

What is the difference between request setAttribute and session setAttribute?

Difference lies in the scope. Request-scoped attribute is visible only while current request is processed. Session attribute is persistent between several requests from the same user.

What is model addAttribute in spring?

1) addAttribute It adds the specified attribute under the supplied name. Model addAttribute(String attributeName, @Nullable Object attributeValue) attributeName - the name of the model attribute - can never be null attributeValue - the model attribute value - can be null.

What is difference between @RequestBody and @ModelAttribute?

@ModelAttribute is used for binding data from request param (in key value pairs), but @RequestBody is used for binding data from whole body of the request like POST,PUT.. request types which contains other format like json, xml.

Can we map a request with model attribute?

Method level ModelAttribute annotation cannot be mapped directly with any request. Let's take a look at the following example for better understanding. We have 2 different methods in the above example.


1 Answers

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).

like image 137
rompetroll Avatar answered Sep 20 '22 22:09

rompetroll