What's the difference between session.setAttribute
and request.setAttribute
?

- 25,822
- 8
- 77
- 77

- 139
- 1
- 1
- 11
-
6The scope..., session attribute live all the session and the request attribute only in a request – DGomez Jun 06 '13 at 20:20
-
Both use a key/value pair mechanism to store attribute values associating with corresponding keys. The difference is in the scope. – Lion Jun 06 '13 at 20:22
-
Does it matter which one I use, when passing an attribute from a servlet to a jsp? – ThePhantom05 Jun 06 '13 at 20:22
-
Why not? If you store a variable in a request, it will disappear (destroy) when the request is over. If you store a variable in a session, it will disappear (destroy) when the session is over. Request attributes are extensively used in MVC architecture. – Lion Jun 06 '13 at 20:27
-
@ThePhantom05 it is good to use request attribute.If you want to access that variable in another page or in another request then use session – PSR Jun 06 '13 at 20:28
3 Answers
The scope, session attribute live all the session and the request attribute only in a request

- 1,450
- 9
- 25
-
3Session attributes must be serializeable (it is very bad not to do so) because they can be unloaded to the hard drive or transferred to the another cluster node. Request attributes stays in RAM on the same JVM and has no such a requirement. – 30thh Aug 01 '14 at 14:57
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. Session support mechanisms may differ (the most widespread are cookie based), but all of them guarantee session attrigbute persistence until user's session stays the same.

- 11,233
- 9
- 54
- 64
Request attribute is only available in the request
object lifetime.
filters, servlet, jsp, include, forward
uses same request object.
Once the request is completed, request object is destroyed.
Whereas session attributes are available till the session ends or till the browser is closed. Hence the difference lies in the scope.
For example, the flow like page1->page2->page3->page4. session.setAttribute
will make the key available in all pages. But if we use request.setAttribute
in page2, then only page3 can get the key value set in page2.
request.setAttribute()
may help you in getting rid of the hidden fields.

- 3,341
- 6
- 24
- 52

- 13
- 4