What is the difference between method setAttribute()
of HttpServletRequest
class and setAttribute()
of HttpSession
class?
Under what circumstances are they used?
The one sets an attribute in the request scope and the other sets an attribute in the session scope. The major difference is in the lifetime of the scope. The request scope ends when the associated response is finished. The session scope ends when the session has been timed out by the client or server. When a scope ends, then all of its attributes will be trashed and they aren't available in a different request or session.
You use the request scope to store data which should be specific to the HTTP request (for example, the database results based on a specific request, the success/error messages, etc). You use the session scope to store data which should be specific to the HTTP session (for example, the logged-in user, user settings, etc). All requests by the same client share the same session (thus, all different browser tabs/windows within the same client session will share the same server session).
if you use httpServletRequest.setAttribute(); then attribute will be binded to that request object ,
while in httpServletSession.setAttribute();
will bind attr. in session.
so if you want the scope of that data to session use session
or if you need the scope of that data for just request use request
For Example:
UserName of logged in user should be shared across session so keep it in session
while, error message you are giving to user while consider authentication failure case, its needed for this request only after that we don't need so keep it in request
When you set an attribute on the Request object, the variable is available only on the scope of the request. That variable can be accessed by other jsp/resources which you forward as part of this request.
While setting an attribute on session scope will be available to all the requests in the user session (unless you remove it from session).
So the major difference it boils down is the scope/life of the attribute.
Always try to use request scope variables unless you need to use it across the user session ex: like user roles. Keeping more data on the session with more concurrent users may lead to out of memory issues. Also if you are using the session sharing backed by a database (like you can do in websphere), it will lead to performance issues.
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