This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Request attributes are used to share information between different J2EE components that play a role in processing a single request. For example, if a servlet controller validates a request and forwards it to a JSP, the servlet could place validation errors in the request. These are no longer relevant after the response is rendered, and are discarded. On future requests, if you try to retrieve them, you will get a null value.
Request attributes come into existence when added to request object and go out of scope as soon as request processing has completed (unless you remove them first). By completion of request processing, I mean the last component that handles the response, such as a JSP or a filter or a servlet. You can run tests on scope by implementing listeners such as ServletRequestListener and ServletRequestAttributeListener.
On the other hand, if you need to display user name on all pages that a user visits after the user has logged in, you'd store a user object in the session. Thus the object would be available to all components of across requests that come in while the session is still active. You could test this by implementing HttpSessionListener or HttpSessionAttributeListener.
Request object lives till the time the request is being processed and the response is sent back to the client. Means per hit, per request you can say.
Whereas, the Session object exists till the time your total session or interaction is done.
You can compare this with the realtime scenario in this way.
Once you login to a web application, lets assume the LOCALE is being considered. So, every page which is displayed should contain the values of that particular locale where the user belongs to. Which object we can associate this with? Request or Session? - it should be session.
You click on the Employee Details - it should fetch a different result. You click on the PaySlip details - it should fetch a different result. - these values should live till the result is fetched. - Request Object. Once the results have been obtained, there is no point in keeping the values attached with the Request Object.