You are on page 1of 23

MODULE ITMAJ02

DISPLAYING SERVER VALUES

Prepared by: Sir Jhon

The manner in which Active Server Pages operates can be illustrated very simply by using VBScript functions to display the system date and time. It is assumed that you have basic familiarity with the Visual Basic language, of which VBScript is a subset. Even if you do not know Visual Basic, you should be able to follow the examples and learn VBScript along the way. The following output reports the current date and time values from the server. This output is produced by an ASP script that embeds the values within the HTML on this page. The current date is 1/17/2012 and the current time is 1:17:17 AM. These date and time values are "live," meaning that they are retrieved from the server the instant the scripts are run. If you reload the page, you should see a different time reported. The current date and time are retrieved from the server clock with the VBScript functions Date() and Time(). Script references to these functions are references to the actual date and time values current on the server. Using the Response.Write() Method Recall that one of the built-in ASP objects is the Response Object. This object handles script output and provides the Write() method to produce text output that appears on the Web page. So, the Response.Write() method can be coded inside a script at the location on the page where the system date and time should appear. It can write HTML text combined with the Date() and Time() values retrieved from the server. In fact, this is the method used to produce the live date and time values displayed above: <% Response.Write("<b>The current date is " & Date()) Response.Write(" and the current time is " & Time() & ".</b>") %> Note that the Response.Write() method can contain literal text strings (enclosed in quotes), values retrieved from VBScript functions or other VBScript commands, along with HTML tags (enclosed in quotes as part of a text string) to control output formatting. Text strings and server values are concatenated, or connected together, with the VBScript concatenation operator & (ampersand) to produce a resulting string of text characters that can be written to the Web page. The general format for the Response.Write() method is shown below:

Response.Write("text string" | & | server value | "<HTML tag>")

In the first line of the above script the literal text string "<b>The current date is " is concatenated with the server value produced by the Date() function to create the output string The current date is 1/17/2012. In the second line of the script the literal text string " and the current time is " is concatenated with the value of the Time() function and with the string ".</b>" to create the output string and the current time is 1:17:17 AM. Notice that even though the script contains two lines of code, the output appears as a single line of text. This is because the output does not contain HTML code to produce a line-break character. You can, in fact, code the script with as many individual Response.Write() statements as you wish. The format of the output, however, depends solely on the HTML coding contained in the output string. Here is the same script written as multiple lines of code with one Response.Write() statement for each section of output: <% Response.Write("<b>") Response.Write("The current date is ") Response.Write(Date()) Response.Write(" and the current time is ") Response.Write(Time()) Response.Write(".</b>") %> Concatenation of strings and values is not necessary in these statements since each Response.Write() statement outputs a single string or value. Alternately, the script can be written as a single line of code, <% Response.Write("<b>The current date is " & Date() & " and the current time is "

Page 1 of 23

MODULE ITMAJ02
& Time() & ".</b>") %> where various text strings and server values are concatenated to produce the output line. Embedding Server Values within HTML

Prepared by: Sir Jhon

The Response.Write() method has a second, abbreviated format that makes it easy to embed server values within the HTML coded on the page. These scripts are in the following format,

<%= server value %>

where the symbols <%= and %> enclose a server-generated data value. This script is placed anywhere within the HTML coding on a page to display the value at that location on the page. The following output, for example, The current date is 1/17/2012 and the current time is 1:17:17 AM. is displayed with the following HTML code and embedded server values positioned at the above location: <b>The current date is <%=Date()%> and the current time is <%=Time()%>.</b> As the ASP processor renders the HTML code for return to the browser, it inserts the data values given by the Date() and Time() functions within the HTML code. This is a shorthand way of coding scripts that produce single data values and is an alternative to coding <b>The current date is <% Response.Write(Date()) %> and the current time is <% Response.Write(Time()) %>.</b> where a full script (even if a single line of code) is embedded on the page. Whether you use the embed method of displaying server output by enclosing it between <%= %> symbols or whether you use Response.Write statements to display script output will generally be determined by your processing and display needs. If you are simply displaying a server value inside HTML that is already hard-coded on the page, you'll normally use the embed method. If your script needs to write HTML code as well as server values, then the Response.Write() method is preferred. DATE AND TIME VALUE

We'll continue with some additional examples of VBScript Date() and Time() functions to help elaborate the ideas behind serverside scripting. In the following example we use the functions: Function Date() Time() Now() Hour(Time()) Year(Date()) Month(Date()) MonthName(Month(Date())) Day(Date()) WeekDay(Date()) WeekDayName(WeekDay(Date())) DateAdd() DateDiff() Returned Value Returns the system date in the format mm/dd/yy. Returns the system time in the format hh:mm:ss AM|PM. Returns the system date and time in the format mm/dd/yy hh:mm:ss AM|PM. Returns the hour of the day in 24-hour (military) time. Returns the year portion of the system date in the format 9999. Returns the numeric month of the year (January = 1). Returns the name of the month. Returns the numeric day of the month. Returns the numeric day of the week (Sunday = 1). Returns the name of the day of the week. Adds date and time intervals to derive a new date or time. Returns the difference between dates and times.

Page 2 of 23

MODULE ITMAJ02
FormatDateTime() Formats display of dates and times.

Prepared by: Sir Jhon

Note that several of the returned values are given by functions applied to other functions. For instance, MonthName(Month(Date())) returns the name of the month. To derive this value, the Month() function is first applied to the Date() function to extract the numeric month of the year (January = 1) from the system date. Then the MonthName() function is applied to this numeric result to get the name of the month. We'll put these and other functions together inside a script that appears next on this page to produce the following output: Today's date is Tuesday, January 17, 2012 <span style="color:#0000FF; font-size:12pt; font-weight:bold"> <% TheDayName = WeekDayName(WeekDay(Date())) TheMonthName = MonthName(Month(Date())) TheDay = Day(Date()) TheYear = Year(Date()) Response.Write("Today's date is " & TheDayName & ", " & TheMonthName & " " & TheDay & ", " & TheYear) %> </span> The HTML code on this page includes a <span> tag to render the enclosed script's output in the displayed font size and color. The script begins by assigning function results to script variables for ease of reference. The variable TheDayName is assigned the result of applying the functions WeekDayName(Weekday(Date())). Thus, the value Tuesday is stored in this variable. Similarly, The variables TheMonthName, TheDay, and TheYear are assigned their respective values ( January, 17, and 2012) from associated functions. Once these server values are stored as script variables, they are written to the page with a Response.Write() statement. Text strings and server values are concatenated to produce the output string displayed on the page. As a reminder that server values can be embedded directly within HTML by placing them between <%= and %> symbols, the following code can be used to produce the same results: <% TheDayName = WeekDayName(WeekDay(Date())) TheMonthName = MonthName(Month(Date())) TheDay = Day(Date()) TheYear = Year(Date()) %> <span style="color:#0000FF; font-size:12pt; font-weight:bold"> Today's date is <%=TheDayName%>, <%=TheMonthName%> <%=TheDay%>, <%=TheYear%> </span> In fact, it is not necessary to store function results as variables prior to displaying them. The above script can be eliminated and the HTML modified to include the embedded functions themselves: <span style="color:#0000FF; font-size:12pt; font-weight:bold"> Today's date is <%=WeekDayName(WeekDay(Date()))%>, <%=MonthName(Month(Date()))%> <%=Day(Date())%>, < %=Year(Date())%> </span> Script Decision Making In addition to the date display let's add a greeting whose format depends on the time of day. If the current time is prior to 12:00 noon, then the greeting is "Good Morning." If the time is between 12:00 noon and 6:00 PM, then the greeting is "Good Afternoon." If the time is after 6:00 in the evening, then the greeting is "Good Evening." Good Morning. Today's date is Tuesday, January 17, 2012. <% If Hour(Time) < 12 Then Greeting = "Good Morning" ElseIf Hour(Time) < 18 Then Greeting = "Good Afternoon"

Page 3 of 23

MODULE ITMAJ02
Else Greeting = "Good Evening" End If %> <span style="color:#0000FF; font-size:12pt; font-weight:bold"> <%=Greeting%>. Today's date is <%=WeekDayName(WeekDay(Date()))%>, <%=MonthName(Month(Date()))%> <%=Day(Date())%>, <%=Year(Date())%>. </span>

Prepared by: Sir Jhon

We can specify that a particular greeting be displayed by coding a script to check the hour of the day and then format the appropriate greeting. To do so, we need to use the VBScript If...End If decision-making structure. Just as in Visual Basic, VBScript contains an If...Else...End If structure. Its general format is

If condition test Then ...statements [ ElseIf condition test Then ...statements ] ... End If

with condition tests formed using the conditional operators < = > less than equal to greater than

<= less than or equal to >= greater than or equal to <> not equal to and with compound condition tests constructed with the logical operators AND OR NOT Our script contains condition tests to determine within which of the three time ranges the current hour of the day falls. In order to determine the current hour of the day, we use the Hour(Time()) functions. The Time() function returns the current system time in the format hh:mm:ss; the Hour() function applied to this value extracts the hour portion, converting it to military (24-hour) time. <% If Hour(Time) < 12 Then Greeting = "Good Morning" ElseIf Hour(Time) < 18 Then Greeting = "Good Afternoon" Else Greeting = "Good Evening" End If %> First, we check whether the current hour is less than 12 (before noon). If so, then we store the character string "Good Morning" in the variable named Greeting. If this condition test is false, we proceed to check whether the current hour is less than 18 (6:00 in the evening). If so, then we store the character string "Good Afternoon" in the variable named Greeting. Otherwise, it's later than 6:00 in the evening and we store the character string "Good Evening" in the variable. At the completion of the script, one of the three text strings is stored in the variable depending on the hour of the day. Script output is embedded within the HTML on the page to display the greeting along with the date: <span style="color:#0000FF; font-size:12pt; font-weight:bold"> <%=Greeting%>. Today's date is <%=WeekDayName(WeekDay(Date()))%>,

Page 4 of 23

MODULE ITMAJ02
<%=MonthName(Month(Date()))%> <%=Day(Date())%>, <%=Year(Date())%>. </span>

Prepared by: Sir Jhon

Remember that the server runs the script prior to sending the page to the browser. Therefore, all that is returned to the browser is the results of script processing, not the script itself. If you were to take a look at your browser's source listing for this page, all you would see are the lines: <span style="color:#0000FF; font-size:12pt; font-weight:bold"> Good Morning. Today's date is Tuesday, January 17, 2012. </span> Comparing Dates and Times Intervals between dates and times are derived from the functions DateDiff() and DateAdd(). Both functions use the following interval strings to indicate the unit of measurement. Interval yyyy q m y d w ww h n s Description Year Quarter Month Day of year Day Weekday Week of year Hour Minute Second

The DateDiff() function requires three arguments:

DateDiff(interval, first date, second date)

where interval is the unit of measurement as an interval string and first date and second date are literal dates or the system date. For example, the following function returns the number of days until Christmas: There are <%=DateDiff("d",Date,"12/25/2012")%> days until Christmas. There are -3310 days until Christmas. The "d" parameter specifies the measurement in days, the Date() function retrieves the current date, and "12/25/2001" is the comparison date. The DateAdd() function also requires three arguments:

DateAdd(interval, multiplier, date)

where interval is the unit of measurement as an interval string, multiplier is the number of units to add, and date is a literal date or the system date. For example, the following function returns the time 2 hours from now: In two hours it will be <%=DateAdd("h",2,Time())%>. In two hours it will be 3:20:16 AM. The "h" parameter specifies the measurement in hours, the 2 specifies the addition 2 hours, and Time is the current system time.

Page 5 of 23

MODULE ITMAJ02
Formatting Dates and Times

Prepared by: Sir Jhon

By default, dates are displayed in short date format (1/17/2012) and times are displayed in long time format (1:20:16 AM). These displays can be formatted by using the FormatDateTime() function to specify either a short or long date or time. The short date is <%=FormatDateTime(Date(),0)%>. The long date is <%=FormatDateTime(Date(),1)%>. The short time is <%=FormatDateTime(Time(),4)%>. The long time is <%=FormatDateTime(Time(),0)%>. The short date is 1/17/2012. The long date is Tuesday, January 17, 2012. The short time is 01:20. The long time is 1:20:16 AM. By passing the date parameter 0 (short) or 1 (long), the function returns the appropriately formatted date. By passing the time parameter 4 (short) or 0 (long), the function returns the appropriately formatted time. SERVER VARIABLES

The ASP Response Object supplies several useful properties and methods for producing server output destined for a Web page. For example, we have used the Response.Write() method to display server data and to write HTML code to a page. As we proceed through this tutorial, other features of the Response Object are introduced as needed. The ServerVariables Collection Another useful built-in ASP object is the Request Object. This object deals with server input, with information transmitted from a Web page to the server. This information is packaged within collections, which are arrays of values collected from a user's URL request for a Web page. Among other features, the Request Object contains the ServerVariables collection. This set of items contains information taken from HTTP headers that are transmitted from the browser to the server when the user makes a URL request. The collection contains information about the browser being used along with other information about the page being accessed. Among the 50 or so items in the ServerVariables collection, the following ones are particularly useful: ServerVariable HTTP_REFERER HTTP__USER_AGENT REMOTE_ADDR SERVER_NAME SCRIPT_NAME PATH_TRANSLATED Description The URL of the page containing the link to this page. The type of browser being used by the visitor. The IP address of the visitor. The IP address or Domain Name of the server. The virtual (Web) path to and identification of the current page. The physical path to and identification of the current page.

Values in this collection are accessed by using the reference

Request.ServerVariables("variableName")

This is a reference to the Request object, the ServerVariables collection, and the specific name of the variable in the collection. We can display the value of any variable by using this reference within a Response.Write() statement. Thus, if we code <% Response.Write(Request.ServerVariables("HTTP_USER_AGENT")) %> we produce the output Mozilla/5.0 (Windows NT 5.1; rv:8.0.1) Gecko/20100101 Firefox/8.0.1

Page 6 of 23

MODULE ITMAJ02

Prepared by: Sir Jhon

which is the value of the server variable HTTP_USER_AGENT identifying the browser being used when a request was made for this page. This reference is, of course, to the browser you are currently using. Determining Browsers For certain ASP applications it may be necessary to know which browser the user is running. Because of incompatibilities between Internet Explorer and Navigator and because of differences in their versions, you may need to provide different coding for different browsers and versions. Therefore, you can include an ASP script on a page to determine a user's browser and to provide alternate coding or alternate pages for different browsers. The HTTP_USER_AGENT server variable is used to discover these browser differences. The values that are returned by this variable are similar to the following: Internet Explorer: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Q312461) Navigator: Mozilla/4.51 [en] (Win95; I) It is a matter, then, of parsing these string values to determine which browser is being used. Among other differences in the values, note that Internet Explorer is identified by the substring "MSIE" which appears for all versions of that browser. Navigator does not produce this substring. So, one way to identify Internet Explorer is to see if "MSIE" appears in the value returned by the HTTP_USER_AGENT variable. Otherwise, this is Netscape Navigator or a compatible browser. VBScript has an InStr function that checks for the presence of a substring within a text string. The general format for this function is:

InStr(string,substring)

The function checks for the presence of substring within string. If it locates the substring of characters, it returns the starting postion of the substring within the string. If the substring of characters is not present within string, then the value 0 is returned. So, the following script <% If InStr(Request.ServerVariables("HTTP_USER_AGENT"),"MSIE") <> 0 Then Response.Write("<b>You are using Microsoft Internet Explorer.</b>") Else Response.Write("<b>You are using Netscape Navigator.</b>") End If %> produces the following output for the browser you are currently using: You are using Netscape Navigator. Thus, at the top of your ASP pages you can code a routine such as the following: <% If InStr(Request.ServerVariables("HTTP_USER_AGENT"),"MSIE") <> 0 Then Browser = "IE" Else Browser = "NN" End If %> Then, throughout your page you can apply different processing or formatting by checking the value of variable Browser: <% If Browser = "IE" Then %> ...apply Internet Explorer processing or formatting <% Else %> ...apply Navigator processing or formatting <% End If %> Determining The Browser Version

Page 7 of 23

MODULE ITMAJ02

Prepared by: Sir Jhon

You can also determine the browser version by referencing the HTTP_USER_AGENT substring containing the version number. In modern browsers these values are at postion 31 (for three characters) in Internet Explorer and position 9 (for four characters) in Navigator: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Q312461) Mozilla/4.51 [en] (Win95; I) You can pick out these version numbers using the VBScript Mid function to extract a substring from a string. Its general format is

Mid(string, start, length)

where string is the string containing the substring of characters, start is the starting position of the substring, and length is the number of characters to extract as the substring. The following script first checks to see whether the visitor's browser is Internet Explorer or Navigator and then extracts the version number substring, assigning it to variable Version: <% If InStr(Request.ServerVariables("HTTP_USER_AGENT"),"MSIE") <> 0 Then Browser = "Internet Explorer" Version = Mid(Request.ServerVariables("HTTP_USER_AGENT"),31,3) Else Browser = "Navigator" Version = Mid(Request.ServerVariables("HTTP_USER_AGENT"),9,4) End If Response.Write("<b>Your browser is " & Browser & " " & Version & ".</b>") %> Your browser is Navigator 5.0 . Determining Other Header Information There is additional useful information in the URL headers transmitted to the server. The following table shows this information pertinent to your current visit to this page. The values displayed in bold are the real-time server values displayed with Response.Write() statements. ServerVariable HTTP_REFERER REMOTE_ADDR SERVER_NAME SCRIPT_NAME PATH_TRANSLATED FORM DESIGN Current Value http://www.maconstateit.net/tutorials/ASP/menu.htm (The URL of the page containing the link to this page.) 121.96.176.39 (The IP address of the visitor.) www.maconstateit.net (The IP address or Domain Name of the server.) /tutorials/ASP/ASP02/asp02-03.asp (The virtual (Web) path to and identification of the current page.) C:\website\Tutorials\ASP\ASP02\asp02-03.asp (The physical path to and identification of the current page.)

Forms processing is a very important feature of Active Server Pages. It is through the use of forms that users interact with your Web pages and through which you can collect information for personalizing pages for your visitors. In a broader information processing sense, forms provide for data entry into your processing systems. They are the primary mechanism for capturing the data that your scripts process to generate information, to update files and databases, and to respond to user requests for information output. As you proceed through this tutorial you will learn about all aspects of forms processing. We will have occasion to discuss and demonstrate all of the controls, or data entry mechanisms, that can be coded on forms. You probably have encounter most of these in your meanderings across the Web: text entry fields, clickable buttons, radio buttons, checkboxes, drop-down menus, and the like. We will cover all of these in the following lessons. For now, we will consider a couple of common controls--text entry boxes and forms submission buttons.

Page 8 of 23

MODULE ITMAJ02
An Example Application

Prepared by: Sir Jhon

This first example of forms processing is a logon application. It involves two pages. The first page, named "logon.asp," contains a form for submitting an account and password. The visitor enters this information and clicks the "Submit" button to submit the form information for checking. logon.asp Logon Page Account: Password:

The second page is a site welcome page named "welcome.asp". The form information is submitted to this page for account and password checking. If the correct account and password is submitted, then the page is viewable. If either the account or password is incorrect, the visitor is returned to the logon.asp page. welcome.asp Welcome Page Welcome to my page.

The <FORM> Tag The HTML coding for the logon.asp page is shown below. A form is provided for entering an account and password, and a button is provided for submitting this information for checking. A table has been used to align items on the form. logon.asp <html> <body> <h3>Logon Page</h3> <form name="Logon" action="welcome.asp" method="post"> <table border="0"> <tr> <td>Account: </td> <td><input type="text" name="Account" size="10"></td> </tr> <tr> <td>Password: </td> <td><input type="password" name="Password" size="10"></td> </tr> </table> <input type="submit" name="SubmitButton" value="Submit"> </form> </body> </html> HTML form controls are displayed on a Web page by coding them within <FORM>...</FORM> tags. These tags surround the form controls; however, they do not need to enclose them "tightly." In other words, the <FORM> tags need not immediately precede the first control nor immediately follow the last control. If your page contains a single form, you can code the opening <FORM> tag right after the <BODY> tag and code the closing </FORM> tag immediately before the closing </BODY> tag. Then, your controls can appear throughout the body of the document, intermixed with other HTML tags or text. The <FORM> tag contains three important attributes for forms processing:

Page 9 of 23

MODULE ITMAJ02

Prepared by: Sir Jhon

The Name Attribute. All forms should be named. Although this is not a requirement for the current exercise, it still is a good habit to follow. It will become necessary to name a form when you wish to perform browser-side validation of data, a topic we will consider throughout the remainder of this tutorial. Forms are named by coding name="FormName" within the <FORM> tag. You can assign any name you wish to the form. In this example name="Logon" is used. The Action Attribute. The Action="url" attribute identifies the location and name of the page to which information from the form is sent for processing. If the page that will process the data is in the same directory as the page containing the form, then the URL in the Action parameter is simply the name of that page. Otherwise, it can be a full URL specifiying a Web address on a different server or in a different directory on the same server. In this example, the account and password entered by the visitor is sent to the welcome.asp page in this same directory: action="welcome.asp" The Method Attribute. The method="GET|POST" attribute specifies the means used to send the form data to the page where they will be processed. There are two methods from which to choose. The GET method is the older-style way of sending data. In this case, the data from the form are appended to the end of the URL for the page to which the data are being sent (the URL in the action attribute). The form data comprise a text string that is concatenated to the URL following a question mark (?). You probably have seen this happening in your browsing of the Web. This method is no longer preferred for submitting form data since there is a limit to the number of characters that can be sent and there is little privacy when the data from the form appear in the URL address box in the browser. We will have occasion to use this method later for other purposes. The POST method gets around these two objections. It sends the form data to the action page as a separate data stream which does not appear in the browser address box; plus, you can transmit as many characters as are required to send your entire form for processing. Unless you have a good reason for not doing so, always use the POST method. In this example method="post" is used. Form Fields Forms are composed of fields, or form controls, through which the user enters data, makes choices, and submits information. The manner in which the information is collected depends upon the type of form element coded within the <FORM> tags. Although we will have occasion to review all of the types of form elements throughout this tutorial, for present purposes we will consider only the three types needed for the logon application. This will give you a good understanding of the general method for processing forms without complicating the coding with a full range of form fields. The Account Field. The example page requires a text box within which the user enters an account. This is a standard text box created using an <INPUT TYPE="TEXT"> tag with an assigned name and size attribute. <input type="text" name="Account" size="10"> The Password Field. A password field appears as a standard text entry box; however, when characters are typed in the field, they are echoed as asterisks (*) or bullets to maintain privacy of the entered data. A password field is created using an <INPUT TYPE="PASSWORD"> tag. The field needs to be assigned a name and its size can be changed from the default 20-character width. <input type="password" name="Password" size="10"> In this example and for all forms that you create you must be sure to assign names to form fields. These names are needed for server processing. In addition, you can control the physical size of the the fields by coding SIZE attributes, and you can restrict the maximum number of characters permitted to be typed by coding the MAXLENGH attribute. The Submit Button. A submit button, when clicked, causes the action specified by the ACTION parameter of the <FORM> tag to take place. In other words, clicking a submit button transmits the data from the form to the indicated page. A submit button is created by coding an <INPUT TYPE="SUBMIT"> tag. In addition, you need to name the button for script reference and assign a value that serves as the label appearing on the button. <input type="submit" name="SubmitButton" value="Submit"> Once the form page is created, it is ready to be activated. Recall that this form submits account and password information to the welcome.asp page. There, these values are checked for authorization to view that page. If an incorrect account and/or password is submitted, the user is returned immediately to the logon.asp page without an opportunity to view the welcome.asp page. FORM SUBMISSION

Page 10 of 23

MODULE ITMAJ02

Prepared by: Sir Jhon

Information entered onto a form is submitted for processing by clicking the form's submit button, <INPUT TYPE="SUBMIT">. The information in the form fields is then transmitted to the page identified in the ACTION attribute of the <FORM> tag. When this URL request and the accompanying form data arrive at the server, the targeted page is retrieved and the data are made available to it for processing. Name/Value Pairs Data from a form are transmitted to the server as a series of name/value pairs. This means that the name of each form element (as appearing in the NAME attribute of the tag) is associated with the value of that element (as typed or selected by the user). The name/value format used for transmission is name=value. There are as many of these name/value pairs as there are elements on the form, and the pairs are concatenated with ampersands (&) to form a text string that resembles the following: name1=value1&name2=value2&name3=value3.... Any blank spaces appearing in the names or values are substituted with the plus (+) character to form a non-breaking string of name/value pairs. In the current application assume that the user entered the account "myaccount" and the password "xyzzy". The resulting name/value string delivered to the server would be: Account=myaccount&Password=xyzzy&SubmitButton=Submit Note that both field and button names and values are transmitted. Although shown here in the same order in which the elements appear on the form, there is no guarantee that the order of the name/value pairs that arrive at the server will be the same as it is on the form.

The Request.Form Collection The ASP Request Object provides valuable assistance in gathering form information transmitted to the server by putting it into a structure for convenient script processing. The Request Object intercepts the name/value string, parses the string into names and associated values, and places this information into a Request.Form Collection. This collection can be visualized as an array of submitted values, each indexed by its associated form field name.

Page 11 of 23

MODULE ITMAJ02

Prepared by: Sir Jhon

Once the data values are in the Request.Form Collection they can be easily referenced by their names using the syntax:

Request.Form("name")

where name is the name assigned to the field in the form. Thus, the reference Request.Form("Account") points to the value entered into the Account field; the reference Request.Form("Password") points to the value entered into the Password field; and the reference Request.Form("SubmitButton") is a reference to the value assigned to the Submit button. From a programming standpoint, Request.Form("name") works like a program variable that references a value stored in that variable. To summarize our application so far: The user calls up the logon.asp page, which is retrieved by the server and sent to the user's browser where the form is displayed. The user then enters information into the Account and Password fields and clicks the Submit button. This submission triggers a URL request to the server for the welcome.asp page (action="welcome.asp"). In addtion, the form attribute method="post" transmits a separate name/value data stream to the server representing the field names and entered values typed or selected by the user. This name/value string is received and parsed by the ASP Request Object, which places the values in its Request.Form Collection where they can be referenced by the names of their associated form fields. This Request.Form Collection is now available to the welcome.asp page as a means for checking the submitted values from the form. Iterating through the Request.Form Collection In the same fashion in which we previously iterated through the Request.ServerVariables Collection we can iterate through the Request.Form Collection. Doing so is not necessary in this example application; however, it does provide a good way of debugging scripts that process form information. It permits you to view the field names and submitted values to make sure that the correct information is being transmitted from the form. You can, for instance, code the following script at the top of the welcome.asp page: <% For Each Item in Request.Form Response.Write(Item & "=" & Request.Form(Item) & "<br>") Next %> This script displays each of the field names (Item) on the form along with its associated value (Request.Form(Item)) with each pair listed on a separate line. Using the example values shown above, the output at the top of the welcome.asp page would appear as follows: Account=myaccount Password=xyzzy SubmitButton=Submit By viewing this output you can confirm that the expected data were transmitted properly to the welcome.asp page prior to the actual processing of the form data.

Page 12 of 23

MODULE ITMAJ02

Prepared by: Sir Jhon

PROCESSING FORM

When a form is submitted, the string of name/value pairs is transmitted to the server and made available to the page named in the form's ACTION parameter. That target page has access to the form data through the Request Object's Form Collection. Any scripts on the page can access these form values through the reference: Request.Form("name"). Script Location Let's consider how to code a script on the welcome.asp page to check the information transmitted from the logon.asp page. We'll assume for the present example that we only need to check that the submitted password is "xyzzy." If users do NOT enter this value, then they do not get to see this page. Rather, the script will direct that the logon.asp page be returned to the user so that the form can be redisplayed. If they submit the correct password, however, the welcome.asp page will be returned to the user. The script needs to be at the top of the welcome.asp page so that it can evaluate the password and determine the course of action (return the logon.asp page or return the welcome.asp page) before a page is returned to the user. You always need to keep in mind that the location of a script depends in large measure on when it is to be run or where on the page where its processing is required. In order to check the password, the VBScipt coding uses an If statement. If the password is incorrect, the user is immediately redirected back to the logon.asp page. If the password is correct, the user does not get redirected and the welcome.asp page is transmitted to the user. Here is the coding for the complete page: welcome.asp <% If Request.Form("Password") <> "xyzzy" Then Response.Redirect("logon.asp") End If %> <html> <body> <h3>Welcome Page</h3> <p>Welcome to my page.</p> </body> </html> Accessing the Request.Form Collection Recall that data submitted from a form are placed into the Request.Form Collection, and that the values from the form fields can be accessed through the reference Request.Form("name"). Therefore, the script references Request.Form("Password") to check the password value that was entered on the form and transmitted to the server: If, as evaluated here, the Password value is not "xyzzy", then the user is redirected to the logon.asp page with the statement Response.Redirect("logon.asp"). If, on the other hand, the value submitted is "xyzzy," then the redirection doesn't take place. The script ends and this welcome.asp page is sent to the user's browser. Note that the value "xyzzy" is enclosed in quotation marks, indicating that this is a text string. Keep in mind that ALL values in an HTML form are text strings. Even if you have a field into which numbers are entered, the numerals are still considered to be text strings. You can perform arithmetic using these numerals; however, they need to be converted from strings to numbers before doing so. More about this later. The Response.Redirect() Method Recall that the ASP Response Object contains properties and methods that generally deal with output from server processing. The Response.Write() method, for example, has been used to write server variables, text, and HTML directly to a Web page. This object also supplies a Redirect() method that is used to transfer script control directly and immediate to a different page. Its general format is shown below.

Response.Redirect("url")

Page 13 of 23

MODULE ITMAJ02
This redirection is exactly what we want to happen if the user types the incorrect password. So, the code Response.Redirect("logon.asp")

Prepared by: Sir Jhon

transfers script control directly to the logon.asp page if the user has submitted the incorrect password. Thus, the user does not get an opportunity to see the welcome.asp page. Before the server finishes processing the welcome.asp page and sending it to the user in response to the action="welcome.asp" URL request that was coded on the form, the script interrupts and directs the server to access the logon.asp page and send it to the user instead. Viewing the Page Source You might be wondering why we would code a password directly on a Web page. Wouldn't it be seen by someone who looks at the code listing through the browser's "View Source" menu? Remember that the server intercepts .asp pages and does not immediately send them back to the browser making the URL request. First, the server runs the page through its ASP processor. It looks for VBScript code and executes that code, all the while recreating a purely HTML version of the page to be sent back to the user. Users never receives and never get to see any code on the pages transmitted back to the browser. They only get to view the results of processing--not the processing instructions themselves. Therefore, it is perfectly safe to include passwords or other private information within a script. This is not to say that this is the best way to check passwords; but it's a sufficient start. Testing the Application You can test this application by clicking the following link. A secondary window is displayed to run the logon.asp and welcome.asp pages. PASSING QUERY STRING In the previous example, when the user enters the incorrect password into the logon form, the welcome.asp page redirects the user back to the logon.asp page. The notion is that the user can try again to enter the correct account and password. However, when the logon.asp page is redisplayed, there is no indication to the user what has happened. We can help the user understand the situation better by displaying a message indicating that an incorrect password has been entered. logon.asp Logon Page Account: Password: Incorrect password

The question is, then, how will the logon.asp page know that an incorrect password has been entered so it can display the message? Well, that information has to come from the welcome.asp page, where the password check is made. Thus, the welcome.asp page needs to pass some information to the logon.asp page indicating that an error was made. Then, the logon.asp page will know to display the message. Query Strings We have already seen how one page can transmit information to another page through a form. A second method of passing information from one page to another is through a query string. A query string is a set of name/value pairs appended to the end of a URL. You have probably noticed these query strings in your browser's address box in your wanderings around the Web. They take on the general format shown below in bold: http://www.site.com?name=value&name=value... A query string is identified by a question mark followed by a collection of one or more names and values. The name/value pairs look and work identically to those transmitted from a form. The difference is that a query string is appended to a URL rather than traveling to the server in a separate data stream. For the logon application we can make use of a query string to have the welcome.asp page inform the logon.asp page that an incorrect password has been submitted. This is accomplished by appending the query string to the end of the URL that is issued when control is redirected to the logon.asp page. Since the query string is an internal control mechanism for our pages, we can use any name and any value that we choose. Here is the rewrite of the script appearing at the top of the welcome.asp page: welcome.asp

Page 14 of 23

MODULE ITMAJ02
<% If Request.Form("Password") <> "xyzzy" Then Response.Redirect("logon.asp?PassCheck=No") End If %> <html> <body> <h3>Welcome Page</h3> <p>Welcome to my page.</p> </body> </html>

Prepared by: Sir Jhon

We have appended the query string ?PassCheck=No to the end of the logon.asp URL. When the logon.asp page is accessed, the query string will be passed to it. The Request.QueryString Collection In a manner similar to which the ASP Request Object gathers form information into its Request.Form Collection, it also gathers query string information into its Request.QueryString Collection. The Request Object intercepts the name/value string following the question mark, parses the string into names and associated values, and places this information into the Request.QueryString Collection. This collection can be visualized as an array of submitted values, each indexed by its associated name. In the following illustration, the query string from the welcome.asp page has been placed into this collection, in this case having a single name and value pair.

The page to which the query string is sent can access names and values in the Request.QueryString Collection in a syntax similar to that used for the Request.Form Collection:

Request.QueryString("name")

where name is the name assigned to a value in the query string. Thus, the reference Request.QueryString("PassCheck") points to the value associated with the name PassCheck that arrives in the query string. We now need to return to the logon.asp page to add script that looks for this query string and determines whether to display the "Incorrect Password" message. PROCESSING QUERY STRING Our logon.asp page is accessed through redirection when the user enters the incorrect password. When this page is accessed by the server it doesn't get sent directly back to the user. It is first run through the ASP processor to check for any scripts. Also, since a query string accompanied the URL request, there is a Request.QueryString Collection made available to the page. So, we can include a script on the logon.asp page to check whether the value of Request.QueryString("PassCheck") is "No" in order to display a message indicating that the password previously submitted was incorrect. logon.asp <html> <body> <h3>Logon Page</h3>

Page 15 of 23

MODULE ITMAJ02
<form name="Logon" action="welcome.asp" method="post"> <table border="0"> <tr> <td>Account: </td> <td><input type="text" name="Account" size="10"></td> </tr> <tr> <td>Password: </td> <td><input type="password" name="Password" size="10"> <% If Request.QueryString("PassCheck") = "No" Then Response.Write("<span style='color:red'>Incorrect Password</span>") End If %> </td> </tr> </table> <input type="submit" name="SubmitButton" value="Submit"> </form> </body> </html>

Prepared by: Sir Jhon

Note that the script appears immediately following the Password field so that the message appears at this position. We have also used a <span> tag with a STYLE attribute to set the color of the displayed message to red. The server, in processing this page prior to sending it to the user, tests whether there is a Request.QueryString Collection containing the name "PassCheck" and associated with the value "No". If so, then an incorrect password has been discovered by the welcome.asp page and this logon.asp page has been accessed through a redirection URL with the query string attached. Thus, the HTML code <span style='color:red'>Incorrect Password</span> is written to the Web page. This is an important point! The server, in effect, rewrites the original HTML code on the page to include this additional line of code. This portion of the page, then, becomes ... <tr> <td>Password: </td> <td><input type="password" name="Password" size="10"> <span style='color:red'>Incorrect Password</span> </td> </tr> ... and this is the code that is delivered to the user's browser when control is redirected to the logon.asp page. Here we begin to see some of the real power within ASP--the ability to customize HTML output to conditions that arise during processing. Null Collections You might note that when the logon.asp page is first accessed--when the user first tries to log on--there is NO query string associated with the URL. The user simply enters http://...logon.asp to load the page. Still, when the server retrieves this page prior to sending it to the browser, the script is activated and the test If Request.QueryString("PassCheck") = "No" is made. At this point there is NO Request.QueryString Collection, nor a name "PassCheck", nor a value "No." These items occur only when a query string has been appended to the URL. They do not exist when the page is access the very first time. Fortunately, ASP does not consider this circumstance an error. It simply notes that the test is false and does not write the accompanying line of code informing the user of an incorrect password. The page returned to the user has this portion coded as follows: ... <tr> <td>Password: </td> <td><input type="password" name="Password" size="10"> </td>

Page 16 of 23

MODULE ITMAJ02
</tr> ...

Prepared by: Sir Jhon

This same processing occurs with the Request.Form Collection. It is perfectly fine to test for the presence of a form field value even if no form has been submitted and no Request.Form Collection exists. We'll have occasion to do this later. Testing the Application You can test this revised application by clicking the following link and entering an incorrect password. A secondary window is displayed to run the logon1.asp and welcome1.asp pages. After entering an incorrect password, check the source listing for the logon.asp page to view how ASP has added the code to display the message. SAME PAGE FORM SUBMISSION The logon.asp and welcome.asp pages work together to authorize visits to the welcome.asp page. In fact, even if a user tries to submit a URL request directly to the welcome.asp page--skipping over the logon.asp page--the script redirects the user to the logon page since welcome.asp still checks for a password. Although these two pages work properly, there is a certain awkwardness about having the logon procedure span two separate pages--to submit the Account and Password on one page and to check the submissions on a different page. There would be better coding efficiencies and fewer maintenance concerns if the entire logon procedure were confined to a single page. A common technique in form submission is to code the script that processes form data on the same page as the form itself. In other words, the page containing the form submits the data to itself and includes the script that processes the data. In this fashion all activities associated with the form and its submission and processing are isolated on the same page. In order to make this technique work properly, the script normally needs to be located at the top of the form page. This notion isn't as odd as it sounds. The page containing the form doesn't actually submit the data to itself. It transmits the data to the server, which, in turn, simply accesses the same page again--retrieving a different instance of the page--to which it makes the data available. Still, it is often convenient to visualize the process as a same-page form submission.

When the page is accessed by the user the first time, no form data has been submitted. Therefore, the script at the top of the page (which needs to check whether form data are available for processing) is not activated. Rather, the server simply sends the page to the user and the form is displayed in the browser. Now, the user fills out the form and submits it. The form's ACTION parameter identifies this same page in the URL request, and the name/value pairs from the form are transmitted to the server. The server then retrieves this same page (a different copy, of course) and makes available to it a Request.Form Collection containing the data from the previous submission from the page. When the page is accessed this second time, data are available to it through the Request.Form Collection. Therefore, the script is activated and the data are processed. When the server finishes processing, the page is again returned to the user for redisplay of the form. Let's apply this technique to our logon procedure. First, we'll move the password-checking script from the welcome.asp page to the top of the logon.asp page. At the same time, we need to enclose the script inside a condition test which runs the script only if there are form data to process. Then, we need to change the ACTION parameter on the form to point to this same logon.asp page, and we need to modify the script code so that when the correct password is entered, redirection is to the welcome.asp page. We also need to change the message display since this page no longer receives a query string from the welcome.asp page. logon.asp

Page 17 of 23

MODULE ITMAJ02
<% If Request.Form("SubmitButton") = "Submit" Then If Request.Form("Password") = "xyzzy" Then Response.Redirect("welcome.asp") Else Message = "Incorrect Password" End If End If %> <html> <body> <h3>Logon Page</h3> <form name="Logon" action="logon.asp" method="post"> <table border="0"> <tr> <td>Account: </td> <td><input type="text" name="Account" size="10"></td> </tr> <tr> <td>Password: </td> <td><input type="password" name="Password" size="10"> <span style="color:red"> <%=Msg%> </span> </td> </tr> </table> <input type="submit" name="SubmitButton" value="Submit"> </form> </body> </html>

Prepared by: Sir Jhon

Let's walk through the submission process. The first time the user makes a URL request for this page it is retrieved by the server, which runs any scripts appearing on the page. At the top of the page is the password-checking script. Since we want to run the script only on the condition that form data have been submitted, we need a way to check if this is the case. We know, for instance, that form data are made available to a page if there is a Request.Form Collection available to it. And, we know that one of the items appearing in the collection from this page is the variable "SubmitButton" with the value "Submit." We know this because we coded the form containing the button named "SubmitButton" and gave it a value of "Submit" as its label. Therefore, one way we can check on whether form data are available for processing by this script is to check the Request.Form Collection for this item. We could perform other tests to determine if the form has been submitted; however, this one is sufficient and, in effect, is a check to see if the user clicked the submit button. This first time this page is retrieved the condition test is evaluated as false. Since no form has yet been submitted, there is no "SubmitButton" item with a value of "Submit" in the Request.Form Collection. In fact, there is no Request.Form Collection at all. So, the body of the script is skipped without any action taking place and the server sends the page to the browser where the form is displayed. Now, the user enters an Account and Password and clicks the Submit button. The action="logon.asp" parameter triggers a URL request for this same page. Also, the name/value pairs from the form are transmitted to the server and placed in the Request.Form Collection where they are made available to this page. Again, the server retrieves the page and runs it through the ASP processor to evaluate any scripts. This time the condition test If Request.Form("SubmitButton")="Submit" is evaluated as true. There is such an item with such a value in the Request.Form Collection because the form has been submitted. Thus, the script is run. The script checks whether Request.Form("Password")="xyzzy"; that is, did the user enter the correct password in the form and is that value in the Request.Form Collection? If so, then redirection takes place to the welcome.asp page. If, however, the incorrect password is submitted, we need to indicate this fact to the user when the form is redisplayed. In this version of the script we assign the value "Incorrect Password" to a script variable named Msg. Then the script ends. Since, however, there was no redirection to the welcome.asp page, the logon.asp page is returned to the user for redisplay, with this message appearing next to the Password field through the code <%=Msg%>. Recall that this is one of the ways of displaying script variables embedded within HTML. Also, we've surrounded the variable display with a <SPAN> tag to set the text color to red.

Page 18 of 23

MODULE ITMAJ02

Prepared by: Sir Jhon

One last point about the script. The first time the page is accessed--prior to submission of the form--the Msg variable is displayed. However, this doesn't cause any message to appear. The variable only takes on the value "Incorrect Password" when the password is rejected. Therefore, when the page is initially accessed--and the script is NOT run--the value of Msg is undefined, or null. Thus, when Msg is displayed, no value appears on the page. The user only sees a blank form. Now that the processing script has been moved to the logon.asp page (localizing all password processing on this single page and removing the need for a query string to flag an incorrect password), a script is not needed on the welcome.asp page. All scripting can be removed with only the HTML coding appearing on this page. Testing the Application You can test this revised application by clicking the following link. A secondary window is opened to run the logon2.asp and welcome2.asp pages. The page displays are identical to the previous example, the differences being that logon2.asp is a selfcontained password-checking page and welcome2.asp is a pure HTML page. REDISPLAYING FORM VALUE When the logon.asp page is submitted with an incorrect password, there is no redirection to the welcome.asp page; the logon.asp page is returned, automatically redisplaying its form so the user can try again. When this form is redisplayed, all of its fields are blank. This happens because a new instance of the logon.asp page has been retrieved by the server and sent to the browser. However, it would be convenient for the user if, when the form is redisplayed, its fields were populated with the information previously submitted. In this way the user would only need to correct the data in error rather than having to reenter values in all the fields. This is not a particular problem with a form containing only two fields. However, it would be a great convenience with a form containing a large number of fields. The fact that the logon.asp page submits a form to itself means that the information is available for repopulating the form fields when the page is redisplayed. All that we need to do is value the fields of the form with the data from the previous submission. Then, when the page is sent back to the browser, it will be displayed with these data appearing in the fields. The data needed for repopulating the form, of course, are in the Request.Form Collection. So, we'll simply embed these values inside the HTML form using VALUE parameters for each of the associated form fields. Here is the entire logon.asp page with this coding added: logon.asp <% If Request.Form("SubmitButton") = "Submit" Then If Request.Form("Password") = "xyzzy" Then Response.Redirect("welcome.asp") Else Message = "Incorrect Password" End If End If %> <html> <body> <h3>Logon Page</h3> <form name="Logon" action="logon.asp" method="post"> <table border="0"> <tr> <td>Account: </td> <td><input type="text" name="Account" size="10" value="<%=Request.Form("Account")%>"></td> </tr> <tr> <td>Password: </td> <td><input type="password" name="Password" size="10" value="<%=Request.Form("Password")%>"> <span style="color:red"> <%=Msg%> </span> </td> </tr> </table> <input type="submit" name="SubmitButton" value="Submit"> </form>

Page 19 of 23

MODULE ITMAJ02
</body> </html> Note the coding added to the Account and Password fields: value="<%=Request.Form("Account")%>" value="<%=Request.Form("Password")%>"

Prepared by: Sir Jhon

Both fields contain a VALUE clause which assigns a value to the fields to appear when the form is displayed. These values are the respective Account and Password values stored in the Request.Form Collection. They are placed in the fields by embedding them with the <%= %> display syntax. In response to these script directives the server places the associated values at these locations within the HTML coding. Thus, when the page is returned to the user following submission of an incorrect password, the previously entered values are displayed when the form is redisplayed. Of course, these values are also displayed when the page is initially accessed, prior to form submission. Again, however, since there is no Request.Form Collection at this time, these values are null. So, blank fields are displayed the first time the form appears. Testing the Application You can view these value redisplays by clicking the following link and entering an incorrect password. The values that you initially submit reappear on the form when it is redisplayed. If you take a look at the source listing for the page when it reappears, you will see that the server has written the submitted values within the HTML code for the form. PASSING STATUS FLAGS The logon.asp page is now working pretty well. However, there is a really big hole in the application. Since we removed the logon script from the welcome.asp page, it is now possible for a person who knows the name of the page to access it directly by entering its URL into the browser, bypassing the logon.asp page. The intent is that the welcome.asp page--as well as any number of other pages at our site--should only be accessed by persons who have logged on. What we need to do, then, is add scripting to the welcome.asp page, and to any other pages we want to protect, to check whether the visitor has logged on. If not, the visitor should be redirected to the logon.asp page. There are two basic methods of setting up status "flags," or controls, to indicate that a processing condition has been satisfied. One method involves the passing of a query string value to a page to indicate the status. The other method involves use of the built-in ASP Session Object. We'll take a look at the query string method on this page and the Session method on the following page. Query Strings Revisited If a Web page needs to be informed of a processing result that occured on another Web page, it can be passed a query string value indicating that fact. Otherwise, there is no way for one page to communicate information directly to another page. In our current logon application, a user account and password are submitted to and checked by the logon.asp page. If a correct password is submitted, the script redirects the visitor to the welcome.asp page. However, this does not prohibit the visitor from directly accessing the welcome.asp page, nor does it prohibit the visitor from accessing any other page at our site by bypassing the logon page. One way to solve this problem is for our logon.asp page to set up some sort of status flag indicating that the visitor has successfully logged on. Then, every other page at our site can check this flag before permitting the visitor to view the page. For example, let's recode the script of the logon.asp page to initialize a status flag indicating a successful password submission: logon.asp <% If Request.Form("SubmitButton") = "Submit" Then If Request.Form("Password") = "xyzzy" Then Response.Redirect("welcome.asp?PassCheck=Yes") Else Message = "Incorrect Password" End If End If %>

Page 20 of 23

MODULE ITMAJ02
...

Prepared by: Sir Jhon

What we've done is added the query string ?PassCheck=Yes to the URL for the welcome.asp page. This name/value pair is sent to that page indicating that, indeed, the user has visited the logon.asp page and submitted the correct password. Of course, we could use any name and value that we wish since this is an internal control flag whose name and value are arbitrarily established by the programmer. Now we can add a short script to the top of the welcome.asp page to check for this query string value. If the value is present (as would be the case if the visitor submitted the correct password to the logon.asp page), then the page can be displayed to the visitor. If the value is absent (as would be the case if the user bypassed the logon.asp page), then the visitor is redirected to the logon page. welcome.asp <% If Request.QueryString("PassCheck") <> "Yes" Then Response.Redirect("logon.asp") End If %> ... This same script would need to be added to the top of every page at our site that needed to be password protected. Then, if visitors tried to access those page directly, they would automatically be redirected to the logon page. There is one remaining situation, though, that we haven't taken care of. Normally, visitors browse the pages of a site by clicking links between pages. Let's assume there is the link <a href="nextpage.asp">Next Page</a> on the welcome.asp page which links to page nextpage.asp. If nextpage.asp contains the script to check for a correct password submission (looking for the query string ?PassCheck=Yes), visitors will be rejected and redirected to the logon.asp page, even if they had previously entered the correct password. The reason is that the script at the top of nextpage.asp looks for a query string flag, but no query string is passed through the link. Of course, we can solve this problem by appending the query string to the link: <a href="nextpage.asp?PassCheck=Yes">Next Page</a> In fact, we would need to pass this query string through every link between pages at our site as a way to keep the flag active and checkable on each page visited. Maintaining State with Query Strings In general, the use of query strings to pass information between Web pages is an important technique to know for Web developers. As a processing environment, the Web does not inherently "maintain state." That is, Web pages exist in virtual isolation from one another. There is no natural connection between them such that any one page is aware of the processing results of another page. After a script is run and the page is delivered to the browser, there are no remnants of processing; all the HTML code, the scripts, and the variables are erased from the server's memory. There is no remembrance of the page even having existed. In such a "state-less" environment the only way for pages to communicate information is by explicitly passing that information, either through query strings or by submitting forms. Thus, in order to coordinate processing among several pages, the developer often needs to explicitly code query strings or forms through which information is passed between pages. Although ASP does provide a mechanism to help overcome some of the difficulties in maintaining state (see the next page), developers still need to have facility with coding explicit exchanges of information through query strings and forms.

Testing the Application The following link implements the query string flag between pages. After submitting the correct password on the logon.asp page, check the URL appearing in the Address box of the browser window. You should see the query string appended to the end of the

Page 21 of 23

MODULE ITMAJ02

Prepared by: Sir Jhon

URL for the welcome.asp page. The same query string should also be appended to the end of the URL for nextpage.asp when that link is clicked. USING SESSION VARIABLES The logon.asp page is now working pretty well. However, there is a really big hole in the application. Since we removed the logon script from the welcome.asp page, it is now possible for a person who knows the name of the page to access it directly by entering its URL into the browser, bypassing the logon.asp page. The intent is that the welcome.asp page--as well as any number of other pages at our site--should only be accessed by persons who have logged on. What we need to do, then, is add scripting to the welcome.asp page, and to any other pages we want to protect, to check whether the visitor has logged on. If not, the visitor should be redirected to the logon.asp page. There are two basic methods of setting up status "flags," or controls, to indicate that a processing condition has been satisfied. One method involves the passing of a query string value to a page to indicate the status. The other method involves use of the built-in ASP Session Object. We'll take a look at the query string method on this page and the Session method on the following page. Query Strings Revisited If a Web page needs to be informed of a processing result that occured on another Web page, it can be passed a query string value indicating that fact. Otherwise, there is no way for one page to communicate information directly to another page. In our current logon application, a user account and password are submitted to and checked by the logon.asp page. If a correct password is submitted, the script redirects the visitor to the welcome.asp page. However, this does not prohibit the visitor from directly accessing the welcome.asp page, nor does it prohibit the visitor from accessing any other page at our site by bypassing the logon page. One way to solve this problem is for our logon.asp page to set up some sort of status flag indicating that the visitor has successfully logged on. Then, every other page at our site can check this flag before permitting the visitor to view the page. For example, let's recode the script of the logon.asp page to initialize a status flag indicating a successful password submission: logon.asp <% If Request.Form("SubmitButton") = "Submit" Then If Request.Form("Password") = "xyzzy" Then Response.Redirect("welcome.asp?PassCheck=Yes") Else Message = "Incorrect Password" End If End If %> ... What we've done is added the query string ?PassCheck=Yes to the URL for the welcome.asp page. This name/value pair is sent to that page indicating that, indeed, the user has visited the logon.asp page and submitted the correct password. Of course, we could use any name and value that we wish since this is an internal control flag whose name and value are arbitrarily established by the programmer. Now we can add a short script to the top of the welcome.asp page to check for this query string value. If the value is present (as would be the case if the visitor submitted the correct password to the logon.asp page), then the page can be displayed to the visitor. If the value is absent (as would be the case if the user bypassed the logon.asp page), then the visitor is redirected to the logon page. welcome.asp <% If Request.QueryString("PassCheck") <> "Yes" Then Response.Redirect("logon.asp") End If %> ...

Page 22 of 23

MODULE ITMAJ02

Prepared by: Sir Jhon

This same script would need to be added to the top of every page at our site that needed to be password protected. Then, if visitors tried to access those page directly, they would automatically be redirected to the logon page. There is one remaining situation, though, that we haven't taken care of. Normally, visitors browse the pages of a site by clicking links between pages. Let's assume there is the link <a href="nextpage.asp">Next Page</a> on the welcome.asp page which links to page nextpage.asp. If nextpage.asp contains the script to check for a correct password submission (looking for the query string ?PassCheck=Yes), visitors will be rejected and redirected to the logon.asp page, even if they had previously entered the correct password. The reason is that the script at the top of nextpage.asp looks for a query string flag, but no query string is passed through the link. Of course, we can solve this problem by appending the query string to the link: <a href="nextpage.asp?PassCheck=Yes">Next Page</a> In fact, we would need to pass this query string through every link between pages at our site as a way to keep the flag active and checkable on each page visited. Maintaining State with Query Strings In general, the use of query strings to pass information between Web pages is an important technique to know for Web developers. As a processing environment, the Web does not inherently "maintain state." That is, Web pages exist in virtual isolation from one another. There is no natural connection between them such that any one page is aware of the processing results of another page. After a script is run and the page is delivered to the browser, there are no remnants of processing; all the HTML code, the scripts, and the variables are erased from the server's memory. There is no remembrance of the page even having existed. In such a "state-less" environment the only way for pages to communicate information is by explicitly passing that information, either through query strings or by submitting forms. Thus, in order to coordinate processing among several pages, the developer often needs to explicitly code query strings or forms through which information is passed between pages. Although ASP does provide a mechanism to help overcome some of the difficulties in maintaining state (see the next page), developers still need to have facility with coding explicit exchanges of information through query strings and forms. Testing the Application The following link implements the query string flag between pages. After submitting the correct password on the logon.asp page, check the URL appearing in the Address box of the browser window. You should see the query string appended to the end of the URL for the welcome.asp page. The same query string should also be appended to the end of the URL for nextpage.asp when that link is clicked.

Page 23 of 23

You might also like