Some Example Code:
List of all examples
The examples can be viewed
- as ~jamie/public_html/CS3172/examples/ on torch,
- as a file list, [all/] or
- from the lists below.
Lists
- List of Examples (and notes) by Topic
- List of Examples by Name within topic
- All of the Examples (organized within topics)
Examples by Topic
These links are to examples and notes grouped by topic
Examples by Name Within Topic
These links are to the named examples within topics
-
XHTML
- template file
- elements example
- entities example
- character codes example
-
CSS
- Simple Example (colour, size, & selectors)
- Nesting (selectors and pseudo-classes)
-
Text Buttons (boxes, colours, & graceful degradation)
- example.html example,
- screens.html example,
- questions.html, and
- button.css example
- centre.html
- image-background.html
- ShowingCSS.html
- container size
- bad layout
- See Also (CSS)
- JavaScript
- SSI
-
CGI (with Forms and Cookies)
- sh.cgi example
- sh-date.cgi example
- perl.cgi example
- perl-date.cgi example
-
Some CGI Parameters
- about.cgi example
- env.cgi example (in the perl section)
-
Forms
- Form Basics
- How Forms Are Processed
-
Dynamically Generated Forms with CGI
- advice.cgi example
- advice2.cgi example
- advice2a.cgi example (CGI program that dynamically generates content)
- multi-page.cgi example and loan.cgi example (CGI programs that produce multiple page forms)
-
Cookies
- time1.cgi (CGI form displaying time and saving state in the form)
- cookie-time.cgi (same form saving state with cookies)
- cookie-colour
-
Perl
- Perl `basics'
- ‘here’ documents
- Subroutines
- Functions
-
Inter-process Communication
- (no list of examples available)
- Servlets
Sources[*]
- The expanding and contracting lists are based on code by Karl Nelson. See the nested lists example for more details.
- Unless specifically noted, in the source files, all examples below are by J. Blustein.
Examples
-
In-Class Examples
Any examples that we did as a class are in the in-class directory.
See also the demonstrations in the materials section of the course website.
HTML/XHTML
CSS (Cascading Style Sheets)
-
Simple
-
Buttons
- button.css example
- as XHTML
- as source
- as presented in various browsers
- (images and long textual descriptions of the buttons as presented in various browsers)
- questions about solving problems with CSS implementation (excerpted from the screen shots webpage)
- button.css example
-
Nesting
-
Centre
- how to centre block level elements with CSS
- Illustration of method by Eric Meyer
-
Image Replacement for Text
- show image with CSS or text without an example of progressive enhancement from 2005 lectures
-
Showing CSS instructions in the
<head>
- show the actual CSS instructions
embedded in the
<head>
of an XHTML file
- show the actual CSS instructions
embedded in the
-
Container size
- how tree-parent/containers affect position an example that is not yet complete
-
Bad Layout
- Example of a layout problem (vertical scrolling) an example that is not yet complete
-
See also
- Correctly using titles with external style sheets (archived copy of article by Eric A. Meyer from Netscape devedge),
- Show Everything: Revealing Normally Hidden Elements,
- CSS demonstrations in the materials list
- Jon Gunderson's lecture with examples in the Lectures list, and
- other information in the CSS section of the resources list.
-
JavaScript
-
dual_presentation
- part 1: run dual_presentation
- part 2: explaining the changing body text
- part 3: explaining the pop-up dialogue box
- source files
- dual_presentation.html (HTML webpage)
- 2-how.html (HTML webpage explaining the variable body text)
- 3-body.html (HTML webpage explaining the variable pop-up dialogue box)
- dual_presentation.js (JavaScript code)
- dual.css (CSS stylesheet)
- dual_presentation filesystem directory
-
dual-redux
- dual-redux example
- using JS and CSS together without reducing accessibilty
- dual-redux filesystem directory
Note about avoiding unwanted side-effects with JS
-
See the note in the source of goback.html about event
handlers and
return
values -
With favelets (aka
bookmarklets) we can avoid side-effects by enclosing all
assignment statements in
void(…)
. The highlight.js part of the dual-redux source shows an example. -
Also note that since highlight.js uses an anchor with the
javascript
scheme (formerly known asprotocol
) (i.e., it begins with
) the link is meaningful only if JavaScript (or ECMAscript) is enabled in the browser. To try to prevent the text of the anchor from appearing when it cannot be used (i.e. when JavaScript is not available) the link is inserted using JavaScript.javascript:
- dual-redux example
-
input methods
-
random_tile.js
- run random_tile
- source files
- random_tile.html (HTML webpage)
- random_tile.js (Javascript code)
- random_tile.css (CSS stylesheet)
- random_tile filesystem directory
- See Also the following from the Resources section's website list:
-
nested lists
Using the DOM to dynamically alter a document and using the
onclick
event. The DOM is also used in the input examples (above). Theonclick
event is also used in the random_tile example (above).- see Nestedlists.html (as HTML)
- see source of Nestedlists.html
- example based on code by Karl Nelson
-
SSI (Server Side Include)
test1.shtml
Notes about SSI files at Dal FCS:
- filenames must end with .shtml
- files must not be in (or beneath) your public_html/cgi-bin directory
- the server that runs www.cs.dal.ca is not the same as the one that runs torch.cs.dal.ca — SSI may work differently on them
CGI (Common Gateway Interface)
Outline of CGI Examples
Notes about the Common Gateway Interface (CGI)
CGI is an interface. The client can pass parameters to the server through HTML forms and back to the client through generated programs. The server-side programs can be written in any language. For instance here are two programs written in the Bourne shell:
- Static output
- run cgi:basic/sh program
(<a href="/~jamie/cgi-bin/3172/cgi:basic/sh.cgi"
)
>run <kbd>cgi:basic/sh</kbd> program</a> - view cgi:basic/sh source
- run cgi:basic/sh program
- Dynamic output
Note that the program file must
- be readable and executable by the server,
- be in your ~/public_html/cgi-bin/ directory,
- be referred to (in hrefs) as being in ~you/cgi-bin/ (where you is your username), and
- have have .cgi as the last four characters of its name.
For the interface to work, there must be a header before the content. The header can contain cookies and other information that the server passes on to the browser.
The last two lines of the header must be:
- the MIME-type of the content to be presented to the user
- empty
For example:
Content-type: text/html
The MIME types are all specified in RFCs. The two most common MIME types used on the WWW are shown in the following table
Two Common MIME Types Type Encodes text/html HTML text/plain Text For more information about MIME types and their use on the WWW see this excerpt from XHTML 1.0 Web Development Sourcebook and this bug report about Internet Explorer.)
When we program CGI in perl we use the CGI.pm package. It includes many handy features, such as
header()
which will produce the MIME-type header for us. If we don't tell it what type of header to produce then it makes one for HTML. Rememberheader()
is a subroutine returning a string, we have to useprint
to make it appear in the output.Here are the same two examples that we saw in Bourne shell but with perl:
- Static output
-
about.pl & env.pl
about.pl
CGI programs are usually not run as suid (set-uid) for security. Do our CGI program's run as suid? Check out the about.pl program:
- run about (on www.cs.dal.ca)
- run about (on torch.cs.dal.ca)
- view about source code
- See also the Apache Server
suexec
documentation
Notes about CGI programs on torch:
- files must be readable and executable by the server (user http);
- filenames must end with .cgi;
- files must be in (or beneath) your public_html/cgi-bin directory;
- Only the file's owner has write permission to the file and the directory;
- There is a checklist for CGI in perl in the system documentation subsection of the materials.
- For related information about access control lists see the ACL part of the system documentation subsection.
-
env.pl
env.pl shows the parameters that are available in a CGI program.
- run env (on www.cs.dal.ca)
- run env (on torch.cs.dal.ca)
- view env source code
- An updated version of this program (named upload2) is below.
-
CGI Form Basics
-
controls-example
The controls-example form demonstrates the most common types of form controls. The controls-example.cgi program shows code that reads the values (on the server) from the form (submitted on the client).
-
file-upload
- upload.cgi
- Description:
file-upload is a CGI program that generates different output depending on conditions (like the advice programs). It makes a
form
that:- reads in a file,
- uses CGI.pm's
uploadInfo()
function to show some of the information that the browser sent with the file, and - reads the file (from the server's cache) to check the file length.
- Note that the length check depends on the assumption that it is a text file.
- Note also that the program generates the form itself.
- Links:
- upload2.cgi
- Description:
- an updated version of the env.pl program that includes command-line arguments and standard input
- Links:
- sample.txt
- is a small file that works well with the file upload.
The file upload programs are based on examples by Lincoln Stein and Ian S. Graham, (see source code for details).
-
simple-get.html and simple-post.html
The simple-get.html and simple-post.html forms use the same
form
but different methods. Look at the URL that they send to the server. -
hidden-get.html and hidden-post.html
The hidden-get.html and hidden-post.html are identical to the simple forms above, but these include
hidden
fields.
-
-
How Forms Are Processed
Here is more detail about how forms are processed.
-
how-post-is-processed.html
This form is almost the same as in the simple form examples above, except that it includes a hidden value. The program shows all three of the ways that data can be passed to the CGI program: through command-line arguments, the environment, and standard input.
- run how-
post
-is-processed (form) - view form-processing.cgi (source code)
- Based on a program by Ian S. Graham (see details in source code)
- run how-
-
how-get-is-processed.html
This form is exactly the same as the
post
form (immediately above) except that it usesget
instead ofpost
. Both forms call the same CGI program so you can see how the parameters are passed.get
sends its parameters in the URL and the server receives them in theQUERY_STRING
environment variable. On the other hand,post
sends its parameters through the standard input device of the server process.- run how-
get
-is-processed (form) - view form-processing.cgi (source code)
- run how-
-
three-penny-form.html
An XHTML file with three
form
s (an example usingmethod="get"
, an example usingmethod="post"
, and an example of a file-upload usingmethod="post"
). Each of theform
s calls form-processing.cgi.sample.txt is a small file that works well with the file upload.
- run three-penny-form.html (form)
- view form-processing.cgi (source code)
-
Notes about
form
methods and encodingsDifferences Between CGI Methods GET POST G1) Thought of as a read
requestP1) Thought of as a write
instructionG2) Can be cached P2) Should not be cached G3) Name=value pairs appear in URL - name=value follows a ? after the address
- each name=value separated by & or ;
P3) Names and values are not visible to the user G4) Names and values received, on server-side, in environment variable QUERY_STRING
P4) Names and values received in standard input (using MIME encoding multipart/form-data
)How CGI Arguments Are Encoded Argument Encoding alphanumerics not encoded blank (space) as +
other as %
h1h2
(where h1 and h2 are hexadecimal digits)-
To decode
%
h1h2 using perl:
$string =~ s/%([A-F0-9]{2})/chr(hex($1))/ige;
(from part 9 of the perl FAQ) To encode characters you can use the tables and lists of hexadecimal codes for printable non-alphanumeric characters.
-
-
Dynamically Generated XHTML
form
sSince CGI can be used to generate XHTML we can write programs that generate their own
form
s. When theform
is submitted the CGI program can then generate a newform
that will be different depending on what values were input in the previousform
. We can use<input type="hidden">
to tell the CGI program whichform
it is responding to. (The file-upload.cgi example, above, uses a similar technique.)-
advice.cgi
advice.pl generates a form that changes depending on what was submitted the previous time it was run. It uses code in CGI.pm to generate most of the HTML. advice2.pl and advice2a.pl are other versions of the same CGI program that do not let CGI.pm generate HTML for it. advice2a.pl also includes slightly more error checking code. (The original advice program was written by Lincoln Stein.)
How advice Works
None of these programs produces valid HTML output. They are meant only to be simple examples without any confusing details.
Many web browsers recognize the markup
<form>
to mean that amethod="post"
form
is being created and that theaction
is to send the results to the same program that generated the form in the first place. This is not valid HTML but it is sufficient for you to understand how dynamically generated forms work.- advice.pl
- advice2.pl
- advice2a.pl
-
multi-page.cgi (and loan.cgi)
multi-page.cgi and loan.cgi are two examples of using hidden fields in forms to save state. Each of these programs generates a form that changes depending on what was submitted the previous time they were run. multi-page.cgi is a basic and somewhat ugly example. loan.cgi is an elegant piece of perl programming (by Lincoln Stein) that happens to use CGI.pm to generate much of the HTML code.
For another example of using forms to save state see the time1 example in the Cookies section.
- multi-page.cgi
- loan.cgi
-
-
Debugging CGI programs
These examples of how to debug CGI programs rely on Perl's CGI.pm module to demonstrate the differences between online and offline execution. The programs cannot be executed offline from this website.
- debugging.cgi
- description: demonstration of perl's
warn()
anddie()
- Perl source of debugging.cgi
- location: /~jamie/public_html/cgi-bin/3172/cgi:basic/debugging.cgi
- see also: the Perl/CGI programming checklist in the system documentation section
- advice2a.cgi
- description: real-world debugging in a simple form, uses
diagnostics
pragma for verbose error messages, and includessanity check
code - location: /~jamie/public_html/cgi-bin/3172/form/advice2a.cgi
- Perl source of advice2a.cgi
- time-1d.cgi
- description: using cookies
- Perl source of time1-d.cgi
- location: /~jamie/public_html/cgi-bin/3172/cookie/time1-d.cgi
-
Cookies
- CGI form displaying time (time1.cgi)
- This form saves state by writing out new default values of the radio buttons every time it is run
- The time1 and time2 examples are based on examples by Lincoln Stein
- Run time1
- view the source code of time1
- For another example of using forms to save state see the mutlti-page example in the CGI forms section.
- same form saving state with cookies (time2.cgi)
- cookie form (cookie-colour)
- run the cookie-colour form
- run env (on www.cs.dal.ca) to see the cookies in passed to the CGI program in environment variables
- CGI program called by the form
- view the source of the CGI program that reads the cookies (based on a program by Deitel, Deitel, and Nieto)
- See also the CGI.pm documentation
about cookies:
- archived copy of original CGI.pm documentation (from 2004-10-11),
CGI::Cookie
at CPAN,- all current CGI.pm documentation (at CPAN)
- CGI.pm documentation about cookies (link is to an archived copy)
- the cookie section in the resource list
Notes about (version 0) Cookies:
- Cookies can only have one value at a time (just like a variable in a program)
-
Cookies are limited to 4Kb (4096
octets) each. We can use Perl's
pack
function to encode lots of data into a string: - Only the name and value parts are required. The domain, expires, path, and secure parts are optional.
- The expires part must be expressed as GMT and be in this format: Wdy, DD-MMM-YYYY HH:MM:SS GMT
- For more detailed information about cookies, and expiration times, see Notes about cookies expiry times (in the System Documentation subsection).
- CGI form displaying time (time1.cgi)
perl
-
perl ‘basics’
-
`here' documents
`Here' documents allow you to include a literal document in one print statement. The syntax is:
print <<end-marker
text to print
end-marker
;
Note:
-
The
end-marker
must be immediately following the<<
-
If the
end-marker
is quoted (with''
,""
, or``
, etc.) then the print statement acts as though each line in the here portion is quoted that way too. (Use''
to quote literaly, as in the here.cgi example below). -
The semi-colon (
;
) that follows the secondend-marker
almost always needs to be on a separate line from theend-marker
-
If you are having trouble with your own
here
documents then read the question about them in section 4 of the perl FAQ (archived copy of perldoc perfaq4 on torch).
here.cgi
Here is an example that uses CGI:
Another example
(from Programming Perl page 67):
If you want your here docs to be indented with the rest of the code, you'll need to remove leading whitespace from each line manually:
($quote = <<'QUOTE') =~ s/^\s+//gm; The Road goes ever on and on, down from the door where it began. QUOTE
-
The
-
subroutines
Parameters are passed by value, but you can pass references.
How to pass more than one list to a subroutine:
-
Functions
mtime.pl
The mtime.pl program demonstrates how to use the
stat
function to find the modification time of a file. It can run as a CGI program or from the command-line. -
Database Interface Examples
- Source code courtesy of Nur Zincir-Heywood. All of these examples use oracle on torch. Examples in the Introduction to Web Databases lecture slides use MySQL.
-
Inter-process Communication
These examples are all perl code that demonstrates aspect of the client-server model and how to implement it using Perl. The example source code listings are in the perl/ipc directory.
-
Servlets
Note about servlet examples:
These servlets were compiled for a different Servlet/JVM combination than is currently installed. The source code is still correct however, and the compilation record can be used as a guide. But the compiled versions might not be executable now.For details about how servlets are supposed to configured, etc. see the
Servlets
document from the CS frquently asked questions website. (The link was current on 16 September 2009; The document was dated 10 September 2009.)HelloClient
- source code
- record of compilation and installation
- directory of all HelloClient servlet files
- Annotated version from Servlet Essentials by Stefan Zeiger
Greeting
Session Tracking
- run ShowSession on torch
- view file system directory containing the source code of ShowSession
- Slightly modified from code by Marty Hall and Larry Brown
- Notes:
- The session tracking is handled by the servlet API (either by cookies or URL rewriting).
- Because we don't know if the client will use cookies (or not) we
can't use the same URL each time, so we must call
request.encodeURL
orrequest.encodeRedirectURL
to generate the correct form of the URL. session.getMaxInactiveInterval()
andsession.setMaxInactiveInterval()
are used to access the number of idle seconds before a session expired (and is closed automatically). Negative values mean that the session never expires.- Sessions can be terminated with
invalidate()
.
Servlet Request Headers
- run ShowRequestHeaders on torch
- view file system directory containing the source code of Headers
- By Marty Hall and Larry Brown
Marty Hall's Examples
- source code (from Marty Hall's tutorial at <URL:http://javaboutique.internet.com/tutorials/JSP/>)