What is the difference between request.setAttribute
and request.getSession().setAttribute()
?
Where are they stored and in which format?
问题:
回答1:
Difference :
When you use request.setAttribute
, you store something for the same request object. You can use this attribute later on when you do a forward from your current servlet/jsp to some other servlet/jsp.
When you use request.getSession().setAttribute()
, you store something for that particular user session. You can use this attribute whenever you want if the user session has not expired.
Where are they stored and in which format :
The servlet container will manage where to store the values. And the values are always stored as String
.
An example :
Let's say that there is an html page for entering student marks which is sent to some servlet X and you want to use those values in servlet Y. So you set the mark values in the servlet X request attribute and then forward to servlet Y and use those variables.
But let's say that you have multiple ui pages and when the user logs out you want to alert him with his name. So what you can do is, to store his name in request.getSession().setAttribute()
and in your logout page, you can get the value stored in session for the alert.