Originally posted by darine darine:
What is the difference of using setAttribute for session object and setAttribute for request ServletRequest ??
when do we use this over using that and in which cases?
The difference is the scope, i.e., the lifetime of your attribute. Session-scoped attributes remain visible as long as your client's session remains valid; you would use it to keep track of conversational state (user information, shopping cart contents, whatever).
Request-scoped attributes on the other hand remain valid only for the duration of the request. This is especially useful when a single request is handled by more than one
servlet or
JSP. For instance, you could have a controller servlet which creates a JavaBean with information which needs to be displayed (say, product information), binds it as a request attribute, then forwards the request to a JSP. The JSP then accesses the information from the JavaBean to generate the HTML. Once that has been done, the servlet engine discards the request object and, with it, the JavaBean.
In my experience, session-scoped objects are often used where request-scoped objects would be more appropriate. On one hand, this is a pity, because session-scoped objects consume valuable memory which scales with server load. Also, they formally need to be threadsafe (is there anyone who does this?) On the other hand, request-scoped objects have to be recreated for every request, increasing your application's object churn.
- Peter