N342 Active Server Pages

Modified

Basics

Microsoft ASP technology is a server-side programming technology primarily used to generate HTML and access databases, files and any other server resource.  Programs consist of scripts executed by an interpreter (JavaScript, VBScript, PerlScript, etc.) within the server space. One advantage of ASP scripts is they are generally light-weight to execute assuming the script interpreter is re-entrant and can be managed by the server to limit resources allocated to the script. The scripting languages are simple to program but limited but can be extended via ActiveX objects. A key disadvantage is ASP is not a cross-platform standard across servers so moving applications from a Microsoft Web server may be painful.

ASP.Net attempts to separate implementation logic (i.e. programming) from the user interface; but it is more tightly integrated into Microsoft software and offers fewer industry standard choices of languages.

We will use ASP and JavaScript as these are most commonly available in some version or flavor on other servers.

Example - The following uses an ASP VBScript on the server to generate text for the current time on the server. The time.Asp file can be executed from a virtual directory by (assuming the time.Asp file is in virtual directory A348 on the localhost):

http://localhost/A348/Time.asp

VBScript time.Asp

Time is <%=Time()  %>. 

HTML Generated

Time is 7:24:07 PM.


Points of Note

Example - Both of the following uses ASP JavaScript to display Hello World three times.

JavaScript HelloWorld.Asp

<%@ LANGUAGE = JScript %> 
<% 
     for(i=1;i<=3;i++) { 
%>
         Hello World <%=i%><br/>
<% 
     } 
%>
HTML Generated
Hello World 1<br/>
Hello World 2<br/>
Hello World 3<br/>
JavaScript HelloWorld.Asp

<%@ LANGUAGE = JScript %> 
<% for(i=1;i<=3;i++) { 
          Response.Write("Hello World "+i+"<br/>");
      } 
%>
HTML Generated
Hello World 1<br/>
Hello World 2<br/>
Hello World 3<br/>

Exercise 1 - ASP, FrontPage  and .Net  

ASP

  1. Copy the above JavaScript HelloWorld.Asp to a file named W:\N342\Exercise1.asp
  2. Execute by: www.ius.edu/username/N342/Exercise1.asp
  3. Right-click and copy to the W:\N342 directory.
  4. Modify the JavaScript to generate HTML to display the digits when script is executed.
  5. Note the HTML: Count<%=i%> generates: Count4 when i is 4.
  6. Execute. You should see . The ASP should generate HTML similar to: <img src="digit0.gif">

FrontPage - To create an ASP file:

  1. Open FrontPage
  2. File | New
  3. Select Blank Page
  4. Switch to Code view
  5. Delete the any unneeded lines.
  6. Save with ASP extension.

.Net - To create an ASP file:

  1. Open MicroSoft Visual Studio .Net
  2. File | New | File | Script | Active Server Page
  3. Delete the any unneeded lines.

 

Mixed Server-side and Client-side

A server-side script must output something useable to the browser such as HTML, JavaScript, image, etc.

The following uses an ASP VBScript (in bold) on the server to generate a combination of HTML and JavaScript for the client browser.

The 4Buttons.Asp file is on the IUS Web server so that clicking 4Buttons.Asp executes directly from the IUS server.  Or download to N342 virtual directory on your personal machine running IIS and execute by: http://localhost/N342/4Buttons.Asp

VBScript 4Buttons.Asp
<%@ Language=VBScript%>
<title>Buttons</title>
<h1>Buttons</h1>
<form>
<% 
     For intCounter = 1 to 4
%>
 <INPUT TYPE = button 
   VALUE = Button<%=intCounter%> 
   OnClick="Button<%=intCounter%>_Click()"
  >
<% 
     Next
%>
</form>
<Script Language="JavaScript">
<%
    For intCounter = 1 to 4
%>
  function Button<%=intCounter%>_Click() {
   alert("Clicked button <%=intCounter%>");
 }
<%
    Next
%>
</Script>
HTML and JavaScript Generated
<title>Buttons</title>
<h1>Buttons</h1>
<form>
  <INPUT TYPE = button 
     VALUE = Button1 
     OnClick = "Button1_Click()">
  <INPUT TYPE = button 
     VALUE = Button2 
     OnClick = "Button2_Click()">
  <INPUT TYPE = button 
     VALUE = Button3 
     OnClick = "Button3_Click()">
  <INPUT TYPE = button 
     VALUE = Button4 
     OnClick = "Button4_Click()">
</form>
<Script Language="JavaScript">
  function Button1_Click() {
   alert( "Clicked button 1");
  }
  function Button2_Click() {
   alert( "Clicked button 2");
  }
  function Button3_Click() {
   alert( "Clicked button 3");
  }
  function Button4_Click() {
   alert( "Clicked button 4");
  }
</Script>

Points of note 

 

Re-execute Script file

An ASP script can generate HTML that re-executes the ASP.  For example, the ASP below re-executes itself each time the Again submit button is clicked.

JavaScript Again.Asp

<%@ LANGUAGE = JavaScript %> 

<FORM Method='GET' Action='Again.asp'> 
    <Input Type=Submit value='Again'>
</FORM>
HTML Generated
<FORM Method='GET' Action='Again.asp'> 
    <Input Type=Submit value='Again'>
</FORM>

 

Exercise 1.5 - Script file only

Start with the Again.asp to implement a JavaScript program Dice.asp to simulate simple dice rolling. The script should generate HTML with:

  • A submit button to roll the dice.
  • When the roll button is clicked, re-execute the script.
  • Display each die. Output expression to the page being generated to the browser client by:
    • Response.Write( expression );
    •  <%= expression %>

Hint: A random number 1-6 is generated by: Math.round(6*Math.random( ))%6+1;
        Use the random number as the value of the dice buttons.

 

Request and Response Objects

Request yields input from the browser GET or POST methods. The value of the form input variable named "BuyHigh" is given by:

Response outputs to the browser among other uses. To output the string <h1>Hello</h1> from JavaScript:

 

User Interaction 

The main motivation for server-side programming is to interact with the Web client by getting input from the client and sending back HTML. There are three main HTML methods for the client to send data back to the server from HTML forms:

  1. GET
  2. POST
  3. Send data as part of the URL, a ? is appended to the URL followed by data. This will be examined later in the course.

 

HTML <FORM> 

Sending parameters to a server program from a HTML input form uses the GET or POST method. The main difference is that the GET passes parameters in the URL or address so is limited to how much data can be passed. The POST method passes parameters back to the server through standard input so is effectively unlimited in the amount of data that can be returned. 

The following uses named parameters in HTML form as program arguments. The <Input Type='Text' name="myname"> defines a text box for input and the parameter of myname.

Form GET Method 

    The GET method passes user data from the browser to the server as part of the URL. The Get method and form to input from a Text box is:

    GetName.htm
    <FORM Method='GET'  
               Action='http://localhost/A348/GetName.asp'>

               Enter your name:
                    <Input Type='Text' name="myname">

    </FORM>
  • GET - Form data is passed to server appended to the URL.  
  • Action - The URL when user presses the Enter key.
  • Text - The browser renders a text box for user input.
  • myname - The name of the text box. Suppose that ABC is entered into the text box. Browser will send myname=ABC for the myname text box value.

    The browser passes the parameters to the server appended to the URL, the server passes the parameters to the ASP program in a Request variable. The GetName.asp program reads the variable and parses out the "myname=" string and assigns whatever string follows to the character array myname. The steps followed are roughly:

    1. Load the GetName.htm file into the browser, enter Ray, and press Enter.
    2. The form instructs the browser to send request http://localhost/A348/GetName.asp?myname=Ray which executes the GetName.asp program with parameter data myname=Ray.
    3. The GetName.asp program requests the value of myname  giving the response output of:
      <H1>Hello Ray</H1>
    4. The output of <H1>Hello Ray</H1> is passed back from the server to the browser which renders the HTML.
<FORM Method='GET'>
GetName.htm
<FORM Method='GET'  
           Action='http://localhost/A348/GetName.asp'>

           Enter your name:
                <Input Type='Text' name="myname">

</FORM>
 

GetName.asp

<%@ LANGUAGE = JavaScript %>
<H1> Hello <%= Request("myname") %> </H1>

URL generated on browser for form

http://localhost/A348/GetName.asp?myname=Ray
Output

<H1>Hello Ray</H1>

    Points of note:

Exercise 2 - Get Method

  • Create two files.
    • HTML BuyHigh.htm file with input form.
      • Use the Get method to input a checkbox value and an action to execute an ASP program to be implemented next. An input form checkbox named BuyHigh can be defined as:
      • <FORM Method='GET'  
                      Action='BuyHigh.asp'>
          <Input Type=CheckBox name='BuyHigh' value='yes'>
          <Input Type=Submit>
        </FORM>

         

    • ASP JavaScript BuyHigh.asp:
      • Send back an HTML response to the browser that box is Checked (when Request("BuyHigh") == "yes") or Not Checked
      • Modify the ASP JavaScript with If-Then-Else conditional:
        <%@ Language=JavaScript %>
        <% 
               x = 1
               if (x == 1) {

                     Response.Write( "HTML 1" );
         
               }
               else {

                     Response.Write( "HTML 2" );

               }
        %>

         

  • Notice the address bar when box is checked.

Form POST Method

<FORM Method='POST'>
Post.htm
<FORM Method='POST'  
            Action='http://localhost/N342/Post.asp'>
Enter your name: <Input Type='Text' name="myname">
</FORM>
 

Post.asp

<%@ LANGUAGE = JavaScript %>
<% Response.Write(
        "<H1> Hello " + Request("myname") + "</H1>");
%>

URL generated on browser for form

http://localhost/N342/Post.asp

Input passed to ASP program
myname=Ray

Output

<H1>Hello Ray</H1> 

 

 

Exercise 3 - Post Method

  • Create two files.
    • HTML input form.
      • Use the Post method to input a checkbox value and an action to execute an ASP to be implemented next. An input form checkbox named BuyHigh can be defined as:
      • <FORM Method='POST'  
                      Action='BuyHigh.asp'>
        <Input Type=CheckBox name='BuyHigh' value='yes'>
        <Input Type=Submit>
      • Save BuyHigh.htm file to N342 directory.
    • ASP JavaScript BuyHigh.asp:
      • Send back an HTML response to the browser that box is Checked (when Request("BuyHigh") == "yes") or Not Checked. 
      • ASP JavaScript with If-Then-Else conditional is:
        <%@ Language=JavaScript %>
        <% 
               x = 1
               if (x == 1) {

                     Response.Write( "HTML 1" );
         
               }
               else {

                     Response.Write( "HTML 2" );

               }
        %>
  • Notice the address bar when box is checked.

 

Server variables

The operating system maintains state in part through the use of global variables. At the Command prompt these variable can be displayed by the SET command.

SET

COMPUTERNAME=RAY
ComSpec=C:\WINDOWS\system32\cmd.exe
HOMEDRIVE=C:
NUMBER_OF_PROCESSORS=2
OS=Windows_NT
Path=c:\apps\imagemagick-6.2.1-q16;C:\apps\
PROCESSOR_ARCHITECTURE=x86
PROCESSOR_IDENTIFIER=x86 Family 15 Model 2
PROMPT=$P$G
SystemRoot=C:\WINDOWS
USERNAME=ray

The server and operating system maintain a large number of server variables that can be examined by an ASP program. The following prints all server variables back to the browser. Note that the browser output has been edited to reduce size.

The ServerVariables collection has the following properties:

The server variable QUERY_STRING contains any form variables returned by the GET method.

Server Variables
Browser Output

4 APPL_PHYSICAL_PATH=C:\N342\
29 PATH_INFO=/N342/ServerVariables.asp
31 QUERY_STRING=myname=Ray
35 REQUEST_METHOD=GET
36 SCRIPT_NAME=/N342/ServerVariables.asp
37 SERVER_NAME=localhost
38 SERVER_PORT=80
39 SERVER_PORT_SECURE=0
40 SERVER_PROTOCOL=HTTP/1.1
41 SERVER_SOFTWARE=Microsoft-IIS/5.0
42 URL=/N342/ServerVariables.asp
URL

http://localhost/N342/ServerVariables.asp?myname=Ray


ServerVariables.asp

<%@ Language=JavaScript%>

<%
  for(i=1; i<=Request.ServerVariables.Count(); i++) {
    strKeyName = Request.ServerVariables.Key(i);
    strKeyValue = Request.ServerVariables.Item(strKeyName);
    Response.Write(
          i + " " + strKeyName + "=" + strKeyValue + "<br>");
  }
 %>

 

Hidden Variables to Maintain State

Maintaining state is critical for user interaction such as games, shopping carts, etc. but somewhat challenging given that the HTTP protocol of the Web is a stateless protocol, the server does not automatically maintain user state. We've examined several ways to maintain state on the client such as client scripts (e.g. JavaScript). Hidden form variables represent yet another way to maintain state on the client but pass the state information to the server. Hidden variable are simply HTML form variables that are declared as hidden, that is there is no visible text box, check box, etc.

Example - Simple Counter

The following is an example in ASP that maintains a counter using hidden form variable formCounter. The basic concept is that the server program has two separate executions:

  1. an initial execution where no data supplied, triggering the generation of the initial HTML form that contains the hidden variable. 
  2. subsequent executions are supplied counter data, which is incremented and returned to the browser as a hidden variable. 

The hidden variable maintains state, the state is the number of times the program has been executed by a specific browser. 

The communication between the browser and server is in two parts.

  1. Browser sends request without any data to the server: http://localhost/N342/counter.asp
    • The server executes counter.asp, checks if the formCount form variable is defined (i.e. Request("formCount").count == 0 implies undefined). If formCount is undefined, indicating the first execution of the program, set ASP variable aspCOUNT = 0.
    • The browser receives the <FORM> with the hidden variable formCount=0.
    • The initial <FORM> with no data is: 
       Count is: 0 <br>
        <FORM Name="CounterForm" Method='GET' 
                    Action='http://localhost/N342/counter.asp'> 
         <Input Type='hidden' name='formCount' value='0'><br> 
         <Input Type=Submit>
        </FORM> 
  2. Browser sends request with data to the server: http://localhost/N342/counter.asp?formCount=0
    • The server checks if the formCount form variable has a value, assign aspCOUNT = 0.
    • Increment aspCOUNT=parseInt(Request("formCount"))+1.
    • Server generated HTML form is returned to the browser with the hidden variable counter value of COUNT in the ASP script. The value of formCount form variable is incremented with each execution. The following would be generated for a aspCOUNT = 1.
     Count is: 1 <br>
      <FORM Name="CounterForm" Method='GET' 
                  Action='http://localhost/N342/counter.asp'> 
       <Input Type='hidden' name='formCount' value='1'><br> 
       <Input Type=Submit>
      </FORM> 

      

Maintaining State of a Counter with a Hidden Variable
counter.asp - Execute when in virtual N342 directory by: 
            
            
            
            
            
            
            
            
             http://localhost/N342/counter.asp

<%@ LANGUAGE = JScript %>

<% 
    if (Request("formCount").count == 0)
       aspCOUNT = 0;
    else
       aspCOUNT = parseInt(Request("formCount")) + 1;
%>

Count is: <%= aspCOUNT %> <br>
  <FORM Name="CounterForm" Method='GET' 
              Action='counter.asp'> 
   <Input Type='hidden' name='formCount'
              value='<%= aspCOUNT %> '>
              <br> 
   <Input Type=Submit>
  </FORM> 
HTML generated by counter.asp execution
Count is: 3 <br>
  <FORM Name="CounterForm" Method='GET' 
              Action='counter.asp'> 
   <Input Type='hidden' name='formCount'
              value='3'>
              <br> 
   <Input Type=Submit>
  </FORM> 

URL generated by Submit when formCount=2

http://localhost/N342/counter.asp?formCount=2

Browser output

Notes

http://localhost/N342/count.asp

To test that the individual form variable is undefined even though other variables may be defined by:

Request("formCount").count == 0

Exercise 4.0

  • Copy and paste the Counter.asp file.
  • Open in a browser.
  • View | Source.

Exercise 4.1 - State

ASP offers a means to maintain state on the server, which will be examined later in the course. For now, state will be maintained by a hidden form variable.

Create a modulus 4 counter using an ASP. 

  1. Create an ASP file named Exercise4.asp using .NET
  2. Collect the four different image files  (right click on the image to save). Name them "digit0.gif", "digit1.gif", etc. for example.
  3. Use a hidden variable to maintain state. The form HTML generated for a count of 2 would be something as:
    <form method="GET" action="Exercise4.Asp" name="Counter">
    <INPUT TYPE = hidden name=formCount value=2 >
    <img src="digit2.gif" onClick="Counter.submit();">
    </form>
  4. On the first execution of Exercise4.Asp the form variable formCount will be empty, there will be 0 parameters. Test for the two cases of form variable empty and with a value.
  5. Define a text link to reset the count to 0 by loading the original ASP file Exercise4.asp with no parameters.
  6. When the digit link is clicked, increment the image displayed to the next image; digit0.gif, digit1.gif, etc. and back to digit0.gif. Use the URL state to count which image is to be displayed. The modulus operator in JavaScript is %, VBScript is Mod.