Issue
What is the difference between method setAttribute()
of HttpServletRequest
class and setAttribute()
of HttpSession
class?
Under what circumstances are they used?
Solution
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).
See also:
Answered By - BalusC