There are two main reasons why developers are keen to build Web sites with Active Server Pages (ASP):
- It helps take advantage of server-side resources (such as a database or credit card processing facilities) to enhance your site’s functionality or make it easier to administer.
In this, the third article in SitePoint’s series on ASP, we’ll focus on the first of these two goals. We’ll look at the Request and Response objects that ASP provides, and how to use them to receive information that a user submits in a form and generate a dynamically-calculated result in return. Since we have not yet covered the concepts surrounding objects in ASP before, I’ll explain them as we go along to make sure you’re up to speed.
This article assumes that you’re familiar with the concepts covered in the previous two articles in this series: Getting Started with ASP and ASP Language Basics. If you haven’t read them, and are approaching ASP for the first time, I would suggest at least skimming them before jumping into this article.
If you’re ready, let’s get started…
Built-in ASP Objects
You’ve probably heard the term object oriented programming bandied about on occasion, whether in newspaper ads seeking to hire programmers or in some other discussion related to current programming trends. I’m sorry to say that writing dynamic Web pages in ASP isn’t object oriented programming, strictly speaking. Most of the programming involved in the development of a typical ASP Web site is procedural in nature; that is to say, it involves the writing of a series of instructions to be executed one at a time, with the possibility of loops and conditional control structures like those we saw in the previous article in this series.
What makes ASP a little special, however, is that very little functionality is actually built into ASP itself. Rather, ASP is a simple framework that allows you to make use of libraries of software objects written in other object oriented languages (typically C++) to do most of the heavy lifting.
A software object is basically a combination of two things: properties and methods. An example of a typical software object in ASP might be a file stored on the server’s hard drive. Properties of the file include its:
- MIME type (e.g. "image/gif" in the case of a GIF file), and
Methods are actions that can be taken using the object. To continue with our file object, methods might include:
- reading a line of text from the file,
- moving the file to a different directory, or
- deleting the file completely.
The properties and methods belonging to a particular object depend on the class (or type) of that object (i.e. every object of class ‘file’ will have a filename). The particular values of the properties, however, are unique to each object (i.e. each file has its own filename, which can be different from every other file out there).
Before I boggle your mind further, however, let me calm you down a little by saying that we’ve already used an object in the simple scripts that we’ve looked at so far. In fact, here’s an extremely simple line of one of the first scripts we looked at. Can you spot the object?
Response.Write "<p>This is a test of ASP.</p>"
The object in this line is
Response. This is a special, built-in object that’s available to all ASP scripts, and it allows you to write to and otherwise control the flow of data that is sent back to the browser in response to the page request. The Response object also has a counterpart called the Request object, which we’ll look at in detail later in this article. In the above line, we used the
Write method of the
Response object to write a line of HTML as part of the page to be returned to the requesting browser. So the code
Response.Write can be roughly read aloud as "In the Response object, invoke the Write method".
The string that makes up the rest of the line,
"<p>This is a test of ASP.</p>", is a parameter that is being passed to the Write method. Parameters provide whatever information is needed for a method to do its job. In this case, the Write method needs to know what to write out, and the parameter provides that information.
Of course, there’s more to the Response object than just this one method. Let’s examine some other methods, as well as some of the properties that it supports.
The Response Object
As the object that controls everything to do with the response that is sent back to the browser, Response contains properties and methods that support this purpose. We’ve already seen the most important and most commonly-used method in ASP – the Write method – in action, so let’s look at another example of a method supported by Response: the Redirect method.
The Redirect method sends a special Hypertext Transfer Protocol (HTTP) code (specifically, HTTP response code "302 Object Moved") to the browser to inform it that the page it requested is actually available at a different address and that it should try loading that address instead. The address in question is provided as a parameter to this method. Thus, the line above will cause the browser to load http://www.sitepoint.com instead of the file that it originally requested.
The Redirect method is useful in situations where you want to send the user to another page. For example, when a user logs out of your site by clicking on a link to logout.asp, you might want to send the user back to the login page of your site (e.g. login.asp) after you log him or her out of the system:
<% ' logout.asp -- log out and redirect to the front page If bLoggedIn Then ' ... Code to log the user out ... End If Response.Redirect "login.asp" ' Send back to login page %>
Because of the way the Redirect method works (sending an HTTP response code to the browser), it may not be called (invoked) after any text or HTML has been sent as part of the page. If other words, if you want to redirect the user to a different page, you must do it before you display any of this page — you can’t have it both ways.
A bunch of the other methods provided by the Response object are related to controlling how the page content is sent to the browser. But before we look at these, we must first examine a property of the Response object: Buffer.
Response.Buffer = False
As you can see in this example, an object property behaves exactly like a variable, except that you must specify the object to which it belongs followed by a dot (.) when you want to refer to it. In the above line, we’ve assigned the Buffer property of the Response object a value of False.
If the Buffer property is set to True, ASP waits for the ASP script responsible for the page to finish executing before it sends the entire page to the browser in one big chunk. If Buffer is set to false, the contents of the page are sent to the browser line by line as they are produced by the script. In general, it’s quicker to send the page all at once than to send it in bits and pieces; thus, as of ASP 3.0, Buffer is set to True by default. If your script is particularly long, however, or if you want visitors to be able to see the output of your script as it is produced, you can set the Buffer property to False using the line above.
Even if your script is very long, you’ll usually want some control over what gets sent back to the browser and when. Two of the additional methods supported by Response give you that control. These methods work only when Response.Buffer is True:
Response.Flush ' Immediately send everything accumulated ' in the response buffer so far. Response.Clear ' Throw away everything accumulated in ' the buffer without sending it.
For example, if a long script was performing a series of complex calculations and you wanted to display the outcome of each computation as it was completed, you could structure your code as follows, using the Flush method:
For calcNo = 1 To 1000 ... ' Perform calculation... Response.Write "The results of calculation number " & calcNo Response.Write " are as follows..." ... ' Print out the results... Response.Flush ' Send the results now Next
The Clear method, meanwhile, is useful when something unexpected happens and you want to print out an error message. If you’re in the middle of an HTML table and an error occurs in your ASP script, you can’t simply print out an error message and end the script there, because the incomplete table may result in a page that is not viewable. Use the Clear method to avoid such problems – it cancels the display of your incomplete page content before printing the error message:
If errorHasOccurred Then Response.Clear ' Clear the output buffer Response.Write "An error has occurred!" Response.End ' Terminate the page here End If
The End method (used above) flushes the buffer (if Buffer is set to True, that is), and then stops executing the script at that point. Another common use of the End method is to abort a long calculation if it is determined that the client (or browser) has already moved on to another page, or has otherwise stopped receiving the page. This condition is detected by checking the IsClientConnected property of the Response object:
' Long calculations... If Not Response.IsClientConnected Then Response.End End If ' More long calculations...
To learn about the other properties and methods supported by the Response object, look them up in the documentation that accompanies Internet Information Server or Personal Web Server.
The Request Object
When a Web browser requests a Web page from a Web server, it can send a lot more information than just a simple URL. For instance, if the user submits a form to make the request, then everything the user typed into that form is sent along with the page request. If the user has been assigned a unique session ID that maintains, for example, a shopping basket of catalogue items they’ve chosen to buy, then that session ID will usually be sent, along with every page request to that site, as a cookie.
If you’re comfortable with the concept of a Response object that handles the process of sending a Web page to the requesting browser, then it should also make sense to you that there is a Request object that takes care of all the details of the request as well.
The most common use for the Request object is to retrieve information that was sent by the browser along with the request. These values can come in several forms:
- defined in the query string
- submitted as part of a form
- stored in cookies
For each of these, the Request object has a special property type called a collection, which contains all the values submitted via each of these methods as part of the request. To demonstrate, let’s start with the simplest method for passing information along with a page request â€“ the query string.
In case you’re not familiar with query strings, the basic idea is to tack on a set of variables to the end of the URL that appears in the browser’s Address field. For example, if there were a page on your site with URL http://www.yoursite.com/welcome.asp, then you could send that page my first and last name by adding a query string to the address as follows:
The portion of the URL that’s in bold is the query string. A query string always begins with a question mark (
?), which marks the end of the standard URL. The query string, which follows the question mark, is a series of one or more name/value pairs separated by ampersands (
&). In this case, we have two such pairs. The variable name
firstname is given a value of
Kevin, and the variable name
lastname is given a value of
When a URL like this is used to load an ASP page, the name/value pairs become accessible through the QueryString collection in the Request object. For example, you can print out the query string that was sent with a request as follows:
Response.Write "Query string: " & Request.QueryString
For the above example, the output would look like this:
Query string: firstname=Kevin&lastname=Yank
When passing more than one value like this, however, you’ll usually want to be able to retrieve these values separately, and that’s where the fact that the QueryString property is a collection, comes in handy. For instance, to retrieve and print out the value of the firstname variable defined in the query string above, you would use this code:
Response.Write "First name: " & Request.QueryString("firstname")
The above line specifies that we’re only interested in the value of the firstname variable defined in the query string. The line output by this code will look like this:
First name: Kevin
Variables in a query string can have multiple values. Consider the following address, which might be seen on a Web site that provided a currency converter:
As you can see, this query string contains three name/value pairs, all three of which assign a different value to the currency variable. On our hypothetical currency converter site, such a request might be used to ask for the current exchange rates for Canadian dollars, US dollars and Australian dollars. Upon receiving this request, if convert.asp were to print out the value of the currency variable (
Request.QueryString("currency")) as we demonstrated above, it would produce the following output:
A more useful way to process this value would be to consider each of the three values one at a time. This can be done using the
Count property of the
QueryString("currency") value, which contains a count of the number of values submitted (in this case, 3). Here’s roughly what the code would look like:
For i = 1 To Request.QueryString("currency").Count currency = Request.QueryString("currency")(i) ' Process currency... Next
In the above code,
Request.QueryString("currency").Count will have a value of 3, so the loop body will be processed three times. The first time through the loop, the loop variable
i will have a value of 1, and so currency will be assigned the value
Request.QueryString("currency")(1). This refers to the first of the three values assigned to the currency variable in the query string, and will yield
"CAD". Similarly, the two subsequent iterations of the loop will yield
As another example, let’s say you wanted to add a personal touch to your Web site by greeting your visitors by name on every page. Here’s the code for a basic page on such a site:
1 <% Option Explicit %> 2 <% 3 4 If Request.QueryString("username").Count < 1 Then 5 ' User has not given his/her name 6 %> 7 <html> 8 <head> 9 <title> Welcome! </title> 10 </head> 11 <body> 12 <form action="<%=Request.ServerVariables("SCRIPT_NAME")%>" method="GET"> 13 <p>Please enter your name: 14 <input type="text" name="username"> 15 <input type="submit" value="OK"></p> 16 </form> 17 </body> 18 </html> 19 <% 20 Response.End 21 End If 22 23 Dim name 24 name = Request.QueryString("username") 25 26 %> 27 28 <html> 29 <head> 30 <title> Typical Page </title> 31 </head> 32 <body> 33 <p>Hi, <%=name%>!</p> 34 <p>Click <a href="page2.asp?username=<%=Server.URLEncode(name)%>"> here</a> for more.</p> 35 </body> 36 </html>
Since this is the most complex ASP script we have seen so far, and because there are a couple of new tricks in there, I’ll explain the important lines one at a time:
4 If Request.QueryString("username").Count < 1 Then
The condition of this If-statement checks whether the Count property of the username variable in the query string is less than one. This will only occur when no value has been submitted for that variable as part of the query string, in which case the Count will be 0. When this condition occurs, instead of displaying the normal content of the page, the script will display a simple form prompting the user for his or her name.
While we could have used Response.Write commands to output the HTML for the form to be displayed, a simpler option is to switch out of ASP mode inside the If-statement. Just like statements appearing in this spot, the HTML code on lines 7 through 18 will only be displayed if the condition in the If-statement is true.
12 <form action="<%=Request.ServerVariables("SCRIPT_NAME")%>" method="GET">
As complicated as this line may look, it’s actually just a standard HTML
<form> tag. For those of you who are unfamiliar with forms, I’ll explain what the two attributes,
The action attribute specifies the URL of the script to which the browser should submit its request (along with the information entered in the form). In this case, once the user has entered his or her name, we want to submit the form to the very same script that generated it, so that the user is then presented with the page he or she originally requested. If you simply typed in the filename of this script, it would work fine, except that if you ever renamed the file, you’d have to remember to come back and change the value of this attribute as well. Also, it makes the code harder to reuse on every page of your site if you have to remember to type in the filename of the page each time you use it. The alternative is to use ASP to print out the name of the file, which is exactly what the code above does. You should recognize
<%=...%> as the shortcut for printing out an ASP value in the middle of a piece of HTML. The value being printed out in this instance is a member of the
Request.ServerVariables collection, which contains all sorts of useful values. We won’t be looking at this collection in detail at this time; however, I’ll explain any values we use from it as they come up. The
"SCRIPT_NAME" value that we use here always contains the path and filename of the ASP script that was requested, as it appears in the URL. Thus, we can print it out as the value of the form’s action attribute, to make the browser submit the request back to the very same page.
The method attribute allows you to specify one of two ways for the form to submit its values. When set to "GET", as it is here, the values entered into the form field are converted into name/value pairs and tacked onto the end of the URL specified by the form’s action attribute. In short, "GET" tells the browser to submit the form as a query string. The alternative, "POST", tells the browser to submit the values in the body of the HTTP request. Basically what this means is that the values do not appear as part of the URL (good for submitting sensitive information like credit card numbers or passwords), but instead, they’re hidden inside the request. We’ll see how to retrieve values submitted this way momentarily.
14 <input type="text" name="username">
This tag creates a text input field that, when it’s completed by the user and submitted as part of the form, creates a variable called username in the query string.
As we’ve seen before, this line causes the script to stop processing, and send all the output generated so far to the browser. This prevents the user from seeing the actual content of the page until he or she has filled out the form with his or her name.
23 Dim name 24 name = Request.QueryString("username")
Once we’ve determined that a name has been provided in the query string, we declare a variable, and store the name from the query string in it. We could have just continued to refer to the value as
Request.QueryString("username") for the rest of the script, but
name is a more convenient way to refer to it, and saves typing.
33 <p>Hi, <%=name%>!</p>
We can then use the variable to display the person’s name as part of a personalized greeting at the top of the page! All that’s left is to ensure that the value is passed on to other pages on the site, which presumably have the same block of code at the top to prompt the user for a name if one is not provided in the query string. To ensure that the user isn’t prompted on every single page he or she views, you must code your HTML links so that they contain a query string with the user’s name in it. The following line contains such a link:
34 <p>Click <a href="page2.asp?username=<%=Server.URLEncode(name)%>"> here</a> for more.</p>
You might have expected the link to be
"page2.asp?username=<%=name%>"; however, because of the rules that apply to URL’s, you can’t put just any value into a query string. Spaces, for example, are not allowed; nor are most non-alphanumeric characters. To include such characters in the value of a query string variable, they must be encoded. Spaces, for example, are inserted as plusses (
+). Other characters are inserted as a percent sign followed by their ASCII character codes.
ASP provides another built-in object (like Request and Response) called Server that contains a number of useful methods for performing miscellaneous tasks. The URLEncode method, used in the line above, takes a text string and converts it into the encoded for required for use in a query string. Thus, to place the name variable in the query string for our link, we must pass it through the URLEncode method as shown above.
That’s all there is to it! Save the file as an ASP script and try it out on your own server. When you first load the page, you’ll be presented with a form that prompts you for your name.
Once you’ve entered your name, as I have above, and clicked ‘OK’, the page will reload and display the welcome message and a simple link.
Notice that the URL has changed to include a query string with the value you entered into the form field. Notice also that the space in the value I entered was automatically encoded as a plus (
+) by the browser. Finally, move your mouse over the link to check that the URL was correctly generated with the appropriate query string to carry the value forward to the next page in the site.
I mentioned in my explanation of the previous example that forms can use one of two methods: GET or POST. The former submits values as part of the query string, while the latter submits them behind the scenes, in the body of the HTTP request. Besides the security advantage I mentioned, POST variables may also contain much more information (even the contents of an entire file!) than a URL query string would allow. There are, however, two downsides to using POST variables:
- You can’t bookmark the result of a form submission that uses the POST method, because the bookmark does not contain the submitted variables and their values. A GET method submission stores all that in the query string that is part of the URL, and thus becomes part of the bookmark.
On the plus side, working with POST variables in ASP is very similar to accessing query string variables. You just have to use the Form collection instead of the QueryString collection. Thus, to print the value that was typed into a form named "testvalue", you would use the following line of code:
In some cases, however, you’ll want to be able to access the value of a variable, whether it’s submitted in the query string, as part of a form, as a cookie, or even as a server variable (like the
"SCRIPT_NAME" value we used in the previous example). A convenient feature of the Request object lets you access a variable from any of these sources, simply by treating the Request object as a collection in and of itself (e.g.
Request("variableName")). This short-form method of value retrieval is extremely convenient. In fact, you’ll probably want to use it in every case, except those times where, for security or other reasons, you want to make sure that a variable is sent from a particular source.
As an exercise, rewrite the personalized welcome message example in the previous section, and use this shorthand notation wherever possible (there are three places in the script that it can be used).
Summary and Resources for Further Reading
In this article, you’ve learned how to use ASP to process submitted values that are provided either through a query string in a normal link, or by asking the user to submit a form. In the process, you learned some of the important built-in objects that ASP provides:
Server. Although we didn’t have time to fully explore all of the methods, properties, and collections that these objects provide, you should now know enough to use the online documentation to learn about what else is available.
In the next article in this series, we’ll learn about a two other important built-in objects:
Session, which allow you to build not just dynamic pages, but also complete Web applications! If you’re in a hurry to get started, the online ASP documentation accompanying Microsoft IIS or PWS are good places to start; however, less experienced readers may prefer to invest in a good book. WROX Press offers several titles for different levels of experience; check out my reviews of them to find out which is best for you!