Beruflich Dokumente
Kultur Dokumente
Sept 2012
Jimma University
Table of Contents
Unit One: Introduction to Web Pages ............................................................................................. 6
1. Architecture of the Internet and WWW ..................................................................................... 6
1.1
1.2
1.3
Standardization ................................................................................................................ 9
2. Protocols ................................................................................................................................... 12
1.1
1.2
HTTP ............................................................................................................................... 12
1.2
1.3
1.4
1.5
1.6
1.8
1.9
1.10
1.11
Search Services
Practice 1.1
1. What are the major components of the Internet?
2. What are the major functionalities of the Internet in todays business environment?
As the accessing of information stored on computers has become more widely accepted
and used, the number of methods, and hence the number of computer applications
needed, has multiplied.
The web provides a way of integrating these methods and applications, using a common
interface to allow easy access to any information stored on any computer
The language of the web, was specifically designed to be easy to learn, and was based
around the concept of marking text functionally, to ensure a wide authorship. As it has
grown, the web has moved away from this concept, becoming more complex and more
graphical than originally envisioned. Though, the core functions still lie beneath all the
complexity, and allow more or less anyone to write their own web pages quickly and easily,
with a minimal set of software tools.
One of the most powerful features of the web is the ability to link documents together
using hyperlinks. On clicking a hyperlink (usually underlined), the browser tries to access
the linked document, providing an almost instantaneous cross-referencing system. This
creates a non-linear orm of text, known as hypertext. Web pages can also contain
multimedia content that can also be hyperlinked, termed hypermedia.
The goal of a web server is to serve information to anyone who requests it; the web pages stored on the
server are made publically available. It's possible to restrict access to certain parts of the Internet, or to
those who have usernames and passwords, but it's not usual: most web sites are open for all to read
their contents. The use of the web as a public space to provoke discussion or to provide otherwise
difficult-to-publish information has been instrumental in its popularity. Examples of this range from the
subversive (political groups publishing propaganda), to the more mundane (businesses publishing timecritical data such as stock information or market prices).
With the rise of commerce on the Web, and the recognition of the market value that certain types of
information can command, parts of the Web have been locked away, hidden behind corporate intranets
and firewalls, sites with passwords, and subscription services.
A high proportion of this Deep or Invisible Web is hidden from view, whether from you and I, or from
search engines. Estimates of the size of this deep Web vary, but most agree that it is many times the size
of the Surface Web, i.e. the web that is open and accessible to the public.
The backbone of the web is the network of web servers across the world. These are really just
computers that have a particular type of software running on them: software: web browser, which
knows how to speak the protocol and knows which information stored on the computer, should be
made accessible through the web. It's possible to turn almost any computer into a web server by
downloading and installing server software (Example: Apache)
The web browser is also particularly clever in the way it displays what it retrieves. Web pages are
written in a certain language, and the browser knows how to display these correctly, whether you have
a huge flat screen or a tiny screen on a handheld device or phone. The language the page has been built
gives the browser hints on how to display things, and the browser decides the final layout itself.
Practice 1.2
1. What are the steps in which information is retrieved from a web?
2. What is the role of protocols in communication of information in the web?
1.3 Standardization
The nature of WWW, which is the connection of different type of computers around the world, would
have created chaos, if it is not for different standards that guild the web developers and owners what to
comply in their websites. The major standards in WWW are the language used to build the web pages:
HTML (Hypertext Markup Language) and the processes of giving address for web pages.
HTML
HTML is a standard language, which should mean that all web browsers interpret it in exactly the same
way. The standard is decided upon by a large body of volunteers and experts, who oversee its progress
and guide its development. This body is managed by the World Wide Web Consortium (the W3C,
http://www.w3.org/), and currently recommends the use of HTML4.01, its latest standard).
One of the reasons that the web is so widely used is that the standardization of HTML has allowed many
developers to produce browser software, for many types of computer. The original definition of HTML
was written in a language called SGML (Standard Generalized Markup Language), designed to allow
computers to read language definitions easily. This means that HTML is defined very precisely, which is
why you need to be equally precise when writing your web pages. If a web page is written in such a way
that it conforms to the SGML definition, then it should be readable by all browsers conforming to that
definition.
The next generation of HTML, called XHTML, is defined in a cut down version of SGML called XML
(eXtensible Markup Language). XHTML is stricter in its definition of tags (has strict syntax rules), but it is
much more flexible, in that it is much easier for computers to interpret. When a computer reads any
kind of document, it must follow a strict pattern or syntax, and the stricter this is, the easier the
computer finds the interpretation, even though we as humans may find it difficult to write so accurately.
Tools such as Dreamweaver and dedicated XML editors make writing this stricter form of HTML much
easier.
10
Domain Name - Most computers on the Internet have a domain name. A domain name is the text name
corresponding to the numeric IP address of a computer on the Internet. A domain name must be
unique. Internet users access your website using your domain name.
A domain name always contains two or more components separated by periods, called dots. Some
examples of domain names are: ibm.com, nasa.gov, aau.edu.telecom.net.et etc. Once a domain name
has been established, sub-domains can be created within the domain. For example, the domain name
for a large company could be vni.com and within this domain, sub-domains can be created for each of
the companys regional offices.
The portion of a domain name after the dot describes the type of organization holding that name. The
major categories are:
The domain names and IP address are what facilitate the information searching process. The key to
accessing all this information is the URI: Uniform Resource Identifier. Each web page has a unique
address, which is used by the URL: Uniform Resource Locator, which tells the client/browser how to
access the page.
For example: http://piglet.exeter.ac.uk/pallas/index.html, the parts of the URL could be decomposed as
follows.
The parts of a URL
http: the method of delivery (ftp, file, etc.). The :// is important to distinguish this from the
server name that follows
piglet.ex.ac.uk: the server computer the document is stored on. This could also be referred to by
its IP number, e.g. 144.173.116.100. Breaking this down further:
piglet the host: the name of the individual computer/ server. These are usually decided upon by
the organization concerned.
exeter: the organisation :exeter or ex (domain name = exeter.ac.uk)
ac: the organisation type: ac or edu for academic sites,
uk: the country code uk, fr, et, etc.
11
Practice 1.3
2. Protocols
1.1 What is Internet Protocol?
The Internet protocols are the worlds most popular open-system (nonproprietary) protocol suite
because they can be used to communicate across any set of interconnected networks and are equally
well suited for LAN and WAN communications. The Internet protocols consist of a suite of
communication protocols, of which the two best known are the Transmission Control Protocol (TCP) and
the Internet Protocol (IP). The Internet protocol suite not only includes lower layer protocols (such as
TCP and IP), but it also specifies common applications such as electronic mail, terminal emulation, and
file transfer. In addition, it includes different application level protocols like Small Mail Transfer Protocol
(SMTP), Network News Transfer Protocol (NNTP), File Transfer Protocol (FTP), Dynamic Host
Configuration Protocol (DHCP) and Hypertext Transfer Protocol (HTTP)
1.2 HTTP
The Hypertext Transfer Protocol (HTTP) is an application level protocol for distributed, collaborative,
hypermedia information systems. HTTP has been in use by the World Wide Web global information
initiative since 1990. The first version of HTTP, referred to as HTTP/0.9, was a simple protocol for raw
data transfer across the Internet. HTTP/1.0, as defined by RFC (Request For Comments) 1945, improved
the protocol by allowing messages to be in the format of Multipurpose Internet Mail Extension (MIME)
like messages, containing meta-information about the data transferred and modifiers on the
request/response semantics. While HTTP/1.0 has provided with many capabilities it does not take in to
consideration the need for persistent connections, or virtual hosts. This has necessitated a protocol
version change. This specification defines the protocol referred to as HTTP/1.1. This protocol includes
more strict requirements than HTTP/1.0 in order to ensure reliable implementation of its features.
Practical information systems require more functionality than simple retrieval, including search, front
end update, and explanation. HTTP allows an open-ended set of methods and headers that indicate the
purpose of a request. It builds on the discipline of reference provided by the Uniform Resource Identifier
(URI), as a location (URL: Uniform Resource Locator) or name (URN: Uniform Resource Name) [20], for
12
indicating the resource to which a method is to be applied. HTTP is also used as a generic protocol for
communication between user agents and proxies/gateways to other Internet systems, including those
supported by the SMTP, NNTP, and FTP protocols. In this way, HTTP allows basic hypermedia access to
resources available from diverse applications.
The HTTP protocol is a request/response protocol. A client sends a request to the server in the form of a
request method, URI, and protocol version, followed by possible body content over a connection with a
server. The server responds with a status line, including the messages protocol version and a success or
error code, followed by a MIME like message containing server information, entity meta-information,
and possible entity body content. Most HTTP communication is initiated by a user agent and consists of
a request to be applied to a resource on some origin server. In the simplest case, this may be
accomplished via a single connection (v) between the user agent (UA) and the origin server (O).
Request chain ------------------------>
UA -------------------v------------------- O
<----------------------- response chain
Practice 1.4
1. What is the relationship between Internet Protocol suite and HTTP?
2. What is the general purpose of HTTP?
Generally, the HHTP request line includes HTTP version, request method and request URL while
the response line include HTTP version, status code: a three digit number and status description
which has textual explanation for the status code.
HTTP request line
Request method (eg. GET, POST, DELETE, Status code (eg. 100, 200)
TRACE, PATCH)
Request URL
13
14
Notepad, you can quickly view the results by going to the browser and hitting refresh.
15
Example: the background color of HTML document can be changed using bgcolor attribute of the
<body> tag.
<body bgcolor=green>, while bgcolor is the name of attrbuite, green is the value.
The HTML code for this link is: <a href= http://mail.yahoo.com> Yahoo mail</a>
HTML Links, the name Attribute: The name attribute specifies the name of an anchor. The name
attribute is used to create a bookmark inside an HTML document. Bookmarks are not displayed in any
special way. They are invisible to the reader.
Example:
A named anchor inside an HTML document: <a name="example">Sample Examples</a>
Create a link to the "Sample Examples" inside the same document: <a href="# example">Go to Sample
16
Example</a>
HTML Headings
Headings are defined with the <h1> to <h6> tags. <h1> defines the largest heading. <h6> defines the
smallest heading.
Example:
<h1>This is a heading one </h1>
<h2>This is a heading two</h2>
<h3>This is a heading</h3>
HTML Paragraphs
Paragraphs are defined with the <p> tag.
Example:
17
<p>This is a paragraph</p>
<p>This is another paragraph</p>
Both of the above tags will enforce a new line whenever you write the tag. If you want additional new
line you can use the break tag (<br>: break tag does not have an end tag)
While the paragraph and heading tags are used to create texts, there are many other tags that you can
use to enhance and change the look of the text. The following are some examples.
The Tag
Meaning of Tag
In addition to the above tags HTML has different facilities concerning the usage of special characters and
reserved words. Some of these tags are listed below.
Tag
<abbr>
<acronym>
<bdo>
<q>
<cite>
<dfn>
& or &
' or '
> or >
¢ or ¢
© or ©
Description
Defines an abbreviation
Defines an acronym
Defines the text direction
Defines a short quotation
Defines a citation
Defines a definition term
Defines character &
Defines character
Defines character >
Defines character
Defines character
18
19
Header 1
Header 2
Attributes of table: the attributes of a table will be applied on the whole table element which include
one or more rows (<tr>), header cells (<th>) or data cells (<td>)
Attribute
align
bgcolor
border
cellpadding
Value
left
center
right
rgb(x,x,x)
#xxxxxx
colorname
pixels
pixels
cellspacing
width
pixels
pixels
%
Table 2.1 attributes of table
Description
Specifies the alignment of a table according to
surrounding text
Specifies the background color for a table
Attributes of rows and cells: this attributes will be applicable only to the header cell or the data cell if
it is used with <th> or <td> tag while it will affect the whole content of the row if it is used by the <tr>
tag.
Attribute
align
bgcolor
colspan
height
Value
left
right
center
justify
char
rgb(x,x,x)
#xxxxxx
colorname
number
pixels
Description
Aligns the content in a cell
20
nowrap
rowspan
width
valign
%
nowrap
number
pixels
%
top
middle
bottom
21
2. Orange
Practice 2.2
1. Write a code that displays the courses that you are currently taking (use unordered list)?
2. Write a code that displays your favorite books in order?
3. Frames
3.1 Working with Frames
Frames can divide the screen into separate windows. Each of these windows can contain an HTML
document. A file that specifies how the screen is divided into frames is called a frameset. If you want to
make a homepage that uses frames you should:
Make an HTML document with the frameset
Make the normal HTML documents that should be loaded into each of these frames.
When a frameset page is loaded, the browser automatically loads each of the pages associated with the
frames. Each HTML document is called a frame, and each frame is independent of the others.
The disadvantages of using frames are:
The web developer must keep track of more HTML documents
It is difficult to print the entire page
The frameset element holds two or more frame elements. Each frame element holds a separate
document. The frameset element states only HOW MANY columns or rows there will be in the frameset
and it uses <frameset> tag. The <frame> tag defines one particular window (frame) within a frameset. In
the example below we have a frameset with two columns. The first column is set to 25% of the width of
the browser window. The second column is set to 75% of the width of the browser window. The
document "frame_a.htm" is put into the first column, and the document "frame_b.htm" is put into the
second column:
<frameset cols="25%,75%">
<frame src="frame_a.htm" />
<frame src="frame_b.htm" />
</frameset>
Note:
The frameset column size can also be set in pixels (cols="200,500"), and one of the columns can
be set to use the remaining space, with an asterisk (cols="25%,*").
You cannot use the body element together with the frameset element. However, if you add a
<noframes> tag containing some text for browsers that do not support frames, you will have to
enclose the text in a body element.
22
Attributes of frame
Attribute
Value
Description
frameborder
0 or 1
marginheight
pixels
marginwidth
pixels
noresize
noresize
scrolling
Yes, no
auto
URL
src
Attributes of frameset
Attribute
Value
cols
rows
Description
Practice 2.3
1. What is the advantage of using frames
2. Create a web page that is divided in to three equal rows and the first row is divided in to two
columns.
3. Create a web page that is divided in to 3:2:1 proportion of columns.
23
Note: the more frames are nested; it will make it complicated hence difficult manageable.
4. HTML Forms
1.7 Building HTML Forms
HTML forms are used to pass data to a server. An HTML form is a section of a document containing
normal content, markup, special elements called controls (checkboxes, radio buttons, menus, etc.), and
labels on those controls. Users generally "complete" a form by modifying its controls (entering text,
selecting menu items, etc.), before submitting the form for further processing (e.g., to a Web server, to a
mail server, etc.) Forms are a vital tool for the webmaster to receive information from the web surfer,
such as: their name, email address, credit card, etc. A form will take input from the viewer and
depending on your needs; you may store that data into a file, place an order, gather user statistics,
register the person to your web forum, or maybe subscribe them to your weekly newsletter.
The <form> tag is used to create an HTML form:
<form>
input elements
</form>
The most important form element is the input element. The input element is used to select user
information. An input element can vary in many ways, depending on the type attribute. An input
element can be of type text field, checkbox, password, radio button, submit button, and more. The most
used input types are described in the next subsections.
Selam
Tibeb
24
Note: The form itself is not visible. Also note that the default width of a text field is 20 characters.
Practice 2.4
1. Create a web page that has a form for course registration; use your registration slip as a guide.
2. Create a web page that has a form for signing in to an email.
Password
<input type="password" /> defines a password field:
<form>
Password: <input type="password" name="pwd" />
</form>
How the HTML code above looks in a browser:
Password:
*********
Practice 2.5
25
1. Create a web page that let students choose their department; use the list of department in your
faculty as a guideline.
2. Use a checkbox to create a web page that will enable students to select a subjects they enjoy
most (more than one selection is possible).
Checkboxes
Check boxes allow for multiple items to be selected for a certain group of choices. The check
box's name and value attributes behave the same as a radio button.
<input type="checkbox" /> defines a checkbox. Checkboxes let a user select ONE or MORE options of a
limited number of choices.
<form>
<input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle" value="Car" /> I have a car
</form>
Selection lists
Drop down menus are created with the <select> and <option> tags. <select> is the list itself and each
<option> is an available choice for the user.
<select name="degree">
<option>Choose One</option>
<option>Some High School</option>
<option>High School Degree</option>
<option>Some College</option>
<option>Bachelor's Degree</option>
<option>Doctorate</option>
<input type="submit" value="Email Yourself">
</select>
Attributes of select
Attribute
Value
Description
disabled
disabled
multiple
multiple
name
name
size
number
26
Practice 2.6
1. Can you think of safe working condition and procedure as technician? Explain its importance?
27
28
1. CSS Basics
1.1 Introduction to CSS
CSS stands for Cascading Style Sheet. A cascading style sheet file allows you to separate your web sites
HTML content from its style. As always you use your HTML file to arrange the content, but all of the
presentation/formatting (fonts, colors, background, borders, text formatting, link effects & so on...) are
accomplished within a CSS.
CSS is a web page layout method that has been added to HTML to give web developers more control
over their design and content layout. Using CSS allows a designer to create a standard set of commands
(either embedded inside the web page or from an external page) that controls the style of all
subsequent pages.
With CSS you can add style (fonts, colors, spacing, and size) to web documents. More advanced
techniques control the layout of the page without the use of tables or other cumbersome HTML.
CSS is that CSS separates the layout and the styles of a web page. This is often difficult to comprehend
for web designers that are used to compiling their creative and HTML coding in a single web page
document. Styles such as fonts, font sizes, margins, can be specified in one place, and then the Web
pages feed off this one master list, with the styles cascading throughout the page or an entire site.
Styles solve a common Problem. HTML tags were originally designed to define the content of a
document. They were supposed to say "This is a header", "This is a paragraph", "This is a table", by using
tags like <h1>, <p>, <table>, and so on. The layout of the document was supposed to be taken care of by
the browser, without using any formatting tags.
Styles sheets define HOW HTML elements are to be displayed, just like the font tag and the color
attribute in HTML. Styles are normally saved in external .css files. External style sheets enable you to
change the appearance and layout of all the pages in your Web, just by editing one single CSS
document!
CSS is a breakthrough in web design because it allows developers to control the style and layout of
multiple web pages all at once. As a web developer you can define a style for each HTML element and
apply it to as many web pages as you want. To make a global change, simply change the style, and all
elements in the Web are updated automatically.
CSS Versions
There are three levels/versions of CSS:
CSS1,
CSS2, and
CSS3
29
CSS 1
The first CSS specification to become an official W3C Recommendation is CSS level1
level1. It was published in
December 1996.
for:
Among itss capabilities are support for
Font properties such as typeface and emphasis
Color of text, backgrounds, and other elements
Text attributes such as spacing between words, letters, and lines of text
Alignment of text, images, tables and other elements
Margin,
gin, border, padding, and positioning for most elements
Unique identification and generic classification of groups of attributes
CSS 2
CSS level 2 specification was developed by the W3C and published as a Recommendation in May 1998. It
is a superset of CSS 1. It includes a number of new capabilities like absolute, relative, and fixed
positioning of elements and z-index,
index, the concept of media types, support for aural style sheets and
bidirectional text, and new font properties such as shadows.
CSS level 2 revision 1 or CSS 2.1 fixes errors in CSS 2. It removes poorly-supported
supported or not fully
interoperable features and adds already
already-implemented
implemented browser extensions to the specification.
CSS 3
CSS Level 3 builds on CSS Level 2 module by module, using the CSS2.1 specification as its core. Each
module adds functionality and/or replaces part of the CSS2.1 specification.
The CSS Working Group intends that the new CSS modules will not contr
contradict
adict the CSS2.1 specification:
only that they will add functionality and ref
refine definitions.
CSS declarations always ends with a semicolon, and declaration groups are surrounded by curly
brackets:
30
p {color:red; text-align:center;}
To make the CSS more readable, you can put one declaration on each line, like this:
p{
color:red;
text-align:center;
}
CSS Comments
Comments are used to explain your code, and may help you when you edit the source code at a later
date. CSS comments, like JavaScript comments, are ignored by browsers.
A CSS comment begins with /* and ends with */ like this:
/*This is a comment*/
p{
text-align:center;
/*This is another comment*/
font-family:arial;
}
31
With this method each HTML file contains the CSS code needed to style the page. Meaning that any
changes you want to make to one page, will have to be made to all. This method can be good if you
need to style only one page, or if you want different pages to have varying styles.
Creating an External Style Sheet
An external CSS file can be created with any text or HTML editor such as "Notepad" or "Dreamweaver".
A CSS file contains no HTML, only CSS. You have to save the CSS file with the .css file extension. You can
link to the file externally by placing one of the following links in the head section of every HTML file you
want to style with the CSS file.
<link rel=stylesheet type=text/css href=filename.css/>
<style type=text/css>@import url(filename.css)</style>
Practice 3.1
1. Write an external CSS that formats paragraphs (<p> tags) and link to HTML page.
2. Write internal CSS to format your HTML page
2. CSS Styling
2.1 Styling Backgrounds
Background
You can style the background of an element in one declaration with the background property.
background: #ffffff url(path_to_image) top left no-repeat fixed;
Values:
attachment
color
image
position
repeat
32
You can specifically declare a color for the background of an element using the background-color
property.
background-color: value;
Values:
color name e.g. red, green, blue
hexadecimal number - e.g. #ff0000, #00ff00, #0000ff
RGB color code e.g. rgb(255, 0, 0), rgb(0, 255, 0), rgb(0, 0, 255)
transparent
e.g h1 { background-color: rgb(255, 255, 0); }
Background Image
You can set an image for the background of an HTML element (<p>, <h1>, <body>, <table>, etc) using
the background-image property.
background-image: url(path_to_image);
Values:
url
none
e.g. p { background-image: url("tulips.jpg"); }
Background Position
You can position an image used for the background of an element using the background-position
property.
background-position: value;
Values:
top left
top center
top right
center left
center center
center right
bottom left
bottom center
bottom right
x-% y-%
x-pos y-pos
Background Repeat
You can set if an image set as a background of an element is to repeat (across=x and/or down=y) the
screen using the background-repeat property.
background-repeat: value;
Values:
repeat
repeat-x
33
repeat-y
normal), -2, 6)
Fig. different letter spacing (0(normal
Word Spacing
You can adjust the space between words in the following m
manner.
anner. You can use negative values.
word-spacing: value;
Possible values are
normal
length
Line height
You can set the distance between lines in the following way:
line-height: value;
Possible values are
normal
number
length
34
percentage(%)
Text Align
You can align text with the following:
text-align: value;
Possible values are
left
right
center
justify
Examples:
This text is aligned left.
This text is aligned center.
This text is aligned right.
Text Decoration
You can decorate text with the following:
text-decoration: value;
Possible values are
none
underline
overline
line through
blink
35
<div> Hebrew and Arabic are written from rright to left. </div>
This is displayed as:
Text Transform
You can control the case of letters in an (X)HTML element with the following:
text-transform: value;
Possible values are
36
none
capitalize
e.g. h3 { text-transform: uppercase;}
lowercase
uppercase
White Space
You can control the whitespace in an (X)HTML element with the following:
white-space: value;
Possible values are
normal
pre
nowrap
pre-wrap
pre-line
This property declares how white space(tab, space, etc) and line break(carriage return, line feed, etc.)
inside the element is handled. Values have the following meanings:
normal: This value directs user agents to collapse sequences of white space, and break lines as
necessary to fill line boxes.
pre: This value prevents user agents from collapsing sequences of white space. Lines are only
broken at preserved newline characters.
nowrap: This value collapses white space as for normal, but suppresses line breaks within text.
pre-wrap: This value prevents user agents from collapsing sequences of white space. Lines are
broken at preserved newline characters, and as necessary to fill line boxes.
pre-line: This value directs user agents to collapse sequences of white space. Lines are broken at
preserved newline characters, and as necessary to fill line boxes.
The white-space processing model is as follows:
1. Each tab (U+0009), carriage return (U+000D), or space (U+0020) character surrounding a linefeed
(U+000A) character is removed if white-space is set to normal, nowrap, or pre-line.
2. If white-space is set to pre or pre-wrap, any sequence of spaces (U+0020) unbroken by an
element boundary is treated as a sequence of non-breaking spaces. However, for pre-wrap, a line
breaking opportunity exists at the end of the sequence.
3. If white-space is set to normal or nowrap, linefeed characters are transformed for rendering
purpose into one of the following characters: a space character, a zero width space character
(U+200B), or no character (i.e., not rendered), based on the content script.
4. If white-space is set to normal, nowrap, or pre-line, every tab (U+0009) is converted to a space
(U+0020) any space (U+0020) following another space (U+0020) is removed.
Practice 3.2
1. Write a CSS that uses background image and aligns paragraphs to right, with red text color.
2. Write internal CSS that gives extra spaces between letters and capitalize all <h1> tags in HTML
page
37
large
x-large
xx-large
The following table provides user agent guidelines for the absolute-size mapping to HTML heading and
absolute font-sizes
CSS absolute-size
xx-small
x-small
small
medium
large
x-large
xx-large
values
HTML font sizes
1
2
3
4
5
6
7
38
39
{
font-size: 12px;
text-indent:
indent: 3em; /* i.e., 36px - based on font-size*/
}
The ex means the x-height. The xx-height is so called because it is often equal to the height of the
lowercase x. However, an ex is defined even for fonts that do not contain an x.
Fig x-height
The x-height
height of a font can be found in different ways. Some fonts contain reliable metrics for the xheight. If reliable font metrics are not available, user agents may determine the x-height
height from the height
hei
of a lowercase glyph. In the cases where it is impossible or impractical to determine the x-height,
x
a value
of 0.5em should be used.
Example:
h1 { margin: 0.5em } /* em */
h1 { margin: 1ex
} /* ex */
Example:
h1 { line-height: 1.2em }
This means the line height of h1 elements will be 20% greater than the font size of the h1 elements.
On the other hand:
h1 { font-size: 1.2em }
This means that the font-size of h1 elements will be 20% greater than the font size inherited by h1
elements.
Font Style
You can set the style of text in an element with the font
font-style property:
font-style: value;
Possible values are
normal
itailc
oblique
40
Font Variant
You can set the variant of text within an element with the font-variant property:
font-variant: value;
Possible values are
normal
small-caps
Font Weight
You can control the weight of text in an element with the font-weight property:
font-weight: value;
Possible values are
lighter
normal
100
200
300
400
500
600
700
800
900
bold
bolder
The font-weight property selects the weight of the font. The values 100 to 900 form an ordered
sequence, where each number indicates a weight that is at least as dark as its predecessor. The keyword
normal is synonymous with 400, and bold is synonymous with 700. Keywords other than normal and
bold have been shown to be often confused with font names and a numerical scale was therefore
chosen for the 9-value list.
The bolder and lighter values select font weights that are relative to the weight inherited from the
parent. It is computed as follows:
inherited value
Bolder
Lighter
100
400
100
200
400
100
300
400
100
400
700
100
500
700
100
600
900
400
700
900
400
800
900
700
900
900
700
41
Example:
body { font-weight: 600;}
p { font-weight: bolder } /* this is based on 600 and it changes to 900*/
42
none
disc
circle
square
decimal
decimal-leading-zero
lower-roman
upper-roman
lower-alpha
upper-alpha
Example:
ul{
list-style-position: inside;
list-style-type: lower-roman;
}
43
lower-greek
lower-latin
upper-latin
armenian
Georgian
Notice that the table in the example above has double borders. This is because both the table, th, and td
elements have separate borders.
Related properties which take the same value as border are:
border-left: [border-width || border-style || border-color ];
border-right: [border-width || border-style || border-color ];
border-top: [border-width || border-style || border-color ];
border-bottom: [border-width || border-style || border-color ];
Border Styles
The border style properties specify the line style of a boxs border (solid, double, dashed, etc.).
border-style: value;
The properties may take one of the following values:
none: no border.
hidden: same as none, but in the collapsing border model , also inhibits any other border.
dotted: the border is a series of dots.
dashed: the border is a series of short line segments.
solid: the border is a single line segment.
double: the border is two solid lines. The sum of the two lines and the space between them
equals the value of border-width.
groove: the border looks as though it were carved into the canvas.
ridge: the opposite of groove: the border looks as though it were coming out of the canvas.
inset: in the separated borders model , the border makes the entire box look as though it were
embedded in the canvas. In the collapsing border model, drawn the same as ridge.
outset: in the separated borders model, the border makes the entire box look as though it were
coming out of the canvas. In the collapsing border model, drawn the same as groove.
Related properties which take the same value as border-style are:
border-top-style: value;
border-bottom-style: value;
border-left-style: value;
border-right-style: value;
Border Width
The border width properties specify the width of the border area.
border-width: value;
Value can be:
thin: a thin border.
medium: a medium border.
44
If there is only one component value, it applies to all sides. If there are two values, the top and bottom
borders are set to the first value and the right and left are set to the second. If there are three values,
the top is set to the first value, the left and right are set to the second, and the bottom is set to the
third. If there are four values, they apply to the top, right, bottom, and left, respectively.
Example (top, right, bottom, and left):
h1 { border-width: thin } /* thin thin thin thin */
h1 { border-width: thin thick } /* thin thick thin thick */
h1 { border-width: thin thick medium } /* thin thick medium thick */
45
Possible values:
collapse
separate
Example:
table{
border-collapse:collapse;
}
table, th, td{
border: 1px solid black;
}
Empty Cells
In the separated borders model, this property controls the rendering of borders and backgrounds
around cells that have no visible content. Empty cells and cells with the visibility property set to
hidden are considered to have no visible content.
empty-cells: value;
Possible values:
show
hide
Border Spacing
The lengths specify the distance that separates adjoining cell borders. If one length is specified, it gives
both the horizontal and vertical spacing. If two are specified, the first gives the horizontal spacing and
the second the vertical spacing.
border-spacing: length;
Table Width and Height
Width and height of a table is defined by the width and height properties. The example below sets the
width of the table to 100%, and the height of the th elements to 50px:
table{
width:100%; /*as wide as the screen*/
}
th{
height:50px;
}
Table Text Alignment
The text in a table is aligned with the text-align and vertical-align properties. The text-align property sets
the horizontal alignment, like left, right, or center:
46
td{
text-align:right;
}
Vertical Alignment
The vertical-align property of each table cell determines its alignment within the row. Each cells content
has a baseline, a top, a middle, and a bottom, as does the row itself. In the context of tables, values for
vertical-align have the following meanings:
baseline: The baseline of the cell is put at the same height as the baseline of the first of the rows
it spans.
top: The top of the cell box is aligned with the top of the first row it spans.
bottom: The bottom of the cell box is aligned with the bottom of the last row it spans.
middle: The center of the cell is aligned with the center of the rows it spans.
sub, super, text-top, text-bottom, <length>, <percentage>: These values do not apply to cells;
the cell is aligned at the baseline instead.
47
Table Padding
To control the space between the border and content in a table, use the padding property on td and th
elements:
td{
padding:15px;
}
Table Color
The color of the borders, and the text and background color of th elements can be specified:
table, td, th{
border:1px solid green;
}
th{
background-color:green;
color:white;
}
48
Normal link
a:visited
a:hover
a:active
49
font-weight: normal;
color: #003300;
}
a:visited {
text-decoration: underline;
font-weight: normal;
color: #999999;
}
2.7.2 CSS ID
IDs are similar to classes, except once a specific ID has been declared it cannot be used again within the
same (X)HTML file. The syntax of ID selectors is very similar to classes, but instead of a dot you must use
a hash sign (#).
The HTML content is:
<div id="container"> I was asleep, but my heart was awake. </div>
The CSS that formats the HTML content:
#container{
width: 80%;
padding: 20px;
margin: auto;
border: 1px solid blue;
background: red;
}
Practice 3.3
1. Write an external CSS that uses Class ID to format DIV element text to blue, font size 20, and
background to silver.
2. Write a CSS that changes visited links to yellow, and active links to green.
3. Write a CSS that creates lists that use small Roman numbers.
50
The box model allows us to place a border around elements and space elements in relation to other
elements. The image below illustrates the box model.
width
51
Values:
color name
hexadecimal number
Border Style
You can set the style of a border independently with the border-style property.
border-style: value;
Values:
dashed
dotted
double
groove
hidden
inset
none
outset
Thin
Or you can set the elements for each borders side individually
52
Medium
Thick
ridge
solid
Border Bottom
You can set the color, style and width of the bottom border around an element in one declaration with
the border-bottom property.
border-bottom: 1px solid #333333;
Values:
color
style
Or you can set each value individually
width
width
53
border-left-width: value;
Border Right
You can set the color, style and width of the right border around an element in one declaration with the
border-right property.
border-right: 1px solid #333333;
Values:
color
style
Or you can set each value individually
width
Description
Values
Margin
margin-bottom
margin-left
margin-right
margin-top
54
margin-top
margin-right
margin-bottom
margin-left
auto
length
%
auto
length
%
auto
length
%
auto
length
%
padding-bottom
padding-left
padding-right
padding-top
Description
Values
A shorthand property for setting all
padding-top
the padding properties in one
padding-right
declaration
padding-bottom
padding-left
Sets the bottom padding of an
length
element
%
Sets the left padding of an element
length
%
Sets the right padding of an
length
element
%
Sets the top padding of an element length
%
Practice 3.4
1. Write a CSS that creates a <p> tag that has silver dotted borders around it.
2. Based on the above, change the top padding to 10, and 30 and see the effect.
55
56
Now is a good time to instill an aspect of JavaScript that will be important to you throughout all your
scripting ventures: JavaScript is case-sensitive. Hence, you must enter any item in your script that uses a
JavaScript word with the correct uppercase and lowercase letters. Your HTML tags (including the
<SCRIPT> tag) can be in the case of your choice, but everything in JavaScript is case-sensitive. When a
line of JavaScript doesnt work, one of the things you have to do is look for the wrong case first.
<SCRIPT LANGUAGE=JavaScript>
//your script here
</SCRIPT>
Here are some tips to remember when writing JavaScript commands:
JavaScript code is case sensitive (e.g. age and Age are different variables)
White space between words and tabs are ignored
Line breaks are ignored except within a statement
JavaScript statements end with a semi colon (;)
Adding JavaScript
There are three ways to add JavaScript commands to your Web Pages.
Embedding code
Inline code
External file
External File
You can use the SRC attribute of the <SCRIPT> tag to call JavaScript code from an external text file. This
is useful if you have a lot of code or you want to run it from several pages, because any number of pages
can call the same external JavaScript file. The text file itself contains no HTML tags. It is called by the
following tag:
<SCRIPT language = "JavaScript" SRC = "filename">
</SCRIPT>
If you want to run the same JavaScript on several pages, without having to write the same script on
every page, you can write a JavaScript in an external file. Save the external JavaScript file with a .js file
extension. The external script cannot contain the <script></script> tags! To use the external script, point
to the .js file in the "src" attribute of the <script> tag.
Where to Put the JavaScript
JavaScripts in a page will be executed immediately while the page loads into the browser. This is not
always what we want. Sometimes we want to execute a script when a page loads, or at a later event,
such as when a user clicks a button. When this is the case we put the script inside a function (you will
learn about functions in a later chapter).
57
Scripts in <head>
Scripts to be executed when they are called, or when an event is triggered, are placed in functions. Put
your functions in the head section, this way they are all in one place, and they do not interfere with page
content.
<html>
<head>
<script language="javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>
<body onload="message()">
</body>
</html>
Scripts in <body>
If you don't want your script to be placed inside a function, or if your script should write page content, it
should be placed in the body section.
<html>
<head> </head>
<body>
<script language="javascript">
document.write("This message is written by JavaScript");
</script>
</body>
</html>
58
documents.write method writes a string to the web page. Anything between double quotes will be
displayed as it is in the web page. However, if there is something out of quotes, it is evaluated as
expression and the result will be sent to the web page.
The alert method is produces a browser alert box. These are incredibly useful for debugging and learning
the language. However, they are not good way to communicate with the users. alert() displays a modal
window that presents a message to the user with a single Ok button to dismiss the dialog box.
The prompt display includes a message, field for user query, and two buttons (Ok, and Cancel). The
prompt() returns string of text entered by user. It takes two parameters: a message providing the
prompt for the response, and a default string which is used to fill in the text field.
A confirm dialog box presents a message in a modal dialog box along with Ok and Cancel buttons. Such
dialog boxes can be used to ask a question of the user, usually prior to performing actions that will not
be undoable. The dialog box returns a Boolean value of Ok=true, and Cancel=false;
Example:
var adult = confirm(Are you sure you are older than 18 years?)
if(adult)
alert(Yes);
else
alert(No);
Example
Description
String
John
Number
4.5
Boolean
True
Null
Null
59
Object
60
61
Practice 4.1
1. Write in body a JavaScript code that declares a variable called name and assigns a value
William to it.
2. Then display the content of the variable.
Perform Subtraction
Multiply numbers
Divide numbers
++
Increment
--
Decrement
X=7
X = y-2
X=3
X = y*2
X=10
X = y/2
X=2.5
X = y%2
X=1
62
X = ++y
X=6
X = --y
X=4
assignment operator
+=
-=
*=
/=
%=
x=5
x+=y
x=x+y
x=15
x-=y
x=x-y
x=5
x*=y
x=x*y
x=50
x/=y
x=x/y
x=2
x%=y
x=x%y
x=0
Equals
===
63
!=
Not equal to
>
Greater than
>=
<
Less than
<=
And
||
Or
Not
true
(x==5 || y==5)
false
!(x==y)
true
Individual operators
member
. []
() new
negation/increment
multiply/divide
* / %
addition/subtraction
+-
bitwise shift
relational
equality
== != === !==
64
bitwise-and
&
bitwise-xor
bitwise-or
logical-and
&&
logical-or
||
Conditional
?:
assignment
comma
65
To use either of these conversion functions, pass the string value you wish to convert as a parameter to
the function.
parseInt(string [,radix])
parseFloat(string [,radix])
radix, which is optional, specifies the base of the number to convert to: hexadecimal, octal, or decimal, ..
For example, look at the results of two different string values when passed through the parseInt()
function:
parseInt(42) // result = 42
parseInt(42.33) // result = 42
Even though the second expression passes the string version of a floating-point number to the function,
the value returned by the function is an integer. No rounding of the value occurs here. The decimal and
everything to its right are simply stripped off.
The parseFloat() function returns an integer if it can; otherwise, it returns a floating-point number as
follows:
parseFloat(42) // result = 42
parseFloat(42.33) // result = 42.33
Converting numbers to strings
Youll have less need for converting a number to its string equivalent than the other way around.
JavaScript gravitates toward strings when faced with an expression containing mixed data types. The
simplest way to convert a number to a string is by adding an empty string to a number:
( + 2500) // result = 2500
( + 2500).length // result = 4
A more elegant way is to use the toString() method. For example, to convert the dollars variable value to
a string, use this statement:
Var dollars = 2500;
dollars.toString() // result = 2500
You can specify a number base for the string representation of the number. Called the radix, the base
number is added as a parameter to the method name. Here is an example of creating a
numeric value for conversion to its hexadecimal equivalent as a string:
var x = 30
var y = x.toString(16) // result = 1e
Practice 4.2
1. Write a JavaScript code that calculates 850*230
2. Write a JavaScript code that return the remainder of dividing 43 by 30
66
if . . . else Condition
Not all program decisions are as simple as the one shown above. Rather than specifying one detour for a
given condition, you might want the program to follow one of many branches depending on that
condition. In the plain if construction, no special processing is performed when the condition evaluates
to false. But if processing must follow one of two special paths, you need the if...else construction. The
formal syntax definition for an if...else construction is as follows:
if (condition) {
statement(s) if true
}
[else if(condition){
statement(s) if true
}]
[else {
67
statement(s) if false
}]
[] indicates optional parts of the JavaScript code. Such statements can be left out of the script.
Example:
If(mark>80)
status=excellent;
else if(mark>60)
status=very good;
else if(mark>50)
Status = fair;
else
status =poor;
switch Statement
A switch statement allows a program to evaluate an expression and attempt to match the expression's
value to a case label. If a match is found, the program executes the associated statement. A switch
statement looks as follows:
switch (expression) {
case label1:
statements1
[break;]
case label2:
statements2
[break;]
...
default:
statementsdefault
[break;]
}
The program first looks for a case clause with a label matching the value of expression. If found, it then
transfers control to that clause, executing the associated statements. If no matching label is found, the
program looks for the optional default clause, and if found, transfers control to that clause, executing
the associated statements. If no default clause is found, the program continues execution at the
statement following the end of switch. By convention, the default clause is the last clause, but it does
not need to be so.
The optional break statement associated with each case clause ensures that the program breaks out of
switch once the matched statement is executed and continues execution at the statement following
68
switch. If break is omitted, the program continues execution at the next statement in the switch
statement.
Example:
switch (fruittype) {
case "Apples":
document.write("Apples are $0.32 a pound.<br>");
break;
case "Bananas":
document.write("Bananas are $0.48 a pound.<br>");
break;
case "Mangoes":
case "Papayas":
document.write("Mangoes and papayas are $2.79 a pound.<br>");
break;
default:
document.write("Sorry, we are out of " + fruittype + ".<br>");
}
Practice 4.3
1. Write a program that checks if student mark is not less than 0 and not greater than 100.
2. Write a program that gives letter grades using student mark. Use the following scale:
A >85
B >75
C > 50
D >40
69
maintains a table of those links. You access them by number (with 0 being the first link) in the array
syntax as in document.links[0], which represents the first link in the document.
To initialize an array for your script, use the new keyword to construct the object for you while assigning
the array object to a variable of your choice:
var myArray = new makeArray(n)
where n is the number of entries you anticipate for the array. This initialization does not make any array
entries or create any placeholders. Such preconditioning of arrays is not necessary in JavaScript.
Example: an array that stores the names of planets
planet = new Array(9); //an array with 9 entries
planet[0] = Mercury
planet[1] = Venus
planet[2] = Earth
planet[3] = Mars
planet[4] = Jupiter
planet[5] = Saturn
planet[6] = Uranus
planet[7] = Neptune
planet[8] = Pluto
You can also create array by directly giving the values:
planet= new Array(Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune,
Pluto);
Access an Array
You can refer to a particular element in an array by referring to the name of the array and the index
number. The index number starts at 0 and end at n-1 for array of n entries. For example, to access the
fifth planet in the planets array, we use:
planet[4]; //Jupiter
Deleting Array Entries
You can always set the value of an array entry to null or an empty string to wipe out any data that used
to occupy that space. But with the delete operator, you could not completely remove the element.
Deleting an array element eliminates the index from the list of accessible index values but does not
reduce the arrays length, as in the following sequence of statements:
planet.length; // result: 9
delete planet[2];
planet.length; //result: 9
document.write(planet[2]); //result: undefined
Array Object Methods
70
array.concat(array2)
The array.concat() method allows you to join two array objects into a new, third array object. The action
of concatenating the arrays does not alter the contents or behavior of the two original arrays.
For example:
var array1 = new Array(1,2,3)
var array2 = new Array(a,b,c)
var array3 = array1.concat(array2)
// result: array with values 1,2,3,a,b,c
If an array element is a string or number value (not a string or number object), the values are copied
from the original arrays into the new one. All connection with the original arrays ceases for those items.
array.sort([compareFunction])
This methods returns array of entries in the order as determined by the compareFunction algorithm.
Look first at the kind of sorting you can do with the array.sort() method by itself. When no parameter is
specified, JavaScript takes a snapshot of the contents of the array and converts items to strings. From
there, it performs a string sort of the values. ASCII values of characters govern the sort, which means
that numbers are sorted by their string values, not their numeric values. This fact has strong implications
if your array consists of numeric data: The value 201 sorts before 88, because the sorting mechanism
compares the first characters of the strings (2 versus 8) to determine the sort order. For simple
alphabetical sorting of string values in arrays, the plain array.sort() method does the trick.
Fortunately, additional intelligence is available that you can add to array sorting. The key tactic is to
define a function that helps the sort() method compare items in the array. A comparison function is
passed two values from the array (what you dont see is that the array.sort() method rapidly sends
numerous pairs of values from the array to help it sort through all entries). The comparison function lets
the sort() method know which of the two items comes before the other, based on the value the function
returns. Assuming that the function compares two values, a and b, the returned value reveals
information to the sort() method:
Return Value Range
Meaning
<0
>0
71
Returns true if every element in this array satisfies the provided testing function.
filter()
Creates a new array with all of the elements of this array for which the provided
filtering function returns true.
forEach()
indexOf(value)
Returns the first (least) index of an element within the array equal to the
specified value, or -1 if none is found.
Joins all elements of an array into a string using separator
join(separator)
lastIndexOf(value)
Returns the last (greatest) index of an element within the array equal to the
specified value, or -1 if none is found.
pop()
Removes the last element from an array and returns that element.
push(value)
Adds one or more elements to the end of an array and returns the new length of
the array.
reverse()
shift()
Reverses the order of the elements of an array the first becomes the last, and
the last becomes the first.
Removes the first element from an array and returns that element.
slice(start [,end])
splice(start, count)
toString()
unshift(value)
Adds one or more elements to the front of an array and returns the new length
of the array.
Table 4.11 array object methods
Example: some array functions
<html>
<head>
72
<title>javascript test</title>
<script language="JavaScript">
function arrayFunction() {
var grade = new Array("70", "60", "80", "90", "20");
document.write("<br> Popped: " + grade.pop());
document.write("<br> After poping:");
for(var i=0;i<grade.length; i++)
document.write(" " + grade[i]);
grade.reverse();
document.write("<br>Reversed: ");
for(var i=0;i<grade.length; i++)
document.write(" " + grade[i]);
document.write("<br>Search 80: " + grade.indexOf("80"));
document.write("<br>Converted to string: " + grade.toString());
document.write("<br>Sliced: " + grade.slice(2));
document.write("<br>Spliced: " + grade.splice(1));
}
</script>
</head>
<body onLoad="arrayFunction();">
</body>
</html>
73
74
while Statement
A while statement executes its statements as long as a specified condition evaluates to true. A while
statement looks as follows:
while (condition){
statement
}
The condition test occurs before statement in the loop are executed. If the condition returns true,
statement is executed and the condition is tested again. If the condition returns false, execution stops
and control is passed to the statement following while.
Example 1: the following while loop iterates as long as n is less than three:
n = 0;
x = 0;
while (n < 3)
{
n++;
x += n;
}
break and continue statements
Use the break statement to terminate a loop, switch, or label statement. It is used to stop the loop when
the condition we need is fulfilled.
Example: the following example loops until the value of loop counter is 5:
for (i = 0; i < 100; i++) {
if (i== 5)
break;
}
The continue statement can be used to restart a while, do-while, for, or label statement. When you use
continue, it terminates the current iteration and continues execution of the loop with the next iteration.
In contrast to the break statement, continue does not terminate the execution of the loop entirely. In a
while loop, it jumps back to the condition check, and in a for loop, it jumps to the increment-expression.
Example: a program that adds numbers between 0 and 100 with the exception of 60, 70, and 80
var counter = 100;
var sum = 0;
for (var i = 0; i <= counter; i++)
{
if(i==60 || i==70 || i==80)
continue;
75
sum = sum + i;
}
document.write(the sum is + sum);
Practice 4.4
1. Write a program that accepts marks of 20 students.
2. Write a program that adds numbers between 1 and 100(1+2+3+..+99+100).
3. Write a program that displays all even numbers between 50 and 100
76
way of a function call. If no parameters occur in the function definition, both the function definition and
call to the function have only empty sets of parentheses.
When a function receives parameters, it assigns the incoming values to the variable names specified in
the function definitions parentheses. Consider the following script segment:
function sayHiToFirst(first, second, third) {
alert(Say hello, + first)
}
sayHiToFirst(Gracie, George, Harry)
sayHiToFirst(Larry, Moe, Curly)
After the function is defined in the script, the next statement calls that very function, passing three
strings as parameters. The function definition automatically assigns the strings to variables first, second,
and third. Therefore, before the alert() statement inside the function ever runs, first evaluates to
Gracie, second evaluates to George, and third evaluates to Harry. In the alert() statement, only the
first value is used and the alert reads
Say hello, Gracie
When the user closes the first alert, the next call to the function occurs. This time through, different
values are passed to the function and assigned to first, second, and third. The alert dialog box reads
Say hello, Larry
Unlike other variables that you define in your script, function parameters do not use the var keyword to
initialize them. They are automatically initialized whenever the function is called.
The return Statement
The return statement is used to specify the value that is returned from the function. So, functions that
are going to return a value must use the return statement. The example below returns the product of
two numbers (a and b):
<html>
<head>
<script type="text/javascript">
function product(op1, op2){
return op1*op2;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>
</body>
77
</html>
Practice 4.5
1. Write a function that that accepts two numbers and displays their sum, difference, product,
quotient, and modulus.
2. Write a JavaScript program accepts five numbers and return their average.
Value
Description
Math.E
2.718281828459045091
Eulers constant
Math.LN2
0.6931471805599452862
Natural log of 2
Math.LN10
2.302585092994045901
Natural log of 10
Math.LOG2E
1.442695040888963387
Log base-2 of E
Math.LOG10E
0.4342944819032518167
Log base-10 of E
Math.PI
3.141592653589793116
Math.SQRT1_2
0.7071067811865475727
Math.SQRT2
1.414213562373095145
Square root of 2
78
79
Practice 4.6
1. Write a program that calculates quadratic equation.
2. Write a program that calculates 1030
3. Write a program that returns the largest and smallest numbers from the given number list.
80
Value Range
Description
dateObj.getTime()
0-...
dateObj.getYear()
70-...
dateObj.getFullYear()
1970-...
dateObj.getMonth()
0-11
dateObj.getDate()
1-31
dateObj.getDay()
0-6
dateObj.getHours()
0-23
dateObj.getMinutes()
0-59
dateObj.getSeconds()
0-59
dateObj.setTime(val)
0-...
dateObj.setYear(val)
70-...
dateObj.setMonth(val)
0-11
dateObj.setDate(val)
1-31
dateObj.setDay(val)
0-6
dateObj.setHours(val)
0-23
dateObj.setMinutes(val)
0-59
dateObj.setSeconds(val)
0-59
81
Description
charAt(index)
charCodeAt(index)
concat(string)
indexOf(string, [start])
lastIndexOf(string,[start])
Returns the index within the calling String object of the first occurrence of
the specified value, or -1 if not found.
Returns the index within the calling String object of the last occurrence of
the specified value, or -1 if not found.
localeCompare(string2)
length()
match(regExpression)
replace(regExpression,replacer) Used to find a match between a regular expression and a string, and to
replace the matched substring with a new substring.
search(regExpression)
Executes the search for a match between a regular expression and a
specified string.
slice(startIndex [,end])
Extracts a section of a string and returns a new string.
82
split(delimiter [,limit])
substr(start [, length])
substring(start, end)
toLocaleLowerCase()
Splits a String object into an array of strings by separating the string into
substrings.
Returns the characters in a string beginning at the specified location
through the specified number of characters.
Returns the characters in a string between the two indexes into a string.
toLowerCase()
toString()
toUpperCase()
toLocaleUpperCase()
83
bgColor - Background color, expressed as a hexadecimal RGB value compatible with HTML
syntax (for example, #FFFFF" for white). Equivalent to the BGCOLOR attribute of the <BODY>
tag.
fgColor - Foreground (text) color, expressed as a hexadecimal RGB value compatible with HTM
syntax. Equivalent to the TEXT attribute of the <BODY> tag.
linkColor - Hyperlink color, expressed as a hexadecimal RGB value compatible with HTML syntax.
Equivalent to the vlinkColor Visited hyperlink color, expressed as a hexadecimal RGB value
compatible with HTML syntax. Equivalent to the VLINK attribute of the <BODY> tag.
alinkColor - Activated (after button press, before button release) hyperlink color, expressed as a
hexadecimal RGB value compatible with HTML syntax. Equivalent to the ALINK attribute of the
<BODY> tag.
forms[ ] - Array of form objects in the document, in the order specified in the source. Each form
has its own form object.
forms.length - The number of form objects within the document.
links[ ] - Array objects corresponding to all HREF links in the document, in the order specified in
the source.
links.length - The number of HREF links in the document.
anchors[ ] - Array of all "named" anchors (between the <A NAME=""> and </A> tags) within the
document, in the order specified in the source.
anchors.length - The number of named anchors in the document.
images[] - Image objects that correspond to each image on the page.
applets[] - Java applet objects that correspond to each applet on the page.
embeds[] - Plugins object that represent each plug-in on the page.
Methods:
write("string")-Writes string to the current window. string may include HTML tags.
writeln("string") - Performs the same as write(), but adds a carriage return. This affects only
preformatted text (inside a <PRE> or <XMP> tag).
clear( ) - Clears the window.
close( ) - Closes the window.
84
Methods
Current
back()
Length
forward()
Next
go()
Previous
Table 4.15 History object properties and methods
history.back() goes back to last visited page
history.forward() goes forward just like clicking forward button on toolbar
history.go(location) goes to the specified history location
Methods
toExponential()
MIN_VALUE
toFixed()
NaN
toLocaleString()
NEGATIVE_INFINITY
toString()
POSITIVE_INFINITY
toPrecision()
valueOf()
There are three Number object methods that let scripts control the formatting of numbers for display as
string text. Each method has a unique purpose, but they all return strings. You should perform all math
operations as unformatted number objects because the values have the most precision. Only after you
are ready to display the results should you use one of these methods to convert the number to a string
for display as body text or assignment to a text field.
85
The toExponential() method forces a number to display in exponential notation. The parameter is an
integer specifying how many digits to the right of the decimal should be returned. For example, if a
variable contains the numeric value 345, applying toExponential(3) to that value yields 3.450e+2, which
is JavaScripts exponential notation for 3.45 102.
Use the toFixed() method when you want to format a number with a specific number of digits to the
right of the decimal. This is the method you use, for instance, to display the results of a financial
calculation in units and hundredths of units (for example, dollars and cents). If the number being
formatted has more numbers to the right of the decimal, the method rounds the rightmost visible digit.
For example, the value 123.455 fixed to two digits to the right of the decimal is rounded up to 123.46.
But if the starting value is 123.4549, the method ignores the 9 and sees that the 4 to the right of the 5
should be rounded down; therefore, the result is 123.45.
The final method is toPrecision(), which enables you to define how many total digits (including digits to
the left and right of the decimal) to display of a number. In other words, you define the precision of a
number. The following list demonstrates the results of several parameter values signifying a variety of
precisions:
var num = 123.45
num.toPrecision(1) // result = 1e+2
num.toPrecision(2) // result = 1.2e+2
num.toPrecision(3) // result = 123
num.toPrecision(4) // result = 123.5
num.toPrecision(5) // result = 123.45
num.toPrecision(6) // result = 123.450
86
Method
Description
window.alert(message)
window.back()
window.blur()
window.captureEvents((Event.eventType)
window.clearInterval(intervalID)
window.clearTimeout(timeoutID)
window.close()
window.confirm(message)
window.dump(message)
window.escape(text)
Encodes a string.
window.focus()
window.forward()
window.GetAttention()
window.getSelection()
window.home()
window.moveBy(pixelX, pixelY)
window.moveTo(x, y)
window.open(URL,name[,features])
window.print()
window.prompt(message[,default])
window.releaseEvents(Event.eventType)
window.resizeBy(pixelX, pixelY)
window.resizeTo(iWidth, iHeight)
window.scroll(x-coord, y-coord)
window.scrollBy(pixelX, pixelY)
window.scrollByLines(lines)
87
window.scrollTo(x-coord, y-coord)
window.setCursor(cursortype)
window.setInterval(funcName, delay)
window.setTimeout(funcName, delay)
window.scrollByPages(pages)
Practice 4.7
1. Write a program that counts how many letters are there in your full name.
2. Write a program that has two buttons where one of the button acts like the back button in
toolbar and the other acts like forward button in toolbar.
3. Write a program that returns array of images and links in your web page.
Event Handler
Description
Load
onLoad
Unload
onUnload
Mouseover
onMouseOver
Mouseout
onMouseOut
88
MouseDown
onMouseDown
MouseMove
onMouseMove
MouseUp
onMouseUp
Select
onSelect
Click
onClick
Focus
onFocus
Blur
onBlur
Change
onChange
Submit
onSubmit
Reset
onReset
Abort
onAbort
Change
onChange
DblClick
onDblClick
Error
onError
Keydown
onKeyDown
KeyPress
onKeyPress
KeyUP
onKeyUp
89
90
Text area has the same property as text field: the value property. Using this property, you can set or
read the content of text area.
Example:
<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function hello ()
{
var urname = document.test.name.value;
alert ("Hello, " + urname);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="test" ACTION="" METHOD="GET">
Enter your name: <INPUT TYPE="text" NAME="name" VALUE=""><br>
<INPUT TYPE="button" NAME="button" Value="Say Hello" onClick="hello()">
</FORM>
</BODY>
</HTML>
Checkboxes and Radio Buttons
To define radio buttons for JavaScript, provide each object with the same name. JavaScript will create an
array using the name you've provided; you then reference the buttons using the array indexes. The first
button in the series is numbered 0, the second is numbered 1, and so forth. Use the checked property to
know the state of the individual radio buttons.
<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function hello () {
var urname = document.test.name.value;
var sex;
if(document.test.sex[0].checked)
sex="male";
else if(document.test.sex[1].checked)
sex="female";
alert ("Hello, " + urname + "! Your are "+sex);
}
91
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="test" ACTION="" METHOD="GET">
Enter your name: <INPUT TYPE="text" NAME="name" VALUE=""><br>
Sex: <INPUT TYPE="radio" NAME="sex" Value="Male">Male<BR>
<INPUT TYPE="radio" NAME="sex" Value="Female">Female<BR>
<INPUT TYPE="button" NAME="button" Value="Say Hello" onClick="hello()">
</FORM>
</BODY>
</HTML>
Check boxes are stand-alone elements which means they don't interact with neighboring elements like
radio buttons do. Using JavaScript you can test if a check box is checked using the checked property.
Likewise, you can set the checked property to add or remove the checkmark from a check box.
Using Selection Lists
List boxes let you pick the item you want out of a multiple-choice box. Use the selectedIndex property to
test which option item is selected in the list. The item is returned as an index value, with 0 being the first
option, 1 being the second, and so forth. If no item is selected, the value is -1.
<HTML>
<HEAD>
<TITLE>List Box Test</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testSelect () {
Item = document.sele.list.selectedIndex;
Result = document.sele.list.options[Item].text;
alert (Result);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="sele" ACTION="" METHOD="GET">
Fruit: <SELECT NAME="list" SIZE="1">
<OPTION>none</OPTION>
<OPTION>Orange</OPTION>
<OPTION>Apple</OPTION>
<OPTION>Papaya</OPTION>
<OPTION>Banana</OPTION>
</SELECT>
<INPUT TYPE="button" NAME="button" Value="Test" onClick="testSelect()">
92
</FORM>
</BODY>
</HTML>
93
94
else
alert("Message ok");
}
</script>
</head>
<body>
<h2> <u> Form validation </u> </h2>
<form name="first">
Enter your name: <input type="text" name="urname"> <br>
Enter your age: <input type="text" name="age"> <br>
Enter your e-mail address: <input type="text" name="email"> <br>
write message: <textarea name="urmessage" cols=40 rows=10></textarea><br><br>
<input type="button" name="validate" value="Check Input" onClick="check(this.form)">
</body>
</html>
Practice 4.8
1. Write a program that uses forms to accept two numbers and calculates their average when a
button is clicked.
2. Can you create a simple JavaScript calculator?
95
96
The <html> node has two child nodes; <head> and <body>
97
The <head> node has one child node; the <title> node
The <title> node also has one child node; the text node "DOM Tutorial"
The <h1> and <p> nodes are siblings, and both child nodes of <body>
The DOM Lesson one is the child of <h1> node and Hello world is the child node of <p>
node
98
99
100
The firstChild property can also be used to access the text of an element:
Example
<html>
<body>
<p id="intro">Hello World!</p>
<script type="text/javascript">
x=document.getElementById("intro");
document.write(x.firstChild.nodeValue);
</script>
</body>
</html>
Practice 5.1
1. Can you write a DOM program that can change the content of the given <p> tag?
2. Write a DOM program that returns the title of the document
3. Write a program that adds a <p> child to HTML <body>.
101
2. Dynamic HTML(DHTML)
2.1 Introduction to DHTML
DHTML stands for Dynamic HTML. DHTML is not a language or a web standard. To most people DHTML
means the combination of HTML, JavaScript, DOM and CSS. It is the art of combining HTML, JavaScript,
DOM, and CSS.
According to the World Wide Web Consortium (W3C):
Dynamic HTML is a term used by some vendors to describe the combination of HTML, style sheets and
scripts that allows documents to be animated.
DHTML is not a scripting language like JavaScript. It is a feature that allows your browser to be dynamic.
Also, DHTML is not one particular, technology or set of features. It includes several technologies and
describes how these technologies interact.
Web pages built with Dynamic HTML are richer and more interactive, react faster, and dont use much
bandwidth. The major elements of DHTML include HTML code, scripting languages such as JavaScript,
the Document Object Model, Cascading Style Sheets, multimedia filters, and the browser itself.
102
103
</script>
</body>
</html>
Example: The following example changes the src attibute of an img element:
<html>
<body>
<img id="image" src="smiley.gif">
<script type="text/javascript">
document.getElementById("image").src="landscape.jpg";
</script>
</body>
</html>
marginBottom
marginLeft
paddings()
paddingTop
paddingRight
paddingBottom
paddingLeft
color
backgroundColor
backgroundImage
borderStyle
borderColor
104
borderWidths
borderTopWidth
borderRightWidth
borderBottomWidth
borderLeftWidth
width
align
clear
display
listStyleType
whiteSpace
Practice 5.2
1. Create a link that changes its color to green when a mouse is over it.
2. Create a simple remark message using DIV that changes its font size when a mouse is over it.
105
Main Use
Example Effects
Overlapping, different
colored/sized fonts
Layers, exact positioning
Link that changes color on
mouseover
Mortgage calculator
Moving logo
Crossword puzzle
Short cartoon
Client-side scripting
(JavaScript, VBScript)
Java applets
Flash animations film
106
presentations, scrolling headlines, pages that update themselves automatically, or elements that appear
and disappear.
On server side, the term generally denotes content assembled on the fly, at the time the page is
requested. If you display the current date and time on a page, for example, the content will change from
one occasion to another and thus will be dynamic. In contrast to a static website, a dynamic website is
one whose content is regenerated every time a user visits or reloads the site.
Server-side Web scripting is mostly about connecting Web sites to back end servers, such as databases.
This enables the following types of two-way communication:
Server to client: Web pages can be assembled from back end-server output.
Client to server: Customer-entered information can be acted upon.
Common examples of client-to-server interaction are online forms with some drop-down lists (usually
the ones that require you to click a button) that the script assembles dynamically on the server.
What is CGI?
The Common Gateway Interface (CGI) is a method used by web servers to run external programs
(known as CGI scripts), most often to generate web content dynamically. Whenever a web page queries
a database, or a user submits a form, a CGI script is usually called upon to do the work.
A plain HTML document that the Web daemon retrieves is static, which means it exists in a constant
state: a text file that doesn't change. A CGI program, on the other hand, is executed in real-time, so that
it can output dynamic information.
CGI is simply a specification, which defines a standard way for web servers to run CGI scripts and for
those programs to send their results back to the server. The job of the CGI script is to read information
that the browser has sent (via the server) and to generate some form of valid response usually (but not
always) visible content. Once it has completed its task, the CGI script finishes and exits.
CGI is not a language. It is a simple protocol that can be used to communicate between Web forms and
your program. A CGI program can be written in any programming language: C/C++, Python, Perl, Visual
Basic, etc. Perl is a very popular language for CGI scripting because of its unrivalled text-handling
107
Web server starts up the handling program. This is heavy weight process creation.
Web server feeds request parameters to handler. This happens through stdin or environment
variables
108
The date the information becomes invalid. This should be used by the
browser to decide when a page needs to be refreshed. A valid date string
should be in the format 01 Jan 1998 12:00:00 GMT.
Location: URL
The URL that should be returned instead of the URL requested. You can use
this field to redirect a request to any file.
Last-modified: Date
Content-length: N
The length, in bytes, of the data being returned. The browser uses this value
to report the estimated download time for a file.
Set-Cookie: String
Fig interaction between HTTP server and CGI program via environment variables
The environment variables are shown in the table below:
Environment variable Description
AUTH_TYPE
The authentication method used to validate a user.
CONTENT_LENGTH
The length of the data (in bytes or the number of characters) passed
109
CONTENT_TYPE
DOCUMENT_ROOT
GATEWAY_INTERFACE The revision of the Common Gateway Interface that the server uses.
HTTP_ACCEPT
A list of the MIME types that the client can accept.
HTTP_COOKIE
The visitors cookie, if one is set
HTTP_FROM
HTTP_REFERER
HTTP_USER_AGENT
HTTPS
PATH
PATH_INFO
PATH_TRANSLATED
QUERY_STRING
REMOTE_ADDR
REMOTE_HOST
REMOTE_IDENT
REMOTE_USER
REQUEST_METHOD
REQUEST_URI
SCRIPT_FILENAME
SCRIPT_NAME
SERVER_NAME
SERVER_PORT
SERVER_PROTOCOL
SERVER_SOFTWARE
The email address of the user making the request. Most browsers do
not support this variable.
The URL of the document that the client points to before accessing
the CGI program.
The browser the client is using to issue the request.
on if the program is being called through a secure server
The system path your server is running under
Extra path information passed to a CGI program.
The translated version of the path given by the variable PATH_INFO.
The query information passed to the program. It is appended to the
URL with a "?".
The remote IP address of the user making the request.
The remote hostname of the user making the request.
The user making the request. This variable will only be set if NCSA
IdentityCheck flag is enabled
The authenticated name of the user.
The method with which the information request was issued.
The interpreted pathname of the requested document or CGI
(relative to the document root)
The full pathname of the current CGI
The virtual path (e.g., /cgi-bin/program.pl) of the script being
executed.
The server's hostname or IP address.
The port number of the host on which the server is running.
The name and revision of the information protocol the request came
in with.
The name and version of the server software that is answering the
client request.
Table Environment variables
#include<stdio.h>
#include<stdlib.h>
#include <iostream.h>
const char* ENV[ 24 ] = {
"COMSPEC", "DOCUMENT_ROOT", "GATEWAY_INTERFACE", "HTTP_ACCEPT",
"HTTP_ACCEPT_ENCODING", "HTTP_ACCEPT_LANGUAGE", "HTTP_CONNECTION",
"HTTP_HOST", "HTTP_USER_AGENT", "PATH", "QUERY_STRING", "REMOTE_ADDR",
"REMOTE_PORT", "REQUEST_METHOD", "REQUEST_URI", "SCRIPT_FILENAME",
"SCRIPT_NAME", "SERVER_ADDR", "SERVER_ADMIN", "SERVER_NAME",
"SERVER_PORT", "SERVER_PROTOCOL", "SERVER_SIGNATURE","SERVER_SOFTWARE"
};
int main ()
{
cout << "Content-type:text/html\r\n\r\n";
cout << "<html>\n";
cout << "<head>\n";
cout << "<title>CGI Envrionment Variables</title>\n";
cout << "</head>\n";
cout << "<body>\n";
cout << "<table border = \"0\" cellspacing = \"2\">";
for ( int i = 0; i < 24; i++ )
{
cout << "<tr><td>" << ENV[ i ] << "</td><td>";
// attempt to retrieve value of environment variable
char *value = getenv( ENV[ i]);
if ( value != 0 )
cout << value;
else
cout << "Environment variable does not exist.";
cout << "</td></tr>\n";
}
cout << "</table><\n";
cout << "</body>\n";
cout << "</html>\n";
return 0;
}
111
Processing Forms
For forms that use METHOD="GET", the data is passed to the script or program in an environment
variable called QUERY_STRING.
It depends on the scripting or programming language used how a program can access the value of an
environment variable. In the C++ language, you would use the library function getenv (envvarname),
which is defined in the standard library stdlib, to access the value as a string. You might then use various
techniques to pick up data from the string, convert parts of it to numeric values, etc.
The output from the script or program to primary output stream (such as cout in the C++ language) is
handled in a special way. Effectively, it is directed so that it gets sent back to the browser. Thus, by
writing a C++ program that it writes an HTML document onto its standard output, you will make that
document appear on users screen as a response to the form submission.
GET vs POST
The difference between the GET and POST is how the information from the form is sent to the CGI
program, from the server. A GET will provide the user's input to the CGI program as an environment
variable called QUERY_STRING. The CGI program would read this environment variable using the C/C++
getenv() function and parse it to get the user's input.
A GET method will show the input data to the user in the URL area of the browser, showing a string like
www.check.com/cgi-bin/test.cgi?name=Tola&sex=male&age=25. The GET method is acceptable for
small amounts of data. It is also the default method when a CGI program is run via a link.
With GET method, there is a limit how large a URL can be before the server starts to have trouble
processing it. The maximum length of a URL, as decreed by HTTP standard, is 256 characters. However,
longer URL may still work, but servers are not obliged to accept them.
In POST, query string is encoded in the HTTP request body, not as part of the URL. As a result, they are
not limited in size. Unlike GET, POST allows arbitrarily long form data to be communicated. Arguments
usually do not appear in server logs. Example POST method is shown below.
POST / HTTP/1.1
Host: localhost:1888
User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.7.12)
Gecko/20051010 Firefox/1.0.7 (Ubuntu package 1.0.7)
Accept:
text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,
*/*; q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
112
Keep-Alive: 300
Connection: keep-alive
Referer: http://springer/~s133ar/cform1.html
Content-Type: application/x-www-form-urlencoded
Content-Length: 22
name=Tola&sex=male&age=25
Your CGI program should inspect the REQUEST_METHOD environment variable to determine if the form
was a GET or POST method, and take the appropriate action to retrieve the form. The CGI Program can
get the request method, Post or Get, using getenv() and environment variable REQUEST_METHOD. Here
is how this can be done in C/C++:
char *method;
method = getenv(REQUEST_METHOD);
if (method==NULL) /* error! */ {}
else if(if (strcmp(method,get)==0)) {}
else if (strcmp(method,post)==0) {}
Example GET handler:
int main()
{
char *method, *query;
method = getenv(REQUEST_METHOD);
if (method==NULL) /* error! */{}
else if(if (strcmp(method,get)==0))
query = getenv(QUERY_STRING);
Cout<<Content-type: text/html\r\n\r\n;
Cout<<<H1>Your query was <<query << </H1>\n;
return(0);
}
A POST will provide the user's input to the CGI program, as if it were type at the keyboard, using the
standard input device, or stdin. If POST is used, then an environment variable called CONTENT_LENGTH
indicates how much data is being sent. You can read this data into a buffer, by doing something like:
char *method, *query;
method = getenv(REQUEST_METHOD);
if(strcmp(method, post) == 0)
{
int len = atoi( getenv("INPUT_LENGTH") );
query = new char[len+1];
fread(query, 1, len, stdin );
}
Cout<<Content-type: text/html\r\n\r\n;
113
Data Parsing
Now we have the data passed from a form stored in a string variable and we want to use it. However,
the data is still in unusable form as it is URL encoded. If you have a form with two input fields, lets call
them name and email, declared as follows
< INPUT TYPE=text MAXLENGTH=30 NAME="name">
< INPUT TYPE=text MAXLENGTH=20 NAME="email">
Suppose the user types John David into name and he types david@host.domain into email. What will
then be read in by your program is
name=John+David&email=david%40host.domain
So as you can see, the data from the fields is not in a particularly usable form because it is in URL
encoded form. Hence, you have to do some further processing to get the data you need.
Data String Formatting
The string consists of the name of the input followed by the value that input takes.
The field name is separated from the data value by an "="
One set of field and data is separated from the next by an "&"
Spaces in the input data are replaced by "+"
Non letters and numbers are replaced by "%xx" where "xx" is the hex value corresponding to
that character.
First, each form element's name, specified by the NAME attribute, is equated with the value entered by
the user to create a key-value pair. For example, if the user entered "30" when asked for the age, the
key-value pair would be age=30. Each key-value pair is separated by the "&" character.
Second, since the variable names for the form element and the actual form data are standard text, it is
possible this text could consist of characters that will confuse browsers. To prevent possible errors, the
encoding scheme translates all special characters to their corresponding hexadecimal codes. These
special characters include control characters and certain alphanumeric symbols. For example, the string
"Thanks for the help!" would be converted to "Thanks+for+the+help%21". This process is repeated for
each key-value pair to create a query string.
URLs can only be sent over the Internet using the ASCII character-set. Since URLs often contain
characters outside the ASCII set, the URL has to be converted into a valid ASCII format. URL encoding
replaces non ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain
spaces. URL encoding normally replaces a space with a + sign.
URL encoding example:
114
Character
URL-encoding
Character
URL-encoding
%80
%A3
%A9
!
"
#
%21
%22
%23
%AE
%C0
%C1
%C2
$
%
&
'
%24
%25
%26
%27
%C3
%C4
%C5
(
)
%28
%29
For text and password fields, the user input will represent the value. If no information was entered, the
key-value pair will be sent anyway, with the value left blank (i.e., "name="). For radio buttons and
checkboxes, the VALUE attribute represents the value when the button element is checked. If no VALUE
is specified, the value defaults to "on." An unchecked checkbox will not be sent as a key-value pair; it will
be ignored.
The CGI program then has to "decode" this information in order to access the form data. The encoding
scheme is the same for both GET and POST.
Understanding the Decoding Process
In order to access the information contained within the form, a decoding must be applied to the data.
First, the program must determine how the data was passed by the client, get or post. If the value
indicates a GET request, either the query string or the extra path information must be obtained from the
environment variables. On the other hand, if it is a POST request, the number of bytes specified by the
CONTENT_LENGTH environment variable must be read from standard input.
The algorithm for decoding form data follows:
1. Determine request protocol (either GET or POST) by checking the REQUEST_METHOD
environment variable.
2. If the protocol is GET, read the query string from QUERY_STRING and/or the extra path
information from PATH_INFO.
3. If the protocol is POST, determine the size of the request using CONTENT_LENGTH and read that
amount of data from the standard input.
4. Split the query string on the "&" character, which separates key-value pairs (the format is
key=value&key=value...).
5. Decode the hexadecimal and "+" characters in each key-value pair.
6. Create a key-value table with the key as the index.
115
116
#include<iostream.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
char *method, *query;
char str[1000], temp[100];
int prevo = -1;
char sepr[100];
char* separate(char []);
char* GET(char *);
char*POST(char*);
void changeSpecialCharacters();
//gets the data submitted by the form
void getQuery()
{
method = getenv("REQUEST_METHOD");
for(int i = 0; i < strlen(method); i++)
method[i] = toupper(method[i]);
if(strcmp(method, "GET") == 0)
query = getenv("QUERY_STRING");
else if(strcmp(method,"POST") == 0)
{
int len = atoi(getenv("CONTENT_LENGTH"));
query = new char[len + 1];
fread(query, len, 1, stdin);
}
else
query = "unknown";
}
//removes URL encoding from form data
void changeSpecialCharacters()
{
int t = 0;
char hex[4], ch;
char digits[17];
strcpy(digits, "0123456789ABCDEF");
strcpy(temp, "\0");
for(int i = 0; i < strlen(query); i++)
{
if(query[i] == '+')
temp[t++] = ' ';
else if(query[i] == '%')
{
hex[0] = query[++i];
hex[1] = query[++i];
117
hex[2] = '\0';
for(int j = 0; j < strlen(digits); j++)
{
if(hex[0] == digits[j])
{
ch = 16 * j;
break;
}
}
for(int j = 0; j < strlen(digits); j++)
{
if(hex[1] == digits[j])
{
ch = ch + j;
break;
}
}
temp[t++] = ch;
}
else
temp[t++] = query[i];
}
temp[t] = '\0';
query = (char*)temp;
cout<<"\n<br>Decoded URL: "<<query;
}
//returns the data entered in the given input name submitted using post method
char* POST(char *name)
{
return (GET(name));
}
//returns the data entered in the given input name submitted using get method
char* GET(char *name)
{
char *value;
int eq = -1;
strcpy(str, "\0");
prevo = -1;
for(int i = 0; i < strlen(query); i++)
{
strcpy(str, "\0");
if(query[i] == '&')
{
for(int j = (prevo + 1), t = 0; j < i; j++, t++)
{
str[t] = query[j];
str[t+1] = '\0';
}
118
119
changeSpecialCharacters();
if (method == NULL)
{
cout<<"<p>No posting method identified.</p>";
return 0;
}
cout<<"\n<br> First name: "<<GET("first_name");
cout<<"\n<br> Last name: "<<GET("last_name");
cout<<"\n<br> Password: "<<GET("password");
return 0;
}
HTML form for above CGI:
<html>
<head>
<title>CGI Test</title>
<script language="JavaScript">
function validate()
{
if(inp.first_name.value=="") {
alert("First name is empty");
return false;
}
if(inp.last_name.value=="") {
alert("Last name is empty");
return false;
}
if(inp.password.value=="") {
alert("Password name is empty");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="inp" method="get" action="/cgi-bin/Test.cgi" onSubmit="return validate();">
<span class="style1"><strong>Registration Form</strong></span>
<br /> <br />
First name: <input type="text" name="first_name" />
<br /> <br />
Last name: <input type="text" name="last_name" />
120
Security
Since a CGI program is executable, it is basically the equivalent of letting the world run a program on
your system, which isn't safe at all it creates security risk. Therefore, there are some security
precautions that need to be taken when it comes to using CGI programs. The first one is the fact that CGI
programs need to reside in a special directory, so that the Web server knows to execute the program
rather than just display it to the browser. This directory is usually under direct control of the webmaster,
prohibiting the average user from creating CGI programs.
The other is, when dealing with forms, it is extremely critical to check the data. A malicious user can
embed shell metacharacters characters that have special meaning to the shell in the form data. This
could cause big problem to your system. For example, here is a form that asks for user name:
<FORM action="/cgi-bin/finger.cgi" method="POST">
<input type="text" name="user" size=40>
<input type="submit" value="Get Information">
</form>
#include<dos.h>
int main()
{
system(mkdir <<get(user));
return 0;
}
What would happen if the user enters danger; del *
121
122
Sybase
PHP supports other databases as well, such as filePro, FrontBase, and InterBase. In addition, PHP
supports ODBC (Open Database Connectivity), a standard that allows you to communicate with even
more databases, such as Access and IBM DB2.
PHP works well for a database-driven Web site. PHP scripts in the Web site can store data in and
retrieve data from any supported database. PHP also can interact with supported databases outside a
Web environment. Database use is one of PHPs best features.
Software Requirements
To work with PHP and to try the example codes given in this unit, you need to install a web server, PHP,
and database server. There are many web servers to choose from; the most commonly used web server
is called Apache which you can download from the internet freely. Similarly, for database, there are
many options to use; the most popular database server for web pages is MySQL which again you can
download freely from internet. PHP is also available freely on the internet.
You can download each of the above three software independently and integrate them by configuring
Apache and PHP to get them work together. However, this is difficult most of the times for
inexperienced web developers. To solve this, software producers integrate the three software and offer
them as bundle. One such bundle that contains Apache, PHP, and MySQL is Vertrigo. Vertrigo is a free
software that you can download from internet and install on your computer. Once you install Vertrigo,
you have all the necessary things to write server side scripting with PHP.
For the apache code to execute properly, it should be saved in your web directory. Your web directory
depends on what web server you use. For example, on my machine which runs vertrigo web server, my
web directory is C:\Program Files\VertrigoServ\www. Hence, I should save my PHP files in this folder.
In addition, you cant run PHP files by opening them using Web browsers directly, unlike html files. For
PHP to execute properly, you should work using your web server. This can be done by typing the address
of your computer in your web browser like:
http://127.0.0.1/
You can add PHP file to execute at the end of the above address like:
http://127.0.0.1/test.php
Practice 6.1
1. Go to www.google.com and search for download location of vertrigo.
2. Download the vertrigo server into your computer.
3. Install the vertrigo server by going to the path it is downloaded to
123
NB: If you have done the above tasks successfully, you now have a vertrigo on your machine. You can
start vertrigo by going to Start->programs->vertrigoServ->vertrigoServ. You will see a vertrigo icon in the
tray.
Attaching PHP to Web Pages
PHP file is attached to web pages by using the <form> tag. Since PHP is written to process data sent from
client computers and form is the means to get that data, this is a logical place to attach the PHP to
HTML.
The form tag has an attribute called action. We use this attribute to specify the PHP to execute when the
web page is submitted. The syntax is:
<form name=formname method=submitingmethod action=phpfiletoexecute.php>
form elements
</form>
Example: to attach a php called saver.php to an HTML page
<form name=detail method=post action=saver.php>
form content
</form>
When this form is submitted, the web server looks for saver.php and executes it. The result from
executed php, saver.php in this case, is sent back the client machine.
Writing PHP
You add PHP code to your web page by using tags, similar, but not identical, to other tags in the HTML
file. The PHP code section is enclosed in PHP tags with the following form:
<?php
PHP statements
?>
For example, you can add the following PHP section to your HTML file.
Remark: Web pages that contains PHP should be saved with .php extension. You can also add several
PHP sections to a Web page.
<?php
echo This line brought to you by PHP;
?>
When the Web server gets the file and sees the .php extension, it checks for PHP tags. When it finds the
PHP tag, it executes the PHP echo statement instead of sending it to the browser. Only the output from
the PHP section (This line brought to you by PHP) is sent on to the browser. In your browser window, you
see the output at the location in the page where you added the PHP section. Even if you view the source
in your browser, you only see the output, not the PHP code.
124
Output Statements
Output statements are used in almost every PHP script. Its rare that you would write a script that would
do something and not output anything. True, a script can do things that are invisible, like checking your
entire hard disk to see if a certain file exists. You would not see it checking. However, the search is pretty
pointless if the script doesnt tell you what it found. Youd want to know where it looked, when it
finished, and whether or not it found the file. Because of this, almost all scripts use output statements.
The two most basic constructs for displaying output in PHP are echo and print. Both can be used either
with parentheses or without them. Function calls always have the name of the function first, followed by
a parenthesized list of the arguments to the function.
The general format of the echo statement is as follows:
echo outputitem1,outputitem2,outputitem3, . . .;
echo (output);
The parameterized version of echo does not accept multiple arguments.
The general format of the print statement is as follows:
print output;
print(output);
Example: different ways of echo and print
echo 123; //output: 123
echo Hello World!;
//output: Hello world!
echo (Hello World!); //output: Hello world!
echo Hello,World!; //output: Hello World!
echo Hello World!;
//output: error, string should be enclosed in quotes
print (Hello world!); //output: Hello world!
125
The command print is very similar to echo, with two important differences:
Unlike echo, print can accept only one argument.
Unlike echo, print returns a value, which represents whether the print statement succeeded.
The value returned by print will be 1 if the printing was successful and 0 if unsuccessful. It is rare that a
syntactically correct print statement will fail, but in theory this return value provides a means to test, for
example, if the users browser has closed the connection.
It is possible to embed HTML tags in echo or print statements. The browser will parse and interpret them
like any tag included in HTML page and display the page accordingly.
echo/print statement
PHP output
HelloWorld!
HelloWorld!
echo Hello;
echo World!;
echo Hello\nWorld!;
HelloWorld!
HelloWorld!
Hello World!
echo Hello<br>World!;
Hello
World!
Hello<br>World
<u>Hello world!</u>
Hello
World!
Hello world!
Comments
Adding comments to your script is essential. Comments describe your script what it does and how it
does it. The larger, more complicated, or more unusual your code is, the more you need comments.
After working 20 hours a day on a script, you may believe its code is permanently burned into your brain.
However, two years from now, when you need to revise this script, you will swear it was written by a
stranger. And theres also the possibility that your scripts may need to be revised by an actual stranger.
Programmers leave a company making it difficult to revise code unless commented.
Comments are notes that are embedded in the script itself. PHP ignores comments; comments are for
humans. You can embed comments in your script anywhere as long as you tell PHP that they are
126
comments.
PHP supports two types of comments: single-line comment (short comment), and multi-line comment
(long comment). The format for multi-line comments is as follows:
/* comment text
more comment text
*/
Your comments can be as long or as short as you need. When PHP sees code that indicates the start of a
comment (/*), it ignores everything until it sees the code that indicates the end of a comment (*/).
PHP has a short comment format too. You can specify a single line comment by using the # or two
slashes (//) in the following manner:
# This is comment line 1
// This is comment line 2
It is customary and useful to put a block of comments at the top of your script giving information about
the script and an overview of what it does. For example, heres one possible format for a comment block
at the top of your script:
/*
name: hello.php
description: Displays Hello World! on a Web page.
written by: Joe Programmer
created: 2/1/03
modified: 3/15/03
*/
127
128
The output from the preceding statements is The day today is Sunday.
Checking variable content
Sometimes you just need to know whether a variable exists or what type of data is in the variable. Here
are some common ways to test variables:
isset($varname) - true if variable is set, even if nothing is stored in it.
empty($varname) - true if value is 0 or is a string with no characters in it or is not set.
You can also test what type of data is in the variable. For example, to see if the value is an integer, you
can use the following:
is_int($number) - the comparison is TRUE if the value in $number is an integer.
Some other tests provided by PHP are as follows:
is_array($var2): Checks to see if $var2 is an array
is_float($number): Checks to see if $number is a floating point number
is_null($var1): Checks to see if $var1 is equal to 0
is_numeric($string): Checks to see if $string is a numeric string
is_string($string): Checks to see if $string is a string
You can test for a negative, as well, by using an exclamation point (!) in front of the expression. For
example, the following statement returns TRUE if the variable does not exist at all:
!isset($varname)
Removing Variables
You can uncreate the variable by using this statement:
unset($age);
After this statement, the variable $age no longer exists. If you try to echo it, you get an undefined
variable notice. You can unset more than one variable at once, as follows:
unset($age, $name, $address);
Creating constants
Constants are set by using the define statement. The general format is as follows:
129
define(constantname, constantvalue);
For example, to set a constant with the weather, use the following statement:
define(PI,3.141);
This statement creates a constant called PI and sets its value to 3.141.
When naming constants, use descriptive names, as you do for variables. However, unlike variables,
constant names do not begin with a dollar sign ($). By convention, constants are given names that are all
uppercase so you can see easily that theyre constants. However, PHP accepts lowercase letters without
complaint.
You can store either a string or a number in a constant. The following statement, which defines a
constant named INTEREST and assigns to it the value .01, is perfectly okay with PHP:
define (INTEREST,.01);
Constants should not be given names that are keywords for PHP. Keywords are words that have meaning
for PHP, such as echo, and they cant be used as constants because PHP treats them as the PHP feature
of the same name.
Displaying constants
You can determine the value of a constant by using print as follows:
print(INTEREST);
You can also use a constant in an echo statement:
echo INTEREST;
When you echo a constant, you cant enclose it in quotes. If you do, it echoes the constant name rather
than the value. You can echo the constant as shown in the preceding example, or you can enclose it with
parentheses. You can build more complicated output statements by using commas, as in the following
example:
echo The Canadian exchange rate is $, INTEREST;
The output from this statement is the following: The Canadian exchange rate is $1.52.
Practice 6.2
1. Write a PHP program that displays your age from a variable with echo statement.
2. Write a PHP program that defines that defines the distance between earth and moon and
displays it using print statement.
130
Mathematical Operators
Arithmetic operators are straightforwardthey are just the normal mathematical operators.
Operator
Description
+
Adds two numbers together.
-
Finds the remainder when the first number is divided by the second number. This
is called modulus.
Table 6.3 mathematical operators
Example: a program that performs all mathematical operation on two numbers
$a = 10;
$b = 20;
$c = $a + $b; //result: 30
$c = $a - $b; //result: -10
$c = $a * $b; //result: 200
$c = $a / $b; //result: 0.5
$c = $a % $b; //result: 10
You should note that arithmetic operators are usually applied to integers or doubles. If you apply them
to strings, PHP will try and convert the string to a number. If it contains an e or an E, it will be
converted to a double; otherwise it will be converted to an int. PHP will look for digits at the start of the
string and use those as the valueif there are none, the value of the string will be zero.
description
example
meaning
++
postfix increment
$x++
$x=$x+1
--
postfix decrement
$x--
$x=$x-1
++
prefix increment
++$x
$x=$x+1
--
prefix decrement
--$x
$x=$x+1
131
description
example
meaning
+=
$x += 5
$x = $x + 5
-=
$x -= 5
$x = $x 5
/=
$x /= 5
$x = $x / 5
*=
$x *= 5
$x = $x * 5
%=
$x %= 5
$x = $x % 5
.=
$x .= " test"
$x = $x." test"
Comparison operators
132
The comparison operators are used to compare two values. Expressions using these operators
return either true or false depending on the result of the comparison.
Operator
Name
description
==
Equal
!=
Not equal
<
Less than
>
Greater than
<=
>=
===
Identical
Logical Operators
The logical operators are used to combine the results of logical conditions. For example, we might be
interested in a case where the value of a variable is between 0 and 100. We would need to test the
conditions $a >= 0 and $a <= 100, using the AND operator, as follows
$a >= 0 && $a <=100
Operator
description
And
Or
!
Xor
Is true if its single argument (to the right) is false and false if its
argument is true
Is true if either (but not both) of its arguments are true
&&
||
133
the truth value of the first expression to decide which of the other two expressions to evaluate and
return. The syntax looks like:
test-expression ? yes-expression : no-expression
The value of this expression is the result of yes-expression if test-expression is true; otherwise, it is the
same as no-expression.
For example, the following expression assigns to $max_num either $first_num or $second_num,
whichever is larger:
$max_num = $first_num > $second_num ? $first_num : $second_num;
134
if($mark<50) {
print(You failed this course);
}
else{
print(You have passed the course);
}
else if Statements
For many of the decisions we make, there are more than two options. We can create a sequence of
many options using the elseif statement. The elseif statement is a combination of an else and an if
statement. By providing a sequence of conditions, the program can check each until it finds one that is
true.
Example: a program that checks if a variable value is between 1 and 5 and display message accordingly
if ($day == 5)
print(Five golden rings<BR>);
elseif ($day == 4)
print(Four calling birds<BR>);
elseif ($day == 3)
print(Three French hens<BR>);
elseif ($day == 2)
print(Two turtledoves<BR>);
elseif ($day == 1)
print(A partridge in a pear tree<BR>);
135
Practice 6.3
1. Write a PHP code that checks the day of week and display appropriate message. For example,
Today is Friday if the day is Friday. Use switch statement.
136
2. Write a program that accepts marks of five courses of a student and calculate the total, the
average, and the range.
3. Write a program that accepts mark of a student and determine if he/she has failed the course or
not (<50 is failure).
137
The statements in the block do not need to be indented. PHP doesnt care whether theyre indented.
However, indenting the blocks makes it much easier for you to understand the script.
You can nest for loops inside of for loops. Suppose you want to print out the times tables from 1 to 9.
1x1=1
...
1x9=9
2x1=2
...
2 x 9 = 18
9x1=9
9 x 9 = 81
You can use the following nested loop statements:
for($i=1; $i<=9; $i++)
{
for($j=1; $j<=9; $j++)
{
$result = $i * $j;
echo $i x $j = $result\n;
}
}
138
while (TRUE)
print(All work and no play makes Jack a dull boy.<BR>);
or it may execute a predictable number of times, as in:
$count = 1;
while ($count <= 10)
{
print(count is $count<BR>);
$count = $count + 1;
}
which will print exactly 10 lines.
139
140
1.6 Arrays
The variables that we looked at in the previous chapters are scalar variables, which store a single value.
An array is a variable that stores a set or sequence of values. One array can have many elements. Each
element can hold a single value, such as text or numbers, or another array. An array containing other
arrays is known as a multidimensional array.
A scalar variable is a named location in which to store a single value; similarly, an array is a named place
to store a set of values, thereby allowing you to group common scalars.
The values stored in an array are called the array elements. Each array element has an associated index
(also called a key) that is used to access the element. Arrays in most programming languages have
numerical indexes that typically start from zero or one. PHP supports this type of array.
In addition to numerical indexes, PHP also supports associative arrays. Associative arrays can have
almost anything as the array indices, but typically use strings.
Creating Arrays
There are different ways to create an array in a PHP script: by assigning a value into one (and thereby
implicitly creating it), by using the array() construct, or by calling a function that happens to return an
array as its value.
The simplest way to create an array is to act as though a variable is already an array and assign a value
into it.
Example: the following code will create an array called $products by assigning value:
$products[0] = Tires;
$products[1] = Oil;
$products[2] = Spark Plugs;
$products[3] = battery;
$products[4] = jar;
If $products does not already exist (which is true in this case), the first line will create a new array with
just one element. The subsequent lines add values to the array. The number in the [] are array indexes
that identify where the element is stored.
The other way to create an array is via the array() construct, which creates a new array from the
specification of its elements and associated keys. In its simplest version, array() is called with no
arguments, which creates a new empty array. In its next simplest version, array() takes a commaseparated list of elements to be stored, without any specification of keys. The result is that the elements
are stored in the array in the order specified and are assigned integer keys beginning with zero.
141
142
You can use foreach to walk through an array one value at a time and execute a block of statements by
using each value in the array. The general format is as follows:
foreach ( $arrayname as $keyname => $valuename)
{
block of statements;
}
In this format, you need to fill in the following information:
arrayname: The name of the array you are walking through.
keyname: The name of the variable where you want to store the key. The keyname variable is
optional. If you leave out $keyname =>, only the value is stored into $valuename.
valuename: The name of the variable where you want to store the value.
Example: foreach loop
$population = array ( Oro => 25000, Amh => 20000, Tig => 5000);
ksort($population);
foreach($population as $state => $population)
{
$population = number_format($population);
echo $state: $population.<br>;
}
Multidimensional Arrays
Arrays do not have to be a simple list of keys and valueseach location in the array can hold another
array. This way, we can create a two-dimensional array. You can think of a two dimensional array as a
matrix, or grid, with width and height or rows and columns.
If we want to store more than one piece of data about products, we could use a two-dimensional array.
143
144
If we are using an associative array to store items and their prices, we need to use different kinds of sort
functions to keep keys and values together as they are sorted. In this case, we use either asort() or
ksort().
The function asort() orders the array according to the value of each element. If the sorting should be
done by key instead of value, we use ksort(). You can use several other sort statements to sort in other
ways. The table lists all the available sort functions.
Sort Statement
What It Does
sort($arrayname)
asort($arrayname)
rsort($arrayname)
Sorts by value; keeps the same key. Good for associative arrays, but not for
indexed arrays.
Sorts by value in reverse order; assigns new numbers as the keys.
arsort($arrayname)
ksort($arrayname)
Sorts by key.
krsort($arrayname)
natsort($arrayname)
Sorts mixed string/number values in natural order. For example, given an array
with values day1, day5, day11, day2, it sorts into the following order: day1,
day2, day5, day11. The previous sort functions sort the array into this order:
day1, day11, day2, day5.
The following code creates an associative array containing the three products and their associated
prices, and then sorts the array into ascending price order.
$prices = array( Tires=>100, Oil=>10, Spark Plugs=>4 );
asort($prices);
//sorts by key
$prices = array( Tires=>100, Oil=>10, Spark Plugs=>4 );
ksort($prices);
Example:
$capitals[1] = Sacramento;
$capitals[2] = Austin;
$capitals[3] = Salem;
After an asort statement, the new array would be as follows:
$capitals[2] = Austin
$capitals[1] = Sacramento
$capitals[3] = Salem
145
146
PHP: indicates the earliest version of PHP that supports the function.
Function
Description
array()
Creates an array
array_combine()
array_count_values()
array_diff()
Compares array
differences
array_diff_assoc()
array_diff_key()
array_fill()
array_filter()
array_flip()
array_intersect()
array_intersect_assoc()
array_intersect_key()
values,
and
returns
the
147
array_key_exists()
array_keys()
array_merge()
array_multisort()
array_pad()
array_pop()
array_product()
array_push()
Inserts one or more elements to the end of $data = array("Donald", "Jim", "Tom");
an array
array_push($data, "Harry"); //Donald Jim Tom Harry
array_rand()
Returns one or more random values from an $data = array("white", "black", "red");
array
echo "Today's color is " . $data[array_rand($data)];
array_reduce()
array_reverse()
array_search()
array_shift()
Removes the first element from an array, and $data = array("Donald", "Jim", "Tom");
returns the value of the removed element
array_shift($data); //Jim Tom
$data
=
array("Donald",
array_pop($data); //removes Tom
148
"Jim",
"Tom");
array_slice()
array_splice()
array_sum()
array_udiff()
array_unique()
array_unshift()
array_values()
array_walk()
arsort()
asort()
compact()
count()
current()
each()
end()
149
extract()
in_array()
key()
krsort()
ksort()
list()
natcasesort()
natsort()
next()
pos()
Alias of current()
prev()
range()
reset()
rsort()
shuffle()
Shuffles an array
sizeof()
Alias of count()
sort()
Sorts an array
uasort()
150
Built-in Arrays
PHP has several built-in arrays that you can use when writing PHP scripts. Different types of information
are stored in different arrays. For example, information about your server (such as headers, paths, and
script locations) is stored in an array called $_SERVER.
Array
$GLOBALS[]
Description
Contains all the global variables. For example, if you use the statement,
$testvar = 1, you can then access the variable as $GLOBALS [testvar].
$ _POST[]
Contains all the variables contained in a form if the form uses method=post.
$HTTP_POST_VARS[]
Same as $ _POST.
$ _GET[]
Contains all the variables passed from a previous page as part of the URL. This
includes variables passed in a form using method=get.
$HTTP_GET_VARS[]
Same as $ _GET.
$ _COOKIE[]
Contains all the cookie variables.
$HTTP_COOKIE_VARS[] Same as $ _COOKIE.
$ _SESSION[]
Contains all the session variables.
$HTTP_SESSION_VARS[] Same as $ _SESSION.
$_REQUEST[]
Contains all the variables together that are in $_POST, $_GET, and $_SESSION.
$_FILES[]
Contains the names of files that have been uploaded.
$HTTP_FILES_VARS[]
Same as $_FILES.
$_SERVER[]
Contains information about your server. Because your Web server provides
the information, the information thats available depends on what server
youre using.
$HTTP_SERVER_VARS[] Same as $_SERVER.
$_ENV[]
Contains information provided by your operating system, such as the
operating system name, the system drive, and the path to your temp
directory. This info varies depending on your operating system
$HTTP_ENV_VARS[]
Same as $_ENV.
The $_SERVER and $_ENV arrays contain different information, depending on the server and operating
system youre using. You can see what information is in the arrays for your particular server and
operating system by using the following statements:
foreach($_SERVER as $key =>$value)
echo Key=$key, Value=$value\n;
The output includes such lines as the following:
Key=HTTP_HOST, Value=127.0.0.1
Key=HTTP_ACCEPT, Value=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Key=HTTP_ACCEPT_LANGUAGE, Value=en-us,en;q=0.5
151
Practice 6.4
1. Write a program that calculates the factorial of a number. For example 10! (10x9xx2x1)
2. Write a program that prints the following:
123456789
23456789
3456789
456789
56789
6789
789
89
9
3. Write a program stores name, sex, age and income of a person using associative array.
152
153
functionname(value1,value2,...);
Example: to call the above addNumbers function:
$result = addNumbers(30,20);
Pass by Reference Versus Pass by Value
If we want to write a function called increment() that allows us to increment a value, we might be
tempted to try writing it as follows:
function increment($value, $amount)
{
$value = $value +$amount;
}
This code will be of no use. The output from the following test code will be 10.
$value = 10;
increment ($value, 1);
echo $value;
The contents of $value have not changed. This is because of the scope rules. This code creates a variable
called $value which contains 10. It then calls the function increment(). The variable $value in the
function is created when the function is called. One is added to it, so the value of $value is 11 inside the
function, until the function ends, and we return to the code that called it. In this code, the variable
$value is a different variable, with global scope, and therefore unchanged.
One way of overcoming this is to declare $value in the function as global, but this means that in order to
use this function, the variable that we wanted to increment would need to be named $value. A better
approach would be to use pass by reference.
The normal way that function parameters are called is called pass by value. When you pass a parameter,
a new variable is created which contains the value passed in. It is a copy of the original. You are free to
modify this value in any way, but the value of the original variable outside the function remains
unchanged.
The better approach is to use pass by reference. Here, when a parameter is passed to a function, rather
than creating a new variable, the function receives a reference to the original variable. This reference
has a variable name, beginning with a dollar sign, and can be used in exactly the same way as another
variable. The difference is that rather than having a value of its own, it merely refers to the original. Any
modifications made to the reference also affect the original.
We specify that a parameter is to use pass by reference by placing an ampersand (&) before the
parameter name in the functions definition. No change is required in the function call.
154
The preceding increment() example can be modified to have one parameter passed by reference, and it
will work correctly.
function increment(&$value, $amount = 1)
{
$value = $value +$amount;
}
We now have a working function, and are free to name the variable we want to increment anything we
like. As already mentioned, it is confusing to humans to use the same name inside and outside a
function, so we will give the variable in the main script a new name. The following test code will now
echo 10 before the call to increment(), and 11 afterwards.
$a = 10;
echo $a;
increment ($a);
echo $a ;
Variable Scope
A variable declared within a function remains local to that function. In other words, it will not be
available outside the function or within other functions. In larger projects, this can save you from
accidentally overwriting the contents of a variable when you declare two variables with the same name
in separate functions.
A variables scope controls where that variable is visible and useable. Different programming languages
have different rules that set the scope of variables. PHP has fairly simple rules:
Variables declared inside a function are in scope from the statement in which they are declared
to the closing brace at the end of the function. This is called function scope. These variables are
called local variables.
Variables declared outside of functions are in scope from the statement in which they are
declared to the end of the file, but not inside functions. This is called global scope. These
variables are called global variables.
Using require() and include() statements does not affect scope. If the statement is used within a
function, function scope applies. If it is not inside a function, global scope applies.
The keyword global can be used to manually specify that a variable defined or used within a
function will have global scope.
Variables can be manually deleted by calling unset($variable_name). A variable is no longer in
scope if it has been unset.
Example: local variable
<?php
function test()
{
$testvariable = "this is a test variable";
155
}
echo "test variable: $testvariable<br>";
?>
The value of the variable $testvariable is not printed. This is because no such variable exists outside the
test() function. Note that the attempt to access a nonexistent variable does not cause an error. Similarly,
a variable declared outside a function will not automatically be available within it.
If you want a variable created within a function to be global, we can use the keyword global as follows:
function fn() {
global $var;
$var = contents;
echo inside the function, \$var = .$var.<br>;
}
fn();
echo outside the function, \$var = .$var.<br>;
output:
inside the function, $var = contents
outside the function, $var = contents
Practice 6.5
1. Write a PHP function that identifies the largest number of the given numbers.
2. Write a PHP function that returns the cubed value of the given number.
3. Write a PHP function that displays numbers between 150 and 200 that are divisible ten.
156
POST method: The form data is passed as a package in a separate communication with the
processing script. The advantages of this method are unlimited information passing and security
of the data. The disadvantages are the additional overhead and slower speed.
The form data is available in the processing script in the PHP built-in arrays. Information from forms that
use the POST method is available in the built-in array called $_POST. If your form uses the GET method,
the information is available in the array $_GET. Both types of form information are also stored in an
array called $_REQUEST. Each array index is the name of the input field in the form. You get information
from the array by using the form field name as the array key. The syntax is:
$_POST[form element name]
$_GET[form element name]
For example, suppose that you echo the following field in your form that uses the POST method:
<input type=text name=firstName>;
The value entered in this textbox can be accessed by $_POST[firstName] which contains the text the
user typed into the field. If the form uses GET method, the above textbox can be accessed as
$_GET[firstName].
157
Password: You have to have a valid password to access the database. The database
administrator sets this up. If youre using a Web hosting company, you will be given a valid
password for your account.
Sex
M
M
M
F
Telephone
4325456342
5424256345
2634345643
3462737485
Status
1
1
0
0
After connecting to the database, the next step is selecting database. An RDBMS can create and
maintain many databases, so you need to tell it which database you want to use.
The syntax for selecting database is:
$db = mysql_select_db(string database, [int database_connection] );
Example:
<?php
$con = mysql_connect("localhost","root","vertrigo");
mysql_select_db(books);
//other statements
?>
Querying the Database
To actually perform the query, we can use the mysql_query() function. Before doing this, however, its a
good idea to set up the query you want to run:
$query = select * from books;
We can now run the query:
$result = mysql_query($query);
The mysql_query() function has the following prototype:
int mysql_query(string query, [int database_connection] );
158
You pass it the query you want to run, and optionally, the database connection (again, in this case $db).
If not specified, the function will use the last opened link. If there isnt one, the function will open the
default one as if you had called mysql_connect().
You might want to use the mysql_db_query() function instead. It has the following prototype:
int mysql_db_query(string database, string query, [int database_connection] );
Its very similar but allows you to specify which database you would like to run the query on. It is like a
combination of the mysql_select_db() and mysql_query() functions. Both of these functions return a
result identifier (that allows you to retrieve the query results) on success and false on failure. You should
store this (as we have in this case in $result) so that you can do something useful with it.
Example: executing query
$sql = SELECT * FROM Product;
$result = mysql_query($sql,$connect);
Putting all together:
<?php
$account = david;
$password = gotago;
$connect = mysql_connect($host, $account, $password);
$db = mysql_select_db(Catalog, $connect);
$sql = SELECT * FROM Product;
$result = mysql_query($sql, $connect);
//other code
?>
Processing Data
To process the data returned from database, you need to get it from the temporary table where it was
placed when the SQL query was executed. You use PHP database functions to get the data from the
temporary table.
The data is stored in the temporary table in rows and columns. You can use PHP functions to retrieve
one row from the table and store it in an array, with the field names as the array keys. For MySQL, the
statement is as follows:
$row = mysql_fetch_array($result);
It requires one of the mysql_fetch functions to make the data fully available to PHP. The fetching
functions of PHP are as follows:
mysql_fetch_assoc: returns rows as associative array
mysql_fetch_row: returns row as an enumerated array
159
160
161
162
</HEAD>
<BODY>
<H1>Newsletter sign-up form</H1>
<P> Please, fill the form to be our registered customer</P>
<FORM METHOD=post ACTION=customer.php>
ID: <INPUT TYPE=text NAME=ID> <BR>
First name: <INPUT TYPE=text NAME=FirstName> <BR>
Last name: <INPUT TYPE=text NAME=LastName> <BR>
Sex: <INPUT TYPE=text NAME=Sex> <BR>
Telephone: <INPUT TYPE=text NAME=Telephone> <BR><BR>
<INPUT TYPE=submit NAME=submit VALUE=Submit>
</FORM>
</BODY>
</HTML>
The customer.php file that process the data collected by the above form is the following:
<?php
// Open connection to the database
mysql_connect(localhost, phpuser, sesame) or die(Failure to connect to database);
mysql_select_db(customers);
$ID = $_POST[ID]);
$fn = $_POST[FirstName];
$ln = $_POST[LastName];
$sx = $_POST[Sex];
$tl = $_POST[Telephone];
$st = 1;
$query = INSERT INTO users VALUES($ID, $fn, $ln, $sx, $tl, $st);
$result = mysql_query($query);
if (mysql_affected_rows() == 1) {
echo <P>Your information has been saved.</P>;
}
else {
echo <P>Something went wrong with your signup attempt.</P>;
}
?>
Example: a program that displays the content of a table called employee from HR database in table
format
$con = mysql_connect(localhost, root, vertrigo) or
die(Cant connect to databse);
163
mysql_select_db(HR);
$res=mysql_query(select * from employee, $con);
echo <table border=1>;
while($row=mysql_feth_array($res, MYSQL_BOTH))
{
echo <tr>
echo <td> $row[name] </td>;
echo <td> $row[ID] </td>;
echo <td> $row[salary] </td>;
echo <td> $row[sex] </td>;
echo <td> $row[BD] </td>;
echo </tr>;
}
echo </table>;
Closing the connection
Any open database connections are closed when the script ends. However, it is good programming
practice to close the connections in the script to avoid any possible problems. You close database
connections the same way you open them with a PHP function. For example, for MySQL, use the
following function to close a database connection:
mysql_close($connect);
Other Important PHP-Database Functions
mysql_affected_rows Get number of affected rows in previous MySQL operation. It helps you to
know how many rows have been deleted, inserted, modified, etc. by the last mysql_query() operation.
int mysql_affected_rows ( [resource link_identifier])
mysql_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or DELETE
query associated with link_identifier. If the link identifier isn't specified, the last link opened by
mysql_connect() is assumed.
mysql_create_db Create a MySQL database. The syntax is:
bool mysql_create_db (string database name [, resource link_identifier]);
mysql_create_db() attempts to create a new database on the server associated with the specified link
identifier.
mysql_drop_db Drop (delete) a MySQL database
bool mysql_drop_db ( string database_name [, resource link_identifier])
mysql_drop_db() attempts to drop (remove) an entire database from the server associated with the
specified link identifier.
mysql_num_rows Get number of rows in result. The syntax is:
164
Using ODBC
PHP can also connect to databases by using ODBC. The following are the functions you can use for such
purpose.
odbc_connect ( string datasourcename, string user, string password [, int cursor_type])
This function returns an ODBC connection id or 0 on error. The connection id returned by this functions
is needed by other ODBC functions. You can have multiple connections open at once.
165
The optional fourth parameter sets the type of cursor to be used for this connection. This parameter is
not normally needed, but can be useful. The following constants are defined for cursortype:
SQL_CUR_USE_IF_NEEDED
SQL_CUR_USE_ODBC
SQL_CUR_USE_DRIVER
SQL_CUR_DEFAULT
odbc_exec ( resource connection_id, string query_string)
This returns an ODBC result identifier if the SQL command was executed successfully. odbc_exec() will
send an SQL statement to the database server specified by connection_id. This parameter must be a
valid identifier returned by odbc_connect().
odbc_do ( resource conn_id, string query)
This will execute a query on the given connection just like odbc_exec.
odbc_fetch_array ( resource result [, int rownumber])
This fetches a result row as an associative array
odbc_fetch_object (resource result [, int rownumber])
This fetches a result row as an object
odbc_fetch_row ( resource result_id [, int row_number])
If odbc_fetch_row() was succesful (there was a row), TRUE is returned. If there are no more rows, FALSE
is returned.
odbc_fetch_row() fetches a row of the data that was returned by odbc_do() / odbc_exec(). After
odbc_fetch_row() is called, the fields of that row can be accessed with odbc_result(). If row_number is
not specified, odbc_fetch_row() will try to fetch the next row in the result set.
odbc_commit ( resource connection_id)
All pending transactions on connection_id are committed. It returns TRUE on success, FALSE on failure.
odbc_close ( resource connection_id)
odbc_close() will close down the connection to the database server associated with the given
connection identifier.
Example:
<?php
$con = odbc_connect(registrar", root", vertrigo") or
die("Connecting to databse failed.");
$sql = "select * from student where ID='" . $_POST['ID']. "'";
$rs = odbc_exec($con, $sql);
166
Practice 6.6
1. Write a program that connects and retrieves data from database. Create a database called
student first, and then fill some data to it. Connect to this database and display its content in
your web page. Student database contains the following table:
first name
last name
city
2. Write a program that accepts data from students and store it in the students table created
above.
3. Write a program that deletes a student with ID SSD/2314/00 from the above table
4. Write a program that displays students who are from Jimma.
Defining a Class
A minimal class definition looks as follows:
class classname
167
{
}
In order to be useful, our classes need attributes and operations. We create attributes by declaring
variables within a class definition using the keyword var. The following code creates a class called
classname with two attributes, $attribute1 and $attribute2.
We create operations by declaring functions within the class definition. The following code will create a
class named classname with two operations. The operation operation1() takes no parameters and
operation2() takes two parameters.
class classname
{
var $attribute1;
var $attribute2;
function operation1()
{
//code here
}
function operation2($param1, $param2)
{
//code here
}
}
Constructors
Most classes will have a special type of operation called a constructor. A constructor is called when an
object is created, and it also normally performs useful initialization tasks such as setting attributes to
sensible starting values or creating other objects needed by this object.
A constructor is declared in the same way as other operations, but has the same name as the class.
Though we can manually call the constructor, its main purpose is to be called automatically when an
object is created. The following code declares a class with a constructor:
class classname
{
function classname($param)
{
echo Constructor called with parameter $param <br>;
}
}
Instantiation of Class
168
After we have declared a class, we need to create an objecta particular individual that is a member of
the classto work with. This is also known as creating an instance or instantiating a class. We create an
object using the new keyword. We need to specify what class our object will be an instance of, and
provide any parameters required by our constructor.
The following code declares a class called person with a constructor, and then creates three objects of
type person:
class person
{
function person($param)
{
echo Constructor called with parameter $param <br>;
}
}
$a = new person(First); //instantiation
$b = new person(Second); //another instantiation
$c = new person();//yet another instantiation
When we use a class method or property, we must use the -> operator. The keyword this tells PHP
that the property of method belongs to the class being defined.
<?php
class automobile_class
{
var $color; //the color of the car
var $max_speed; //the maximum speed
var $price; //the price of the car, in dollars
function is_cheap()
{
$this->display();
return ($this->price < 5000); //returns TRUE if the price is smaller than 5000 dollars
}
function display()
{
echo "The price is $this->price<br>";
}
}
$car_object = new automobile_class();
$car_object->color = "red";
$car_object->price = 6000;
$cheap = $car_object->is_cheap(); //call is_cheap() method of the class
if($cheap)
print "This car is cheap!";
169
else
print "This car is expensive!";
?>
You can see that we use the "->" operator to access and modify objects properties. After that, we use
the same operator to call a method.
170
You can display a form that allows a user to upload a file by using an HTML form designed for that
purpose. The general format of the form is as follows:
<form enctype=multipart/form-data action=processfile.php method=POST>
<input type=hidden name=MAX_FILE_SIZE value=30000>
<input type=file name=user_file>
<input type=submit value=Upload File>
</form>
Notice the following points regarding the form:
The enctype attribute is used in the form tag. You must set this attribute to multipart/form-data
when uploading a file to ensure the file arrives correctly.
A hidden field is included that sends a value (in bytes) for MAX_FILE_SIZE. If the user tries to
upload a file that is larger than this value, it wont upload. When sending the value for
MAX_FILE_SIZE in your form, you need to consider two size settings in php.ini, as follows
upload_max_filesize: The MAX_FILE_SIZE you send in your upload form cant be larger than the
value of upload_max_filesize. If you are uploading a larger file and need to send a
MAX_FILE_SIZE larger than the current value of upload_max_filesize, you need to increase the
value of upload_max_filesize by editing the php.ini file. The default value for this setting is 2M.
post_max_size: The total amount of information you send in a POST form cant be larger than
the value of post_max_size. The default value for this setting is 8M. You can increase this value if
necessary by editing your php.ini file.
The input field that uploads the file is of type file.
The value for MAX_FILE_SIZE must be sent before the file is uploaded if you want the file size limit to
apply to the uploading file.
When the user submits the form, the file is uploaded to a temporary location. The script that processes
the form needs to copy the file to another location because the temporary file is deleted as soon as the
script is finished. You can use phpinfo() to see where the temporary files are stored. If you dont like the
location of the temporary directory, you can change it by changing upload_tmp_dir in the php.ini file. If
no directory is specified in php.ini, a default temporary directory is used.
171
For example, suppose you use the following field to upload a file:
<input type=file name=user_file>
If the user uploads a file named test.txt by using the form, the resulting array that can be used by the
processing script looks something like this:
echo $_FILES[user_file][name];
// test.txt
echo $_FILES[user_file][type];
// text/plain
echo $_FILES[user_file][tmp_name]; //D:\WINNT\php92C.tmp
echo $_FILES[user_file][size];
// 435
In this array, name is the name of the file that was uploaded, type is the type of file, tmp_name is the
path/filename of the temporary file, and size is the size of the file. Notice that name contains only the
filename, while tmp_name includes the path to the file as well as the filename.
If the file is too large to upload, the tmp_name in the array is set to none, and the size is set to 0. By
default, PHP stores the temporary uploaded file in your system directory on Windows (Windows for
Win98/XP and Winnt for Win2000) or /tmp on Unix/Linux. You can change the location of temporary
files by setting php.ini. Look in your php.ini file for the following line:
upload_tmp_dir =
172
a message after the file has been successfully uploaded. This script expects the uploaded file to be an
image file, and tests to make sure that it is an image file, but any type of file can be uploaded.
<?php
/* Script name: uploadFile.php
* Description: Uploads a file via HTTP using a POST form.
*/
if($_FILES[pix][tmp_name] == none)
{
echo <b>File did not successfully upload. Check the file size. File must be less than 500K.<br>;
include(form_upload.inc);
exit();
}
if(!ereg(image,$_FILES[pix][type]))
{
echo <b>File is not a picture. Please try another file.</b><br>;
include(form_upload.inc);
exit();
}
else
{
$destination = c:\data.\\.$_FILES[pix][name];
$temp_file = $_FILES[pix][tmp_name];
move_uploaded_file($temp_file,$destination);
echo <p>The file has successfully uploaded: $_FILES[pix][name] $_FILES[pix][size];
}
?>
173
</form>
</body>
</html>
174
read only
r+
write only
w+
If the file does not exist, PHP attempts to create it. If the
file exists, PHP overwrites it.
If the file does not exist, PHP attempts to create it. If the
file exists, PHP overwrites it.
If the file does not exist, PHP attempts to create it.
a+
175
You can open a file in a specified directory to store information by using the following type of statement:
$fh = fopen(c:/testdir/happy.txt,w);
If the file does not exist, it is created in the indicated directory. However, if the directory doesnt exist,
the directory is not created, and a warning is displayed.
You can also open a file on another Web site by using a statement such as the following:
$fh = fopen(http://janet.valade.com/index.html,r);
You can use a URL only with a read mode, not with a write mode.
To close a file after you have finished reading or writing it, use the following statement:
fclose($fh);
In this statement, $fh is the file handle variable you created when you opened the file.
Reading from file
You can read from a file by line by line using the fgets statement, which has the following general
format:
$line = fgets($fh)
Sometimes you want to read strings of a certain size from a file. You can tell fgets to read a certain
number of characters by using the following format:
$line = fgets($fh, n)
This statement tells PHP to read a string that is n-1 characters long until it reaches the end of the line or
the end of the file.
Example: a program that reads file line by line until end_of_file and displays it
<?php
$fh = fopen("test.txt", "r") or die("Can't open file");
while(!feof($fh)) {
$line = fgets($fh);
print ("\n$line");
}
fclose($fh);
?>
Another option for file processing is to read a single character at a time from a file. You can do this using
the fgetc() function. We can replace the while loop in our original script with one that uses fgetc():
while (!feof($fp)) {
$char = fgetc($fp);
echo ($char);
176
}
This code reads a single character from the file at a time using fgetc() and stores it in $char, until the end
of the file is reached.
Instead of reading from a file a line at a time, we can read the whole file in one go. This can be done
using readfile(). We can replace the entire script we wrote previously with one line:
readfile(test.txt);
A call to the readfile() function opens the file, echoes the content to standard output (the browser), and
then closes the file. The prototype for readfile() is
int readfile(string filename, int [use_include_path]);
The optional second parameter specifies whether PHP should look for the file in the include_path.
The final way we can read from a file is using the fread() function to read an arbitrary number of bytes
from the file. This function has the following prototype:
string fread(int fp, int length);
The way it works is to read up to length bytes or to the end of file, whichever comes first.
Writing to a File
Writing to a file in PHP is relatively simple. You can use either of the functions fwrite() or fputs(); fputs()
is an alias to fwrite(). We call fwrite() in the following:
fwrite($fp, $outputstring);
This tells PHP to write the string stored in $outputstring to the file pointed to by $fp. Well discuss
fwrite() in more detail before we talk about the contents of $outputstring.
The function fwrite() actually takes three parameters but the third one is optional. The prototype for
fwrite() is:
int fwrite(int fp, string str, int [length]);
The third parameter, length, is the maximum number of bytes to write. If this parameter is supplied,
fwrite() will write string to the file pointed to by fp until it reaches the end of string or has written length
bytes, whichever comes first.
Example: write data to file
<?php
$fh = fopen(test.txt,a);
$data = This content is written to file \n;
$data = $data . This line is also written;
fwrite($fh, $data);
fclose($fh);
?>
177
The other way to write to file is to use fputs function. The syntax is:
Int fputs($fh, String str, [int length]);
This writes text to a file, an alias for fwrite. It returns the number of bytes written to the file or FALSE if
the function fails.
Seeking in File
The function fseek() can be used to set the file pointer to some point within the file. It moves the file
pointer, depending on the parameters. The syntax is:
fseek($fh, int offset, mode);
The value specified in offset is the character location to move the pointer to. You can set mode to:
SEEK_SET (moves to char in position offset),
SEEK_CUR (moves offset characters forward from current position), or
SEEK_END (moves offset characters back from the last character).
The rewind() function is equivalent to calling the fseek() function with an offset of zero. For example,
you can use fseek() to find the middle record in a file or to perform a binary search.
Getting information about files
Often you want to know information about a file. PHP has functions that allow you to find out file
information about the files from within a script.
You can find out whether a file exists with the file_exists statement, as follows:
$result = file_exists(filename);
After this statement, $result contains either TRUE or FALSE. The function is often used in a conditional
statement, such as the following:
if(!file_exists(stuff.txt))
{
echo File not found!\n;
}
Other functions are:
Function
is_file(stuff.txt)
What It Does
Output
is_dir(stuff.txt)
is_executable(do.txt)
TRUE or FALSE
is_writable(stuff.txt)
TRUE or FALSE
is_readable(stuff.txt)
TRUE or FALSE
filesize(stuff.txt)
Integer or FALSE
178
basename(/t1/do.txt)
do.txt
dirname(/t1/do.txt)
/t1
copy(oldfile, newfile)
TRUE or FALSE
rename(oldname,newname)
TRUE or FALSE
unlink(badfile.txt)
TRUE or FALSE
Example:
if(!file_exists(book.txt))
copy(book.txt, library.txt);
else
echo File already exists!\n;
Description
Seconds past the minute (059)
Minutes past the hour (059)
Hours of the day (023)
Day of the month (131)
Day of the week (06)
Month of the year (112)
Year (4 digits)
Example
28
7
12
20
4
1
2000
179
yday
weekday
month
0
19
Thursday
January
948370048
180
Example
pm
PM
20
Thu
January
12
12
12
12
i
j
l
L
m
M
n
s
S
r
Minutes
Day of the month (no leading zeroes)
Day of the week (name)
Leap year (1 for yes, 0 for no)
Month of year (numberleading zeroes)
Month of year (three letters)
Month of year (numberno leading zeroes)
Seconds of hour
Ordinal suffix for the day of the month
Full date standardized to RFC 822
U
y
Y
z
Z
Timestamp
Year (two digits)
Year (four digits)
Day of year (0365)
Offset in seconds from GMT
47
20
Thursday
1
09
Sep
9
24
th
Mon, 15 Sep 2003
08:25:55 -0700
1063639555
00
2003
257
0
Example:
<html>
<head>
<title>Formatting a date with date()</title>
</head>
<body>
<?php
$time = time(); //stores the exact timestamp to use in this script
echo date("m/d/y G.i:s", $time);
echo "<br> Today is ";
echo date("j \of F Y, \a\\t g.i a", $time);
?>
</body>
</html>
Output:
11/29/11 11.26:53
Today is 29 of November 2011, at 11.26 am
You can get information about the current time, but you cannot yet work with arbitrary dates. mktime()
returns a timestamp that you can then use with date() or getdate(). mktime() accepts up to six integer
arguments in the following order: Hour, Minute, Seconds, Month, Day of month, Year. The format is
$importantDate = mktime(hour, minute, seconds, month, date, year);
For example, you would store the date January 15, 2003, by using the following statement:
$birthdate = mktime(0, 0, 0, 1, 15, 2010);
181
Example:
<?php
// make a timestamp for Aug 23 2003 at 4.15 am
$ts = mktime(4, 15, 0, 8, 23, 2003);
echo date("m/d/y G.i:s", $ts);
echo "<br>";
echo "The date is ";
echo date("j of F Y, \a\\t g.i a", $ts );
?>
Output:
08/23/03 4.15:00
Practice 6.7
1. Write a program that accepts comments from users using HTML form and save it in a file on the
server.
2. Write a program that reads contents of a file and display in your web page.
3. Write a program that declares a class called car that has car related attributes like speed,
consumption, etc. It should also have a method called calculatePetrolLeft() that calculates the
amount petrol left after driving for hours. This depends on consumption pers second which is
constatnt. Also add a method called timeTaken() that calculates how long it would take to drive
the given distance in kilometers. e.g. how long to cover 330Km distance given contant speed.
182
183
mktime: This function returns a date and time in a format that the computer can understand.
You must provide the desired date and time in the following order: hour, minute, second,
month, day, and year. If any value is not included, the current value is used. You use the mktime
function to set the expiration time of the cookie
This is shown in the following statements:
setcookie(state,CA,mktime(3,0,0,4,1,2003)); #expires at 3:00 AM on April 1, 2003
setcookie(state,CA,mktime(13,0,0,,,)); #expires at 1:00 PM today
Deleting a Cookie
Officially, to delete a cookie, you should call setcookie() with the name argument only:
setcookie("vegetable");
This approach does not always work well, and hence should not be relied on.
It is safest to set the cookie with a date you are sure has already expired:
setcookie("vegetable", "", time()-60);
3.3.2 Session
A session is the time that a user spends at your Web site. Users may view many Web pages between the
time they enter your site and leave it. Often you want information to be available for a complete
session. Beginning with version 4.0, PHP provides a way to do this.
Understanding how PHP sessions work PHP allows you to set up a session and store session variables.
After you create a session, the session variables are available for your use on any other Web page. To
make session information available, PHP does the following:
1. PHP assigns a session ID number.
The number is a really long nonsense number that is unique for the user and that no one could
possibly guess. The session ID is stored in a PHP system variable named PHPSESSID.
2. PHP stores the variables that you want saved for the session in a file on the server.
The file is named with the session ID number. Its stored in a directory specified by
session.save_path in the php.ini file. The session directory must exist before session files can be
saved in it.
3. PHP passes the session ID number to every page.
If the user has cookies turned on, PHP passes the session ID by using cookies. If the user has cookies
turned off, PHP behavior depends on whether trans-sid is turned on in php.ini.
4. PHP gets the variables from the session file for each new session page.
Whenever a user opens a new page that is part of the session, PHP gets the variables from the file
by using the session ID number that was passed from the previous page. The variables are available
in the $_SESSION array.
184
185
Mathematical Functions
PHP has built-in mathematical constants, and trigonometric, logarithmic, and base conversion functions.
PHP constants are:
Constant
M_PI
M_PI_2
M_PI_4
M_1_PI
M_2_PI
M_2_SQRTPI
Description
Pi
pi/2
pi/4
1/pi
2/pi
2/sqrt(pi)
Constant
M_SQRT2
M_SQRT1_2
M_LOG2E
M_LOG10E
M_LN2
M_LN10
186
Description
sqrt(2)
1/sqrt(2)
log2(e)
log10(e)
loge(2)
loge(10)
M_E
the constant e
187
numberdigits higher than 9 (from 10 to 35) are represented by the letters az. Both
the original and desired bases must be in the range 236.
Example:
function display_bases($val, $first_base)
{
for ($new_base = 2; $new_base <= 9; $new_base++)
{
$converted = base_convert($val, $first_base, $new_base);
print($val in base $first_base is $converted in base $new_base<BR>);
}
}
display_bases(150, 10);
Output:
150 in base 10 is 10010110 in base 2
150 in base 10 is 12120 in base 3
150 in base 10 is 2112 in base 4
150 in base 10 is 1100 in base 5
150 in base 10 is 410 in base 6
150 in base 10 is 303 in base 7
150 in base 10 is 226 in base 8
150 in base 10 is 176 in base 9
floor(), ceil(), and round() convert doubles to integers, min() and max() take the minimum and maximum
of their numerical arguments, and abs() is the absolute value function.
Practice 6.8
1. Write a PHP code that uses session to store the persons who logged into your web page. It
should store user name and password of the person logged in.
2. Can you handle log out? It is done by removing the session. Allow users to log out.
188
189
190
here.
</applet>
191
192
The paint() method is called after the init method has completed and after the start() method has begun
most importantly, code in the paint() method is guaranteed to run each time the window needs to be
re-drawn i.e. after the browser has been minimized, covered, the HTML page has changed, etc.
The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics
context, which describes the graphics environment in which the applet is running. This context is used
whenever output to the applet is required.
The structure of paint method is:
public void paint(Graphics g)
{
//code
}
The code in the paint() method is used to draw the window that will be displayed in the Web Browser. To
do that we use the drawString() method of the Graphics object, supplying the text that we wish to
appear in the window and it's dimensions.
g.drawString("I love Java", 20, 20);
The stop( ) method is called when a web browser leaves the HTML document containing the applet
when it goes to another page, for example. When stop( ) is called, the applet is probably running. You
should use stop( ) to suspend threads that dont need to run when the applet is not visible. You can
restart them when start( ) is called if the user returns to the page.
The destroy( ) method is called when the environment determines that your applet needs to be
removed completely from memory. At this point, you should free up any resources the applet may be
using. The stop( ) method is always called before destroy( ).
// An Applet skeleton.
import java.awt.*;
import java.applet.*;
public class AppletSkel extends Applet
{
public void init() {
// initialization
}
public void start() {
// start or resume execution
}
public void stop() {
// suspends execution
}
public void destroy() {
// perform shutdown activities
}
public void paint(Graphics g) {
// redisplay contents of window
193
}
}
Example: A simple applet that sets the foreground and background colors and outputs a string
import java.awt.*;
import java.applet.*;
public class Sample extends Applet
{
String msg;
//set the foreground and background colors.
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
msg = "Inside init( ) --";
}
// Initialize the string to be displayed.
public void start()
{
msg += " Inside start( ) --";
}
// Display msg in applet window.
public void paint(Graphics g)
{
msg += " Inside paint( ).";
g.drawString(msg, 10, 30);
}
}
Color.pink
Color.darkGray
Color.red
Color.gray
Color.white
Color.green
Color.yellow
Color.lightGray
There are many more methods in Graphics classs of the paint() method:
void drawArc(int x, int y, int width, int height, int degreesstart,int degreesend)
194
195
Creating GUI
GUI can be created in two different ways: using AWT or swing. Swing is the latest technology in Java GUI
development and is recommended than AWT.
Swing supplies the following UI components (the class that implements each component is listed in
parentheses):
Buttons (javax.swing.JButton)
Checkboxes (javax.swing.JCheckBox)
Single-line text fields (javax.swing.JTextField)
Larger text display and editing areas (javax.swing.JTextArea)
Labels (javax.swing.JLabel)
Lists (javax.swing.JList)
Pop-ups (javax.swing.Popup)
Scrollbars (javax.swing.JScrollBar)
Sliders (javax.swing.JSlider)
Drawing areas (java.awt.Canvas)
Menus (javax.swing.JMenu,javax.swing.JMenuBar javax.swing.JMenuItem,
javax.swing.JCheckBoxMenuItem)
Containers (javax.swing.JPanel, javax.swing.JWindow and its subclasses)
196
GUI components are built as objects in Java. Hence, to create instance of them, we use the new
keyword. To include GUI components in applet, you have to define them first, then instantiate with new
keyword, and finally add to applet.
For example, button can be created like this:
JButton bok; //define Button
bok = new Jbutton(); //instantitate button
add(bok); //add button to Applet
For text boxes:
JTextField tname = new JTextField(15);
add(tname);
GUI components have properties and methods through which you can control and use them. For
example, a JTextField has getText() and setText() methods to read content of the text box, or set the
content.
Because the JApplet class inherits from the AWT Container class, it's easy to add components to applets
and to use layout managers to control the components' onscreen positions. Here are some of the
Container methods an applet can use:
add(componentname) - Adds the specified Component to applet.
remove(componentname) - Removes the specified Component.
setLayout(layoutname) - Sets the layout manager.
Example: a simple applet GUI
import javax.swing.*;
import java.applet.*;
public class SwingGUIExample extends JApplet
{
JButton okButton;
// A Button to click
JTextField nameField;
// A textField to get text input
ButtonGroup radioGroup; //A group of radio buttons
JRadioButton radio1;
JRadioButton radio2;
JCheckBox option;
//An independant check box
public void init()
{
setLayout(null);
//Tell the applet not to use a layout manager.
okButton = new JButton("A button");
//initialze the button and give it a text.
nameField = new JTextField("A TextField", 100); //text and length of the field
radioGroup = new ButtonGroup();
//initialize the radio buttons group
radio1 = new JRadioButton("Happy", true);
197
//Specify position of GUI components by specifying the x and y coordinate and width and height.
okButton.setBounds(20,
Bounds(20, 20, 100, 30);
nameField.setBounds(20, 70, 100, 40);
radio1.setBounds(20, 120, 100, 30);
radio2.setBounds(140, 120,100, 30);
option.setBounds(20, 170, 100, 30);
add(okButton);
add(nameField);
add(radio1);
add(radio2);
add(option);
}
}
This produces a GUI that looks like the following:
Example: a program that accepts two numbers and adds them together when button is clicked
import javax.swing.JApplet.*;
import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Adder extends Applet implements ActionListener
{
JButton add, clear;
JTextField fnum, snum, result;
JLabel first, second, third;
double outcome = 0;
198
199
200
Using applet, you can create photo album that you can navigate through using buttons.
//file: PhotoAlbum.java
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;
public class PhotoAlbum extends Applet implements ActionListener
{
//create buttons and picture display area
JButton previous = new JButton("Previous"), first = new JButton("First");
JButton last = new JButton("Last"), next = new JButton("Next");
Canvas imageCanvas = new Canvas();
final int total = 6;
int i = 0;
// total no of images
// this is value of currently displayed image
201
if (i <= -1)
i = total - 1;
displayImage(i);
}
public void drawNext()
{
i = i + 1;
if (i == total)
i = 0;
displayImage(i);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == previous)
drawPrevious();
else if (e.getSource() == first)
drawFirst();
else if (e.getSource() == last)
drawLast();
else if (e.getSource() == next)
drawNext();
}
public void paint(Graphics g)
{
drawFirst();
i = 0;
}
private void makeGUI()
{
setBackground(Color.black);
setForeground(Color.white);
setLayout(new BorderLayout());
Panel p1 = new Panel();
p1.add(previous);
p1.add(first);
p1.add(next);
p1.add(last);
add(BorderLayout.NORTH, p1);
add(BorderLayout.CENTER, imageCanvas);
previous.addActionListener(this);
first.addActionListener(this);
last.addActionListener(this);
next.addActionListener(this);
}
}
202
The HTML that contains the above photo album applet is as follows:
<html>
<head>
<title>Photo Album in Java Applets </title>
</head>
<body>
Enjoy our photo album. <br>
<applet code="PhotoAlbum.class" width=600 height=500> </applet>
</body>
</html>
Playing Audio
AudioClip is an interface for playing audio file. It has methods that help you load and play audio files. To
load audio, we use getAudioClip() method.
AudioClip getAudioClip(URL url) - returns an AudioClip object that encapsulates the audio clip found at
the location specified by url.
The AudioClip interface has the following methods that enable you to control the play of the audio:
void loop(); //repeatedly plays the audio when it finishes
void play(); //palys the audio
void stop(); //stop playing audio
After you have loaded an audio clip using getAudioClip( ), you can use these methods to play it.
Example
AudioClip onceClip;
onceClip = applet.getAudioClip(getCodeBase(), "train.au");
onceClip.play(); //Play it once.
onceClip.stop(); //Stop the sound.
Since an applet that continues to make noise after you've left its page could be annoying, you can make
the applet stop playing the continuously looping sound when the user leaves the page, and resumes
playing it when the user comes back. It does this by implementing its stop and start methods as follows:
public void stop()
{
if (playing) {
onceClip.stop(); //stop the sound
}
}
public void start()
{
203
if (!playing) {
onceClip.play(); //play the sound
}
}
Example: an applet that plays sound/audio
//file: Player.java
import javax.swing.*;
import java.applet.*;
import java.awt.event.*;
public class Player extends Applet implements ActionListener
{
JButton play, stop, loop;
AudioClip mySong;
public void init()
{
play = new JButton("Play");
add(play);
play.addActionListener(this);
stop = new JButton("Stop");
add(stop);
stop.addActionListener(this);
loop = new JButton("Loop");
add(loop);
loop.addActionListener(this);
// Load the audio file
mySong = getAudioClip(getDocumentBase(), "Songs/song.au");
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == play)
mySong.play();
if (e.getSource() == stop)
mySong.stop();
if (e.getSource() == loop)
mySong.loop();
}
}
You can also play sound/audio using the paly method:
void play(URL url) - If an audio clip is found at the location specified by url, the clip is played.
204
void play(URL url, String clipName) - If an audio clip is found at the location specified by url with
the name specified by clipName, the clip is played.
205
Because there are no predefined tags in XML, you, the author, can create the tags that you need. Do you
need a tag for price? Do you need a tag for a bold hyperlink that floats on the right side of the screen?
Then make them:
<price currency=usd>499.00</price>
<toc xlink:href=/newsletter>Pineapplesoft Link</toc>
HTML has a very forgiving syntax. This is great for authors who can be as lazy as they want, but it also
makes Web browsers more complex. According to some estimates, more than 50% of the code in a
browser handles errors or sloppiness on the authors part. Hence, it was decided that XML would adopt
a very strict syntax. A strict syntax results in smaller, faster, and lighter browsers.
When creating an XML document, you must begin with the XML declaration statement. This statement
alerts the browser or other processing tools that this document contains XML tags. The declaration looks
like this:
<?xml version=1.0?>
This is the first line of your document.
Java Servlet
In the early days of the Web, a server could dynamically construct a page by creating a separate process
to handle each client request. The process would open connections to one or more databases in order
to obtain the necessary information. It communicated with the Web server via the Common Gateway
Interface (CGI).
CGI allowed the separate process to read data from the HTTP request and write data to the HTTP
response. However, CGI suffered serious performance problems. It was expensive in terms of processor
and memory resources to create a separate process for each client request. It was also expensive to
open and close database connections for each client request. In addition, the CGI programs were not
platform-independent. Therefore, other techniques were introduced, among these are servlets.
Servlets offer several advantages in comparison with CGI. First, performance is significantly better.
Servlets execute within the address space of a Web server. It is not necessary to create a separate
process to handle each client request. Second, servlets are platform-independent because they are
written in Java. A number of Web servers from different vendors offer the Servlet API. Programs
206
developed for this API can be moved to any of these environments without recompilation. Third, the
Java security manager on the server enforces a set of restrictions to protect the resources on a server.
Servlets are programs that run on a Web server or application server and act as a middle layer between
a request coming from a Web browser or other HTTP client and databases or applications on the HTTP
server.
207
response data involves telling the browser or other client what type of document is being returned (e.g.,
HTML), setting cookies and caching parameters, and other such tasks.
Because servlets are written in the Java programming language, they have access to the full set of Java
APIs. This makes them ideal for implementing complex business application logic and especially for
accessing data in the enterprise. The Java Database Connectivity (JDBC) API, which allows Java programs
to access relational databases , is one example. Because there are no graphics associated with servlets,
access to the GUI Java APIs (the AWT) is not relevant.
Writing Servlets
The Java Servlet API is a set of classes that define a standard interface between a Web client and a Web
servlet. In essence, the API encases requests as objects so the server can pass them to the servlet; the
responses are similarly encapsulated so the server can pass them back to a client.
The Java Servlet API has two packages. javax.servlet contains classes to support generic protocolindependent servlets, and javax.servlet.http includes specific support for the HTTP protocol.
The Servlet interface class is the central abstraction of the Java Servlet API. This class defines the
methods that manage the servlet and its communications with clients.
To write an HTTP servlet for use on the Web, use the HttpServlet class.
A client request to a servlet is represented by an HttpServletRequest object. This object
encapsulates the communication from the client to the server. It can contain information about
the client environment and any data to be sent to the servlet from the client.
The response from the servlet back to the client is represented by an HttpServletResponse
object. This is often the dynamically generated response, such as an HTML page, and is built
with data from the request and from other sources accessed by the servlet.
Most servlets need access to at least three packages javax.servlet, javax.servlet.http, and java.io. As a
result, you usually start with these import statements:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Depending on what other processing your servlet does, you may need additional import statements.
Get request is made when you do not specify form submission METHOD or specifies METHOD="GET".
Servlets can also handle POST requests, which are generated when someone submits an HTML form that
specifies METHOD="POST". HTTP POST request is handled by doPost() method, whereas GET requests
are handled by doGet().
Example: Hello world servlet
208
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
Both doGet and doPost take two arguments: an HttpServletRequest and an HttpServletResponse. The
HttpServletRequest lets you get all of the incoming data. This class has methods by which you can find
out about information such as form data, HTTP request headers, and the clients hostname. The
HttpServletResponse lets you specify outgoing information such as HTTP status codes and response
headers (Content-Type, Set-Cookie, etc.).
Most importantly, HttpServletResponse lets you obtain a PrintWriter that you use to send document
content back to the client. For simple servlets, most of the effort is spent in println statements that
generate the desired page.
Both doGet and doPost throw two exceptions: ServletException and IOException. Hence, you are
required to include them in the method declaration. You must import classes in java.io for PrintWriter,
javax.servlet for HttpServlet, and javax.servlet.http for HttpServletRequest and HttpServletResponse.
209
I.
Suppose you want to perform complex setup tasks when the servlet is first loaded, but not repeat those
tasks for each request. The init method is designed for this case; it is called when the servlet is first
created, and not called again for each user request. So, it is used for one-time initializations. The servlet
is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify
that the servlet be loaded when the server is first started.
When the servlet is first created, its init method is invoked, so init is where you put one-time setup code.
The init method definition looks like this:
public void init() throws ServletException
{
// Initialization code...
}
II.
Each time the server receives a request for a servlet, the server spawns a new thread and calls service
method. The service method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls
doGet, doPost, doPut, doDelete, etc., as appropriate. A GET request results from a normal request for a
URL or from an HTML form that has no METHOD specified. A POST request results from an HTML form
that specifically lists POST as the METHOD. Other HTTP requests are generated only by custom clients.
Multiple concurrent requests normally result in multiple threads calling service simultaneously, although
your servlet can implement a special interface (SingleThreadModel) that stipulates that only a single
thread is permitted to run at any one time. The service method then calls doGet, doPost, or another
doXxx method, depending on the type of HTTP request it received.
210
III.
The destruction phase of the Servlet life cycle represents when a Servlet is being removed from use by a
container. The Servlet interface defines the destroy() method to correspond to the destruction life cycle
phase. Each time a Servlet is about to be removed from use, a container calls the destroy() method,
allowing the Servlet to gracefully terminate and tidy up any resources it might have created.
public void destroy()
{
//releasing resources
}
During initialization a Servlet loads everything it needs to use for servicing requests. The resources are
then readily used during the service phase and can then be cleaned up in the destruction phase.
The general skeleton of servlets looks like this:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Database extends HttpServlet
{
public void init()
{
//code for initialization
}
public void destroy()
{
//code for releasing resource
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//process GET request
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//process POST request
211
}
}
212
II.
HttpServletRequest
213
request.getAuthType()
CONTENT_LENGTH
request.getContentLength()
CONTENT_TYPE
request.getContentType()
DOCUMENT_ROOT
getServletContext().getRealPath("/")
HTTP_XXX_YYY
request.getHeader("Xxx-Yyy")
PATH_INFO
request.getPathInfo()
PATH_TRANSLATED
request.getPathTranslated()
QUERY_STRING
request.getQueryString()
REMOTE_ADDR
request.getRemoteAddr()
REMOTE_HOST
request.getRemoteHost()
REMOTE_USER
request.getRemoteUser()
REQUEST_METHOD
request.getMethod()
SCRIPT_NAME
request.getServletPath()
SERVER_NAME
request.getServerName()
SERVER_PORT
request.getServerPort()
SERVER_PROTOCOL
request.getProtocol()
SERVER_SOFTWARE
getServletContext().getServerInfo()
214
One of the nice features of servlets is that all the form data parsing is handled automatically. You simply
call the getParameter method of HttpServletRequest, supplying the parameter name as an argument.
You use getParameter exactly the same way when the data is sent by GET or by POST.
The servlet knows which request method was used and automatically does the right thing behind the
scenes. The return value is a String corresponding to the URL-decoded value of the first occurrence of
that parameter name. An empty String is returned if the parameter exists but has no value, and null is
returned if there is no such parameter in the request.
The general syntax is:
String request.getParameter(form input field name);
215
Parameter names are case sensitive. Hence, for example, request.getParameter("Param1") and
request.getParameter("param1") are not interchangeable.
Technically, it is legal for a single HTML form to use the same form element name twice, and in fact this
situation really occurs when you use SELECT elements that allow multiple selections. If the parameter
could potentially have more than one value, you should call getParameterValues which returns an array
of strings. The return value of getParameterValues is null for nonexistent parameter names and is a oneelement array when the parameter has only a single value.
Example: HTML form
<HTML>
<HEAD>
<TITLE>Adding Two Numbers</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">Collecting Three Parameters</H1>
<FORM method=POST ACTION="/servlet/adder">
First number: <INPUT TYPE="TEXT" NAME="fnum"><BR>
Second number: <INPUT TYPE="TEXT" NAME="snum"><BR>
<CENTER><INPUT TYPE="SUBMIT"></CENTER>
</FORM>
</BODY>
</HTML>
// Simple servlet that reads two numbers from the form data.
package moreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ThreeParams extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Three Request Parameters";
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
216
}
}
217
doGet is called by the server to allow a servlet to handle a GET request; doPost to handle a POST
request. The service method receives standard HTTP requests from the public service method and
dispatches them to the doXXX methods defined in the class.
doGet() method is called by the servlet engine to process an HTTP GET request. Input parameters, HTTP
headers, and the input data (if any) can be obtained from the request object, and response headers and
the output stream from the response object.
void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {}
doPost() method is called by the servlet engine to process an HTTP POST request. No different from
doGet() from the standpoint of obtaining parameters and input data or returning the response.
void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
doPut() method is called by the servlet engine to process an HTTP PUT request. The request URI in this
case indicates the destination of the file being uploaded.
void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
doPut() is called by the servlet engine to process an HTTP PUT request. The request URI in this case
indicates the destination of the file being uploaded.
void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
doDelete() is called by the servlet engine to process an HTTP DELETE request. The request URI indicates
the resource to be deleted.
void doDelete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
Example: handling HTTP POST requests
<html>
<body>
<center>
<form name="colorchoice" method="post" action=" ColorPostServlet">
<B>Color:</B>
<select name="color" size="1">
218
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
Servlet to process color choice by user
//file: ColorPostServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
Accessing Database
Before you can use JDBC to access a database, you must first establish a connection to the database. The
first step to establishing a connection involves registering the driver class so the class is available. To do
that, you use the forName method of the Class class, specifying the package and class name of the
driver.
For example, to register the MySQL connector, use this statement:
Class.forName(com.mysql.jdbc.Driver);
To register the standard ODBC driver, use this statement instead:
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
219
Note that the forName method throws ClassNotFoundException, so you have to enclose this statement
in a try/catch block that catches ClassNotFoundException.
For a JDBC driver to be used, it must first be registered with the driver manager. You can accomplish this
in several ways, but each involves calling DriverManager.registerDriver(). The most common approach
is simply to load the driver class:
try {
Class.forName("MyJdbcDriver");
}
catch (ClassNotFoundException e) {
// Report the exception
}
A driver class loaded in this fashion should create an instance of itself and register it with the driver
manager.
To use the JDBC-ODBC bridge in a Java application, a suitable ODBC data source must be configured. The
data source should be configured as a System DSN, not a User DSN. The driver class name is
sun.jdbc.odbc.JdbcOdbcDriver if the Sun JVM is being used.
The database URL used in the getConnection() statement is jdbc:odbc:dsn, where dsn is the data source
name. Microsoft supplies ODBC drivers for its Access database product, as well as dBase, Excel, FoxPro,
and a number of others, including a text driver that can use ordinary text files (.txt and .csv) as a simple
database system.
Connecting to a Database
After you register the driver class, you can call the static getConnection method of the DriverManager
class to open the connection. This method takes three String parameters: the database URL, the user
name, and a password.
Heres an example:
String url = jdbc:mysql://localhost:3306/teaching;
String user = root;
String pw = pw;
con = DriverManager.getConnection(url, user, pw);
DriverManager provides three different methods to get connection:
DriverManager.getConnection(String url)
DriverManager.getConnection(String url, String userID, String password)
DriverManager.getConnection(String url, Properties prop)
Internally, DriverManager uses the same private worker method to handle each of these methods. The
driver manager maintains a list of registered drivers. When its getConnection() method is invoked, it
interrogates each driver in turn to see if it will accept the specified URL. The driver manager does this by
calling the drivers connect() method, which returns either null if the driver cannot accept the URL or an
active Connection object if it can.
220
The key argument to DriverManager.getConnection() is a JDBC URL, which is a string with three
components separated by semicolons:
<protocol>:<subprotocol>:<subname>
where
protocol is always jdbc.
subprotocol is a vendor-specific string that identifies the driver to be used. The driver indicates
whether it can handle that subprotocol when asked by the driver manager. For example, the
JDBC-ODBC bridge uses the reserved value odbc as its subprotocol. This value is intended to be
unique across all driver vendors. Sun Microsystems acts as an informal registrar of JDBC
subprotocols.
subname identifies the specific database to connect to. This string contains whatever the driver
needs to identify the database. It may also contain connection parameters the database needs.
Examples of JDBC URLs are
jdbc:odbc:finance
This would indicate an ODBC data source named finance that is accessed by the JDBC-ODBC bridge
driver.
You can also specify like this
jdbc:idb:c:/path/database.prp
Example: connecting to Mysql server
private static Connection getConnection()
{
Connection con = null;
try
{
Class.forName(com.mysql.jdbc.Driver);
String url = jdbc:mysql://localhost:3306/teaching;
String user = root;
String pw = servletprogramming;
con = DriverManager.getConnection(url, user, pw);
}
catch (ClassNotFoundException e)
{
System.out.println(e.getMessage());
System.exit(0);
}
catch (SQLException e)
{
System.out.println(e.getMessage());
System.exit(0);
}
return con;
}
221
Querying a Database
After you establish a connection to a database, you can execute select statements to retrieve data. To
do so, you have to use several classes and interfaces:
Connection: The Connection class has two methods youre likely to use. The close() method
closes the connection, and the createStatement() method returns a Statement object, which you
then use to execute statements.
Statement: The Statement interface contains the methods necessary to send statements to the
database for execution and return the results. In particular, you use the executeQuery() method
to execute a select statement or the executeUpdate() method to execute an insert, update, or
delete statement.
ResultSet: The ResultSet interface represents rows returned from a query. It provides methods
you can use to move from row to row and to get the data for a column.
Statement createStatement (int type, Creates a Statement object that can execute an SQL statement
int concur)
on the database connected by the connection.
Statement Interface Methods
ResultSet executeQuery(String sql)
int executeUpdate(String sql)
Description
Executes the select statement contained in the string
parameter and returns the result data as a ResultSet object.
Executes the insert, update, or delete statements contained in
the string parameter and returns the result data as a ResultSet
object.
ResultSet.TYPE_FORWARD_ONLY - The result set cannot be scrolled; its cursor moves forward
only, from before the first row to after the last row.
ResultSet.TYPE_SCROLL_INSENSITIVE - The result can be scrolled; its cursor can move both
forward and backward relative to the current position, and it can move to an absolute position.
The result set is insensitive to changes made to the underlying data source while it is open. It
contains the rows that satisfy the query at either the time the query is executed or as the rows
are retrieved.
ResultSet.TYPE_SCROLL_SENSITIVE - The result can be scrolled; its cursor can move both forward
and backward relative to the current position, and it can move to an absolute position. The
result set reflects changes made to the underlying data source while the result set remains open.
222
The second parameter is the concurrency of a ResultSet object. The concurrency of a ResultSet object
determines what level of update functionality is supported. This indicates whether the result set is readonly or updatable, and can be one of the following:
ResultSet.CONCUR_READ_ONLY
ResultSet.CONCUR_UPDATABLE
Executing a select statement
The following snippet executes a select statement and puts the result in Resultset:
Connection con = null;
try
{
Class.forName(com.mysql.jdbc.Driver);
String url = jdbc:mysql://localhost:3306/teaching;
String user = root;
String pw = dbconn;
con = DriverManager.getConnection(url, user, pw);
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
System.exit(0);
}
Statement st = con.createStatement();
String select = Select title, year, price from movie order by year;
ResultSet rows = st.executeQuery(select);
Here, the result set is stored in the rows variable.
Navigating through the result set
The ResultSet object returned by the executeQuery statement contains all the rows that are retrieved by
the select statement. You can only access one of those rows at a time. The result set maintains a pointer
called a cursor to keep track of the current row. You can use the following methods to move the cursor
through a result set.
Description
void close()
boolean next()
boolean previous()
boolean first()
void last()
223
void beforeFirst()
Moves the cursor to the front of this ResultSet object, just before the
first row.
void afterLast()
Moves the cursor to the end of the ResultSet object, just after the last
row
Moves the cursor to the given row number in this ResultSet object.
int getRow()
boolean isBeforeFirst()
boolean isAfterLast()
boolean isFirst()
boolean isLast()
telephone
Aroun Moken
Male
aroun@yahoo.com
786958475
Lalise Tola
Female
lal@gmail.com
998374655
..
Example: the following code shows how you can process each row in a result set:
Connection con = null;
Statement statement = null;
ResultSet records = null;
String sql;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:customers", "", "");
224
Method
Description
225
226
out.print("</table>");
records.close();
con.close();
out.print("</body> \n </html>");
}
catch(SQLException xx) {
out.print("Querying: " + xx.getMessage());
}
catch(Exception xx) {
out.print("Querying: " + xx.getMessage());
}
finally {
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return "Short description";
}
}
An HTML side that invokes the above Servlet
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h2 style="text-decoration: underline"> Database Access Using Servlet </h2>
<a href="Database">See Customer Table</a>
</body>
</html>
Updating Database
227
Description
void cancelRowUpdates()
Cancels the updates made to the current row in this ResultSet object.
void deleteRow()
Deletes the current row from this ResultSet object and from the
underlying database.
void insertRow()
Inserts the contents of the insert row into this ResultSet object and into
the database.
void moveToCurrentRow()
Moves the cursor to the remembered cursor position, usually the current
row.
void moveToInsertRow()
void refreshRow()
Refreshes the current row with its most recent value in the database.
void updateRow()
Updates the underlying database with the new contents of the current
row of this ResultSet object.
Deleting Rows
Example: deleting a row
try
{
rs.absolute(3);
rs.deleteRow();
}
catch (SQLException e)
{
out.println(e.getMessage());
}
Updating Rows
For a result set to be updated, it must have been produced by a Statement object created with a
concurrency type of ResultSet.CONCUR_UPDATABLE. JDBC provides updateXXX() methods, where XXX is
the JDBC data type, similar to the existing getXXX() methods. These methods take a column number or
column name parameter, and a value parameter.
The following example illustrates this:
double mySalary = rs.getDouble(SALARY);
mySalary *= 2.0;
rs.updateDouble(SALARY, mySalary);
rs.updateString(HOME_PHONE, unlisted);
rs.updateRow();
228
New rows can be added to the result set and the underlying table with insertRow(). This involves a
special cursor position known as the insert row. The following example illustrates how this works:
rs.moveToInsertRow();
rs.updateString(name, David Jacques);
rs.updateString(sex, Male);
rs.updateString(email, jacques@yahoo.com);
rs.updateInt(telephone, 8954578693567);
rs.insertRow();
rs.moveToCurrentRow(); // Return to where we were
Update Methods of the ResultSet Interface
Update by Column Name
The above update can be done by using SQL statements. Here is an example:
Class.forName(com.mysql.jdbc.Driver);
String url = jdbc:mysql://localhost:3306/teaching;
Connection con = DriverManager.getConnection(url, root, vertrigo);
try
{
Statement stmt = con.createStatement();
sql = insert into customers values(David Jacques, Male, jacques@yahoo.com, 8954578693567);
int i = stmt.executeUpdate(sql);
if (i == 1)
System.out.println(Loan recorded.);
else
System.out.println(Loan not recorded.);
}
catch (SQLException e)
{
System.out.println(e.getMessage());
System.exit(0);
}
229
Batch Updating
JDBC 2.0 introduced the capability to submit a group of update statements to be executed as a batch. In
some cases, this can represent a significant performance improvement. The methods used in connection
with batch updates are these:
clearBatch resets a batch to the empty state.
addBatch adds an update statement to the batch.
executeBatch submits the batch and collects update counts.
import java.io.*;
import java.sql.*;
import java.util.*;
public class TransactionExample
{
public void CreateTable() throws ClassNotFoundException, SQLException, IOException
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = null;
try
{
con = DriverManager.getConnection ("jdbc:odbc:teaching");
Statement stmt = con.createStatement();
stmt.executeUpdate(" CREATE TABLE Student (lastName VARCHAR(20), +
firstName VARCHAR(20), age INTEGER )");
// Set up for handling all-or-nothing transaction
con.setAutoCommit(false);
// Add insert statements to a batch
stmt.clearBatch();
stmt.addBatch("INSERT INTO Student VALUES ('Rodrigo','Joaquin',30)");
stmt.addBatch("INSERT INTO Student VALUES ('Gossec','Francois-Joseph',36)");
stmt.addBatch("INSERT INTO Student VALUES ('Ruggles','Carl',36)");
stmt.addBatch("INSERT INTO Student VALUES ('Widor','Charles,34)");
stmt.addBatch("INSERT INTO Student VALUES ('Sibelius','Jean',23)");
stmt.addBatch("INSERT INTO Student VALUES('Copland','Aaron',21)");
stmt.addBatch("INSERT INTO Student VALUES('Auber','Daniel Francois',30)");
stmt.addBatch("INSERT INTO Student VALUES('Stravinsky','Igor',40)");
// Execute the batch and check the update counts
int[] counts = stmt.executeBatch();
boolean allGood = true;
for (int i = 0; i < counts.length; i++)
if (counts[i] != 1)
allGood = false;
230
Using Cookies
Cookies can be created using the Cookie class. Create a cookie using the Cookie constructor with two
parameters: a name and a value. The value parameter represents the information that you want to
store. This value may include the users name or any arbitrary string value. To create a cookie, put the
following in your servlet:
Cookie myCookie = new Cookie("Cookiename", "value");
The cookie is added to the Set-Cookie response header by means of the addCookie method of
HttpServletResponse. Here's an example:
Cookie userCookie = new Cookie("user", "uid1234");
response.addCookie(userCookie);
The values stored in cookies can only be strings. Therefore, you should text-encode all data that you
store in a cookie. Once you add a cookie to your response object, WebLogic Server automatically places
it in the client browser. The client browser stores the cookie to the local computer disk for future
requests.
When WebLogic Server invokes a servlet, the cookies sent by the browser are included in the
HttpServletRequest object. These cookies are retrieved as an array of cookie objects using the following
code:
Cookie[] cookies = request.getCookies();
231
Once you have the cookie objects, you can search for your specific cookie. You can use the getName()
method to look at each cookies name:
// assign the name of the first cookie in the array to string foo
String foo = Cookies[0].getName();
If the users browser does not accept cookies it does not include cookies in subsequent requests. In this
case, the result of request.getCookies() returns null (or an array without the cookie you added). In
general, the servlet author has no way to determine in advance whether a particular client will accept
cookies.
You can manipulate all aspects of a cookie using familiar Java methods. The Cookie object has the
following methods:
getComment(): The getComment() method returns the comment describing the purpose of this
cookie, or null if the cookie has no comment.
setComment(String purpose): The setComment() method is used to specify a comment that
describes a cookies purpose.
getMaxAge(): The getMaxAge() method returns an int value representing the maximum age of
the cookie, specified in seconds.A value of 1 indicates the cookie will persist until browser
shutdown.
setMaxAge(int expiry): The setMaxAge() method sets the maximum age of the cookie in
seconds.
getName(): The getName() method returns a String object representing the name of the cookie.
setName(String name): sets the name of the cookie. The name and the value are the two things
you always care about in cookies. Since the getCookies method of HttpServletRequest returns an
array of Cookie objects, it is common to loop down this array until you have a particular name,
then check the value with getValue.
getSecure(): The getSecure() method returns a boolean value that is true if the browser is
sending cookies only over a secure protocol, or false if the browser can send cookies using any
protocol. HTTP is an insecure protocol. Secure protocols such as SSL and TLS.
setSecure(boolean flag): Indicates to the browser whether the cookie should only be sent using
a secure protocol, such as HTTPS or SSL.
getValue(): The getValue() method returns a String object representing the value of the cookie.
setValue(String newValue): The setValue() method assigns a new value to a cookie after the
cookie is created. The default value of a cookie is specified when calling the constructor.
setDomain(String pattern): The setDomain() method specifies the domain within which this
cookie should be presented.
Example: using cookie
<html>
<body>
<center>
<form name="cookie" method="post" action=" AddCookieServlet">
232
233
{
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++)
{
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name + ", value = " + value);
}
pw.close();
}
}
Using Sessions
A servlet indicates it wants to use a session by calling the getSession() or getSession(boolean create)
methods in HttpServletRequest, as shown here:
HttpSession session = request.getSession(true);
The servlet specification defines four methods that you can use to access the values in the HttpSession
object:
Object getAttribute (String name)Returns the object bound with the specified name in this
session, or null if no object is bound under the name.
void setAttribute (String name, Object attribute)Binds an object to this session using the
name specified.
Enumeration getAttributeNames()Returns an Enumeration of string objects containing the
names of all the objects bound to this session.
void removeAttribute(String name)Removes the object bound with the specified name from
this session.
Here is a summary of important methods available through HttpSession object:
Method
Description
getAttribute(String name)
Enumeration getAttributeNames()
long getCreationTime()
String getId()
234
long getLastAccessedTime()
int getMaxInactiveInterval()
void invalidate()
boolean isNew()
void setMaxInactiveInterval(int
interval)
Example:
HttpSession session = request.getSession (true);
// check to see if the session is new
if (session.isNew()) {
//we send a redirect to login page
responseObj.sendRedirect("http://www.learnweblogic.com/login");
}
Use sessions to mark login status. Create a new session only on login and look for a session to confirm
login status. When the user logs out, invalidate the session. Use filters to apply security checks
consistently throughout your Web application.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Session extends HttpServlet
{
int cntr;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
HttpSession session = req.getSession(true);
res.setContentType("text/html");
235
236
URL rewriting requires that the servlet call an encoding method in the servlet response object for URLs
in the generated HTML page. For URL rewriting to work reliably, all servlets in a Web application must
use rewriting on all URLs. The methods to rewrite URLs take two forms:
String encodeURL(String url)Includes the logic required to encode the session information in
the returned URL. WebLogic Server automatically determines whether the session ID needs to
be encoded in the URL. If the browser supports cookies, or if session tracking is turned off, URL
encoding is unnecessary. To encode the URL, add the following code to your servlet:
//Add the Session Information Via URL Encoding
myHttpServletResponse.encodeURL(thisURL);
So, if your original URL was
<a href="foo.jsp">bar</a>
you would use the encodeURL() method on that URL:
out.println("<a href=\"" +response.encodeURL("foo.jsp">) + "\">bar</a>");
String encodeRedirectURL(String url)Performs the same task as the previous method, except
it is specially geared to redirects in the response object. For redirection, you should have the
following in your servlet:
// Sending a Redirect with URL Encoded session ID
response.sendRedirect(response.encodeRedirectUrl(anotherURL);
237
238
include
taglib
239
240
241
Scriptlets
Scriptlets provide a method for directly inserting bits of Java code between chunks of template text. A
scriptlet is defined with a start, <%, an end, %>, with code between. Using Java, the script is identical to
normal Java code but without needing a class declaration or any methods. Scriptlets are great for
providing lowlevel functionality such as iteration, loops, and conditional statements, but they also
provide a method for embedding complex chunks of code within a JSP.
The syntax for scriptlet is:
<%
code goes here
%>
Example: loop.jsp
<html>
<head>
<title>Loop Example</title>
</head>
<body>
<% for (int i=0; i<5; i++) { %>
Repeated 5 Times.<br>
<% } %>
</body>
</html>
Comments
The JSP specification provides two means of including comments in a JSP page: one for hidden
comments only visible in the JSP page itself and one for comments included in the HTML or XML output
generated by the page. The syntax is:
<%- - This is a hidden JSP comment - -%>
When the JSP compiler encounters the start tag <%- - of a JSP comment, it ignores everything from that
point in the file until it finds the matching end tag - -%>.
The other comment type uses the normal HTML or XML comment tag. Comments of this type are passed
through unaltered to the response output stream and are included in the generated HTML. They are
invisible in the browser window, but can be seen by invoking the View Source menu option.
<!- - This is included in the generated HTML - ->
Expressions
JSP provides a simple means for accessing the value of a Java variable or other expression and merging
that value with the HTML in the page. The syntax is
<%= exp %>
where exp is any valid Java expression.
The expression can have any data value, as long as it can be converted to a string. This conversion is
usually done simply by generating an out.print() statement. For example, the JSP code:
The current time is <%= new java.util.Date() %>
242
Declarations
Like scriptlets, declarations contain Java language statements, but with one big difference: scriptlet code
becomes part of the _jspService() method, whereas declaration code is incorporated into the generated
source file outside the _jspService() method.
This tag allows the developer to declare variables or methods. Code placed in this tag must end with
semicolon (;). Declarations do not generate output, they are used with JSP expressions or scriptlets.
The syntax of a declaration section is
<%!
statement;
[statement; ...]
%>
Declaration sections can be used to declare class or instance variables, methods, or inner classes. Unlike
scriptlets, they have no access to the implicit objects described in the next section. If you use a
declaration section to declare a method that needs to use the request object, for example, you need to
pass the object as a parameter to the method.
<%!
int pageCount = 0;
void addCount() {
pageCount++;
}
243
%>
Example: using JSP scripting elements and directives
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h3><u>Checking Java Server Pages</u> <br> </h3>
<form name="info" action="ServerInfo.jsp" method="get">
Name: <input type="text" name="name"> <br><br>
Country: <input type="text" name="country"> <br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
//file: ServerInfo.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<HTML>
<HEAD>
<TITLE>Using Java Server Pages</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E0" TEXT="#000000" LINK="#0000EE" VLINK="#551A8B" ALINK="#FF0000">
<H3 style="text-decoration: underline"> Using Java Server Pages </H3>
Some dynamic content created using various JSP mechanisms:
<UL>
<LI><B>Expression.</B><BR>
Your host name: <%= request.getRemoteHost() %>.
<LI><B>Scriptlet.</B><BR>
<% out.println("Attached GET data: " + request.getQueryString()); %>
<LI><B>Declaration (plus expression).</B><BR>
<%! private int accessCount = 0; %>
Accesses to page since server reboot: <%= ++accessCount %>
<LI><B>Directive (plus expression).</B><BR>
<%@ page import = "java.util.*" %>
Current date: <%= new Date() %>
</UL>
</BODY>
</HTML>
244
Predefined Variables
To simplify code in JSP expressions and scriptlets, you are supplied with eight automatically defined
variables, sometimes called implicit objects. The available variables are request, response, out, session,
application, config, pageContext, and page.
I. request
This is the HttpServletRequest associated with the request, and lets you look at the request parameters
via getParameter, the request type (GET, POST, HEAD, etc.), and the incoming HTTP headers (cookies,
Referer, etc.). Strictly speaking, request is allowed to be a subclass of ServletRequest other than
HttpServletRequest, if the protocol in the request is something other than HTTP. This is almost never
done in practice.
II. response
This is the HttpServletResponse associated with the response to the client. Note that, since the output
stream is buffered, it is legal to set HTTP status codes and response headers, even though this is not
permitted in regular servlets once any output has been sent to the client.
III. out
This is the PrintWriter used to send output to the client. However, in order to make the response object
useful, this is a buffered version of PrintWriter called JspWriter. Note that you can adjust the buffer size,
or even turn buffering off, through use of the buffer attribute of the page directive. Also note that out is
used almost exclusively in scriptlets, since JSP expressions automatically get placed in the output stream,
and thus rarely need to refer to out explicitly.
IV. session
This is the HttpSession object associated with the request. Recall that sessions are created automatically,
so this variable is bound even if there was no incoming session reference. The one exception is if you use
the session attribute of the page directive to turn sessions off, in which case attempts to reference the
session variable cause errors at the time the JSP page is translated into a servlet.
V. application
245
VI. config
This is the ServletConfig object for this page.
VII. pageContext
JSP introduced a new class called PageContext to encapsulate use of server-specific features like higher
performance JspWriters. The idea is that, if you access them through this class rather than directly, your
code will still run on "regular" servlet/JSP engines.
VIII. page
This is simply a synonym for this, and is not very useful in Java. It was created as a placeholder for the
time when the scripting language could be something other than Java.
Actions
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can
dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate
HTML for the Java plugin. Available actions include:
jsp:include - include a file at the time the page is requested.
jsp:useBean - find or instantiate a JavaBean.
jsp:setProperty - set the property of a JavaBean.
jsp:getProperty - insert the property of a JavaBean into the output.
jsp:forward - forward the requester to a new page.
jsp:plugin - generate browser-specific code that makes an OBJECT or EMBED tag for the Java
plugin.
Remember that, as with XML in general, the element and attribute names are case sensitive.
The jsp:include Action
This action lets you insert files into the page being generated. The syntax looks like this:
<jsp:include page="relative URL" flush="true" />
Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet,
this action inserts the file at the time the page is requested. This pays a small penalty in efficiency, and
precludes the included page from containing general JSP code (it cannot set HTTP headers, for example),
but it gains significantly in flexibility.
For example, here is a JSP page that inserts four different snippets into a "What's New?" Web page. Each
time the headlines change, authors only need to update the four files, but can leave the main JSP page
unchanged.
<!--file: WhatsNew.jsp-->
<HTML>
<HEAD>
<TITLE>What's New</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6" TEXT="#000000" LINK="#0000EE" VLINK="#551A8B" ALINK="#FF0000">
246
Connecting to Database
Before you can use JDBC to access a SQL database, you must first establish a connection to the
database. The first step to establishing a connection involves registering the driver class so the class is
available. To do that, you use the forName method of the Class class, specifying the package and class
name of the driver.
For example, to register the MySQL connector, use this statement:
Class.forName(com.mysql.jdbc.Driver);
To register the standard ODBC driver, use this statement instead:
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Note that the forName method throws ClassNotFoundException, so you have to enclose this statement
in a try/catch block that catches ClassNotFoundException.
Registering a Driver
For a JDBC driver to be used, it must first be registered with the driver manager. You can accomplish this
in several ways, but each involves calling DriverManager.registerDriver(). The most common approach
is simply to load the driver class:
try {
Class.forName("MyJdbcDriver");
}
catch (ClassNotFoundException e) {
// Report the exception
}
A driver class loaded in this fashion should create an instance of itself and register it with the driver
manager, using logic similar to the following:
247
static {
PrintStream log = DriverManager.getLogStream();
if (log != null)
log.println("MyJdbcDriver class loaded");
MyJdbcDriver driver = new MyJdbcDriver();
try {
DriverManager.registerDriver(driver);
}
catch (SQLException e) {
if (log != null)
log.println("Unable to register driver");
}
}
To use the JDBC-ODBC bridge in a Java application, a suitable ODBC data source must be configured. The
data source should be configured as a System DSN, not a User DSN. The driver class name is
sun.jdbc.odbc.JdbcOdbcDriver if the Sun JVM is being used or com.ms.jdbc.odbc.JdbcOdbcDriver for the
Microsoft virtual machine.
The database URL used in the getConnection() statement is jdbc:odbc:dsn, where dsn is the data source
name. Microsoft supplies ODBC drivers for its Access database product, as well as dBase, Excel, FoxPro,
and a number of others, including a text driver that can use ordinary text files (.txt and .csv) as a simple
database system.
Connecting to a Database
After you register the driver class, you can call the static getConnection method of the DriverManager
class to open the connection. This method takes three String parameters: the database URL, the user
name, and a password.
Heres an example:
String url = jdbc:mysql://localhost/Movies;
String user = root;
String pw = pw;
con = DriverManager.getConnection(url, user, pw);
DriverManager provides three different methods to get connection:
DriverManager.getConnection(String url)
DriverManager.getConnection(String url, String userID, String password)
DriverManager.getConnection(String url, Properties prop)
Internally, DriverManager uses the same private worker method to handle each of these methods. The
driver manager maintains a list of registered drivers. When its getConnection() method is invoked, it
interrogates each driver in turn to see if it will accept the specified URL. The driver manager does this by
calling the drivers connect() method, which returns either null if the driver cannot accept the URL or an
active Connection object if it can.
The key argument to DriverManager.getConnection() is a JDBC URL, which is a string with three
components separated by semicolons:
248
<protocol>:<subprotocol>:<subname>
where
protocol is always jdbc.
subprotocol is a vendor-specific string that identifies the driver to be used. The driver indicates
whether it can handle that subprotocol when asked by the driver manager. For example, the
JDBC-ODBC bridge uses the reserved value odbc as its subprotocol. This value is intended to be
unique across all driver vendors. Sun Microsystems acts as an informal registrar of JDBC
subprotocols.
subname identifies the specific database to connect to. This string contains whatever the driver
needs to identify the database. It may also contain connection parameters the database needs.
Examples of JDBC URLs are
jdbc:odbc:finance
This would indicate an ODBC data source named finance that is accessed by the JDBC-ODBC bridge
driver.
jdbc:idb:c:/path/database.prp
Example: connecting to Mysql server
private static Connection getConnection()
{
Connection con = null;
try
{
Class.forName(com.mysql.jdbc.Driver);
String url = jdbc:mysql://localhost/Movies;
String user = root;
String pw = NuttMutt;
con = DriverManager.getConnection(url, user, pw);
}
catch (ClassNotFoundException e)
{
System.out.println(e.getMessage());
System.exit(0);
}
catch (SQLException e)
{
System.out.println(e.getMessage());
System.exit(0);
}
return con;
}
Querying a Database
After you establish a connection to a database, you can execute select statements to retrieve data. To
do so, you have to use several classes and interfaces:
249
Connection: The Connection class has two methods youre likely to use. The close() method
closes the connection, and the createStatement() method returns a Statement object, which you
then use to execute statements.
Statement: The Statement interface contains the methods necessary to send statements to the
database for execution and return the results. In particular, you use the executeQuery() method
to execute a select statement or the executeUpdate() method to execute an insert, update, or
delete statement.
ResultSet: The ResultSet interface represents rows returned from a query. It provides methods
you can use to move from row to row and to get the data for a column.
Description
Closes the connection.
Creates a Statement object that can execute a SQL statement
on the database connected by the connection.
Statement createStatement (int type, Creates a Statement object that can execute an SQL statement
int concur)
on the database connected by the connection.
Statement Interface Methods
ResultSet executeQuery(String sql)
int executeUpdate(String sql)
Description
Executes the select statement contained in the string
parameter and returns the result data as a ResultSet object.
Executes the insert, update, or delete statements contained in
the string parameter and returns the result data as a ResultSet
object.
250
Description
void close()
boolean next()
boolean previous()
boolean first()
void last()
void beforeFirst()
Moves the cursor to the front of this ResultSet object, just before the
first row.
void afterLast()
Moves the cursor to the end of the ResultSet object, just after the last
row
Moves the cursor to the given row number in this ResultSet object.
int getRow()
boolean isBeforeFirst()
boolean isAfterLast()
boolean isFirst()
251
boolean isLast()
telephone
Aroun Moken
Male
aroun@yahoo.com
786958475
Lalise Tola
Female
lal@gmail.com
998374655
..
Example: the following code shows how you can process each row in a result set:
Connection con = null;
Statement statement = null;
ResultSet records = null;
String sql;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:customers", "", "");
sql = "select * from customer";
statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
records = statement.executeQuery(sql);
records.next();
}
catch(SQLException xx) {
JOptionPane.showMessageDialog(null, "Querying: " + xx.getMessage());
}
catch(Exception xx) {
JOptionPane.showMessageDialog(null, "1: " + xx.getMessage());
}
while(records.next())
{
252
records.getString("name");
records.getString("sex");
records.getString("email");
records.getInt("telephone");
}
records.close();
con.close();
Get Methods of the ResultSet Interface
Method
Description
253
<HR COLOR="#000000">
<%
// Get driver name and database URL from configuration parameters stored in web.xml
String DRIVER = application.getInitParameter("jdbc.driver");
String URL = application.getInitParameter("jdbc.url");
// Load the driver
Class.forName(DRIVER);
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Connect to the database
con = DriverManager.getConnection(URL);
// Open a statement that supports scrollable result sets
stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
// Execute the query
rs = stmt.executeQuery(" SELECT itemcode, price, description FROM products
+ WHERE prodtype = 'IN' ORDER BY description");
// Calculate number of rows
rs.last();
int nRows = rs.getRow();
// Back up ten rows
rs.relative(-10);
// Now print last page of result set
%>
<H3>
Musical Instruments - Items <%= rs.getRow() + 1 %> through <%= nRows %>
</H3>
<TABLE BORDER=1 CELLPADDING=3 CELLSPACING=0>
<TR><TH>Item</TH><TH>Price</TH><TH>Description</TH></TR>
<%
while (rs.next())
{
String itemcode = rs.getString(1);
double price = rs.getLong(2) / 100.0;
String description = rs.getString(3);
254
%>
<TR>
<TD> <%= itemcode %> </TD>
<TD ALIGN="RIGHT"><%= PRICE_FMT.format(price) %></TD>
<TD><%= description %></TD>
</TR>
<%
}
}
finally {
if (rs != null) { rs.close(); rs = null; }
if (stmt != null) { stmt.close(); stmt = null; }
if (con != null) { con.close(); con = null; }
}
%>
</TABLE>
</BODY>
</HTML>
Updating Database
Methods for Updatable ResultSets
Method
Description
void cancelRowUpdates()
Cancels the updates made to the current row in this ResultSet object.
void deleteRow()
Deletes the current row from this ResultSet object and from the
underlying database.
void insertRow()
Inserts the contents of the insert row into this ResultSet object and into
the database.
void moveToCurrentRow()
void moveToInsertRow()
void refreshRow()
Refreshes the current row with its most recent value in the database.
void updateRow()
Deleting Rows
Example: deleting a row
try
{
rs.absolute(3);
rs.deleteRow();
255
}
catch (SQLException e)
{
out.println(e.getMessage());
}
Updating Rows
For a result set to be updated, it must have been produced by a Statement object created with a
concurrency type of ResultSet.CONCUR_UPDATABLE. JDBC provides updateXXX() methods, where XXX is
the JDBC data type, similar to the existing getXXX() methods. These methods take a column number or
column name parameter, and a value parameter.
The following example illustrates this:
double mySalary = rs.getDouble(SALARY);
mySalary *= 2.0;
rs.updateDouble(SALARY, mySalary);
rs.updateString(HOME_PHONE, unlisted);
rs.updateRow();
256
257