can any one tell me the difference between request.setAttribute
and model.addAttribute
in spring web app?
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.
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.
@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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With