Online programs are by default statelessthat is, when you load a page a number of times in succession, the data in the page is reinitialized each time. If you want to track, say, the number of times the user has accessed the page, you need to specifically store that data somewhere.
In a standard desktop program, where you're interacting with the user while the program is running, you can store data in variables. That data won't be reset to its default values the next time you look at it. Using JSP sessions, you actually can do the same thing in JSPyou can interact with the user as part of a "session."
While the session is active, you can store data in it, and that data will be preserved on the server in between user accesses to the page. You can set your variables in one page access, and they'll hold the same data the next time you see the page, as long as the session hasn't timed out (the default session timeout is 30 minutes).
JSP session objects are based on the javax.servlet.http.HttpSession interface. The data you store in a session is stored as session attributes. You can use the session object's setAttribute method to store data, and you can use the getAttribute method to recover that data as long as the session is active. You'll find the significant methods of the javax.servlet.http.HttpSession interface in Table 5.2.
This is all best seen in an example. For instance, say you were trying to create a hit counter and therefore needed to store the number of times a page has been viewed. You're not going to get very far doing something like this, where you simply increment a variable each time a page is accessed, as shown in ch05_06.jsp:
<HTML> <HEAD> <TITLE>A non-working hit counter</TITLE> </HEAD> <BODY> <H1>A non-working hit counter</H1> <% int counter = 0; counter++; %> Number of times you've been here: <%=counter%> </BODY> </HTML>
The problem is that each time the JSP is displayed, all the data in it is reinitialized, which means that the counter variable will never hold more than 1, no matter how many times you view the page, as shown in Figure 5.8.
Figure 5.8. A non-working hit counter.