Chapter 4
Response
Object
The response object is useful, feature rich and subtle. We are going to focus on
it's most fundamental capabilities. It has many more capabilities than we use
here, but we think this is the 20% you will use 80% of the time. The capabilites
we think are vital include: response.write, response.redirect and response.end
which effectively halts a script in it's tracks.
4.1- Properties:
4.1.1- ContentType :
You can use the ContentType property of the Response object to set the HTTP
content type string for the content you send to a user. The general syntax is
Response.ContentType = ContentType
where ContentType is a string describing the content type. For a full list of
supported content types, see your Web browser documentation or the current HTTP
specification.
For example, if you want to send source (that is, the .asp file from which an
ASP page is generated) to a browser, set ContentType to text/plain:
<% Response.ContentType = "text/plain" %>
The browser then displays the page as text, rather than interpreting the page
as HTML.
4.1.2-Buffer :
This property controls whether page content generated
from your ASP script is returned to the browser as it is generated or all at
once when your page has finished executing. This becomes important when your
script modifies the HTTP headers. Any property or method that changes some part
of those headers (Response.Redirect,Response.Expires , Response.AddHeader,
Response.Status, and so on) must occur before any content is returned to the
browser. If Response.Buffer is set to false (buffering is off), then those
commands must all occur before the opening <HTML> tag. Buffering is turned off
by default for all ASP pages in all applications by setting the BufferingOn
registry setting to 0. (ASP registry setting will be discussed later.). If
buffering is on, then it essentially tells the browser don't write anything at
all until
a) response.end executes thus stopping the page dead in tracks and sending to
browser
b) response.flush executes
c) 100% of the page is completely transmitted to browser. And those commands can
be used anywhere in the page because the entire page will be executed before any
content is returned.
Normally, it is not a problem to place these commands before the <HTML> tag, it
is just a matter of moving your script around, but in certain cases (such as
error handlingcode), you can't control when it is executed. In those cases, you
must use buffering.
The default setting for buffering of all ASP pages is off. However, you can set
the Buffer property of the Response object to True to process all of the script
on a page before sending anything to the user:
<% Response.Buffer = True %>
You can use buffering to determine at some point in the processing of a page
that you do not want to send previous content to a user. You can, instead,
redirect the user to another page with the Redirect method of the Response
object, or clear the buffer with the Clear method of the Response object and
send different content to the user. The following example uses both of these
methods.
<% Response.Buffer = True %>
<html>
<body>
.
.
.
<%
If Request("FName") = "" Then
Response.Clear
Response.Redirect "/aspsamp/samples/test.html"
Response.End
Else
Response.Write Request("FName")
End If
%>
</body>
</html>
When you call the Buffer method in a script and do not call the Flush method in
the same script, the server will maintain Keep-Alive requests made by the
client. The benefit of writing scripts in this manner is that server performance
is improved because the server does not have to create a new connection for each
client request (assuming that the server, client, and any proxies all support
keep-alive requests). However, a potential drawback to this approach is that
buffering prevents any of the
response from being displayed to the user until the server has finished all
script processing for the current .asp file. For long involved scripts, the user
might be forced to wait a considerable amount of time before the script is
processed.
Following is an example for Buffering output to allow error handling
<%
Response.Buffer=TRUE
On Error Resume Next
%>
<HTML>
<HEAD><TITLE>Buffering Example</TITLE></HEAD>
<BODY>
<%
Set Obj = Server.CreateObject("SyncDateTime.clsSyncDateTime")
If Err.Number > 0 Then
ErrorURL = "ErrorHandler.asp"
ErrorURL = ErrorURL & "?Source=" & Server.URLEncode(Err.Source)
ErrorURL = ErrorURL & "Number=Err.Number"
Err.Clear
Response.Redirect ErrorURL
` Buffering allows us to do a redirect at any point in the page.
Else
Obj.DateTime = Now
Response.Write Obj.DateString
End If
%>
</BODY>
</HTML>
4.1.3-Expires:
Expires
is the property you'll probably use the most in your ASP applications.This value
represents the number of minutes before the page's content expires from the
browser's cache. This means that if a particular client returns to this page
within the time set by Expires, then the cached content is used. If it has been
longer than the time specified, the page is requested from the server again. To
ensure that users are always seeing the most up-to-date information on pages,
usually you'll set this property to zero, telling the browser not to cache the
page at all--to always go back to the server for a fresh copy.
Response.Expires = time (in minutes)
The following two examples show how this
property can affect page updating. To view the
examples, place each one onto your Web server and then go to them through your
browser. Once the pages have been displayed, browse to a different page and
return to each example page quickly (within 5 minutes). The page with Expires
set to 5 minutes will still show the time of your first visit, while the other
page will show the time of your current visit. For your applications, you can
adjust this property as necessary to balance between too frequent of a return
query to your page and making sure you have the most current information.
An example Setting Response.Expires to Zero
<%Response.Expires=0%>
<HTML>
<HEAD><TITLE>Never Cache This Page</TITLE></HEAD>
<BODY>
<H1>The Current Date and Time is:</H1>
<P align="center"><%=Now%></P>
</BODY>
</HTML>
An example Setting Response.Expires to Five Minutes
<%Response.Expires=5%>
<HTML>
<HEAD><TITLE>Cache This Page for 5 minutes</TITLE></HEAD>
<BODY>
<H1>The Current Date and Time is:</H1>
<P align="center"><%=Now%></P>
</BODY>
</HTML>
4.1.4-ExpiresAbsolute:
This is a simpilar property to expires , but instead of specifying the number of
minutes before the cached copy of the page expires, you specify a date and time.
This version of the Expires property is useful for information that is current
up to a certain time each day or every week. An example is a page displaying
currency exchange rates, or other information that is updated only at certain
specific times. Expiration dates and times (for this property and the previous
one) are client-based, meaning that if you moved your clock forward on the
client machine, the cached pages would expire early.
4.1.5-Status:
The Status property specifies the value of the status line returned by the
server. Status values are defined in the HTTP specification.
Response.Status = StatusDescription
The StatusDescription is string that consists of both a three-digit
number that indicates a status code and a brief explanation of that code. For
example: “310 Move Permanently”.
This property is used to modify the status line returned by the server. The
following example sets the response status.
<% Response.Status = "401 Unauthorized" %>
4.2- Methods:
4.2.1-Write:
The Write method is the most commonly used method of the
Response object. You can use the Write method to send information to a user from
within ASP delimiters.
Response.Write variant
Where variant can be any data type supported by your default primary scripting
language.
For example, the following statement sends a greeting to the user:
<%
Response.Write "<H3 ALIGN=CENTER>Welcome Back to the My Home Page</H3>"
%>
The Response.Write method is especially useful if you want to send content back
to the user from within a procedure.
You do not have to use Response.Write to send content back to the user. Content
that is not within scripting delimiters is sent directly to the browser, which
formats and displays this content accordingly. For example, the following script
produces exactly the same output as the previous script:
<H3 ALIGN=CENTER>
<% If user_has_been_here_before Then %>
Welcome Back to the Overview Page.
<% Else %>
Welcome to the Overview Page.
<% End If %>
</H3>
The response object could be used to write text in a varity of ways
<html><head>
</head><body>
<%
response.write "Hello, Joe<br>"
who="Joe"
response.write "Hello, " & who & "<br>"
%>
Hello, <%=who%><br>
Which Book? <input type="TEXT" name="book" value="The Stand"><br>
<%
response.write "Which Book? <input type=""TEXT"" name=""book"" value=""The
Stand""><br>"
%>
<%
quote=chr(34)
response.write "Which Book? <input type=" & quote & "TEXT" & quote & " name=" &
quote & "book" & quote & "
value=" & quote & "The Stand" & quote & "><br>"
%>
<%bookname="The Stand"%>
Which Book? <input type="TEXT" name="book" value="<%=bookname%>"><br>
<%
response.write "Which Book? <input type=""TEXT"" name=""book"" value=""" &
bookname & """><br>"
%>
</body></html>
4.2.2- Redirect:
Instead of sending content to a user, you can redirect the
browser to another URL with the Redirect method.
Response.Redirect URL
The following example redirects the user to a page based on the operating system
he is using. Two users could go to the same page, click the same link, and yet
be shown different information from different pages, each page containing
information targeted at their specific operating system. This type of processing
is one of the keys todynamic Web sites: showing users content tailored to their
needs.
<% Select Case Request.ServerVariables("HTTP_UA_OS")
Case "Windows95"
Response.Redirect "Win95.htm"
Case "WindowsNT"
Response.Redirect "WinNT.htm"
Case "MacOS"
Response.Redirect "MacOS.htm"
Case Else
Response.Redirect "Other.htm"
End Select
%>
<HTML>
<HEAD><TITLE>Redirection</TITLE></HEAD>
<BODY>
</BODY>
</HTML>
CAUTION: Response.Redirect modifies the HTTP headers, so it must
occur before any content is returned to the browser (see Response.Buffer for
more information).
4.2.3- AddHeader:
The AddHeader method adds an HTML header with a specified value. This method
always adds a new HTTP header to the response. It will not replace an existing
header of the same name. Once a header has been added, it cannot be removed.
This method is for advanced use only. If another Response method will provide
the functionality you require, it is recommended that you use that method
instead.
Response.AddHeader name, value
The name parameter is the name of the new header variable.
Note : To avoid name ambiguity, name should not contain any underscore
(_) characters. The ServerVariables collection interprets underscores as dashes
in the header name. For example, the following script causes the server to
search for a header named MY-HEADER.
<% Request.ServerVariables("HTTP_MY_HEADER") %>
The value parameter is the initial value stored in the new header variable.
Because HTTP protocol requires that all headers be sent before content, you
must call AddHeader in your script before any output (such as that generated by
HTML code or the Write method) is sent to the client. The exception to this rule
is when the Buffer property is set to TRUE. If the output is buffered, you can
call the AddHeader method at any point in the script, as long as it precedes any
calls to Flush. Otherwise, the call to AddHeader will generate a run-time error.
The following two .asp files illustrate this point.
-------file1.asp---------
<% Response.AddHeader "WARNING", "Error Message Text" %>
<HTML>
Some text on the Web page.
</HTML>
In the preceding example, the page is not buffered. The script works,
however,because the AddHeader method is called before the server sends the
output some text on the Web page to the client. If the order were reversed, the
call to the AddHeader method would generate a run-time error.
------file2.asp----------
<% Response.Buffer = TRUE %>
<HTML>
Here's some text on your Web page.
<% Response.AddHeader "WARNING", "Error Message Text" %> Here's some more
interesting and illuminating text.
<% Response.Flush %>
<%= Response.Write("some string") %>
</HTML>
In the preceding example, the page is buffered, and as a result, the server
will not send output to the client until all the ASP scripts on the page have
been processed or until the Flush method is called. With buffered output, calls
to AddHeader can appear anywhere the script, so long as they precede any calls
to Flush. If the call to AddHeader appeared below the call to Flush in the
preceding example, the script would generate a run-time error.
You can use this method to send multiple copies of the same header with
different values, as with "WWW-Authenticate" headers.
The following example uses the AddHeader method to request that the client use
BASIC authentication.
<% Response.Addheader "WWW-Authenticate", "BASIC" %>
Note : The preceding script merely informs the client browser which
authentication to use. If you use this script in your Web applications, you
should ensure that the Web server has BASIC authentication enabled.
4.2.4-AppendToLog:
The AppendToLog method adds a string to the end of the Web
server log entry for this request. You can call it multiple times in one section
of script. Each time the method is called it appends the specified string to the
existing entry.
Response.AppendToLog string
The string is the text to append to the log file. Because fields in the
Internet Information Server log are comma-delimited, this string cannot contain
any comma characters (,). The maximum length of this string is 80 characters.
4.2.5-BinaryWrite:
The BinaryWrite method writes the specified information to the current HTTP
output without any character conversion. This method is useful for writing
nonstring information such as binary data required by a custom application.
Response.BinaryWrite data
The data parameter is the
data to write to the HTTP output.
If you have an object that generates an array of bytes, you can use the
following call to BinaryWrite to send the bytes to a custom application.
<%
set bg = Server.CreateObject(MY.BinaryGenerator)
pict = bg.MakePicture
Response.BinaryWrite pict
%>
4.2.6- Clear:
The Clear method erases any buffered HTML output. However, the Clear method only
erases the response body--it does not erase response headers. You can use this
method to handle error cases. Note that this method will cause a run-time error
if Response.Buffer has not been set to TRUE.
4.2.7- End :
The End method causes the Web server to stop processing the script and return
the current result. The remaining contents of the file are not processed.
Response.End
If Response.Buffer has been set to TRUE, calling Response.End will flush the
buffer. If you do not want output returned to the user, you should call:
<%
Response.Clear
Response.End
%>
4.2.8- Flush:
The Flush method sends buffered output immediately. This method will cause a
run-time error if Response.Buffer has not been set to TRUE.
Response.Flush
If the Flush method is called on an ASP page, the server does not honor
Keep-Alive requests for that page.
4.3- Collections:
Cookies : A cookie is a token that either a client browser sends
to a Web server or a Web server sends to a client browser. Cookies allow a set
of information to be associated with a user. ASP scripts can both get and set
the values of cookies by using the Cookies collection.
This section discusses how to set the value of cookies your Web server sends to
a client browser. (We will talk in details about cookies later in this
documentation).
To set the value of a cookie, use Response.Cookies. If the cookie does
not already exist, Response.Cookies creates a new one:
<% Response.Cookies("animal")="elephant" %>
Similarly, to set the value of a cookie key:
<% Response.Cookies("animal")("elephant")="African" %>
If an existing cookie has key values but Response.Cookies does not specify a
key name, then the existing key values are deleted. Similarly, if an existing
cookie does not have key values but Response.Cookies specifies key names and
values, the existing value of the cookie is deleted and new key-value pairs are
created. |