Article
ASP Sessions and Applications
Putting it All Together
To demonstrate the use of Application, Session, and global.asa together in a single system, let's create a more practical and interesting version of the example we saw last time. In this example, users were prompted for their name, and were then welcomed by a personalized message at the top of each page they visited. This time, we'll use the Session object to track each user's name, instead of having to code every link on our site to pass the variable onto the next page. We'll also use the Application object to track the number of users on our site (and how many of those have given us their name).
To start, create a new global.asa file with the following contents:
1 <script language="VBScript" runat="Server">
2 Sub Application_OnStart
3 Application("users") = 0
4 Application("namedUsers") = 0
5 End Sub
When our application starts up, we set the two variables (the first of which tracks the number of users, while the second variable tracks users who have logged in by providing their names [named users]), to zero.
6 Sub Session_OnStart
7 Session.Timeout = 5 ' minutes
8 Session("name") = ""
9 Application.Lock
10 Application("users") = Application("users") + 1
11 Application.Unlock
12 End Sub
When a new user connects to our site (starting a new session), we set a Session.Timeout value of 5 (minutes) - the session will end after 5 minutes of inactivity (instead of the usual 10). We then create a variable to store the user's name (which he or she may eventually provide), and set it to "" (the empty string), which indicates that the user is as yet unnamed. We then Lock the Application object while we increase the number of users by one.
13 Sub Session_OnEnd
14 Application.Lock
15 Application("users") = Application("users") - 1
16 If Len(Session("name")) > 0 Then
17 Application("namedUsers") = Application("namedUsers") - 1
18 End If
19 Application.Unlock
20 End Sub
21 </script>
When a user leaves the site, and their session times out after the requisite 5 minutes' inactivity, we again Lock the Application in preparation for the changes we're about to make, and decrease the user count by 1. Next, we check the length of the string that's stored in Session("name") with the help of the built-in Len() function. If the string is longer than zero characters (i.e. ""), we know that the user has logged in by providing a name, so we also decrease the namedUsers count by 1.
Now we need to create a sample page on our site. Name the file default.asp and type the following code:
1 <% Option Explicit %>
2 <!-- #include FILE="login.asp" -->
3 <html>
4 <head>
5 <title>My Sample Application</title>
6 </head>
7 <body bgcolor="#FFFFFF" text="#000000">
8 <p><!-- #include FILE="welcome.asp" --></p>
9 </body>
10 </html>
The magic is in the <!-- #include ... --> tags. As there'll be a significant chunk of code involved in handling both the login process, and in displaying the tally of users, and since this is something we'll presumably want to handle on every page of our site, we're going to place the code for each of these functions in separate files (login.asp and welcome.asp respectively). This means we'll only have to type this code once in order to have all pages on our site share the same code. This <!-- #include ... --> tag basically inserts the contents of the specified file at the location of the tag, before the ASP code in the file is processed.
So our next task, obviously, is to create the login.asp and welcome.asp files. We'll start with welcome.asp:
1 <%
2 ' Displays welcome message or login prompt
3 If Len(Session("name")) > 0 Then
4 Response.Write("Logged in as: " + Session("name"))
5 Else
6 Response.Write("Not logged in. <a href=""")
7 Response.Write(Request.ServerVariables("SCRIPT_NAME"))
8 Response.Write("?login=1"">Log in</a>")
9 End If
We start by checking the length of the Session("name") variable to see if the user has logged in. If they have, we display the message /"Logged in as: name". Otherwise, we display "Not logged in", followed by a link for the user to log in. The code for this link may seem a little complicated at first, but bear with me as I explain it.
First we print out the start of the link tag (<a href="). Because we're already using quotes to tell Response.Write where the string that's to be sent to the browser begins and ends, we use double quotes ("") for the quotes that appear in this bit of code. The third quote is the one that marks the end of the string, as usual. Next, we output the "SCRIPT_NAME" server variable. As we have seen before, this will make the link point back to the very same page that is currently being processed. Finally, we tack ?login=1 onto the end of the URL, to signal the user's intent to log in (login.asp will watch for this, as we'll see in a moment). Next, we print out the tally of users (and how many are logged in) by simply outputting the appropriate Application variables.
10 ' Display tally of users
11 Response.Write("<br>" & Application("users") & " users online")
12 Response.Write(" (" & Application("namedUsers") & " logged in)")
13 %>
That's all there is to welcome.asp; now here's login.asp:
1 <%
2 ' User wishes to log in
3 If Request.QueryString("login").Count > 0 Then
4 %>
5 <html>
6 <head>
7 <title> Log In </title>
8 </head>
9 <body>
10 <form action="<%=Request.ServerVariables("SCRIPT_NAME")%>"
11 method="POST">
12 <p>Enter your name:
13 <input type="text" name="name">
14 <input type="submit" value="OK"></p>
15 </form>
16 </body>
17 </html>
18 <%
19 Response.End
20 End If
First, we catch page requests that result from the user clicking the "Log In" link generated by welcome.asp above. As we saw in the previous article, we spot this by checking if Request.QueryString("login").Count is greater than zero. When such a request is found, we display a simple page that prompts the user for his or her name. The form submits to Request.ServerVariables("SCRIPT_NAME"), so our next task in this script is to process submissions of this form, which will be marked by Request.Form("name").Count greater than zero:
21 ' User is logging in
22 If Request.Form("name").Count > 0 Then
23 Session("name") = Request.Form("name")
24 Application.Lock
25 Application("namedUsers") = Application("namedUsers") + 1
26 Application.Unlock
27 Response.Redirect(Request.ServerVariables("SCRIPT_NAME"))
28 Response.End
29 End If
42 %>
This code begins by taking the name submitted in the form (Request.Form("name")) and storing it in Session("name"). Then we Lock the Application and increase the number of named users by 1. Finally, we redirect the user to the page that was originally requested.
With all these files in place, load default.asp (e.g. http://localhost/myapp/default.asp) in a few instances of your browser, and you should see the system in action!
