Home > Articles > Programming > Visual Basic

This chapter is from the book

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>"
   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.


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


   sCheckName = Request.Form("txtusername")
   sCheckPW = Request.Form("txtpassword")

   If sCheckName = "" then Response.Redirect "login.html"

   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 rs.EOF Then
      Response.Redirect "login.html"
   End If

   If UCase(rs.Fields("Password")) <> UCase(sCheckPW) Then
      Response.Redirect "login.html"
   End If



   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.


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:


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>")


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>")

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

<H1 align="center">Server Variables</H1>
For Each item in Request.ServerVariables

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.

Figure 31.6

The Server variable HTTP_USER_AGENT allows you to determine a user's browser type.


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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020