Thursday, 17 January 2013

difference between request scope and session scope

setAttribute in HttpServletRequest vs setAttribute in HttpSession

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).

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.