Session object
What's a session?
We speak of a session when a user requests a page on a website. All
the pages that the user opens (within the site) belong to the same session. A session ends when
a user closes the browser or when a user hasn't requested any pages during a certain amount of
time.
What is the Session object?
Within a session it's practical to save data that's relevant for the user,
like a username and password so that we know if the user has access to certain data.
It would be awkward for the user to supply this data everytime. We can save this data in the
Session object. The Session object works
almost the same as the Application object, with
the difference that the data in the Application
object is "visible" for all users. This also means that no locking of the data as with the
Application object is required.
session1.asp
<HTML>
<BODY>
<%
Session("Counter") = Session("Counter") + 1
Response.Write Session("Counter")
%>
</BODY>
</HTML>
If you would execute the code above several times, you would think it does exactly the same
thing as the Application object.
Even if you would open a new window of the browser, the counter just counts on.
That's because that browser is opened everytime by the browser from where you're reading in now.
If you would close this one also and then open a new browser, then there would be a new session
and the counter starts again at 1. You can also start a new browser (from the Start menu) and
then request the page again.
How does the Session object work?
The values in the Session object are saved in the memory of
the server. To keep track of which session belongs to a user, a cookie
is sent to the browser with a unique value in it: the SessionID.
Every time the browser makes a request, this cookie is sene with the request and the server will
know which session it belongs. This cookie becomes invalid when the browser is closed, or 20
minutes have passed since the last request.
session2.asp
<HTML>
<BODY>
<%
Response.Write Session.SessionID
%>
</BODY>
</HTML>
Browsers that don't accept cookies, can't work with sessions.
Adding to this, if you store a lot of values in the Session
object this has disadvantages for the server speed. So only use this
when it's really necessary.
The Session object has more possibilities. Because they
aren't used very often, these possibilities aren't part of this lesson.
|