Share via


Module Two: Using COM Components in ASP Pages

Using Microsoft Component Object Model (COM) components in your ASP pages can dramatically extend the power that ASP already offers. COM components are pieces of compiled code that can be called from ASP pages. COM components are secure, compact, reusable objects that are compiled as DLLs and can be written in Microsoft Visual C++, Microsoft Visual Basic, or any language that supports COM. For example, Microsoft ActiveX Data Objects (ADO), which are used in Module 1 of this tutorial, provides you with methods and properties to efficiently query databases. By using ADO, you don't have to write your own complex data access code because ADO objects are built using COM components.

In this module, you use COM components that are included with ASP, and you also have a chance to write one of your own. This module shows how to develop an ASP page that delivers services useful in e-commerce and includes the following lessons:

  • Lesson 1: Rotating Advertisements: Rotate ads on a Web page, record user data, and redirect users when advertisements are clicked on.
  • Lesson 2: Counting Page Hits: Track the number of times users request a page.
  • Lesson 3: Creating a Visual Basic COM Object: Create your own ActiveX object using Microsoft Visual Basic.
  • Lesson 4: Creating a Java COM Object: Create your own Java object using Microsoft Visual J++.

Lesson 1: Rotating Advertisements

Advertising is big business on the Web. This lesson describes how to use the Ad Rotator component, installed with IIS, to rotate advertisements on your Web pages. The Ad Rotator component selects an advertisement for your Web page each time the user loads or refreshes the Web page. Furthermore, if you want to change an advertisement, you only need to change it in the redirection and rotation schedule files, instead of changing all the ASP files that contain the advertisement. This saves development time if the advertisement appears on numerous pages within your Web site.

Two files are required to set up the Ad Rotator component: a redirection file, which contains URL links to ads, and a rotation schedule file, which contains display data. By setting up these two files, the Ad Rotator component can be called by any ASP page on your Web site.

In this lesson you perform the following tasks:

  • Example 1: Create an Ad Rotator rotation schedule file that creates ad-image links on any page that calls this file.
  • Example 2: Create an Ad Rotator redirection file that specifies global ad-display data and information specific to each advertisement.
  • Example 3: Create an include file to hold your Ad Rotator calling code.
  • Example 4: Test the Ad Rotator by creating an ASP page that calls the Ad Rotator component to display and rotate ads. This example requires that examples 1, 2, and 3 are completed first.

Example 1: Create an Ad Rotator Rotation Schedule File

A rotation schedule file is used to catalog information about the ads you want to display, including redirection information after the advertisement is clicked on, the size of the displayed advertisement, the image to display, a comment for the advertisement, and a number that indicates how often a particular advertisement is chosen. When methods of the Ad Rotator component are called in an ASP page, the component uses this file to select an advertisement to display.

The rotation schedule file is divided into two sections that are separated by an asterisk (*). The first section provides information common to all the ads, and the second section lists specific data for each ad. To test the rotation schedule file, you will use some images from Microsoft.com for your ad images. The following list outlines the structure of the rotation schedule file:

Section 1
  • Redirection: In URL form, the path and name of the ASP file that can be executed before showing an advertisement. This file can be used to record information about the user who clicks on your ad. You can record information such as the client's IP address, what page the client saw the advertisement on, how often an advertisement was clicked on, and so forth. This ASP file can also handle the case where there is no URL associated with any advertisement in Section 2. When charging advertisers for each hit on their advertisement, it is good practice to prove to them that all the hits aren't resulting from the same user repeatedly hitting Refresh.
  • Width: The width of each ad image, in pixels. The default is 440.
  • Height: The height of each ad image, in pixels. The default is 60.
  • Border: The border thickness around each ad image. The default is 1.
  • Asterisk (*): Separates the first section from the second section. This character must be on a line by itself.
Section 2

You need to complete the following for each advertisement:

  • Image URL: The virtual path and filename of the image file for the advertisement.
  • Advertiser's Home URL: The URL to jump to when this link is selected. If there is no link, use a hyphen (-).
  • Text: The text to display if the browser does not support graphics.
  • Impressions: An integer indicating the relative weight to give to this ad when the Ad Rotator component selects an advertisement. For example, if you list two advertisements, an ad given an impression of 3 has a 30% probability of being selected while an ad given an impression of 7 has a 70% probability of being selected. In this example, the Ad Rotator component selects the Microsoft Windows advertisement two times out of five and the Microsoft Office advertisement is selected three times out of five.

Copy and paste the following code in your text editor, and save the file as MyAdRot.txt in the x:\Inetpub\Wwwroot\Tutorial directory.

  REDIRECT AdRotRedirect.asp 
  WIDTH 250 
  HEIGHT 60 
  BORDER 0 
  https://www.microsoft.com/windows/images/bnrWinfam.gif 
  https://www.microsoft.com/windows 
  Microsoft Windows 
  2 
  https://www.microsoft.com/office/images/office_logo.gif 
  https://www.microsoft.com/office 
  Office 2000 
  3

Example 2: Create an Ad Rotator Redirection File

When a user clicks on an advertisement, an Ad Rotator redirection file written in ASP can capture some information before showing the advertisement and write that information to a file.

For this to work, the x:\InetPub\Wwwroot\Tutorial folder must give Read/Write access to the IUSR_ComputerName and IWAM_ComputerName accounts. Alternatively, you can write this information to a Microsoft Access database using the code from Lesson 3 in Module 1 of this tutorial.

note Note In the code below, Server.HTMLEncode is used to encode header fields. In previous lessons, HTMLEncode was used to encode form input only. However, it is possible for a malicious user to manipulate header information, so it is a good security practice to encode all input generated from a request, not just form input.

Copy and paste the following code in your text editor, and save the file as AdRotRedirect.asp in the x:\Inetpub\Wwwroot\Tutorial directory.

  <%@ Language=VBScript %> 
<html> 
<head> 
<title>AdRotRedirect file</title> 
</head> 
<body> 

<% 
'Create some variables. 
dim strLogFile 

'Get the physical path of this Web directory so that we know the path exists. 
'The ASP Server object has many useful methods. 
strLogFile = Server.MapPath(".") & "\AdRotLog.txt" 

'Set some constants for working with files. 
Const cForAppending = 8 
Const cTristateUseDefault = -2 

'Create a FileSystemObject object, 
' which gives you access to files and folders on the system. 
Set fsoObject = Server.CreateObject("Scripting.FileSystemObject") 

'Open a handle to the file. 
'True means that the file will be created if it doesn't already exist. 
Set tsObject = fsoObject.OpenTextFile(strLogFile, cForAppending, True) 

'Record the data for the user who has just clicked on an advertisement. 
'We have used the Write method of the ASP Request object. 
'The ServerVariables collection of the ASP Request object holds vast 
' amounts of data for each request made to a Web server. 
tsObject.WriteLine "--------------------" 
tsObject.WriteLine Date & ", " & Time 
tsObject.WriteLine Server.HTMLEncode(Request.ServerVariables("LOGON_USER")) 
tsObject.WriteLine Server.HTMLEncode(Request.ServerVariables("REMOTE_ADDR")) 
tsObject.WriteLine Server.HTMLEncode(Request.QueryString("url")) 
tsObject.WriteLine Server.HTMLEncode(Request.ServerVariables("HTTP_REFERER")) 
tsObject.WriteLine Server.HTMLEncode(Request.ServerVariables("HTTP_USER_AGENT")) 
tsObject.Close 

'Redirect to the Advertiser's Web site using the Redirect method 
' of the ASP Response object. 
'When the AdRotator component calls AdRotRedirect.asp, it 
' automatically passes in the advertiser's URL in the QueryString. 
Response.Redirect Server.HTMLEncode(Request.QueryString("url")) 
%> 

</body> 
</html>

Example 3: Create an Ad Rotator Include File

Include files are used to store any code that will be used by more than one ASP or HTML file. It makes sense to put your Ad Rotator code into a simple function in an include file. With an Ad Rotator include file, you need to make only one function call from any ASP or HTML file when you want to display an advertisement. Alternatively, you can put the code from the include file in every ASP file where you plan to show an advertisement. However, if you want to change that code, you have to make the change in every ASP file instead of in one include file.

In this example, you create an Ad Rotator include file containing a function named GetAd. This function randomly selects ads to display on your ASP pages.

Copy and paste the following code in your text editor, and save the file as AdRotatorLogic.inc in the x:\Inetpub\Wwwroot\Tutorial directory.

  <% 
Function GetAd() 

dim objLoad 

'Create an instance of the AdRotator component. 
Set objLoad = Server.CreateObject("MSWC.AdRotator") 

'Set the TargetFrame property, if any. If you have a Web 
' page using frames, this is the frame where the URL opens. 
'If the HTML page does not find the TARGET name, 
' the URL will be opened in a new window. 
objLoad.TargetFrame = "TARGET=new" 
 
'Set one of the other AdRotator properties. 
objLoad.Border = 1 

'Get a random advertisement from the text file. 
GetAd = objLoad.GetAdvertisement("MyAdRot.txt") 

End Function 
%>

Example 4: Test the Ad Rotator

To test the application you have built on the Ad Rotator component, you need an ASP page that calls the function in the Ad Rotator include file you created.

Copy and paste the following code in your text editor, and save the file as DisplayAds.asp in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your browser by typing https://localhost/Tutorial/DisplayAds.asp in the address bar.

  <%@ Language=VBScript %> 

<html> 
<head> 
<title>Display an Advertisement</title> 
</head> 
<body> 
<font face="MS Gothic"> 

<h2>Display an Advertisement</h2> 
 
<comment>Include the file you created to get an advertisement.</comment> 
<!-- #include File = "AdRotatorLogic.inc" --> 

<comment>Call the Function in the include file.</comment> 
<%=GetAd()%> 

</font> 
</body> 
</html> 

In the browser, you should see the following:

Display an Advertisement

Microsoft Windows

Click the Refresh button in your browser about 20 times to watch the advertisement change. Click the advertisement to see how AdRotRedirect.asp redirects you to the advertiser's Web site. Open AdRotLog.txt to see what was recorded when you clicked on an advertisement.

Lesson 2: Counting Page Hits

It may be useful to know how many times someone requests, or hits, your Web pages. Sites with high traffic may attract more advertising revenue for you. Some Web sites use this data to charge advertisers a flat fee per hit. Traffic information also indicates how customers are navigating through your site and where ads should be placed. And pages that never seem to be hit might indicate that design changes are needed.

The PageCounter component uses an internal object to record Web page hits on the server. At regular intervals, PageCounter saves all information to a text file so that no counts are lost due to power loss or system failure. The PageCounter component uses three methods, as follows:

  • Hits This method displays the number of hits for a Web page. The default is the calling page.
  • PageHit This method increments the hit count for the current page. If you want hits recorded for an ASP page, this method must be called inside that page.
  • Reset This method sets the hit count for a page to zero. The default is the calling page.

Copy and paste the following code in your text editor, and save the file as PageCounter.asp in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your browser by typing https://localhost/Tutorial/PageCounter.asp in the address bar.

  <%@ Language=VBScript %>
<html> 
<head> 
<title>Page Counter Example</title> 
</head> 
<body> 
<font face="MS Gothic"> 

<H3>Page Counter Example</H3> 

<p> 
<FORM NAME="PageCounter" METHOD="GET" ACTION="PageCounter.asp"> 
<INPUT TYPE="CHECKBOX" NAME="reset" VALUE="True">Reset the Counter for this page?<BR> 
<INPUT TYPE="SUBMIT" VALUE="Submit"> 
</FORM> 
</p> 

<% 
 'Instantiate the PageCounter object. 
 Set MyPageCounter = Server.CreateObject("MSWC.PageCounter") 

 'Increment the counter for this page. 
 MyPageCounter.PageHit 
 
 If Server.HTMLEncode(Request.QueryString("reset")) = "True" Then 
 'Reset the counter for this page. 
 MyPageCounter.Reset("/Tutorial/PageCounter.asp") 
 End If 
%> 
 
Hits to this page = <%=MyPageCounter.Hits %><BR> 
</font> 
</body> 
</html> 

In the browser, you should see the following:

Page Counter Example

Check boxReset the Counter for this page?

Hits to this page = 1

Click the Refresh button in your browser or the Submit button on the page to watch the hit count grow. Check the box if you want to reset the counter.

Lesson 3: Creating a Visual Basic COM Object

In this lesson, you use Visual Basic to create a simple COM object, which you can call from an ASP page. This example requires Visual Basic with the ActiveX Wizard, and it is not supported on 64-bit platforms until the Visual Basic runtime is developed for 64-bit platforms. You create a 32-bit COM object that runs on a 64-bit platform, but you must call the 32-bit COM object from a 32-bit application. Because IIS is a 64-bit application on 64-bit platforms, it cannot call 32-bit objects.

Suppose you want to create a Web application that needs functionality VBScript does not have. In this case, you must create a custom procedure that is called, as needed, from any ASP page in your application.

Normally, this approach is an adequate solution for encapsulating custom functionality. However, imagine that you are creating a Web application intended to service thousands of users and that your procedure encapsulates proprietary functions you do not want other people to see. In this case, encapsulating your functionality in the form of a COM component is a superior approach. Components provide better security and performance than scripts because they are compiled code. Components also allow you to use functionality provided by Visual Basic, C++, Java, or any of the other COM-compliant languages.

Create the ActiveX COM Object

The ActiveX DLL Wizard of Visual Basic is the easiest way to create a COM component. You can also use Microsoft Visual C++ to create a COM component, either by using the Active Template Library (ATL) or by writing all the code yourself. This example uses Visual Basic.

In this lesson, you learn how to create and encapsulate a Visual Basic function as a component. Visual Basic includes many financial functions not available to VBScript. This example computes the future value of an investment based on a fixed interest rate and periodic, fixed payments.

  1. Open Visual Basic. If you don't see a window titled New Project, choose File and then click New Project.
  2. Select ActiveX DLL, and click OK.
  3. A window should open called Project1 - Class1 (Code). This is where you enter your code.
  4. From the Project menu, click Project1 Properties. In the General property sheet, in the Project Name box, type ASPTut. Your DLL is called ASPTut.dll. Select the Unattended Execution check box so that the project runs without user interaction and has no user interface elements. Make sure the Threading Model is Apartment Threaded so that more than one user at a time can use the DLL. Click OK.
  5. In Visual Basic, you define a class to group together methods and properties. Under the Project - ASPTut window, click the Class1 (Class1) node to list the class properties below. Under Properties - Class1, click in the text field beside (Name) and change the class name to Finance. When you call this COM component in an ASP page or other script, you will reference it with ASPTut.Finance. Click the drop-down box beside Instancing, and select 5 - MultiUse.
  6. Learn about the Visual Basic function you are about to use. FV is documented in the MSDN Online Library under the Visual Basic library.
  7. The window that was previously titled Project1 - Class1 (Code) should now be titled ASPTut - Finance (Code). Copy and paste the following text into that window:
    
    Option Explicit

'Declare the global variables that will be set by the Property functions. Dim gAnnualIntRate As Double Dim gNumPayPeriods As Integer Dim gPayment As Double Dim gPresentSavings As Variant 'Optional Dim gWhenDue As Variant 'Optional

Public Function CalcFutureValue() As Double

'The global variables you pass to the FV function are set 'when user sets the properties in the ASP page. 'You could pass variables into the CalcFutureValue() function 'if you wanted to avoid using properties. 'CalcFutureValue becomes a method in your component.

Dim IntRatePerPeriod As Double Dim FullFutureValue As Double

If (gAnnualIntRate = Null) Or (gNumPayPeriods = Null) Or (gPayment = Null) Then CalcFutureValue = 0 Else IntRatePerPeriod = gAnnualIntRate / 100 / 12 FullFutureValue = FV(IntRatePerPeriod, gNumPayPeriods, gPayment, gPresentSavings, gWhenDue) CalcFutureValue = Round(FullFutureValue, 2) End If

End Function

Public Property Get AnnualIntRate() As Double 'Get functions return the value of the global variables 'as if they were properties. 'In your ASP page, you might say x = oASPTut.Rate. AnnualIntRate = gAnnualIntRate End Property

Public Property Let AnnualIntRate(ByVal vAnnualIntRate As Double) 'Let functions set the global variables when your ASP page 'makes a call such as oASPTut.Rate = 5. gAnnualIntRate = vAnnualIntRate End Property

Public Property Get NumPayPeriods() As Integer NumPayPeriods = gNumPayPeriods End Property

Public Property Let NumPayPeriods(ByVal vNumPayPeriods As Integer) gNumPayPeriods = vNumPayPeriods End Property

Public Property Get Payment() As Double Payment = gPayment End Property

Public Property Let Payment(ByVal vPayment As Double) gPayment = -(vPayment) End Property

Public Property Get PresentSavings() As Variant PresentSavings = gPresentSavings End Property

Public Property Let PresentSavings(ByVal vPresentSavings As Variant) gPresentSavings = -(vPresentSavings) End Property

Public Property Get WhenDue() As Variant WhenDue = gWhenDue End Property

Public Property Let WhenDue(ByVal vWhenDue As Variant) gWhenDue = vWhenDue End Property

  1. All server components require an entry (starting) point. This is the code that will be called when the object is first instantiated with Server.CreateObject Your ASPTut component does not have to do anything special when it is first called. For this reason, you can provide an empty Sub Main procedure. From the Project menu, select Add Module. In the Add Module window, under the New tab, select the Module icon and click Open. In the Module 1 code window, type Sub Main and hit Enter. An empty sub is created for you.
  2. Save your Sub Main module as Main.bas. Save your class file as Finance.cls. Save your project as ASPTut.vbp.
  3. Click File, and click Make ASPTut.dll. This compiles and registers the ASPTut.dll. After you have called ASPTut.dll from an ASP page, you cannot make the DLL in Visual Basic until you unload the application in which the ASP file is running. One way to do this is to use the IIS Manager to open the properties on your default Web site and click the Unload button. If you want to register your DLL on another Web server, copy ASPTut.dll to the server, click Start, click Run, and type cmd into the Open text box. In the same directory as ASPTut.dll, type regsvr32 ASPTut.dll.
  4. Exit Visual Basic.

Create an ASP Page to Use Your Visual Basic COM Object

This example ASP page uses a form to read in user data, creates an instance of your object, and calculates the future value of your savings plan.

Copy and paste the following code in your text editor, and save the file as CalculateFutureValue.asp in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your browser by typing https://localhost/Tutorial/CalculateFutureValue.asp in the address bar.

  <%@ Language=VBScript %> 
<% 
Response.Expires = 0 
Payment = Server.HTMLEncode(Request.Form("Payment")) 
AnnualIntRate = Server.HTMLEncode(Request.Form("AnnualIntRate")) 
NumPayPeriods = Server.HTMLEncode(Request.Form("NumPayPeriods")) 
WhenDue = Server.HTMLEncode(Request.Form("WhenDue")) 
PresentSavings = Server.HTMLEncode(Request.Form("PresentSavings")) 
%> 

<HTML> 
<HEAD>
<TITLE>Future Value Calculation</TITLE>
</HEAD> 
<BODY> 
<FONT FACE="MS Gothic"> 

<H2 align=center>Calculate the Future Value of a Savings Plan</H2> 

<FORM METHOD=POST ACTION="calculatefuturevalue.asp"> 
<TABLE cellpadding=4 align=center> 
<TR> 
<TD>How much do you plan to save each month?</TD> 
<TD><INPUT TYPE=TEXT NAME=Payment VALUE=<%=Payment%>> (Required)</TD> 
</TR><TR> 
<TD>Enter the annual interest rate.</TD> 
<TD><INPUT TYPE=TEXT NAME=AnnualIntRate VALUE=<%=AnnualIntRate%>> (Required)</TD> 
</TR><TR> 
<TD>For how many months will you save?</TD> 
<TD><INPUT TYPE=TEXT NAME=NumPayPeriods VALUE=<%=NumPayPeriods%>> (Required)</TD> 
</TR><TR> 
<TD>When do you make payments in the month? </TD> 
<TD><INPUT TYPE=RADIO NAME=WhenDue VALUE=1 <%If 1=WhenDue Then Response.Write"CHECKED"%>>Beginning 
<INPUT TYPE=RADIO NAME=WhenDue VALUE=0 <%If 0=WhenDue Then Response.Write"CHECKED"%>>End </TD> 
</TR><TR> 
<TD>How much is in this savings account now?</TD> 
<TD><INPUT TYPE=TEXT NAME=PresentSavings VALUE=<%=PresentSavings%>> </TD> 
</TR> 
</TABLE> 
<P align=center><INPUT TYPE=SUBMIT VALUE=" Calculate Future Value "> 
</FORM> 
<% 
If ("" = Payment) Or ("" = AnnualIntRate) Or ("" = NumPayPeriods) Then 
 Response.Write "<H3 align=center>No valid input entered yet.</H3>" 
ElseIf (IsNumeric(Payment)) And (IsNumeric(AnnualIntRate)) And (IsNumeric(NumPayPeriods)) Then 
 Dim FutureValue 
 Set oASPTut = Server.CreateObject("ASPTut.Finance") 
 oASPTut.AnnualIntRate = CDbl(AnnualIntRate) 
 oASPTut.NumPayPeriods = CInt(NumPayPeriods) 
 oASPTut.Payment = CDbl(Payment) 
 
 If Not "" = PresentSavings Then oASPTut.PresentSavings = CDbl(PresentSavings) 

 oASPTut.WhenDue = WhenDue 
 FutureValue = oASPTut.CalcFutureValue 
 Response.Write "<H3 align=center>Future value = $" & FutureValue & "</H3>" 
Else 
 Response.Write "<H3 align=center>Some of your values are not numbers.</H3>" 
End If 
%> 
</FONT> 
</BODY> 
</HTML> 

In the browser, you should see the following:

Calculate the Future Value of a Savings Plan

How much do you plan to save each month? Text box (Required)
Enter the annual interest rate. Text box (Required)
For how many months will you save? Text box (Required)
When do you make payments in the month? Radio buttonBeginning Radio buttonEnd
How much is in this savings account now? Text box

No valid input entered yet.

Lesson 4: Creating a Java COM Object

In this lesson, you use Microsoft Visual J++ to create a COM object which does the same thing as the Visual Basic component in Lesson 3. This step requires Visual J++ 6.0 or later.

Create the Java COM Object

  1. Open Visual J++. If you don't see a window titled New Project, click the File menu and click New Project.

  2. Select Visual J++ Projects, and click the Empty Project icon. In the Name text box, type ASPTut. Click Open.

  3. In the Project menu, click Add Class. In the Name text box, type ASPTut.java. The class name must be the same as the project name for a Java server component. Click Open. The following should appear in a text editing window:

    public class  ASPTut
    {
    }
    
    

  4. Copy the following code, and paste it between the brackets {}. Watch capitalization because Java is case-sensitive. The following is a method in your component:

    public double CalcFutureValue(
    double dblAnnualIntRate,
    double dblNumPayPeriods,
    double dblPayment,
    double dblPresentSavings,
    boolean bWhenDue)
    {
    double dblRet, dblTemp, dblTemp2, dblTemp3,  dblIntRate;

if (dblAnnualIntRate == 0.0) { dblRet = -dblPresentSavings - dblPayment * dblNumPayPeriods; } else { dblIntRate = dblAnnualIntRate / 100 / 12; dblPayment = -dblPayment; dblPresentSavings = -dblPresentSavings; dblTemp = (bWhenDue ? 1.0 + dblIntRate : 1.0); dblTemp3 = 1.0 + dblIntRate; dblTemp2 = Math.pow(dblTemp3, dblNumPayPeriods); dblRet = -dblPresentSavings * dblTemp2 - dblPayment * dblTemp * (dblTemp2 - 1.0) / dblIntRate; }

return dblRet; }

  1. From the Build menu, click Build. Look in the Task List window below the text editing window to see whether any errors are generated.
  2. The Java class file must be registered on the same machine as the Web server. In a command window, find the ASPTut.class file that was built. It is most likely either in %USERPROFILE%\My Documents\Visual Studio Projects\ASPTut or in x:\Documents and Settings\user name\My Documents\Visual Studio Projects\ASPTut, where x: is the drive on which you installed Windows. Copy ASPTut.class to x:\Winnt\Java\Trustlib. Type javareg /register /class:ASPTut /progid:MS.ASPTut.Java, and press ENTER to register the Java class.
  3. Close Visual J++.

Create an ASP Page to Use Your Java COM Object

This example ASP page uses a form to read in user data, creates an instance of your object, and calculates the future value of your savings plan. This example uses JScript, but you can call a Java component from VBScript as well.

Copy and paste the following code in your text editor, and save the file as CalculateFutureValueJava.asp in the x:\Inetpub\wwwroot\Tutorial directory. View the example with your browser by typing https://localhost/Tutorial/CalculateFutureValueJava.asp in the address bar.

  <%@ Language=JScript %>  

<%  
Response.Expires = 0;  
Payment = Server.HTMLEncode(Request.Form("Payment"));  
AnnualIntRate = Server.HTMLEncode(Request.Form("AnnualIntRate"));  
NumPayPeriods = Server.HTMLEncode(Request.Form("NumPayPeriods")); 
WhenDue = Server.HTMLEncode(Request.Form("WhenDue"));  
PresentSavings = Server.HTMLEncode(Request.Form("PresentSavings"));  
%>  

<HTML>  
<HEAD>
<TITLE>Future Value Calculation - Java</TITLE>
</HEAD>  
<BODY>  
<FONT FACE="MS Gothic">  

<H2 align=center>Calculate the Future Value of a Savings Plan</H2>  

<FORM METHOD=POST ACTION="calculatefuturevaluejava.asp">  
<TABLE cellpadding=4 align=center>  
<TR>  
<TD>How much do you plan to save each month?</TD>  
<TD><INPUT TYPE=TEXT NAME=Payment VALUE=<%=Payment%>> (Required)</TD>  
</TR><TR>  
<TD>Enter the annual interest rate.</TD>  
<TD><INPUT TYPE=TEXT NAME=AnnualIntRate VALUE=<%=AnnualIntRate%>> (Required)</TD>  
</TR><TR>  
<TD>For how many months will you save?</TD>  
<TD><INPUT TYPE=TEXT NAME=NumPayPeriods VALUE=<%=NumPayPeriods%>> (Required)</TD>  
</TR><TR>  
<TD>When do you make payments in the month? </TD>  
<TD><INPUT TYPE=RADIO NAME=WhenDue VALUE=1 <%if (1==WhenDue) Response.Write("CHECKED")%>>Beginning  
<INPUT TYPE=RADIO NAME=WhenDue VALUE=0 <%if (0==WhenDue) Response.Write("CHECKED")%>>End </TD>  
</TR><TR>  
<TD>How much is in this savings account now?</TD>  
<TD><INPUT TYPE=TEXT NAME=PresentSavings VALUE=<%=PresentSavings%>> </TD>  
</TR>  
</TABLE>  
<P align=center><INPUT TYPE=SUBMIT VALUE=" Calculate Future Value ">  
</FORM>  

<%  

if (("" == Payment) || ("" == AnnualIntRate) || ("" == NumPayPeriods)) {  
  Response.Write("<H3 align=center>No valid input entered yet.</H3>");  
} else {  
  AnnualIntRate = parseFloat(AnnualIntRate)  
  NumPayPeriods = parseFloat(NumPayPeriods)  
  Payment = parseFloat(Payment)  
  
  if ("" != PresentSavings) PresentSavings = parseFloat(PresentSavings);  
  
  if ((isNaN(Payment)) || (isNaN(AnnualIntRate)) || (isNaN(NumPayPeriods))) 
  {  
    Response.Write("<H3 align=center>Some of your values are not numbers.</H3>");  
  } 
  else 
  {  
    var FutureValue, Cents;  
    var oASPTut = Server.CreateObject("MS.ASPTut.Java");  
    FutureValue = oASPTut.CalcFutureValue(AnnualIntRate, NumPayPeriods, Payment, PresentSavings, WhenDue);  
    
    Response.Write("<H3 align=center>Future value = $" + parseInt(FutureValue) + "</H3>");  
  }  
}  
%>  

</FONT>  
</BODY>  
</HTML>

In the browser, you should see the following content, which should be identical to the display generated using the Visual Basic component in Lesson 3 of this module:

Calculate the Future Value of a Savings Plan

How much do you plan to save each month? Text box (Required)
Enter the annual interest rate. Text box (Required)
For how many months will you save? Text box (Required)
When do you make payments in the month? Radio buttonBeginning Text boxEnd
How much is in this savings account now? Text box

No valid input entered yet.

Up Next: Maintaining Session State in a Web Application