This is a question I always wanted to ask. We always read that it is better to use request object when we have to carry data from one page to other. Now let's say I have about 10 different data items that I need on 4-5 pages. Is it better to use a session variable, or is there an alternative to that? In my app I have about 10 menus where each menu performs different operations. In each such menu I have such different data which are not common between menus. Which is the best way to handle this?
You could dump stuff in the session, or you could just fetch it when you need it and then forget about it again. Me - I tend to go for the latter nowadays. To less you have to keep track of in memory, the less chance you have of that information going out of sync. Machines nowadays have plenty of resources at their disposal, you don't have to cache stuff to save some CPU cycles. Bearing in mind there are exceptions to every rule of course, when it takes a good deal of time to fetch data (like from a web service), it might pay off to cache it. But then I'd use a proper caching solution and not the session.
If the data that you want to share on multiple pages are not related to the user or client then storing data in the session is not the ideal way because when session is destroyed the data is destroyed and you have to fetch the data again with the new session so store the data in the servlet context object . context will not be destroyed until you shut down the application so one time fetch will be enough. If the data is related to the client or user then the better option is session.