Chapter 10:
Web Programming
10.1
Introduction
The last several years has seen a
tremendous growth in new scripting and programming languages. These languages
allow you to extend the capabilities of HTML by making the web documents more
dynamic and more interactive. This chapter focuses on several of the more
popular languages used in extending HTML documents.
10.2
JavaScript
(http://csc.ColumbusState.edu/summers/NOTES/javascrp.htm)
10.2.1
Introduction
JavaScript is
not Java. JavaScript is an easy to learn scripting language used with HTML to
increase the functionality and interaction of the document with the
viewer. It was developed by Netscape as
part of Navigator 2.0 beta using Sun's Java language and was originally called
LiveScript. JavaScript is not an
object-oriented programming language but a compact, object-based scripting
language for developing client and server Internet applications. Scripts are
performed after specific user-triggered events. JavaScript allows web pages to become dynamic in response to events generated by the user or other
objects.
Its syntax and structure are similar to
Java but JavaScript can only be used as part of an HTML page.
JavaScript |
Java |
Object-based |
Object-oriented |
Interpreted by the client |
Compiled before execution on the
client |
Integrated with HTML |
Applets are distinct applications |
Dynamic binding of object references |
Static binding at compile time |
Variables are not declared |
Strong typing of variables |
JavaScript is supported by all versions
of Netscape Navigator 2.0 and later and Microsoft Internet Explorer 3.0 and
later. Internet Explorer actually uses
a version of JavaScript called Jscript. Unfortunately, the two browsers support
different features in their JavaScript. Netscape Navigator 2.0 contained a
defect “stuck onLoad” that allows hackers to gather information about the
client computer and should not be used with JavaScript.
10.2.2
JavaScript Features
JavaScript
can
JavaScript
should be used to
10.2.3
JavaScript Language
1.
JavaScript functions can be embedded directly in the HTML code and
should be placed in the head of the HTML document.
<HTML>
<HEAD>
<SCRIPT
LANGUAGE="JavaScript">
<!—Hide the script
document.write(“Hello
World”);
// end hiding-->
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
2. To use JavaScript functions the code
needs to follow the line: <SCRIPT LANGUAGE="JavaScript"> and
precede </SCRIPT>.
3. JavaScript code needs to be bracketed
by <!-- and --> so that non-JavaScript enabled browsers will ignore the
JavaScript code.
4. JavaScript is case sensitive and
uses new lines to terminate a line of code; semicolons can be used to separate
lines of code on a line.
5.
JavaScript can use either // or /* */ to indicate comments.
6.
JavaScript supports data types: numeric (real and integer), string,
Boolean, and null.
7. Variable names
must begin with a letter or an underscore (_) with the remaining characters
either digits or letters. Variables by
default are global, unless declared as local by preceding with var:
var count=0
8. JavaScript
supports assignment, arithmetic, bit-wise, logical, comparison and string
operators: +, -, *, /, %, ++, --, =, +=, -=, *=, /=, %=, &&, ||, !,
&, |, ^, ==, !=, >, <, >=, <=.\
9. JavaScript
uses the control structures: if (else), for, and while.
ex.
<HTML>
<HEAD>
<SCRIPT
LANGUAGE="JavaScript">
<!—Hide the script
for (count=1; count <= 10;
count++)
{
sqr = count * count;
document.write (“number:
“ + count + “squared: “ + sqr +
“<BR>”)
}
// end hiding-->
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
10. A JavaScript function is a group of
statements that perform a specified task and may be called from any point in
the HTML document. The format is:
function FunctionName (parameter list)
{
statements;
}
Functions can return values to be
processed by other JavaScript functions as well as processing values in HTML
forms as shown below.
<SCRIPT
LANGUAGE="JavaScript">
<!—Hide the
JavaScript code
function calc(form)
{
form.answer.value = form.number1.value
* form.number2.value;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<H1>Sample
Javascript</H1>
<FORM>
enter first number:
<INPUT
TYPE="TEXT" NAME="number1" SIZE=5 MAXLENGTH=5><P>
enter second number:
<INPUT
TYPE="TEXT" NAME="number2" SIZE=5 MAXLENGTH=5><P>
<P>
<INPUT
TYPE="BUTTON" NAME="Caclulate" VALUE="Multiply"
onClick = "calc(this.form)">
The product is:
<INPUT
TYPE="TEXT" NAME="answer"
SIZE=5 MAXLENGTH=5>
<INPUT
TYPE="RESET" NAME="Reset" VALUE="Erase">
</FORM>
11. JavaScript contains three user
interfaces: alert(message), prompt(message, [Default]), confirm(message). The
sample program displays all three. The screen shot below illustrates the alert
window.
<SCRIPT
LANGUAGE="JavaScript">
<!--
function TestMethods()
{
window.alert("Bienvenidos");
window.confirm("do a
homepage");
window.prompt("Nombre?","");
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<H1>Javascript
example - Windows methods
</H1>
<FORM>
<INPUT
TYPE="BUTTON" NAME="Display" VALUE="Press here"
onClick = "TestMethods()">
Test Windows methods
with JavaScript
</FORM>
10.2.3
JavaScript and Objects
JavaScript is an object-based language.
It can access three built-in objects, several Netscape-defined built-in objects
as well as external objects created in Java and C++. Objects have properties
and methods. Methods include entities like length, name, etc. while methods are
the functions associated with the object.
The built-in objects are Window, String, Math, and Date. To facilitate
processing objects and their properties and methods, JavaScript includes
additional statements: for..in, with, new, this.
The for..in statement provides a loop
mechanism for interating through all of the properties of an object. This example uses this statement to list the
properties and their values for an object.
<SCRIPT
LANGUAGE="JavaScript">
<!--
function ListProperties (obj,
objName)
{
for (var prop in obj)
document.write(objName +
"." + prop + " = " + obj[prop] + "<BR>");
}
//-->
</SCRIPT>
The with
statement establishes a default object for a bracketed set of statements. The new function is used to create a new
instance of a given object type. This
is used to refer to the current object.
JavaScript does not have built-in
support for arrays, but does allow for building of arrays using objects.
Function MakeArray
(size)
{
this.length = size;
for (var count = 1; count <=
size; count++)
this[count] = 0;
return this;
}
:
SampleArray = new MakeArray(10);
The String object has only the length
property and methods: anchor, big, blink, bold, charAt, fixed, fontcolor,
fontsize, indexOf, italics, lastOf, link, small, strike, sub, sibstring, sup,
toLowerCase, and toUpperCase.
The Math object has properties: E, LN2,
LN10, LOG2E, LOG10E, PI, SQRT1_2, SQRT2 and methods: abs, acos, asin, atan,
ceil, cos, exp, floor, log, max, min, pow, random, round, sin, sqrt, and tan.
The Date object requires that an
instance of the Date object exist before the use of its methods. This can be
done by:
dateObjectName = new Date()
dateObectName = new Date(“month,
day, year, hours:minutes:seconds”)
dateObectName = new Date(“year, month, day)
dateObectName = new Date, (“year,
month, date, hours, minutes, seconds)
Methods include getDate, getDay,
getHours, getMinutes, getMonth, getSeconds, getTime, getTimezoneOffset,
getYear, setDate, setHours, setMinutes, setMonth, setSeconds, setTime, setYear,
toGMTString, toLocaleString, parse, and UTC.
ex. Found on http://csc.ColumbusState.edu/summers/internet.htm
<SCRIPT
LANGUAGE="JavaScript">
<!-- hide ...
// This script displays the date that
this document was last updated.
update = new
Date(document.lastModified)
theDate= update.getDate()
theMonth = update.getMonth() + 1
theYear = update.getYear()
document.writeln ("last update:
" + theMonth + "/" + theDate + "/" + theYear)
// end hide -->
</SCRIPT>
10.2.4
Netscape Objects
In addition to the JavaScript objects,
there is a collection of objects and properties that are supported by the Netscape
browser. The following tree illustrates these objects and their relationships:
window
|
| | | |
frames location history document
|
| | |
forms links anchors
|
elements
Note that frames also have a hierarchy
that includes location, history and document.
The window object is the parent of all
of these objects and has properties: name, parent, self, top, defaultstatus,
status, script, location, frame, history, navigator, document and methods:
Alert, Confirm, Prompt, Open, Close, SetTimeout, ClearTimeout, Navigate with
events: Onload, Unload. When the
browser initially loads the HTML document, it starts with a single instance of
the window object.
The location object contains
information about the current URL and consists of properties: protocol,
hostname, port, pathname, search, hash, href, and host. It is recommended that any changes be made
the entire href and not the other individual properties.
The history object has been disabled
since version 2.01 because of its ability to be misused.
The document object consists of the
properties, objects, and methods that define the way the document (everything between <BODY> and
</BODY>) is presented. Its properties
include: bgColor, fgColor, linkColor, alinkColor, vlinkColor, lastModified,
location, referrer, title, anchors, link and cookie. The document object
methods are write, writeln, open, close, and clear. The anchors object contains an array of all anchors declared by
the NAME attribute of the <A> tag. The array begins at 0 and ends with
document.anchors.length-1. The link
object contains an array of all links defined by the HREF and NAME attributes
of the <A> tag or the link method.
The link object supports the two event handlers: onClick and
onMouseOver.
ex. <A HREF="notes/CS101/intro.htm"
ONMOUSEOVER="window.status='Computer Literacy course'; return
true">CS101 - Living with Computers</A> [See http://csc.ColumbusState.edu/summers/CLASS.htm].
The cookie property contains a string
value of the cookie entry from the cookies.txt file for the document.
10.2.5
The Form Object
The HTML <FORM> tag provides a
means for receiving user input of data. Before the development of JavaScript, a
server using CGI could only process this input. JavaScript provides a facility
to do the processing on the client machine through the use of event handlers.
The following example illustrates the use of an event handler to process a form
by calling a JavaScript function:
<input
type=”radio” value=”Submit” onClick=”validate(this.form)”>
Event handlers supported by JavaScript
include:
·
onBlur – executes when the user leaves the field causing it
to lose focus.
·
onChange – executes when the user leaves the field and the
value of the object has changed.
·
onClick – executes when the user clicks on a form or link.
·
onFocus – executes when a field receives input focus by
tabbing to the field or clicking on it with the mouse.
·
onLoad – executes when the browser finishes loading a
document.
·
onMouseOver – executes when the mouse moves over an object.
·
onSelect – executes when the user selects text within a text
or textarea field.
·
onSubmit – executes when the user submits a form.
·
onUnload – executes when a document is existed.
Object |
Event handlers |
button |
OnClick |
checkbox |
OnClick |
form |
OnSubmit |
link |
OnClick, onMouseOver |
radio |
OnClick |
reset |
OnClick |
select |
onBlur, onChange, onFocus |
submit |
OnClick |
text |
onBlur, onChange, onFocus, onSelect |
textarea |
onBlur, onChange, onFocus, onSelect |
Window |
onLoad, onUnLoad |
The forms array contains entries for
each form object created by the <FORM> tag. For JavaScript, each form
entry contains the following properties: action, element, encoding, length,
method, and target and the submit method.
The table below lists the element objects, their properties and methods.
Element object |
Properties |
Methods |
Button |
name, value |
click |
Checkbox |
name, value, checked, defaultChecked |
click |
Hidden |
name, value |
(has no methods) |
Password |
name, value, defaultValue |
blur, focus, select |
Radio |
name, value, checked, defaultChecked,
length |
click |
Reset |
name, value |
click |
Select |
name, length, options array,
selectedIndex |
blur, focus |
Submit |
name, value |
click |
Text |
name, value, defaultValue |
blur, focus, select |
Textarea |
name, value, defaultValue |
blur, focus, select |
ex. Uses the button object and the
onclick event to change the color of the document (found on
http://csc.ColumbusState.edu/summers/guide.htm):
<FORM>
<CENTER>
<INPUT
TYPE="button" VALUE="silver"
ONCLICK="document.bgColor='silver'">
<INPUT
TYPE="button" VALUE="slate"
ONCLICK="document.bgColor='slate'">
<INPUT
TYPE="button" VALUE="pink"
ONCLICK="document.bgColor='pink'">
<INPUT
TYPE="button" VALUE="green"
ONCLICK="document.bgColor='lightgreen'">
<INPUT
TYPE="button" VALUE="blue"
ONCLICK="document.bgColor='lightblue'">
<INPUT
TYPE="button" VALUE="purple" ONCLICK="document.bgColor='purple'">
</CENTER>
</FORM>
Another
example that combines forms with JavaScript is the following that allows the
viewer to select the next destination from a drop-down list.
<script LANGUAGE="JavaScript">
<!--
function switch_page() {
location =
document.menuform.destination[document.menuform.destination.selectedIndex].value;
}
// -->
</script>
:
:
<table>
<tr>
<td><form
NAME="menuform">
<p><select
NAME="destination" ONCHANGE="switch_page();"
ALIGN="left" size="1">
<option>Choose a
Subject... Click here! <!-- Enter new quick menu options here -->
</option>
<option
VALUE="biology.htm">Biological Sciences </option>
<option
VALUE="physics.htm">Physical Sciences (Physics, Earth Sciences)
</option>
<option
VALUE="nasa.htm">Nasa and Astronomy </option>
<option
VALUE="math.htm">Mathematical Sciences </option>
<option
VALUE="social.htm">Social Sciences </option>
<option
VALUE="arts.htm">Humanities and Fine Arts </option>
<option
VALUE="english.htm">English </option>
<option
VALUE="chem.htm">Chemistry </option>
<option
VALUE="language.htm">Language Learning </option>
<option
VALUE="philosophy.htm">Philosophy </option>
<option
VALUE="refer.htm">Library Science & Reference Works
<!-- End of Menu --> </option>
</select><br>
</p>
</form>
</td>
<td><font
SIZE="-2"><a HREF="http://home.netscape.com">For
Javascript Enabled Browsers
Only!</a></font></td>
</tr>
</table>
Because of
the differences between Netscape’s JavaScript and Microsoft’s JScript, an
attempt has been made to standardize the language through a standards
organization - European Computer Manufacturers Association (ECMA - http://www.ecma.ch/)
that has released three versions of ECMAScript. Unfortunately, the ECMA
specification does not describe the Document Object Model (DOM). The DOM
defines the way in which HTML document objects are exposed to your script. The
DOM for Netscape and Microsoft is significantly different. The World Wide Web
Consortium (W3C) is standardizing the DOM.
For more
information on JavaScript, you can look at http://csc.ColumbusState.edu/summers/NOTES/CS463/wk3.html
for further discussion and examples and http://csc.ColumbusState.edu/summers/NOTES/javascrp.htm
for more examples and JavaScript resources.
10.3
VBScript (http://csc.ColumbusState.edu/summers/notes/vbscript.htm)
10.3.1
Introduction to VBScript
VBScript is a subset of the Visual
Basic language and was written as an alternative to JavaScript. As with
JavaScript, VBScript is used with HTML pages to increase functionality and
interaction with the end user. Its only purpose is to enhance Web documents.
VBScripts are contained inside the HTML
<SCRIPT> tags or inside the form element tags and are executed when the
HTML document is loaded or in response to an event. If the VBScript statements are not inside procedures, they are executed
when the document is loaded. Procedure definitions should be placed inside the
<HEAD> tags.
Listed below is a simple “hello world”
VBScript.
<HTML>
<HEAD>
<SCRIPT
LANGUAGE="VBScript">
<!—Hide the script
document.open
document.write “Hello
World”
document.close
// end hiding-->
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
Below is an example that uses
procedures:
<HTML>
<HEAD>
<SCRIPT
LANGUAGE="VBScript" >
<!— Hide the
script
Sub sendAlert (msg)
Alert msg
End Sub
-->
</SCRIPT>
</HEAD>
<BODY>
<H1>VBScript
Example</H1>
<FORM>
<INPUT
NAME=”btnHello” OnClick=sendAlert(“HelloWorld!”) TYPE=”button” VALUE=”Say
Hello”>
</FORM>
</BODY>
</HTML>
10.4
Dynamic HTML (dHTML) (http://csc.ColumbusState.edu/summers/NOTES/dyn-html.htm)
10.4.1
Introduction to dHTML
Dynamic HTML
is the newest wave of innovation to the Web. Unfortunately Netscape and
Microsoft are battling it out over which way to do dynamic HTML. Netscape has
introduced a new <LAYER> tag while Microsoft has added to the
functionality of the <DIV> tag. Netscape Navigator and Communicator 4.0
only support Netscape’s <LAYER> tag and higher while Microsoft's
<DIV> tag is only supported by Internet Explorer 4.0 and higher. In order
to see the effects of dynamic HTML in the examples below, you must be using the
appropriate browser. Dynamic HTML is basically a combination of the document
object with its associated style sheet and some type of scripting. Since
Netscape and Microsoft support different Document Object Models (DOM), it
becomes difficult to write one script that is supported by both of the major
browsers. To overcome these deficiencies, you need to either write separate
documents for each browser or test for the browser within the script and handle
each separately. Most of the examples
below will work in one, but not both browsers. The scripts can be written in
either JavaScript (JScript) or VBScript, but remember that VBScript is only
supported by the Microsoft browsers.
10.4.2
dHTML Examples
This first
example will change the background color of the page to green when the page is
clicked. It only works in IE 4.0 and above.
<html>
<head>
<title>Welcome</title>
<script language="JavaScript">
<!--
function changeMe()
{
document.body.style.color = "green"
}
// -->
</script>
</head>
<body onclick="changeMe()">
<h3>Dynamic HTML!</h3>
Click in the body of this document for a surprise. [Note it only works in
IE 4.0 and later]
</body>
</html>
This next
example is from Netscape’s site (http://developer.netscape.com/docs/manuals/communicator/dynhtml/flower.htm)
and illustrates the use of the LAYER tag. Another site http://developer.netscape.com/docs/manuals/communicator/dynhtml/flowercs.htm
accomplishes the same effect with style sheets. Neither of these pages will
work with IE.
<HTML>
<HEAD>
<TITLE>Flowering Layers Example</TITLE>
</HEAD>
<BODY>
<HR>
<H1 align="center">Welcome to Fancy Flowers Farm
</H1>
<HR>
<P>We sell bulbs, seeds, seedlings, and potted plants, in all
shapes, sizes, colors, and varieties. This page presents information about our
most popular varieties.</P>
<!-- position the form layer -->
<! -- let the top value default to the natural
position -->
<ILAYER NAME="formlayer" LEFT=50 >
<H3>Please select a flower:</H3>
<FORM NAME=form1>
<SELECT
name=menu1 onChange="changeFlower(this.selectedIndex); return
false;">
<OPTION >Mona Lisa Tulip
<OPTION >Mixed Dutch Tulips
<OPTION
>Bijou Violet
<OPTION >Pink Chrysanthemum
</SELECT>
</FORM>
</LAYER>
<!-- We have four different layers, each with
different info about flowers -->
<!-- position this layer below the form layer -->
<LAYER name="flower0" LEFT=50 width=400
BGCOLOR="#FFFFDD">
<HR>
<H3
align="center">Mona Lisa Tulip</H3>
<IMG
src="images/redtul.jpg"
align="LEFT" hspace=5 >
<P>These tulips have
been specially designed to withstand late winter frost in areas with harsh
winters.They are a beautiful red color, and we guarantee that they'll grow for
at least four years in a row. Don't
wait to order them, they sell fast!</P>
<BR
CLEAR="ALL">
<P>Priced at only $1
a bulb, they are a bargain.</P>
<HR>
</LAYER>
<LAYER name="flower1" LEFT=50 width=400
VISIBILITY="HIDE"
BGCOLOR="#DDFFDD">
<HR>
<H3 align =
center>Mixed Dutch Tulips</H3>
<IMG
src="images/tulmulti.jpg"
align="LEFT" hspace=5
>
<P>These colorful
tulips have been specially bred for us by Dr. Hans Tulip in Amsterdam. He has spent the last ten years perfecting the hybrid. These
tulips start blooming early,
sometimes they beat the crocuses out of the ground! </P>
<BR CLEAR="ALL">
<P>They come in a
variety of intense colors, and they have a velvety, sweet-smelling
bloom.</P>
<P>Priced at $5 for
ten, these tulips are a cheap way to bring color to your garden. </P>
<HR>
</LAYER>
<LAYER name="flower2" LEFT=50 width=400 VISIBILITY="HIDE" BGCOLOR="#DDDDFF">
<HR>
<H3 align
="center">Bijou Violets</H3>
<IMG
src="images/violets.jpg" align="LEFT" hspace=5>
<P>These pale purple
African violets are much hardier than most violets. You don't need green fingers to keep these
flowers thriving! Just water them four times a day at regular intervals, and
they will thrive forever!</P>
<P>These flowers are
VERY small, the picture has been magnified so you can see their shape. The
plants usually grow to about an inch high. Thus they make excellent indoor plants for tiny
apartments. </P>
<BR
CLEAR="ALL">
<P>The price for
these lovely lilac blooms is $4 for a half inch pot, or $10 for four pots.
</P>
<HR>
</LAYER>
<LAYER name="flower3" LEFT=50
TOP=&{document.flower0.top;}; width=400 VISIBILITY="HIDE" BGCOLOR="#FFDDDD">
<HR>
<H3
align="center">Pink Chrysanthemum</H3>
<IMG
src="images/spikey.jpg" align="LEFT" hspace=5 >
<P>These modern
chrysanthemums look delicate but are very hardy. They come in a variety of
colors, and they can grow to 5 feet tall. They start blooming in autumn, and
will keep flowering until the snow falls.
So if you live somewhere
that never gets snow, they'll never stop blooming!</P>
<BR
CLEAR="ALL">
<P>These flowers
sell for $6 for a 4 inch pot, or $10 for 2 pots.</P>
<HR>
</LAYER>
<SCRIPT>
// this function hides all the flower layers
function hideAllflowerLayers() {
document.flower0.visibility = "hide";
document.flower1.visibility = "hide";
document.flower2.visibility = "hide";
document.flower3.visibility = "hide";
}
// this function makes a single flower layer visible we have cunningly named the flower layers so
we
// can tell which one to show based on the
selectedIndex of the menu
function changeFlower(n) {
hideAllflowerLayers();
document.layers["flower" + n].visibility = "show";
}
</SCRIPT>
</BODY>
</HTML>
More links to
examples and resources can be found at http://csc.ColumbusState.edu/summers/NOTES/dyn-html.htm.
10.5
Active Server Pages (ASPs) (http://asia.nmhu.edu/jamesll/)
10.5.1
Introduction to ASPs
Active Server
Pages (ASPs) are a CGI-like (see 10.6) technology developed by Microsoft that
supports execution of programs and scripts on the server. These are part of a
larger group of programs collectively called server-side programs that include
server-side includes and Java Servlets. ASPs allow the programmer to create
dynamically generated web pages from the server side using VBScript or
JavaScript. Active Server Pages have an ".asp" extension instead of
the traditional ".html". ASP is not a language (ex.VBScript or
JavaScript) but rather a hosting environment that extends the normal
capabilities of a web server and exposes objects for use by web documents. ASPs
typically use embedded VBScript or JavaScript code, but could actually be
written in just about any language. Many of the functions you use client-side
with scripting languages can be
embedded into an ASP page. ASP's coding is used right along side normal
HTML and is delimited by <% and %>. It has certain built-in objects that
can be used to store and retrieve variables, get information from user
submitted forms, get information about the server itself and write HTML based
on this information.
ASPs were
designed by Microsoft to run on their Internet Information and the latest Peer
Web Servers. A company called Chilisoft
has a product called Chilisoft ASP, which provides support to a wide variety of
web servers, including Apache, Lotus, Netscape, O'Reilly, Sun Solaris and IBM
AIX. One of the strengths of ASPs is its ability to interface with databases on
the server. This requires the use of ADOs or ActiveX Data Objects, which are
application-programming interface (API) that are part of Microsoft's Data
Access Components. They provide a number of objects that are used in the
manipulation of databases through ASP. ADO objects are used by first creating
an instance of the object you want on the server. This is done with simple ASP
code. Then, you simply use the methods and properties of the objects to
accomplish what you want.
10.5.2
ASP Examples (http://csc.ColumbusState.edu/summers/NOTES/asps/examples.html)
The first
example is the necessary “Hello World” asp written in JavaScript.
<% @LANGUAGE = JavaScript %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<HTML>
<HEAD>
<TITLE>Simple
Example</TITLE>
</HEAD>
<BODY bgcolor=Lime aLink=DarkTurquoise>
<P> </P>
<% Response.Write("Hello,
world!") %>
</BODY>
</HTML>
The first line, <% @LANGUAGE = JavaScript %>, is necessary if VBScript is not used. All script instructions must be included inside <% %>. Otherwise everything looks like regular HTML.
This next
example shows an ASP written in VBScript.
<% @LANGUAGE = VBScript %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<HTML>
<HEAD>
<TITLE>Simple ASP Example</TITLE>
</HEAD>
<BODY>
<H1>Wayne's Welcome Page</H1>
<P><% If
Time >- #12:00:00 AM# And Time < #12:00:00 PM# Then %> </P>
<H2>Good
Morning!!! Bueno Dias!!! Guten Morgen!!! Selamat Pagi!!!</H2>
<P><%
ElseIf Time >- #12:00:00 PM# And Time < #6:00:00 PM# Then %>
</P>
<H2>Good
Afternoon!!! Buena Tarde!!! Guten Tag!!! Selamat Tengah Hari!!!</H2>
<P><%Else%> </P>
<H2>Good
Evening!!! Buena Noche!!! Gute Nacht!!! Selamat Malam!!! </H2>
<P><%End
If %> </P>
<H2>Thanks. Gracias. Danke. Terimakasih.</H2>
</BODY>
</HTML>
Notice the
way that the HTML is embedded inside the VBScript. The script compares the
server’s time and displays only the appropriate greetings. For more information
on ASPs and other types of server side
programming, check http://csc.ColumbusState.edu/summers/NOTES/ssp.html.
10.6
CGI and Perl
10.6.1
Introduction to CGI (http://csc.ColumbusState.edu/summers/notes/CS463/wk5.html)
Common Gateway Interface (CGI) is not a
language. It's a simple protocol or standard for communicating between external
applications and Web servers. CGI allows for dynamic interaction with HTML
documents. A CGI script can be written in any language that can read STDIN
(Standard Input), write to STDOUT (Standard Output), and read environment
variables, i.e. virtually any programming language, including C, Perl, Visual
Basic, or even shell scripting. The CGI script
is a program or subroutine that is invoked by the server through the CGI
interface. The server is the
application program running on a separate computer. CGI uses an environment variable, which is a
parameter, used to carry information between the server and the script.
10.6.2 Structure of a CGI Script
Here's the typical sequence of steps
for a CGI script:
1.Read the user's input.
2.Do what you want with the data.
3.Write the HTML response to STDOUT.
When the user submits the form, the
script receives the form data as a set of name-value pairs. The names are what
you defined in the INPUT tags (or SELECT or TEXTAREA tags), and the values are
whatever the user typed in or selected. If the form tag includes the GET method
<FORM ACTION=CGI URL METHOD=GET>, then the CGI program receives the tags
in the QUERY_STRING environment variable.
This set of name-value pairs is given
to you as one long string, which you need to parse. It's not very complicated,
and there are plenty of existing routines to do it. The format of the long
string is "name1=value1&name2=value2&name3=value3".
This must be split on the ampersands
and equal signs. Then, for each name and value:
1.Convert all "+" characters to spaces, and
2.Convert all "%xx" sequences to the single character whose
ascii value is "xx", in hex. For example, convert "%3d" to
"=". Software to automate
this can be downloaded from
ftp://ftp.winsite.com/pub/pc/win95/misc/mtf50_32.exe.
This is needed because the original
long string is URL-encoded, to allow for equal signs, ampersands, and so forth
in the user's input. For example, entering a name and e-mail address in a form
may result in the following:
UserName=Wayne+Summers&e-mail=wsummers%40cs.nmhu.edu
If the form tag includes the POST
method <FORM ACTION=CGI URL METHOD=POST>, read it from STDIN. The exact
number of bytes to read is in the environment variable CONTENT_LENGTH. POST is more general-purpose, but GET is
fine for small forms.
ex.
<FORM METHOD=POST>
<INPUT NAME=”X” SIZE=5> {Assume user enters “A B C”}
<INPUT NAME=”Y” SIZE=3> {Assume user enters “123”}
</FORM>
The CGI program receives the following:
CONTENT_LENGTH=13
stdin: X=A+B+C&Y=123
To send the
response back to the user, write the line
Content-Type: text/html
plus another blank line, to STDOUT.
After that, write your HTML response page to STDOUT, and it will be sent to the
user when your script is done. That's all there is to it.
In addition to text/html, images, audio
clips and plain-text documents can be returned. A CGI program can also direct
the browser to a particular document or have the server automatically send a
new one by using a Location line:
The two line-feed characters are
necessary to form a blank line after the Location: line.
The following is an example of a C
program that could be called from an HTML document.
#include
<stdio.h>
void main() {
/** Print the CGI response header,
required for all HTML output. **/
/** Note the extra \n, to send the blank
line. **/
printf("Content-type:
text/html\n\n") ;
/** Print the HTML response page to
STDOUT. **/
printf("<html>\n") ;
printf("<head><title>CGI
Output</title></head>\n") ;
printf("<body>\n") ;
printf("<h1>Hello,
world.</h1>\n") ;
printf("</body>\n") ;
printf("</html>\n") ;
exit(0) ;
}
This same program could be written and
compiled in just about any language. Most CGI programs are written in a
scripting language, like perl.
10.6.3
Introduction to Perl (http://csc.ColumbusState.edu/summers/notes/CS463/wk6.html)
Perl (Practical Extraction and
Reporting Language) is an interpreted language designed for scanning arbitrary
text files, extracting information from these files, and printing reports based
on the information. It is a scripting
language that combines many of the features of C, sed, awk and sh from the UNIX
environment. It is available on most
platforms including UNIX, DOS, Windows, OS/2 and Macintosh and is often
distributed for free.
The following is a simple Perl “Hello
World” CGI program.
#!/usr/bin/perl
##########################
# Hello World CGI
program
##########################
print <<EOF;
Content-type:
text/html
<HTML>
<HEAD>
<TITLE>Hello
World!</TITLE>
</HEAD>
<BODY>
Hello World!!!
</BODY>
</HTML>
EOF
;
The above program prints everything
between print <<EOF; and EOF exactly as it appears. The first line #!/usr/bin/perl
indicates
that the path to the perl interpreter is at /usr/bin. The two symbols #!
(called a she-bang) indicates that the perl script is to be executed.
Most Perl programmers writing for CGI
use a library of routines that print the routine HTML code. The above “Hello World” CGI program could
also be written as follows:
#Module which
implements common CGI handling routines
require ‘cgi-lib.pl’;
print
&PrintHeader();
$title = “Hello
World!’; #sets title to be used by
&HtmlTop
print &HtmlTop();
print “Hello
World!!\n”;
print &HtmlBot();
The subroutine HtmlTop and others would
be coded as follows:
# HtmlTop
# Returns the
<HEAD> of a document and the beginning of the body with the title and a #
body <H1> header as specified by the parameter
sub HtmlTop
{
local ($title) = @_;
return <<EOT;
<HTML>
<HEAD>
<TITLE>$title</TITLE>
</HEAD>
<BODY>
<H1>$title</H1>
EOT
}
10.6.4
Simple Perl Examples
This first example reads data from the
keyboard and then echoes it back to the user.
#!/usr/bin/perl
$inputline =
<STDIN>;
print( $inputline );
The following example is an interactive
“Hello World” program that uses a form to find the name of the user and then
says hello.
#!/usr/bin/perl
#module which
implements common CGI handling routines
require ‘cgi-lib.pl’;
$HtmlAction =
‘hello.pl’;
if (&MethGet())
{ #send the form
print &PrintHeader();
$title
= “Interactive Hello World!’;
print
&HtmlTop();
print
<<EOT;
<FORM
ACTION=”$HtmlAction” METHOD=POST>
Please
enter your first name:
<INPUT
SIZE=20 NAME=”fname”><P>
<INPUT
TYPE=SUBMIT>
<INPUT
TYPE=RESET>
</FORM>
EOT
;
print
&HtmlBot();
} elsif
(&MethPost()) {
&ReadParse(); #Process the form
# Output the form
including the name
print &PrintHeader();
$title
= “Interactive Hello World!’;
print
&HtmlTop();
print
“Hello, $in{‘fname’}!”;
print
&HtmlBot();
}
The following example illustrates a
more complicated example that parses a date and displays the date and time.
#!/usr/bin/perl
#########################################################################
# date.cgi #
#
#
# This script was
written by Selena Sol (selena@eff.org http://www.eff.org/~erict) having #
# been inspired by
countless other perl authors. Feel free
to copy, cite, reference, sample,#
# borrow or plagiarize the contents. However, please let me know where it goes
so that I #
# can at least watch
and take part in the development of the memes. Information wants #
# to be free, support
public domain freeware. #
#
#
#########################################################################
# Set some server
specific variables. You'll have to
change these for your own system.
$graphic =
"http://purple.tmn.com/Community/tachib/Images/asterix_icon.gif";
$return_url =
"http://www.eff.org/~erict/Scripts";
# Run the shell
command "date" and assign the output to the variable $date
$date = `date`;
# Now $date looks
like this: Wed Aug 16 09:17:55 EDT
1995. But since that is an ugly,
# user-unfriendly
format, we want to reorder the terms.
So we assign to the array "@date"
# the contents of
$date. Except we define the terms of
@date, as each item separated by
# white space. @date
now looks like this:
WedAug1609:16:09EDT1995
@date = split(/\s+/, $date);
# Now we break up
@date into its subcomponents so that each term in @date is represented
# by its own holder
variable. This way we can reorder
everything just the way we want them.
# Since there are 6
terms in @date, we need 6 holder
variables.
$day=$date[0];
$date1=$date[1];
$day1=$date[2];
$time=$date[3];
$time1=$date[4];
$year=$date[5];
# Tell the server
(communicating in MIME) to get ready to send an html document to the
client. This is
# basically the mime
"header". Make sure that this
extra blank line is included! This is
another MIME
# "command"
which lets the server know that we are done with the MIME header.
print "Content-type:
text/html\n\n";
# Begin by giving
this new, created on the fly, document a title and head and all that "template" sort of stuff. # And then send the results of the newly
formatted date command to the browser.
Note, in order for
# perl to understand
that the "" in the link is not a perl command, and is something it is
supposed to send to
# the browser, you
escape them " with / BTW, the table and image are just there to make the
page look nice # but serves as a good template if you want to use nice
formatting for an otherwise dull
service.
print
"<HTML><HEAD><TITLE>The Time and
Date</TITLE></HEAD><BODY>";
print "<TABLE BORDER=0
CELLPADDING=2 CELLSPACING=2>";
print "<TR ALIGN=CENTER>";
print "<TD><IMG
SRC=\"$graphic\"></TD>";
print "<TD
ALIGN=CENTER><BR><HR><BR><H2>Today is: $day, $date1
$day1 $year
<BR>The time is: $time
$time1<BR><HR><BR></TD>\n";
print
"</TR></TABLE>";
print "</H2><BR>";
# Okay, now include a
little link back to the "scripts page so the user doesn't feel
"stuck" on this drab little
# page. Finally, make sure to include those closing
tags for tidy HTML coding!
print "<CENTER><A
HREF=\"$return_url\">Go back to Selena Sol's Sample
Scripts</a> </CENTER>";
print “</BODY></HTML>”;
Perl is a very elegant scripting
language, but requires quite a bit of practice to become adept at coding in.
For a series of examples, check http://csc.ColumbusState.edu/summers/NOTES/CS463/wk6.html
and http://csc.ColumbusState.edu/summers/NOTES/CS463/wk7.html. One of the better books on programming in Perl and CGI is a small
book Perl and CGI for the World Wide Web by Elizabeth Castro (ISBN:
0-201-35358-X). http://csc.ColumbusState.edu/summers/NOTES/cgi.htm
lists an extensive list of CGI and perl sites on the Internet.
10.7
Java (http://csc.ColumbusState.edu/summers/notes/java.htm)
10.7.1
Introduction to Java
Java is a full-blown object-oriented
programming language. Java was developed by Sun Microsystems in 1991 as part of
the Green project and originally named Oak. It was first used in
developing an interface for a PDA (Personal Data Assistant) and was used with
the Web in 1994 when the HotJava browser was released. It was finally
introduced by Sun at SunWorld in May 1995. It brings the capacity for
interactivity to the Internet through multimedia and animation.
A Java applet is a form of a Java
program designed to run on a Java-compliant Web browser. This includes Netscape
Navigator 2.0+ and Microsoft Internet Explorer 3.0+. Java programs and applets can be developed using a variety of
tools including Microsoft’s Visual J++, Borland’s JBuilder, Symantec’s Café and
Sun’s Java Development Kit (JDK). The JDK is freely downloadable from http://java.sun.com/ while the other products are
commercialware.
It is not possible in this short
introduction to explain all of the details of Java. Listed below are some simple examples of Java programs and
Applets. These and other examples can
be found at http://csc.ColumbusState.edu/summers/notes/java.htm
10.7.2
Java Program Examples
The following are some simple Java programs.
1.
public class Hello
// program which prints "Hello World!"
// written by Wayne Summers
{
public static void
main(String[] args)
{
System.out.println("Hello
World!");
}
}
2.
public class Temperatures
// program which converts temperatures in Celcius to Fahrenheit
// written by Wayne Summers
{
public static void
main(String[] args)
{
System.out.println("Temperature
conversions");
computeFahrenheit(30);
double celcius
= 25;
computeFahrenheit(celcius);
}
public static void
computeFahrenheit(double celciusTemp)
{
double
fahrenheitTemp;
fahrenheitTemp
= 9 / 5 * celciusTemp + 32;
System.out.println("Celcius
temperature =" + celciusTemp);
System.out.println("temperature
in Fahrenheit =" + fahrenheitTemp);
}
}
10.7.3
Java Applets
Java Applets are applications that
cannot stand alone but must be invoked from an HTML document. A simple example
follows.
import
java.awt.Graphics;
// Applet that displays Hello
World on the screen
public class HelloWorldC extends
java.applet.Applet {
public void paint(Graphics g)
{
g.drawString("Hello
World", 5, 50);
}
}
To invoke this applet from an HTML
document requires the following
<APPLET
CODE=HelloWorldC.class WIDTH=200 HEIGHT=100>
ALT= "Applet
could not be loaded"
Sorry, it is time to
upgrade your browser to a Java powered one.<P>
</APPLET>
The source code
is typed in and saved as the file HelloWorldC.java. It is then compiled into an
intermediate language called bytecodes and saved as HelloWorldC.class. This
bytecode file is then interpreted by the Java plugin to the web browser. The
example can be found at http://csc.ColumbusState.edu/summers/notes/Cs463/index.html
This next example illustrates the use
of windows programming features to allow interaction with the user. The example
can be found at http://csc.ColumbusState.edu/summers/notes/Cs463/fibo.html.
//
Fibo.java
// Recursive Fibonacci Method
import java.applet.Applet;
import java.awt.*;
public class fibo extends Applet {
Label numLabel, resultLabel;
TextField num, result;
public void init()
/**************************************************************************/
/* initialize both labels and
Textfields */
/*************************************************************************/
{
numLabel = new
Label("Enter an integer and press return");
num = new TextField(10);
resultLabel = new
Label("Fibonacci value is");
result = new TextField(15);
result.setEditable(false);
add( numLabel);
add( num);
add (resultLabel);
add (result);
}
public boolean action(Event e,
Object o)
/**************************************************************************/
/* get number from first
TextField, compute and display its
*/
/* fibonacci number */
/*************************************************************************/
{
long number, fibonacciVal;
number = Long.parseLong(
num.getText());
showStatus("Calculating ...");
fibonacciVal = fibonacci
(number);
showStatus
("Done.");
result.setText
(Long.toString( fibonacciVal ));
return true;
}
long fibonacci (long n)
/**************************************************************************/
/* recursive definition to compute
fibonacci numbers */
/*************************************************************************/
{
if ( n == 0 || n == 1)
return n;
else
return
(fibonacci(n-1) + fibonacci(n-2));
}
}
The final example is one of the
original examples shipped with the JDK and was developed by Sun Microsoystems.
A copy of the program can be found at
http://csc.ColumbusState.edu/summers/notes/Java/Clock/example1.html.
/*
* Copyright (c) 1994-1996 Sun Microsystems,
Inc. All Rights Reserved.
*
* Permission to use,
copy, modify, and distribute this software and its documentation for
* NON-COMMERCIAL or COMMERCIAL purposes and
without fee is hereby granted.
* Please refer to the
file http://java.sun.com/copy_trademarks.html for further important copyright
and
* trademark
information and to http://java.sun.com/licensing.html for further important
licensing
* information for the Java (tm) Technology.
*
*/
// author: Rachel
Gollub, 1995
// modified 96/04/24
Jim Hagen : use getBackground()
// Time!
import java.util.*;
import java.awt.*;
import java.applet.*;
public class Clock2
extends Applet implements Runnable {
Thread timer = null;
int lastxs=0, lastys=0, lastxm=0, lastym=0,
lastxh=0, lastyh=0;
Date dummy = new Date();
String lastdate = dummy.toLocaleString();
public void init() {
int x,y;
resize(300,300); // Set clock window size
}
// Plotpoints allows calculation to only
cover 45 degrees of the circle, and then mirror
public void
plotpoints(int x0, int y0, int x, int y, Graphics g) {
g.drawLine(x0+x,y0+y,x0+x,y0+y);
g.drawLine(x0+y,y0+x,x0+y,y0+x);
g.drawLine(x0+y,y0-x,x0+y,y0-x);
g.drawLine(x0+x,y0-y,x0+x,y0-y);
g.drawLine(x0-x,y0-y,x0-x,y0-y);
g.drawLine(x0-y,y0-x,x0-y,y0-x);
g.drawLine(x0-y,y0+x,x0-y,y0+x);
g.drawLine(x0-x,y0+y,x0-x,y0+y);
}
// Circle is just Bresenham's algorithm for
a scan converted circle
public void
circle(int x0, int y0, int r, Graphics g) {
int x,y;
float d;
x=0;
y=r;
d=5/4-r;
plotpoints(x0,y0,x,y,g);
while (y>x){
if (d<0) {
d=d+2*x+3;
x++;
}
else {
d=d+2*(x-y)+5;
x++;
y--;
}
plotpoints(x0,y0,x,y,g);
}
}
// Paint is the main part of the program
public void
paint(Graphics g) {
int xh, yh, xm, ym, xs, ys, s, m, h,
xcenter, ycenter;
String today;
Date dat = new Date();
s = dat.getSeconds();
m = dat.getMinutes();
h = dat.getHours();
today = dat.toLocaleString();
xcenter=80;
ycenter=55;
// a= s* pi/2 - pi/2 (to switch 0,0 from
3:00 to 12:00)
// x = r(cos a) + xcenter, y = r(sin a) +
ycenter
xs = (int)(Math.cos(s * 3.14f/30 - 3.14f/2)
* 45 + xcenter);
ys = (int)(Math.sin(s * 3.14f/30 - 3.14f/2)
* 45 + ycenter);
xm = (int)(Math.cos(m * 3.14f/30 - 3.14f/2)
* 40 + xcenter);
ym = (int)(Math.sin(m * 3.14f/30 - 3.14f/2)
* 40 + ycenter);
xh = (int)(Math.cos((h*30 + m/2) * 3.14f/180
- 3.14f/2) * 30 + xcenter);
yh = (int)(Math.sin((h*30 + m/2) * 3.14f/180
- 3.14f/2) * 30 + ycenter);
// Draw the circle and numbers
g.setFont(new Font("TimesRoman",
Font.PLAIN, 14));
g.setColor(Color.blue);
circle(xcenter,ycenter,50,g);
g.setColor(Color.darkGray);
g.drawString("9",xcenter-45,ycenter+3);
g.drawString("3",xcenter+40,ycenter+3);
g.drawString("12",xcenter-5,ycenter-37);
g.drawString("6",xcenter-3,ycenter+45);
// Erase if necessary, and redraw
g.setColor(getBackground());
if (xs != lastxs || ys != lastys) {
g.drawLine(xcenter, ycenter, lastxs,
lastys);
g.drawString(lastdate, 5, 125);
}
if (xm != lastxm || ym != lastym) {
g.drawLine(xcenter, ycenter-1, lastxm,
lastym);
g.drawLine(xcenter-1, ycenter, lastxm,
lastym); }
if (xh != lastxh || yh != lastyh) {
g.drawLine(xcenter, ycenter-1, lastxh,
lastyh);
g.drawLine(xcenter-1, ycenter, lastxh,
lastyh); }
g.setColor(Color.darkGray);
g.drawString(today, 5, 125);
g.drawLine(xcenter, ycenter, xs, ys);
g.setColor(Color.blue);
g.drawLine(xcenter, ycenter-1, xm, ym);
g.drawLine(xcenter-1, ycenter, xm, ym);
g.drawLine(xcenter, ycenter-1, xh, yh);
g.drawLine(xcenter-1, ycenter, xh, yh);
lastxs=xs; lastys=ys;
lastxm=xm; lastym=ym;
lastxh=xh; lastyh=yh;
lastdate = today;
}
public void start() {
if(timer == null)
{
timer = new Thread(this);
timer.start();
}
}
public void stop() {
timer = null;
}
public void run() {
while (timer != null) {
try {Thread.sleep(100);} catch
(InterruptedException e){}
repaint();
}
timer = null;
}
public void update(Graphics
g) {
paint(g);
}
}
10.5
ActiveX (http://csc.ColumbusState.edu/summers/notes/activex.htm)
ActiveX is part of Microsoft’s overall
Internet strategy and was developed in response to the development of Java.
ActiveX helps build dynamic Internet tools, content and sites. ActiveX controls
are reusable software components created by a variety of software vendors that
can be used to quickly add specialized functionality to Web sites, desktop
applications, and development tools. For example, a stock ticker control could
be used to add a live stock ticker to a Web page, or an animation control could
be used to add animation features to a Web page. ActiveX Controls are based upon the OLE 2.0 specification and
support interaction with other applications including word processing and
spreadsheets. At this time, ActiveX Controls are not supported in Netscape or
on UNIX platforms.
The following example displays a
digital clock on the web page.
<HEAD>
<TITLE>CyberTime</TITLE>
<SCRIPT
LANGUAGE="VBScript">
<!--
Sub lblClock_Click
PopUpWindow.Popup
"http://132.163.135.130:14/"
End Sub
Sub Timer_Timer()
lblClock.caption=time
End Sub
-->
</SCRIPT>
<OBJECT
ID="lblClock"
WIDTH=400
HEIGHT=25
CLASSID="CLSID:99B42120-6EC7-11CF-A6C7-00AA00A47DD2"
CODEBASE="http://activex.microsoft.com/controls/iexplorer/ielabel.ocx"
>
<PARAM NAME="Caption"
VALUE="Dept. of Commerce Time Server">
<PARAM NAME="FontName"
VALUE="Arial">
<PARAM NAME="FontBold"
VALUE="1">
<PARAM NAME="FontSize"
VALUE="12">
<PARAM NAME="backcolor"
VALUE="1">
<PARAM NAME="forecolor"
VALUE="1">
<PARAM NAME="Alignment"
VALUE="Left">
</OBJECT>
<Object
ID="PopUpWindow"
ClassID="clsid:A23D7C20-CABA-11CF-A5D4-00AA00A47DD2"
CodeBase="http://activex.microsoft.com/controls/iexplorer/iepopwnd.ocx"
Type="application/x-oleobject"
></Object>
<Object
ID="Timer"
ClassID="clsid:59CCB4A0-727D-11CF-AC36-00AA00A47DD2"
CodeBase="http://activex.microsoft.com/controls/iexplorer/ietimer.ocx"
Type=application/x-oleobject"
Align=Middle
>
<Param Name="Interval"
Value="100">
<Param Name="Enbaled"
Value="True">
</Object>
</HEAD>
CAUTION: It is possible to receive an
ActiveX Control that can perform malicious acts on computers. Always use
caution when activating an ActiveX control.