Session is a state management technique to keep track of the server-side user activities. As we know that HTTP does not maintain a user state, so ASP creates a unique cookie for each user. The cookie is sent to the user and contains information that identifies the user. This is done through the Session Object.
The session object stores variables such as the name, id, and preferences. This object is common for all the associated pages of the application. The server creates a new session object for each newly joined user and destroys the session whenever the user’s session expires.
A session is created whenever:
A session expires after the user is idle for some time. By default, this timeout is set to be 20 minutes.
We can change this default value by changing the Timeout property.
The example below sets a timeout of 10 minutes:
<%
Session.Timeout=10
%>
The Abandon property allows destroying the session immediately.
<%
Session.Abandon
>
The Session object can store different variables in it, accessible to any page in the application.
This example shows how to store a variable in the Session object:
<%
Session("username")="Lio Messi"
Session("driversLicense")="FX-101"
%>
We can retrieve the variables by accessing the key we stored in the Session:
<%
Session("username")
Session("driversLicense")
>
To access all the variables stored in the Session object, we can use the .Contents
method and loop through it:
<%
dim i
For Each i in Session.Contents
//execution
Next
>
To remove a variable from the Session object, we can use the Remove
method.
The following example removes the session variable “eligible” if the value of the session variable driverLicense
is empty:
<%
If Session.Contents("driverLicense") == "" then
Session.Contents.Remove("sale")
End If
%>
We can also remove all variables in a session by using the RemoveAll
method:
<%
Session.Contents.RemoveAll()
%>
Free Resources