The ASP Objects
Active Server Pages has several built-in objects accessible from script code. So far, you have seen some examples of the Response and the Server objects. In this section, you explore these objects in a little more detail and give examples of their uses. The objects are as follows:
-
Session
-
Response
-
Request
-
Server
-
Application
Managing Security with the Session Object
As alluded to earlier, IIS has features that allow your ASP application to retain information between pages. You can, for example, have a form in which the user selects a country from a list and then submits that value to an ASP page. The ASP page can store this value on the server so it is available to other ASP pages. This is accomplished through the use of session variables. Session variables are declared and accessed like a collection. To create a session variable, simply give it a name and value:
Session("Country")="United States"
One frequent use of ASP session variables is to manage security. When database information is on the Internet, you probably do not want everyone in the world to be able to update it. Additionally, you might want to restrict access so that only certain people can see certain information. If you want to add security to your Web site, the obvious solution is to display some type of login page so that only valid users can get into your site. Your login page can be a simple HTML form with fields for user name and password. The form submits these values to an ASP file that checks the user name and password for validity.
But even if you add such a login page, how do you prevent users from simply entering the URL they want and bypassing the login screen? The answer is to use session variables. Suppose that you have an ASP file, REPORT.ASP, that you want to secure. You can add a simple If statement at the top of the page to verify that a session variable has been set:
<% If Session("UserName")="" Then Response.Write "You are not logged in!<BR>" Response.End End If Response.Write ("Welcome, " & Session("UserName")) %>
The If statement checks the contents of a session variable called UserName, and ends the response from the Web server if the value is empty. In other words, the contents of REPORT.ASP after the If statement are available only to users who have the session variable UserName set to a value.
TIP
If you have multiple pages that you want to secure, use an include file to make the security check easier to maintain.
To validate a user login and set the UserName session variable, you need to write some ASP code. This code, shown in Listing 31.6, checks the information from the login form and sets the session variable if the user's password is correct.
Listing 31.6 Verifying Logins Against a Database
<% Dim cn Dim rs Dim sCheckName Dim sCheckPW 'CLEAR SESSION VARIABLE Session("UserName")="" 'GET USERNAME AND PASSWORD FROM THE FORM sCheckName = Request.Form("txtusername") sCheckPW = Request.Form("txtpassword") 'IF THEY DIDN'T ENTER ANYTHING THEN RETURN TO LOGIN PAGE If sCheckName = "" then Response.Redirect "login.html" 'CHECK USER PASSWORD IN THE DATABASE Set cn = Server.CreateObject("ADODB.Connection") cn.Open "Driver=Microsoft Access Driver (*.mdb);DBQ=C:\data\security.mdb" sSQL = "SELECT * FROM UserList WHERE UserName='" & sCheckName & "'" Set rs = cn.Execute(sSQL) 'IF THEY AREN'T IN DATABASE THEN RETURN TO LOGIN PAGE If rs.EOF Then rs.Close cn.Close Response.Redirect "login.html" End If 'IF PASSWORD DOESN'T MATCH THEN RETURN TO LOGIN PAGE If UCase(rs.Fields("Password")) <> UCase(sCheckPW) Then rs.Close cn.Close Response.Redirect "login.html" End If rs.Close cn.Close 'PASSWORD IS VALID! - SET SESSION VARIABLE Session("UserName")=sCheckName 'GO ON TO REPORT PAGE response.redirect "report.asp" %>
The code in Listing 31.6 makes use of the Response.Redirect command, which redirects the user's browser to a new URL. Unless he or she enters a valid user name and password, he or she is continuously redirected back to the login page. If this were a real application, you might want to have a counter that alerts an administrator after a certain number of failed attempts.
CAUTION
The type of security described here can be thought of as application-level security. It does not provide network-level security. For example, someone could use specialized hardware to listen to the network transmissions to and from the Web server—much like tapping a telephone line—to determine your password. To prevent this kind of spying, you need to investigate a secure connection using the https protocol.
Because a browser operates on a request-and-response basis, the user does not really establish a continuous connection with the Web server. Therefore, the server has no real way of knowing when the connection is broken, so a session will time out after a certain number of minutes. You control this with the TimeOut property of the Session object:
Session.TimeOut = 60
Executing the previous statement causes the timeout to be set to 60 minutes. After 60 minutes of inactivity, the server ends the user's session, destroying any session variables. You can also purposely end a session with the Abandon method, as in the following line of code:
Session.Abandon
Controlling Output with the Response Object
Another useful object in Active Server Pages is the Response object. You have already been introduced to Response.Write, which is used to send HTML or other text back to the browser.
The Response.Write Statement
You can build a string in the Response.Write statement by using the string concatenation operator (&),as in the following example:
<% Response.Write ("Hello, " & Session("USERID") & "<BR>") %>
NOTE
You can also use the short script tags and the equals sign (=) to send
the contents of a variable back to the browser, as in the following example:
Hello, <% =Session("USERID") %><BR>
I prefer using the Response.Write method, but this short form is
good when you need to embed a simple value in your HTML.
In addition to standard HTML, you can use Response.Write to generate client-side script from the server. For example, consider the following segment of ASP code:
<% sString = "This is an ASP variable" Response.Write (vbCrLf & "<SCRIPT LANGUAGE=VBScript>" & vbCrLf) Response.Write ("Msgbox " & Chr(34) & sString & Chr(34) & vbCrLf) Response.Write ("</SCRIPT>" & vbCrLf ) %>
The preceding code actually generates VBScript statements that will be executed by the browser. The Response.Write statements execute on the server, causing <SCRIPT> tags and code to be sent back to the browser. In other words, you use code in an ASP page to generate code for the browser. This might seem confusing at first, but if you type in the example and view the source in the browser, it will make more sense. Also, note that you paid particular attention to quotes and carriage returns in the client code, just as if you had entered it manually.
One use of server-generated client script is to control an ActiveX object embedded in a Web page. For example, your ASP page could contain the <OBJECT> tag for a list box or other control, plus the dynamically generated statements to add specific data items to it.
The Response Object and Other Methods
In the security example, you learned about two other methods of the Response object: Redirect and End. The End is used to end the current response to the client, as in this example:
<H1> Here is some HTML the browser will see! </H1> <% Response.End %> <H1> but the browser will never see this! </H1>
The Redirect method is used to ask the browser to move to a new URL, as in the following example:
<% Response.Redirect ("http://www.callsomeonewhocares.com/" %>
The previous line of code works only if no HTML has been returned. In other words, if you attempt to use Response.Redirect after a Response.Write, an error occurs.
One property of the Response object that you should have mentioned in the security section is the Expires property. As you might know, the browser stores everything it reads from the Internet temporarily on your hard drive. This group of temporary files is known as the cache. Certain files, such as graphic images, are ideal for storing in the cache. Others, such as the login page (with name and password), are not. You set the Expires property to the number of minutes you want the page to remain in the cache. For the security page, you would probably want to set it to zero, as in the following example:
Response.Expires = 0
The Response object is also used to send cookies to the user's browser. Cookies work like session variables, but are stored on the client PC. (IIS actually uses cookies to help maintain the session IDs.) Cookies are useful when you want to save personal settings on a user's hard drive and retrieve them later. However, cookies are not guaranteed to be available—a lot of users consider them an invasion of privacy, so they disable them. To send a cookie to the user's browser, simply assign a value as you would with a session variable:
Response.Cookies("MYCOOKIE") = 1234
A similar Cookies collection used with the Request object is used to retrieve cookie values.
Retrieving Data with the Request Object
The Request object allows ASP code to access everything about an incoming browser request. You already know that you can use the Request object to get the value of a parameter in an URL by using the parameter name with the QueryString property. Like many other collections, QueryString has a Count property and an index, which allow you to iterate through the values:
Dim n For n = 1 to Request.QueryString.Count Response.Write ("Parameter " & n & "Value = " & Request.QueryString(n) & "<BR>") Next
You can also receive information from HTML forms with the Form collection of the Request object. For example, if you have a form field name txtLastName, you can display the value submitted with the following code:
Response.Write "You entered " & Request.Form("txtLastName")
As you can see, a lot of the information in the Request object is accessed through collections. You can use a For Each loop to list all of the objects in a collection. Listing 31.7 displays all of the information in the Request.Servervariables collection.
Listing 31.7 VARIABLES.ASP Lists the Contents of the ServerVariables Collection
<%@ LANGUAGE="VBSCRIPT" %> <HTML> <HEAD><TITLE>Variables</TITLE></HEAD> <BODY> <HR> <H1 align="center">Server Variables</H1> <% For Each item in Request.ServerVariables %> <STRONG><%=item%></STRONG>=<%=Request.ServerVariables(item)%><BR> <% Next %> </BODY> </HTML>
Create a new ASP file called VARIABLES.ASP on your Web server. Enter the code from Listing 31.7, and load the page in your browser. You should see a list of all the server variables, as shown in Figure 31.6.
The Server variable HTTP_USER_AGENT allows you to determine a user's browser type.
NOTE
You could add more For Each loops to Listing 31.2 to show what is contained in other collections, such as the Request.Form collection, and use it as a debugging tool.
The Server Object
The primary use of the ASP Server object is to create objects on the Web server so your ASP application can access them. You have already seen how to create an ADO connection object:
Set cn = Server.CreateObject("ADODB.Connection")
You can also create objects from classes that you compile into an ActiveX DLL, as you will see shortly.
As an alternative to the Server.CreateObject statement, you can embed an <OBJECT> tag in your ASP file with the RUNAT option set to Server:
<OBJECT RUNAT="Server" ID=cn PROGID="ADODB.Connection"></OBJECT>
Either syntax creates an ADODB.Connection object on the Web server. However, the <OBJECT> tag cannot be used inside the script tags.
The Application Object and GLOBAL.ASA
Earlier in this chapter, you discovered how the directory layout is used to identify ASP applications. This is important if you want to program the Start and End events associated with applications and sessions. To write procedure code for these events, you place a special file called GLOBAL.ASA in the ASP application's root directory. The GLOBAL.ASA can contain code for these events, as in the following example:
Sub Session_OnStart() Dim x Set x = Server.CreateObject("ADODB.Connection") Set Session("CONNECTION") = x End Sub
You can use the GLOBAL.ASA file to add a Web page hit counter, close and open databases, or perform any other activity that needs to occur when a user starts and exits your application.