|
SessionsCookies are a useful way of link small amounts of information to a specific user, but suppose your needs are more complicated ?
eg, you have a form for data entry which is split over several pages, but you want all the information entered on the earlier pages to be 'stored' so that it can
all be processed in one go. One common solution is to use HIDDEN input tags inside the later forms to store the selections from the earlier forms eg :
When submitted, 'FirstServlet' would dynamically generate the form for the second stage of the process so that it includes the data from the first as part of the form :
This method is very reliable, but can be cumbersome. A much more effective method is to use an HttpSession. Sessions allow you to associate Java objects with a given user of the website (usually identified by a cookie, but this is automatic, so you don't have to worry about it). The Session stores these objects using Strings as keys, in use this is very similar to a Hashtable. The following Servlet picks up a parameter which the user has entered and stores it in a session. :
The second Servlet will try to pick up a pre-existing session and extract the stored parameters from it. It will then clear the session from memory. You may not always want to do this, if you have many servlets that need to pick up the data in the session and you can safely leave sessions 'behind', the Servlet engine will automatically clear out any sessions which have been inactive for a certain length of time. However, if you have a Servlet which represents a definitive 'end point' after which the session is not needed, you should explicitly call the invalidate() method to clear the session.
You can try out the sessions servlets below : Click here to test session
| ||||||||
|
Tims Home Page | Page last modified : 19 May 2003 | |||||||||