Sunteți pe pagina 1din 137

Syllabus 4/4 B.

Tech (Mech)-Web Technology


UNITI: Introduction to Web Technology: Internet, WWW, Web Browsers, Web Servers, URL. UNIT II: Introduction to HTML & DHTML: Syntax, Forms, Cascade Style Sheets. UNIT III: The Basic of java Script, Perl, Primitives, Operator and Expression. Dynamic Document with Java Script. UNIT IV: Introduction to Java Servelets Programming., Introduction to Applet Programming. UNIT V: Structure of Web Application, Deploying Web Application. Text Books: 1. Programming the World Wide Web by Robert W Sebesta 2. Professional Java Servelets 2.3 by John Bell Wrox Publical 3. Beginners PHP, Apache, MY Sql, Web Development, by Michael Glass Wrox.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 1

MODEL QUESTION PAPER 4/4 B.TECH.MECH SECOND SEMESTER WEB TECHNOLOGY (EURME863) Max Marks: 60 Time: 3 Hrs Note: Answer the following units each carries equal marks: (5x12=60) UNIT-I 1. Explain about web Servers and web Browsers? (OR) 2. Explain about Internet, WWW and URL. UNIT-II 3. A) Write some of the important tags present in HTML and mention the syntax for HTML document. B) Generate DHTML that collects the following information from the user: last name, middle initial,
age(restricted to be greater than 17),and weight(restricted to the range of 50-100).you must have handlers for the form elements that collect this information that check the input data for correctness. messages in ALERT windows must be produced when the errors are detected.

(OR) 4. A) Explain about Cascading Style Sheets (CSS) with syntax. B) Create HTML document that includes CSS has six paragraphs of text. you must define three different styles P1, P2,P3.The P1 style must use left and right margins of 20pixels,a background color of pink, and foreground color of blue. The P2 style must use left and right margins of 30pixels,a background color of red, and foreground color of black. The P3 style must use a text indent of 1 centimeter, a background color of red, and foreground color of black. The first and fourth paragraph must use P1; The second and fifth paragraphs must use P2; The third and sixth paragraph must use P3.

UNIT-III 5. A) Describe the primitive data types that JavaScript uses. B) Write a script that reads an integer and determines and displays whether it is an odd or even number. (OR) 6. A) What is a Perl and performed Operators Operations B) Explain about String- and numeric-comparison operators Success is not the result of spontaneous combustion. You must set yourself on fire . Page 2

UNIT-IV 7. A) Write a Servlet program that uses the doGet and doPost methods to return our HTML document and access data from any backend. Explain its procedure clearly. B) Discuss how servlets can be used to extend a web servers functionality and life cycle of servlet. (OR)
8 . A) Explain about Java Applet Programming with example and mention its advantages. B) Explain about life cycle of Java Applet.

UNIT-V 9. Explain about Structure of Web Application. (OR) 10. Explain about Deploying Web Application.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 3

Materials UNIT I
Introduction to Web Technology:

1. Internet
Internet History
1969 Defense Advanced Research Project Agency (DARPA) creates ARPANET Internet project creates protocols (TCP/IP) Transmission Control Protocol (TCP) Internet Protocol (IP) Allows computers to talk over networks Creates the Internet 4 nodes Links together DARPA supported sites 1979 USENET started Interconnection of Computer Science Departments Duke and UNC-Chapel Hill First emoticon created -) (tongue in cheek) 1982 :- ) and :- ( get added

Internet History Continued

1985 first domain name Symbolics.com 1986 NSFNET government support for major Internet backbone 1988 Internet Worm affects 6,000 of 60,000 Internet sites 30 seconds on NBC evening news Son of National Security Agency Chief Scientis

What is Internet
The internet in simple terms is a network of the interlinked computer networking worldwide, which is accessible to the general public. These interconnected computers work by transmitting data through a special type of packet switching which is known as the IP or the internet protocol.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 4

Internet is such a huge network of several different interlinked networks relating to the business, government, academic, and even smaller domestic networks, therefore internet is known as the network of all the other networks. These networks enable the internet to be used for various important functions which include the several means of communications like the file transfer, the online chat and even the sharing of the documents and web sites on the WWW, or the World Wide Web. It is always mistaken said that the internet and the World Wide Web are both the same terms, or are synonymous. Actually there is a very significant difference between the two which has to be clear to understand both the terms. The internet and World Wide Web are both the networks yet; the internet is the network of the several different computers which are connected through the linkage of the accessories like the copper wires, the fiber optics and even the latest wireless connections. However, the World Wide Web consists of the interlinked collection of the information and documents which are taken as the resource by the general public. These are then linked by the website URLs and the hyperlinks. Therefore World Wide Web is one of the services offered by the whole complicated and huge network of the internet. The use of IP in the Internet is the integral part of the network, as they provide the services of the internet, through different layers organization through the IP data packets. There are other protocols that are the sub-classes of the IP itself, like the TCP, and the HTTP.

Advantages and Disadvantages of Internet


Internet is undoubtedly the most crucial technology of the modern world, the useful application has not only made our lives easier than ever before but it also plays a very important role in the future developments. Everyone is of course very well known that internet has the global advantages than just a few concentrated ones. With the introduction of the internet the global communication has become a matter of just the finger tips of the users. The internet has brought about the various different, innovative communication means like the emailing, chatting, and the voice conversation system over the internet. These systems have not only made the communication easy but also the daily lives interactions following the business of people living on the other sides of the world. The other blessings of the internet include the umpteen resources that we can get on anything at all over the net and also the entertainment via the games, websites, and media access which was never so easy before. Everything has the negative aspect to it and so does the internet, the biggest threat of the internet is in the pornography and the security threats. Pornography is widespread over the internet making it inappropriate to be used by the children below certain age so as to prevent the psychological damage from the early days. These sites are easily accessible and attractive for the teenagers and young kids. The security over the internet cannot be guaranteed due to the major hacking techniques and theories, even the interaction between the two strangers can lead to friendship and then serious Success is not the result of spontaneous combustion. You must set yourself on fire . Page 5

cases of murders and serial killers plots which have become increasingly popular because of the internet launch. Despite of a few major problems the Advantages of the Internet use clearly outweigh the few disadvantages.

2. WWW
Web History
1991 World Wide Web released by CERN First Web Server WhatYouSeeIsWhatYouGet (WYSYWIG) First Web Site (Stanford Linear Accelerator) 1992 50 Web servers 1993 first Internet Worms/Spiders/Wanderers/Robots First search engines Mosaic first graphical browser for Web 341,000% growth rate in WWW

Web History Continued


Yahoo Yet Another Hierarchical Officious Oracle 2 Ph.D. Students from Stanford Peaks about Dec. 2001 at 40 million web servers Keys to success: Client-server architecture Users all over world can run programs on my computer Dont need to ship software, just publish the url Dont have to create a GUI just create a web page Browser runs on client, displays web page Sends messages to server Receives and displays answers The World Wide Web (abbreviated as WWW or W3 and commonly known as the Web) is a system of interlinked hypertext documents accessed via the Internet. With a web browser, one can view web pages that may contain text, images, videos, and other multimedia, and navigate between them via hyperlinks. Using concepts from his earlier hypertext systems like ENQUIRE, British engineer and computer scientist Sir Tim Berners-Lee, now Director of the World Wide Web Consortium (W3C), wrote a proposal in March 1989 for what would eventually become the World Wide Web. At CERN, a European research organization near Geneva situated on Swiss and French soil, Berners-Lee and Belgian computer scientist Robert Cailliau proposed in 1990 to use Success is not the result of spontaneous combustion. You must set yourself on fire . Page 6

hypertext "... to link and access information of various kinds as a web of nodes in which the user can browse at will", and they publicly introduced the project in December.

3. Web Browsers
A web browser is a software application for retrieving, presenting, and traversing information resources on the World Wide Web. An information resource is identified by a Uniform Resource Identifier (URI) and may be a web page, image, video, or other piece of content. Hyperlinks present in resources enable users easily to navigate their browsers to related resources. A web browser can also be defined as an application software or program designed to enable users to access, retrieve and view documents and other resources on the Internet. Although browsers are primarily intended to access the World Wide Web, they can also be used to access information provided by web servers in private networks or files in file systems. The major web browsers are Firefox, Google Chrome, Internet Explorer, Opera, and Safari

Historical
A rough estimate of usage share by percent of layout engines of web browsers as of Q2 2009, see usage share of web browsers. See also: Timeline of web browsers This is a table of personal computer web browsers by year of release of major version, in chronological order, with the approximate number of worldwide Internet users in millions. Note that Internet user data is related to the entire market, not the versions released in that year. The increased growth of the Internet in the 1990s and 2000s means that current browsers with small market shares have more total users than the entire market early on. For example, 90% market share in 1997 would be roughly 60 million users, but by the start of 2007 9% market share would equate to over 90 million users.[1]
Internet users (in millions)
[2]

Year

Web browsers

1991 WorldWideWeb (Nexus) 1992 ViolaWWW, Erwise, MidasWWW, MacWWW (Samba) 1993 Mosaic, Cello,[3] Lynx 2.0, Arena, AMosaic 1.0 1994 IBM WebExplorer, Netscape Navigator, SlipKnot 1.0, MacWeb, IBrowse, Agora (Argo), Minuet 1995 Internet Explorer 1, Netscape Navigator 2.0, OmniWeb, UdiWWW,[4] Internet Explorer 2, Grail Arachne 1.0, Internet Explorer 3.0, Netscape Navigator 3.0, Opera 2.0, 1996 PowerBrowser 1.5,[5] Cyberdog, Amaya 0.9,[6] AWeb, Voyager Internet Explorer 4.0, Netscape Navigator 4.0, Netscape Communicator 4.0, Opera 3.0,[7] Amaya 1997 1.0[6] 1998 iCab, Mozilla 1999 Amaya 2.0,[6] Mozilla M3, Internet Explorer 5.0

4 7 10 21 16-40 36-74 70-119 147-186 248-279

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 7

2000 Konqueror, Netscape 6, Opera 4,[8] Opera 5,[9] K-Meleon 0.2, Amaya 3.0,[6] Amaya 4.0[6] 2001 Internet Explorer 6, Galeon 1.0, Opera 6,[10] Amaya 5.0[6] 2002 Netscape 7, Mozilla 1.0, Phoenix 0.1, Links 2.0, Amaya 6.0,[6] Amaya 7.0[6] 2003 Opera 7,[11] Safari 1.0, Epiphany 1.0, Amaya 8.0[6] 2004 Firefox 1.0, Netscape Browser, OmniWeb 5.0 Safari 2.0, Netscape Browser 8.0, Opera 8,[12] Epiphany 1.8, Amaya 9.0,[6] AOL Explorer 1.0, 2005 Maxthon 1.0, Shiira 1.0 SeaMonkey 1.0, K-Meleon 1.0, Galeon 2.0, Camino 1.0, Firefox 2.0, Avant 11, iCab 3, Opera 2006 [13] 9, Internet Explorer 7, Sputnik 2007 Maxthon 2.0, Netscape Navigator 9, NetSurf 1.0, Flock 1.0, Safari 3.0, Conkeror Konqueror 4, Safari 3.1, Opera 9.5,[14] Firefox 3, Amaya 10.0,[6] Flock 2, Chrome 1, Amaya 2008 11.0[6] 2009 Internet Explorer 8, Chrome 2-3, Safari 4, Opera 10,[15] SeaMonkey 2, Camino 2, Firefox 3.5 2010 K-Meleon 1.5.4, Firefox 3.6, Chrome 4-8, Opera 10.50,[16] Safari 5, xxxterm, Opera 11 Chrome 9-16, Firefox 4-8, Internet Explorer 9, Maxthon 3.0, SeaMonkey 2.1-2.3, Opera 11.50, 2011 Safari 5.1

361-393 513-494 587-673 719-783 817-909 1018-1021 1093-1146 1319-1357 1574-1586 1802 1971 2095

4. Web Servers
The primary function of a web server is to deliver web pages on the request to clients. This means delivery of HTML documents and any additional content that may be included by a document, such as images, style sheets and scripts. A user agent, commonly a web browser or web crawler, initiates communication by making a request for a specific resource using HTTP and the server responds with the content of that resource or an error message if unable to do so. The resource is typically a real file on the server's secondary memory, but this is not necessarily the case and depends on how the web server is implemented. While the primary function is to serve content, a full implementation of HTTP also includes ways of receiving content from clients. This feature is used for submitting web forms, including uploading of files. Many generic web servers also support server-side scripting using Active Server Pages (ASP), PHP, or other scripting languages. This means that the behaviour of the web server can be scripted in separate files, while the actual server software remains unchanged. Usually, this function is used to create HTML documents dynamically ("on-the-fly") as opposed to returning static documents. The former is primarily used for retrieving and/or modifying information from databases. The latter is typically much faster and more easily cached. Web servers are not always used for serving the World Wide Web. They can also be found embedded in devices such as printers, routers, webcams and serving only a local network. The web server may then be used as a part of a system for monitoring and/or administering the device in question. This usually means that no additional software has to be installed on the client computer, since only a web browser is required (which now is included with most operating systems). Success is not the result of spontaneous combustion. You must set yourself on fire . Page 8

Every Web site sits on a computer known as a Web server. This server is always connected to the internet. Every Web server that is connected to the Internet is given a unique address made up of a series of four numbers between 0 and 256 separated by periods.for example, 68.178.157.132 or 68.122.35.127. When you register a Web address, also known as a domain name, such as tutorialspoint.com you have to specify the IP address of the Web server that will host the site. You can load up with Dedicated Servers that can support your web-based operations. There are four leading web browsers: Apache, IIS, lighttpd and Jagsaw. Now we will see these servers in bit more detail. Apart from these Web Servers, there are other Web Servers also available in the market but they are very expansive. Major ones are Netscape's iPlanet, Bea's Web Logic and IBM's Websphere. Apache HTTP Server This is the most popular web server in the world developed by the Apache Software Foundation. Apache web server is an open source software and can be installed on almost all operating systems including Linux, Unix, Windows, FreeBSD, Mac OS X and more. About 60% of the web server machines run the Apache Web Server. You can have Apache with tomcat module to have JSP and J2EE related support. You can have detailed information about this server at Apache HTTP Server Internet Information Services The Internet Information Server (IIS) is a high performance Web Server from Microsoft. This web server runs on Windows NT/2000 and 2003 platforms ( and may be on upcoming new Windows version also). IIS comes bundled with Windows NT/2000 and 2003; Because IIS is tightly integrated with the operating system so it is relatively easy to administer it. You can have detailed information about this server at Miscrosoft IIS lighttpd The lighttpd, pronounced lighty is also a free web server that is distributed with the FreeBSD operating system. This open source web server is fast, secure and consumes much less CPU power. Lighttpd can also run on Windows, Mac OS X, Linux and Solaris operating systems. You can have detailed information about this server at lighttpd Success is not the result of spontaneous combustion. You must set yourself on fire . Page 9

Sun Java System Web Server This web server from Sun Microsystems is suited for medium and large web sites. Though the server is free it is not open source. It however, runs on Windows, Linux and Unix platforms. The Sun Java System web server supports various languages, scripts and technologies required for Web 2.0 such as JSP, Java Servlets, PHP, Perl, Python, Ruby on Rails, ASP and Coldfusion etc. You can have detailed information about this server at Sun Java System Web Server Jigsaw Server Jigsaw (W3C's Server) comes from the World Wide Web Consortium. It is open source and free and can run on various platforms like Linux, Unix, Windows, Mac OS X Free BSD etc. Jigsaw has been written in Java and can run CGI scripts and PHP programs.

5. URL
URL- Universal Resource Locator
The Uniform Resource Locator was created in 1994 by Tim Berners-Lee and the URI working group of the Internet Engineering Task Force (IETF) as an outcome of collaboration started at the IETF Living Documents "Birds of a Feather" session in 1992. The format combines the preexisting system of domain names (created in 1985) with file path syntax, where forward slashes are used to separate folder and file names. Conventions already existed where server names could be prepended to complete file paths, preceded by a double-slash (//). Unique address for a resource on the Internet Scheme://hostname[:port]/path/filename Scheme: http: HyperText Transfer Protocol ftp: File Transfer Protocol mailto: send email News: newsnet news

UNIT- II
Success is not the result of spontaneous combustion. You must set yourself on fire . Page 10

1.

Introduction to HTML

HTML HyperText Markup Language


Create textual description of appearance of documents Document Structure <HTML> <HEAD> <TITLE> My Lecture </TITLE> </HEAD> <BODY> I have to say something. </BODY> </HTML>

Meta Document Information


meta - information about Meta document - information about the document Meta data information about the data Meta tags <META NAME="name" HTTP-EQUIV="FieldName" CONTENT="value" >

MetaTags
<META HTTP-EQUIV="Refresh" CONTENT="2;URL=http:nextdoc.html"> - in 2 sec. redirect browser to nextdoc.html. <META NAME="keywords" CONTENT="Web, HTML, tags"> Set keywords for the document, used by search engines to index your docume

Basic HTML Tags


<b> </b> - bold <ul> - unnumbered list <li> first thing <li> second thing </ul> <ol> </ol> - ordered (numbered) list <p> </p> - paragraph begin and end <br> - line break <pre> </pre> - preformatted text <h1> </h1> - big heading (also h2 .. h6) <i> </i> - italics Success is not the result of spontaneous combustion. You must set yourself on fire . Page 11

<center> </center> - center <!-- comment -->

A Minimal HTML Document


<html> <head> <TITLE>A Simple HTML Example</TITLE> </head> <body> <H1>HTML is Easy To Learn</H1> <P>Welcome to the world of HTML. This is the first paragraph. While short, it is still a paragraph! </P> <P>And this is the second paragraph. </P> </body> </html>

Special Characters and Links


Special Characters - unlike rest of HTML, case sensitive &lt; - less than < &gt; - greater than > &nbsp; - non-blocking space

Linking to Documents and Images


Links to Documents and Images - The displayed text is called the anchor <A HREF=Presentation.ppt"> Document in same directory</A> <A HREF=http://www.csce.uark.edu/~sgauch"> Full path to a page</A> <img src="images/sgauch.jpg" WIDTH=190 HEIGHT= 200> -

Tables Syntax
<TABLE> <TR> <TD> Row 1, Cell 1 </TD> <TD> Row 1, Cell 2 </TD> </TR> <!-- end of first row definition --> <TR> <!-- start of last row definition --> <TD> Row 2, Cell 1 </TD> <TD> Row 2, Cell 2 </TD> </TR> <!-- end of last row definition --> Success is not the result of spontaneous combustion. You must set yourself on fire . Page 12

</TABLE> <!-- end of table definition -->

Tables Output Row 1, Cell 1 Row 1, Cell2

Row 2, Cell 1

Row 2, Cell 2

HTML Tables
Tables are defined with the <table> tag. A table is divided into rows (with the <tr> tag), and each row is divided into data cells (with the <td> tag). td stands for "table data," and holds the content of a data cell. A <td> tag can contain text, links, images, lists, forms, other tables, etc.

Table Example
<table border="1"> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> </tr> </table> How the HTML code above looks in a browser: row 1, cell 1 row 1, cell 2 row 2, cell 1 row 2, cell 2

HTML Tables and the Border Attribute


If you do not specify a border attribute, the table will be displayed without borders. Sometimes this can be useful, but most of the time, we want the borders to show. Success is not the result of spontaneous combustion. You must set yourself on fire . Page 13

To display a table with borders, specify the border attribute: <table border="1"> <tr> <td>Row 1, cell 1</td> <td>Row 1, cell 2</td> </tr> </table>

HTML Table Headers


Header information in a table are defined with the <th> tag. All major browsers display the text in the <th> element as bold and centered. <table border="1"> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> </tr> </table> How the HTML code above looks in your browser: Header 1 Header 2

row 1, cell 1 row 1, cell 2 row 2, cell 1 row 2, cell 2

HTML Unordered Lists


An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 14

The list items are marked with bullets (typically small black circles). <ul> <li>Coffee</li> <li>Milk</li> </ul> How the HTML code above looks in a browser:

Coffee Milk

HTML Ordered Lists


An ordered list starts with the <ol> tag. Each list item starts with the <li> tag. The list items are marked with numbers. <ol> <li>Coffee</li> <li>Milk</li> </ol> How the HTML code above looks in a browser: 1. Coffee 2. Milk

HTML Definition Lists


A definition list is a list of items, with a description of each item. The <dl> tag defines a definition list. The <dl> tag is used in conjunction with <dt> (defines the item in the list) and <dd> (describes the item in the list): <dl> <dt>Coffee</dt> <dd>- black hot drink</dd> <dt>Milk</dt> Success is not the result of spontaneous combustion. You must set yourself on fire . Page 15

<dd>- white cold drink</dd> </dl> How the HTML code above looks in a browser: Coffee - black hot drink Milk - white cold drink

HTML Forms
HTML forms are used to pass data to a server. A form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A form can also contain select lists, textarea, fieldset, legend, and label elements. The <form> tag is used to create an HTML form: <form> .

input elements
. </form>

HTML Forms - The Input Element


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 below.

Text Fields
<input type="text" /> defines a one-line input field that a user can enter text into: <form> First name: <input type="text" name="firstname" /><br /> Success is not the result of spontaneous combustion. You must set yourself on fire . Page 16

Last name: <input type="text" name="lastname" /> </form> How the HTML code above looks in a browser: First name: Last name: Note: The form itself is not visible. Also note that the default width of a text field is 20 characters.

Password Field
<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: Note: The characters in a password field are masked (shown as asterisks or circles).

Radio Buttons
<input type="radio" /> defines a radio button. Radio buttons let a user select ONLY ONE of a limited number of choices: <form> <input type="radio" name="sex" value="male" /> Male<br /> <input type="radio" name="sex" value="female" /> Female </form> How the HTML code above looks in a browser: Male Female Success is not the result of spontaneous combustion. You must set yourself on fire . Page 17

Checkboxes
<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> How the HTML code above looks in a browser: I have a bike I have a car

Submit Button
<input type="submit" /> defines a submit button. A submit button is used to send form data to a server. The data is sent to the page specified in the form's action attribute. The file defined in the action attribute usually does something with the received input: <form name="input" action="html_form_action.asp" method="get"> Username: <input type="text" name="user" /> <input type="submit" value="Submit" /> </form> How the HTML code above looks in a browser: Username: If you type some characters in the text field above, and click the "Submit" button, the browser will send your input to a page called "html_form_action.asp". The page will show you the received input.

HTML Frames
With frames, you can display more than one HTML document in the same browser window. Each HTML document is called a frame, and each frame is independent of the others. The disadvantages of using frames are:

Frames are not expected to be supported in future versions of HTML Page 18

Success is not the result of spontaneous combustion. You must set yourself on fire .

Frames are difficult to use. (Printing the entire page is difficult). The web developer must keep track of more HTML documents

The HTML frameset Element


The frameset element holds one or more frame elements. Each frame element can hold a separate document. The frameset element states HOW MANY columns or rows there will be in the frameset, and HOW MUCH percentage/pixels of space will occupy each of them.

The HTML frame Element


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%,*").

Basic Notes - Useful Tips


Tip: If a frame has visible borders, the user can resize it by dragging the border. To prevent a user from doing this, you can add noresize="noresize" to the <frame> tag. Note: Add the <noframes> tag for browsers that do not support frames. Important: You cannot use the <body></body> tags together with the <frameset></frameset> tags! 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 <body></body> tags! See how it is done in the first example below. Success is not the result of spontaneous combustion. You must set yourself on fire . Page 19

More Examples
How to use the <noframes> tag How to use the <noframes> tag (for browsers that do not support frames). Nested framesets How to create a frameset with three documents, and how to mix them in rows and columns. Frameset with noresize="noresize" How to use the noresize attribute. Move the mouse over the borders between the frames and notice that you cannot move the borders. Navigation frame How to make a navigation frame. The navigation frame contains a list of links with the second frame as the target. The file called "tryhtml_contents.htm" contains three links. The source code of the links: <a href ="frame_a.htm" target ="showframe">Frame a</a><br> <a href ="frame_b.htm" target ="showframe">Frame b</a><br> <a href ="frame_c.htm" target ="showframe">Frame c</a> The second frame will show the linked document. Jump to a specified section within a frame Two frames. One of the frames has a source to a specified section in a file. The specified section is made with <a name="C10"> in the "link.htm" file. Jump to a specified section with frame navigation Two frames. The navigation frame (content.htm) to the left contains a list of links with the second frame (link.htm) as a target. The second frame shows the linked document. One of the links in the navigation frame is linked to a specified section in the target file. The HTML code in the file "content.htm" looks like this: <a href ="link.htm" target ="showframe">Link without Anchor</a><br><a href ="link.htm#C10" target ="showframe">Link with Anchor</a>.

HTML Frame Tags


Tag Description <frameset> Defines a set of frames <frame /> Defines a sub window (a frame) <noframes> Defines a noframe section for browsers that do not handle frames

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 20

How to Use Styles


When a browser reads a style sheet, it will format the document according to it. There are three ways of inserting a style sheet:

External style sheet Internal style sheet Inline styles

External Style Sheet


An external style sheet is ideal when the style is applied to many pages. With an external style sheet, you can change the look of an entire Web site by changing one file. Each page must link to the style sheet using the <link> tag. The <link> tag goes inside the <head> section: <head> <link rel="stylesheet" type="text/css" href="mystyle.css" /> </head>

Internal Style Sheet


An internal style sheet can be used if one single document has a unique style. Internal styles are defined in the <head> section of an HTML page, by using the <style> tag, like this: <head> <style type="text/css"> body {background-color:yellow;} p {color:blue;} </style> </head>

Inline Styles
An inline style can be used if a unique style is to be applied to one single occurrence of an element. To use inline styles, use the style attribute in the relevant tag. The style attribute can contain any CSS property. The example below shows how to change the text color and the left margin of a paragraph: Success is not the result of spontaneous combustion. You must set yourself on fire . Page 21

<p style="color:blue;margin-left:20px;">This is a paragraph.</p> To learn more about style sheets, visit our CSS tutorial.

HTML Style Tags


Tag Description <style> Defines style information for a document <link /> Defines the relationship between a document and an external resource

UNIT- III
http://www.ryerson.ca/JavaScript/lectures/contents.html

The Basic of java Script

JavaScript
Introduction
JavaScript is a scripting language designed and first implemented by Netscape (with help from Sun Microsystems). Netscape first introduced a JavaScript interpreter in Navigator 2. The interpreter was an extra software component in the browser that was capable of interpreting JavaSript source code inside an HTML document. This meant that Web page authors using no more than a simple text editor could place special instructions or programs directly inside Web pages to make them more dynamic and interactive. For example, JavaScript can be used to:

validate user input in an HTML form before sending the data to a server; Page 22

Success is not the result of spontaneous combustion. You must set yourself on fire .

build forms that respond to user input without accessing a server; change the appearance of HTML documents and dynamically write HTML into separate Windows; open and close new Netscape windows or frames; manipulate HTML "layers" including hiding, moving, and allowing the user to drag them around a browser window; build small but complete client side programs.

The definition of the JavaScript language and the ability of the Netscape browser (and others..) to process it are still evolving. As the language grows, and Netscape, Microsoft, and others issue new versions of their browsers, programmers are discovering new and exciting things they can do with JavaScript and Web pages.

Advantages of JavaScript
JavaScript gives web authors an unprecedented degree of control over the behaviour of Netscape and the behaviour of their documents. You can do things with 20 lines of JavaScript that will significantly reduce the load on your server, give the user better feed back, and enhance the appearance of your web pages. JavaScript is often the most efficient solution to many Web authoring problems. JavaScript is also an easy language to get started using. With little more than a text editor a few helpful websites and some interest it is possible to produce some but useful scripts.

Disadvantages of JavaScript
The first browser that reliably implemented JavaScript was Netscape 2.02. Since then, new features have been added to the language and have been supported by later versions of Netscape's browsers. Different versions of Netscape will behave differently depending on the language features you use. It is possible to write JavaScript programs that use advanced JavaScript features but do not cause problems (JavaScript errors) on older browsers. However, doing this is can be a complex and labour intensive process. Unfortunately, even the same version of Netscape may behave differently depending on the operating system it is run on. The language is very new and still evolving. Few software development tools exist to help you write and debug your scripts. And while you can do a lot with JavaScript, some things like animation, scrolling/animated banners and notices, and complex programming are often better done using animated GIFs, Netscape Plugins such as Flash, or Java applets. To make matters more complicated, Microsoft's support for JavaScript (they call it Jscript) in Internet Explorer has been evolving at a different pace than Netscape's. And while Microsoft has done a reasonable job of implementing the Javascript language they have decided to introduce differences in how the language interacts with the more recent and advanced methods for manipulating Web pages and responding to user input losely referred to as dynamic HTML. The growing market share of Internet Explorer and these differences have made it difficult for anyone to reliably use the more advanced features of dynamic HTML on the Web. From a scripter's perspective this situation is quite discouraging. It will take a number of years before a standard for dynamic HTML/Javascript is in place and the vast majority of the browsers Success is not the result of spontaneous combustion. You must set yourself on fire . Page 23

on the Web completely support the standard. Also bad is the fact that so many of the different browser versions have serious bugs in how Javascript interacts with HTML objects. Documenting these and working out code work arounds could easily occupy a small group of people full time.

Learning JavaScript
Netscape and others have claimed that JavaScript can be learned by anyone who can write HTML. While this is probably true, learning to program in JavaScript is not as simple as creating HTML documents. Even programmers who are new to event-driven programming find learning JavaScript often requires a significant investment of time. On the other hand, anyone who can write HTML can, with a certain amount of effort, learn to incorporate and modify prewritten JavaScript functions into their pages. Learning to program in JavaScript requires learning two things at once. One is learning the JavaScript language itself, including things like how to declare functions, looping and conditional branching constructs, and the other aspects of the language. The second part of learning JavaScript, is learning to write scripts that interact with HTML objects and the Web browser. For example, if you want to write a function that checks some user input in an HTML form, you usually need to do two things: first, you must write a segment of code to correctly check data (a function) and second, have your function called by Netscape when a user enters something into a field in the form. Writing a function is part of the language. Writing code to have it called by Netscape is part of working with the HTML page and the browser. When you learn to program in JavaScript you are usually learning to do both things at the same time.

Finding Information on JavaScript


For a long time the best, most complete, documentation on JavaScript came from Netscape. The Netscape site was at.: http://developer.netscape.com/library/documentation/javascript.html However, most of this information is being copied over to the Sun/Netscape alliance site called iPlanet. Also, since the early days the language has undergone a standardization process under the auspices of a european standards association (ECMA). Finally, Microsoft has documented their implementation of JavaScript. Here are their addresses: 1. The ECMA standard is available as a downloadable PDF or Postscript file: http://www.ecma.ch/ecma1/STAND/ECMA-262.HTM. 2. The Sun/Netscape Alliance site has JavaScript Documentation: http://developer.iplanet.com/tech/javascript/index.html. 3. Microsoft's site: http://msdn.microsoft.com/scripting/default.htm?/scripting/jscript/techinfo/jsdocs.htm. There are a number of books on JavaScript. Of all the ones I have read, I can only recommend one of them. David Flanagan's JavaScript, The Definitive Guide, 3rd Edition, from O'Reilly and

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 24

Associates, Inc. It is not a gentle introduction to programming or the language but is a thorough and well written book and makes an excellent reference.

A Simple Script
Placing JavaScript Statements inside HTML Documents
JavaScript programing statements (source code) may only be placed in certain locations within HTML documents. When a browser with a JavaScript interpreter reads the JavaScript code it can interpret and execute it so that some scripting task is completed. The simple document below shows JavaScript source code placed within HTML <SCRIPT></SCRIPT> tags.

<HTML> <HEAD> <TITLE>The Script Tag 1</TITLE> <SCRIPT> document.write("<P>Script tags can be placed ") document.write("in the Head of an HTML document.</P>") </SCRIPT> </HEAD> <BODY> <H1>The Script Tag: Example 1</H1> <P>Script tags can also be placed in the Body of an HTML document.</P> <SCRIPT> document.write("<P>Script tags will be ignored by ") document.write("browsers that do not understand them.</P>") </SCRIPT> </BODY> </HTML>

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 25

The Difference Between HTML and JavaScript


When the browser is reading in an HTML document it needs to be able to determine what text is HTML and therefore what to display in the browser window, and what text is JavaScript source code to be interpreted and executed. One way to let a browser know that part of an HTML document is JavaScript is to enclose it inside the HTML <SCRIPT></SCRIPT> tags as illustrated above. A browser that knows how to interpret JavaScript will attempt to interpret text inside the script tags while reading and displaying HTML elements correctly. Script tags are most often placed inside the head or body tags but may also be placed inside other elements. Not every version of every browser correctly interprets JavaScript code when script tags are placed inside other HTML elements such as table data cells.

JavaScript Statements and Source Code


The JavaScript text is often referred to as "source code" or just "code" and is made up of statements. In the example above these two JavaScript statements:
document.write("<P>Script tags can be placed ") document.write("in the Head of an HTML document.</P>")

write some text, consisting of an HTML paragraph, into the Web page being loaded by the browser. The first statement writes the first half of the paragraph and the second writes the last

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 26

half. A full description of the parts of these statements is provided later but the net effect is to make the text:
<P>Script tags can be placed in the Head of an HTML document.</P>

part of the HTML document. Use the View Page button above to see what happens when you load a page containing this script into a Web browser.

Simple Statements
Here is a simpler JavaScript statement:
a = 2 + 3

The JavaScript interpreter will read in this line of text (or source code) and interpret it. The first thing it will do is evaluate the right hand part of the statement after the " = ". This is the expression 2 + 3 which the interpreter will evaluate to the number 5. The next thing it will do is place the number 5 in the variable named a. On its own, adding two plus three to get five and storing this number in a storage location named a is not very exciting. But it does give an example of a simple JavaScript statement that contains a simple expression. Statements can be more complicated and we will often need to look closely at the expressions within them.

Introducing the Document Object


One of JavaScript's strengths is its ability to work with objects. In object-oriented programming and scripting languages, objects are a way to group or package together information and methods of working with this information in a convenient way. In order to access or change the attributes and contents of a Web page JavaScript provides a convenient object called the document object. According to Netscape it "contains information on the current document, and provides methods for displaying HTML output to the user." Here is a simple example broken down into four parts:

document.write("<P>Hello World</P>")
document
An application object that contains information about the document loaded into a frame or window. In the JavaScript documentation the information about an object is referred to as its properties. Some of the properties of the document object can be changed others are read only. Success is not the result of spontaneous combustion. You must set yourself on fire . Page 27

The dot between the document object and the write() method is significant. The dot operator allows you to access information (object properties) and methods for working with that information in an object. The method or property of an object are on the right side of the dot and the object is on the left side. For example, information about the document that contains the script is available using the document object, the dot notation, and the names of properties of the document object:
document.bgColor - makes it possible to get or set the background colour of the

document
document.location - contains the URL for the current document document.lastModified - holds the date when the document was last modified on

server

write()
write() is a method (also called a function) belonging to the document object. write()

will output a string of text to the document. The round brackets following the word write are required. Any JavaScript expression can be placed inside the round brackets. The expression will be evaluated and the result converted, if necessary, to text to be written into the current Web page.

"<P>Hello World</P>"
The double quoted text is a "literal" string of text including HTML markup. In this case the literal text - the actual series of text characters - will be written into the current Web page.

Working with the Document Object


JavaScript provides a number of application objects such as the document, window, string, and Date objects. Each object has properties that can be read and sometimes set in JavaScript statements. Many objects have methods such as document.write() that give the object significant functionality. Information about the object often called the attributes of the object are stored in variables called "properties" of the object. Some of the basic properties and methods of the document object are introduced below using simple JavaScript statements.

Properties
Properties are the attributes of an object. For example the background colour and the URL the document was retrieved from are attributes of an HTML document. In the examples below various properties of the document object are accessed using the dot operator and assigned to a variable called result. Success is not the result of spontaneous combustion. You must set yourself on fire . Page 28

Getting the Properties of an Object

result = document.location
result will contain the URL of the document.

result = document.lastModified
result will contain the date of the last time the document was modified.

result = document.bgColor
result will contain the background colour of the document.

Setting the Properties of an Object It is also possible to assign values to some object properties. So while it does not make sense to be able to change the location where the document came from, you can change the background colour of the document this way:

document.bgColor = "#800080"
Methods
Methods are a way of asking an object to do something more complicated than changing a property. For example:

document.write( JavaScript expression )


write() is a method (a function) that belongs to the document object. Calling write() is like

asking a document to append HTML to itself. The JavaScript expression inside the round brackets will be evaluated and the result (whatever it is) written out to the HTML page. Here are some more methods for the document object:

document.writeln( JavaScript expression )


writeln() does the same thing as the write() method except that it appends a new line

character to the string of text it writes into the document. writeln is a convenient method to use when writing out data from short test programs within <PRE></PRE> tags. Here are some more methods for the document object:

document.clear()
Clears the document (doesn't appear to do anything in Netscape 2.02) Success is not the result of spontaneous combustion. You must set yourself on fire . Page 29

document.close()
"Closes the output stream and forces data sent to layout to display." In Netscape 2.02 it is not required to display the last ouput.

document.open()
"Opens a stream to collect the output of write or writeln methods."

Comments - Making Notes Inside Scripts


Introduction
Learning to read and understand source code is an important skill that takes some time and practice to develop. It is important

to help understand how other people have solved problems by reading their code; for correctly adapting other people's code for your own uses; for modifying and extending your own code as needed.

However, even trying to understand your own code after being away from it for some months may be quite challenging. As your facility with a language improves, so will your ability to read code. Even a skilled reader will find reading large amounts of code without the aid of some form of documentation or descriptive text can still be very time consuming and difficult - even painful. There are a number of things you should do to make understanding your code easier. These include using descriptive variable names, formatting code so it is easier to read, and documenting what you have done. JavaScript, like other languages, provides a way to include documentation interspersed with JavaScript code to make the code easier to understand without interfering with the execution of the script.

Comments
Comments are notes, usually written by the authors of a script, that documents how the script works, how it can be used, and other information the writers of the script thought important to note. Comments are text that is not interpreted by the JavaScript interpreter. To exclude comments from being interpreted, they must be preceded by special characters or enclosed in special characters.
//Single Line Comments

Two forward slashes // begin a comment that begins with the // and goes to the end of the line. For example: Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 30

//Global Variables for the Quiz var maxQuestions = 12 //Change this value if you want to allow more questions. var firstQuestion = 0 //Change this to any number from 0 to (maxQuestions 1). //Do Not edit code from this point on! /*Multiline or Bracketed Comments*/

The /* and */ characters can be used to enclose a comment. Here are some examples:
/* Global Variables for Quiz */ var maxQuestions = 12 /*Change this value if you want to allow more questions.*/ var firstQuestion = 0 /*Change this to to any number from 0 to one less than maxQuestions.*/ /* Do Not edit code from this point on! */ /** * The checkAnswer(choice) method is called when the user selects an answer * from a list of radio buttons. If the answer is correct the method returns * true. If not it returns false. The method keeps track of the number of * user guesses by incrementing a counter in the question object. * The function expects one numeric parameter to be passed to it. **/ function checkAnswer(choice){ this.guesses++ if (choice == this.answer) return true else return false }

While developing a script, comments are often left to the end to add to a source file. This is an unfortunate practice as it increases the probability that few comments will ever be added to a script as it nears completion. Adding comments as the script progresses is a good practice perhaps something like cleaning while you cook - the comments will be more complete and writing them may help in clarifying what was being attempted as the work progresses. Comments are particularly essential for scripts where numerous sections of code must work together and where more complex tasks are being performed.

Working with JavaScript


Exercises Success is not the result of spontaneous combustion. You must set yourself on fire . Page 31

Working with JavaScript requires little more than a simple text editor and a Web browser. The only way to learn to write scripts is to begin by experimenting with them. The easiest way to do this is to download them, bring them into a text editor, make some changes, and then load the page into a browser to see what happens. You may have noticed the little document icon at the upper left of source code listings: . To download the source code right click on the icon and select Save Link As... in the pop up menu. Here is some code you should download now.
<HTML> <HEAD> <TITLE>Hello World</TITLE> <SCRIPT Language="JavaScript"> <!-document.write("<H1>Hello World!</H1>") // --> </SCRIPT> </HEAD> <BODY> <SCRIPT Language="JavaScript"> <!-document.write("<P>The background colour is ") document.write(document.bgColor) document.write("</P>") // --> </SCRIPT> </BODY> </HTML>

Once you have downloaded the file, open your favourite text editor (it must be able to read and write plain ASCII text files). Load the document into the text editor. Then open your browser and load the same file into it. In Netscape 4.X choose File, Open Page, and then press the Choose File button to find the file and load it into the browser. Your screen should look something like this:

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 32

Once you can see the same file in your text editor and browser you can make changes to the file and save it in the editor. Then, press the reload (or refresh) button in you browser to see the affects your changes have had. In this example the double quotes are used inside the write() method when a string, or sequence, of text characters are to be written into the document. For example: document.write("</P>"). However, in the previous line no double quotes are used: document.write(document.bgColor). In this case the document.bgColor inside the brackets is not literal text to be written into the page. It is a JavaScript expression that must first be evaluated. In this case document.bgColor returns the background property of the document object, which is a string of text in the format #FFFFFF. This text is then written into the document by the write method.

Variables and Values


Variables
A variable is a named area in computer memory that is used to store information and from which information can be retrieved. As JavaScript is a relatively high-level language, it is not necessary to know most of the details of how information is stored in memory by a JavaScript interpreter. Success is not the result of spontaneous combustion. You must set yourself on fire . Page 33

JavaScript provides for the automatic creation of variables whenever values are assigned to them. Here is a very short example showing how the assignment operator ( = ) is used to assign a value to a variable:
x = 3.4

A JavaScript interpreter will read this single line of code and do something like this: 1. break the text into three parts called tokens; Tokens are the separate words, names, and symbols that have some meaning in JavaScript. In the statement above the tokens are:
x = 3.4

2. evaluate the right most token 3.4 as a number value; 3. determine the centre token is the assignment operator and that the value 3.4 is to be assigned to a variable; 4. if a variable named x does not already exist it is created; 5. the number 3.4 is stored in the variable named x. In short, just by writing x = 3.4 a variable named x is both created and has a value stored in it. Variables can also hold text in the form of a sequence (or "string") of characters:
y = "Let's go for lunch!"

In this case y is the variable that will hold the string. The = indicates that the string following it should be stored in the variable y. The double quotes are used to indicate that the sequence of characters within them is a literal string of text characters and not variable names or other JavaScript to be interpreted. Strings may also be enclosed in single quotes. Note the single quote inside the double quotes in this example is treated as a literal character. Here are a few lines of code:
x = 3.4 y = "Let's go for lunch!" x = y

In the last line of this example, the value stored in y is being assigned to x. The JavaScript interpreter will copy the value in y into x. The 3.4 value that was in x will no longer exist and both x and y will contain strings that contain the same characters: Let's go for lunch! If you have experience with strongly typed languages such as Pascal, Java, or C++, or lower level languages such as C, this can be a little confusing. In those languages a variable may only hold a certain type of data. For example an integer or a string but not either at different times. JavaScript is a "loosely typed" language. A variable may hold a number, string or other values at different times.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 34

Rules to Make this Work How does the JavaScript interpreter tell the difference between a variable name like y and a string of characters that are to be taken as a literal string of text such as "Let's go for lunch!"? The quotes indicate that what is inside them are literally just a sequence of text characters. And since variable names are not allowed to start with a quote character, there is no problem. How does the interpreter tell the number 3.4 is a value and x is a variable? Because JavaScript provides rules on what is a valid variable name and a valid number value. Variable names must start with a letter or underscore _ character. The letters can be any upper or lower case letter. After the first character, variable names may also contain numbers. Literal number values must begin with a number, a decimal point followed by a number, or a + or - followed by a number or decimal point followed by a number. Here are a few examples:
x1 = 3.14159 x2 = .5 x3 = -24e3

The e is another allowed character in a number that permits writing numbers in scientific notation. -24e3 is that same as -24 103 or -24000. Since a variable name cannot contain an = character the assignment operator is recognized as an operator by the JavaScript interpreter. As mentioned, when the interpreter "reads" a line of code it breaks it into separate pieces called tokens based on these types of rules. The line x1 = 3.14159 has three tokens: x1 is a variable, = is the assignment operator; and 3.14159 is a numeric value. Variables can store two other types of simple values: the two boolean values true or false and the special null value. Here is an example of using Boolean values that is not very useful:
test = false if (test) alert("test is true")

The Boolean value false is assigned to the variable test. How do we know false is not a variable name? It is a reserved word. There are many words that cannot be used for variable names because they have a special meaning in JavaScript. Other reserved words you can't use for variable names include: var, function, Array, for, new, this, while, and import. There are many others. In the previous short example an alert with the message "test is true" will never appear because test contains the Boolean value false. If statements are described later. Here is a more realistic bit of code:
if (a < 10) alert("a is too small")

In this case the expression a < 10 will be evaluated (is the value stored in a less than ten?). If a is less than 10 the true value will be returned and the alert dialog will appear. If a is not less than 10 it will not. The actual literal Boolean values true and false are not always seen in scripts. Usually, expressions are evaluated to produce a value of true or false and an action is taken, or not taken, as a result.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 35

Finally, the null value is a special value (and reserved word) that indicates that a variable does not contain a usable value such as a number, string, or Boolean value. To make a variable null assign null to it:
x = null

There are other more complex data types in JavaScript but numbers, strings, the two Boolean values and null, are considered JavaScript's basic types of data. Declaring a Variable It is possible to declare a variable before actually assigning a value to it. To do this use the special keyword var:
var x1

This means that there is a variable named x1 but that it has no value stored in it. In other words it's contents are undefined. It is also possible to declare a variable explicitly and assign it a value in one line:
var x1 = 'He said "be seeing you" as he left.'

Why bother when you get the same effect without using var? The short answer is that creating variables with var inside a function creates variables that exist only inside the function and this will be very useful later.

Problems with Variables


A loosely typed language may seem easier to use and more convenient than a strongly typed language. Strongly typed languages require that every variable is declared as capable of holding only one type of primitive value before it can be used. This is useful in avoiding all sorts of errors because software tools (compilers and syntax aware editors) can catch many coding errors very easily. Here are some errors you may run into as a result of JavaScript's loose typing. These two short examples involve a simple typing error. Instead of typing x1, x has been typed once in each example by mistake. Typos Can Create New Variables
var x1 = 'He said "be seeing you" as he left.' document.write(x1) x = "New Message" document.write(x1)

The intention here was to display two messages. First x1 is assigned a message that is written into a Web page, then, x1 is supposed to be assigned a different message which will also be written into the page. Unfortunately, the first message will show up twice in the document. Why? Because of the typing error. The x = "New Message" creates a new variable named x when what was intended was to assign another string to x1. Leaving the 1 off the variable name resulted in a new variable being created. Since the string "New Message" was assigned to the Success is not the result of spontaneous combustion. You must set yourself on fire . Page 36

wrong variable, x1 still contains the original string which will be written into the document a second time. Accessing Undefined Variables
var x1 = 'He said "be seeing you" as he left.' document.write(x)

This causes a runtime error. That is, a browser running this script will stop executing the script and report the error: "Error: 'x' is undefined." Since x was never declared and never had a value assigned to it, it does not exist and so cannot contain a value that can be written into the document.

JavaScript Data Types


Numbers

"no explicit distinction between integers and real" numbers though integers may be stored differently than floating point or real numbers. Here are some literal numbers being assigned to a variable (not a complete sampling): x=8 //integer x = .7343 //floating point x = -4.3e3 //same as -4.3 103 x = 4.3e-3 //same as 4.3 10-3

Boolean Values

true or false are the two boolean values Examples when true or false values result from an expression (not a complete sampling): 10 < 11 //will be evaluated to result in the value true 10 > 11 //will be evaluated to false

Strings

strings can be created by assigning a literal value to a variable or by creating a String object initialized with a literal string. msg = "I there is no end to the details I have to remember?" msg = new String("Is there is not end to the details I have to remember?")

null

null - "special key word denoting a null value" x = null

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 37

JavaScript Numbers
Working with Numbers
JavaScript is a loosely typed language. Any variable can be assigned any datatype. Programmers used to strongly typed languages such as Pascal, C++, or Java will find this difficult to get used to when working with numbers. For example in C/C++/Java the following statements:
int result; result = 5/10;

does the following:


a variable named result is created that can only hold an integer number such as 1 - it cannot hold a number with a fractional part such as 1.5. five is divided by ten, however, since the result is 0.5 and the variable result can only hold an integer, it is assigned the value 0. The fractional part (the .5) is thrown away.

C programmers are used to integer division where the decimal part of the result is truncated. In JavaScipt there are no explicit integers or floating point numbers. Depending on how a number is assigned to a variable and the operations performed on it, the number may be stored as an integer or a "floating point" number in memory. In JavaScript the following single line of code:
result = 5/10

would do the following:


5/10 would be evaluated to equal the number 0.5 0.5 would be assigned to the variable result.

Here are some other examples of working with JavaScript numbers. Please take a minute to read through this table. On the far left are statements that assign the value that results from a simple expression using an operator. The name of the operator appears in the next column and the value that is stored in the variable is described in the last two columns.

Expression result = 5 + 10 result =

Operation Addition Concatenation

result is assigned 15 5Hello

Data Type of result Number String


Page 38

Success is not the result of spontaneous combustion. You must set yourself on fire .

5 + "Hello"

Note: a number and a string are being "added" together. Whenever a string is involved the number is converted to text and concatenated with the string to form a longer text string.

result = 5 - 10 result = 5 * 10 result = 5 / 10 result = 10 / 5 result = 5 % 10 result = 10 % 5 result = 5 < 10 result = 5 > 10 result = 5 <= 10 result = 5 >= 10 result = 5 == 10 result = 5 != 10 x = 5 result = x++ x = 5

Subtraction Multiplication Division Division Remainder


Note: Five does not divide evenly into ten so the remainder is five.

-5 50 0.5 2

Number Number Number Number

Number

Remainder
Note: 10 divides evenly into five (2 times). So the remainder is 0.

Number

Less than test Greater than test Less than or equal test Greater than or equal test Test for equality Test for inequality Post Increment Add one to the value in x after the value in x is used in the expression.

true false true false false true

Boolean Boolean Boolean Boolean Boolean Boolean

5 6

Number Number
Page 39

Post Increment

Success is not the result of spontaneous combustion. You must set yourself on fire .

x++ result = x x = 5 result = ++x x = 5 result = x-x = 5 x-result = x x = 5 result = --x Pre Increment Add one to the value in x and use the new value in the expression.

Number

Post Decrement
Subtract one from the value in x after using current value of x in the expression.

Number

Post Decrement

Number

Pre Decrement Subtract one from the value in x and use 4 the new value in the expression.

Number

Here is a short script that writes out some of these values:


<HTML> <HEAD><TITLE>Examples of using JavaScript Numbers and Operators</TITLE> </HEAD> <BODY> <PRE> <SCRIPT Language="JavaScript"> <!-document.write("5 / 10 = ") document.writeln(5 / 10) document.write("5 + 10 = ") document.writeln(5 + 10) document.write("5 + \"Hello\" = ") document.writeln(5 + "Hello") document.write("5 - 10 = ") document.writeln(5 - 10) document.write("5 * 10 = ") document.writeln(5 * 10) document.write("10 / 5 = ") document.writeln(10/5) document.write("5 % 10 = ") document.writeln(5%10)

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 40

document.write("10 % 5 = ") document.writeln(10 % 5) document.write("5 < 10 = ") document.writeln(5 < 10) document.write("5 > 10 = ") document.writeln(5 > 10) document.write("5 <= 10 = ") document.writeln(5 <= 10) document.write("5 >= 10 = ") document.writeln(5 >= 10) document.write("5 == 10 = ") document.writeln(5 == 10) document.write("5 != 10 = ") document.writeln(5 != 10) document.writeln() document.writeln("x = 5") x = 5 document.write("x++ = ") document.writeln(x++) document.write("x = ") document.writeln(x) document.writeln() document.writeln("x = 5") x = 5 document.write("++x = ") document.writeln(++x) document.writeln() document.writeln("x = 5") x = 5 document.write("x-- = ") document.writeln(x--) document.write("x = ") document.writeln(x) document.writeln() document.writeln("x = 5") x = 5 document.write("--x = ") document.writeln(--x) document.writeln() // --> </SCRIPT> </PRE> </BODY> </HTML>

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 41

JavaScript Strings
Character Sequences
At the most basic level JavaScript strings are sequences of text characters. The text characters may be symbols such as +/-%$#@, numbers such as 1234567890, and characters such as abcde and so on. However, unlike lower level languages like C, the text characters cannot be directly manipulated within the string. Short one character strings can be extracted from a string and new strings can be built from smaller one character strings, but characters are not a separate datatype as in C. Strings are often created in JavaScript by assigning literal text to a variable. For example:
welcome = "Hello World"

In this example we want the sequence of characters that spell out the words:
Hello World

to be stored in the variable welcome. To indicate that these characters are to be taken literally as text and not be interpreted as JavaScript variables or key words the characters must be enclosed in single or double quotes. Either can be used.
welcome = 'Hello World'

does the same thing as:


welcome = "Hello World"

String Objects
After the assignment of the literal string "Hello World", the variable welcome may be treated as a string object. Just as the document object had properties that could be read (and set) and methods that provide more complex functionality, JavaScript strings have properties that can be read and methods to perform useful functions. Here are some introductory examples showing some simple JavaScript statements where a value is returned to a variable named result. They do not completely document these methods. Determining String Length
welcome = "Hello World" result = welcome.length

The length property contains the number of characters that are in a string. In this example result will be assigned the number 11.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 42

To make string length and the position of characters within the string easier to visualize the simple illustration below shows the eleven characters in the string Hello World numbered from 0 through 10. Note that because JavaScript strings start with the first character in position 0 the last character is always one less than the string length.

Getting a Single Character String The charAt() method returns a single character string from a string object. It is passed the position in the string of the single character to return. The character returned is a copy of the character at that position within the string. The original string stored in this case in the welcome variable is unaffected.
result = welcome.charAt(0)

result is the character H Getting a Portion (substring) of the String Part of a string from one position to another can be returned using the substring() method. The first value to be passed to substring is the starting position of the string to return - in this example the first character in position 0. The second value (after the comma) is the character AFTER the substring that is NOT to be returned. In this case the space character in position 5 will be the first character to not be returned. Again, as with all these methods, a new string is being returned that is a copy or modified version of the original. The original string object is unaffected by these methods.
result = welcome.substring(0,5)

result is the string Hello Searching for a String inside a String It is often useful to be able to check for the location within a string of some smaller string. In this example the indexOf() method of the string object is used to look for the word World inside the welcome string. The position of the first character in World - the W - is returned if the string is found.
result = welcome.indexOf("World")

return is the number 6. If the string is not found indexOf returns -1.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 43

Another method of the string object lastIndexOf() does the same thing but begins its search from the end of the string and finds the last occurence (if there is one) of the search value. In the following example lastIndexOf is used to find the last period in the string.
fileName = "my.picture.jpeg" result = fileName.lastIndexOf(".")

In this case result is the number 10. Changing Case When user input is stored in a string it is often useful to convert it to all upper case or all lower case characters before checking what the user has entered. There are two methods that do this:
result = welcome.toUpperCase()

The toUpperCase function returns a copy of the string in the string object but with each letter capitalized. Result is HELLO WORLD
result = welcome.toLowerCase()

result is hello world Here is a short script that writes out some of these values:
<HTML> <HEAD><TITLE>Examples of using the JavaScript String Object</TITLE> </HEAD> <BODY> <SCRIPT Language="JavaScript"> <!-var welcome = "Hello World" document.writeln("<PRE>") document.writeln(welcome) document.writeln(welcome.toUpperCase()) document.writeln(welcome.toLowerCase()) document.writeln(welcome.charAt(0)) document.writeln(welcome.substring(0,5)) document.writeln(welcome.indexOf("World",0)) document.writeln("</PRE>") // --> </SCRIPT> </BODY> </HTML>

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 44

Using string methods together


The string methods - and there are more of them than listed here - are often used together to perform useful functions. For example: a user fills in a form including a file upload field that you are expecting contains a path to a JPEG formated file and you want to make sure the file has the extension .jpg, .jpeg, .JPG, or .JPEG. Assmuming the full path to the file has already been stored in a variable named path you might check the path by extracting the file extension and comparing it to the valid extensions. This short demonstration script writes a report into the document if the extension is correct or not. It also reduces the number of comparisons by forcing the extension extracted from the path to lower case. Finally, the script uses if else statements to make decisions - these are described later.
<HTML> <HEAD> <TITLE>Using lastIndexOf, length, substring, and toLowerCase together</TITLE> </HEAD> <BODY> <PRE> <SCRIPT> <!-// This short script demonstrates how a number of string methods // can be used together to check the extension of a file name. path = "C:\pictures\mmProject11\assembly3.jpg" //sample file name for testing - change this and rerun the script errorMsg = "Invalid File Name. File must have a .jpg or .jpeg extension." //standard error message start = path.lastIndexOf(".") //find the last period character in the string if (start == -1){ //if there isn't one report the problem document.writeln(errorMsg) } else{ start++ //the first character of the extension is the one after the . extension = path.substring(start, path.length).toLowerCase() //force the rest of the string to lower case if ((extension == "jpg") || (extension == "jpeg")){ extension is jpg or jpeg then it's ok. document.writeln("The extension is correct.") } else{ //otherwise report the error document.writeln(errorMsg) } } //--> </SCRIPT> //if

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 45

</PRE> </BODY>

Making Decisions
Doing Something under Certain Conditions
In the random image project, a sequence of JavaScript statements were used to write an image tag into a document. The JavaScript interpreter executed each statement in the order that it was written in the HTML document. Every time the page is loaded or reloaded into a browser the same sequence - in the same order - of statements are executed. Every general purpose programming language has facilities to optionally execute statements. To do this some test condition is evaluated to see if the optional statement should be executed. As a simple example, suppose you wanted to write into a Web page the greeting Good Morning if the time of day where your Web page was being browsed was before noon. It turns out this is fairly easy to do:
<HTML> <HEAD> <TITLE>Example of using a Date object and an if statement.</TITLE> </HEAD> <BODY> <PRE> This script provides an example of using the Date object to obtain the hour of the day. The hour is used to write out a Good Morning greeting if the time of day is before noon(12 hours). <SCRIPT Language="JavaScript"> now = new Date() hour = now.getHours() //create a Date object named: now //hours range from 0 to 23.

if (hour < 12) document.writeln("Good Morning.") </SCRIPT> </PRE> </BODY> </HTML>

Here is a step-by-step description of this works:


now = new Date()

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 46

JavaScript provides a Date object that makes dealing with dates and times relatively easy. In this line a new Date object named now is created using the new object creation operator. This is a little different from how objects have been used in the examples up until now. String objects can be created by assigning literal text to a variable and then treating that variable as though it has properties and methods. The document and Math objects are created by the browser and interpreter environments and are ready to use by any script executed by them. The Date object however is designed to provide a way to create Date objects for a given date or time. The sample line creates a Date object named now that contains the date and time when the now Date was created. Like the String, document, and Math objects the Date object provides numerous useful methods for working with dates and times.
hour = now.getHours()

Just one of the useful methods provided by the Date object is the getHours() method. getHours()returns the hour of the time stored in the now variable. The hour is between 0 (midnight) and 23 (11 PM). If the time was between noon and less than 1 PM (13 hours) getHours() will return 12.
if (hour < 12) document.writeln("Good Morning.")

The simplest if statement has the standard format:


if (expression) statement

The expression part of the if statement is always placed inside round brackets following the if keyword and is evaluated by the JavaScript interpreter to return a value of true or false. If the expression is true then the statement following the expression is executed. If it is not, then the statement is NOT executed. In the example, the expression being evaluated is hour < 12. It contains three tokens:

hour is the variable that contains the hour - any integer value from 0 through 23. < is the less than operator. The less than operator compares the numeric values on either side of it. If the first numeric value is less than the last one the operator returns a true value. If the first value is not less than the last one then false is returned.

If the hour is between 0 and 11 then these values are less than 12 and the statement document.writeln("Good Morning.") will be executed. If the hours 12 to 23 occur the statement will not be executed and no Good Morning greeting will appear in the Web page. If you try running this script before twelve and again after noon you will see this. No Good Morning message will occur from noon on - that is, provided the system time is correct on your computer. Here is a flow chart that shows each step in the execution of this script.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 47

Style Simple if statements can be written in either of the following formats. The statement to be executed if the expression in brackets is true can be placed on the same line :
if (expression) statement

or on the next line:


if (expression) statement

When the second form is used, the statement to be executed is usually indented by a few spaces to show that it is part of the if statement. The indentation is to make the script easier to read by anyone who has to work on it in the future. While it is not necessary for the JavaScript interpreter it is necessary to make the code human readable.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 48

Statement Blocks The if statement may also contain a statement block that is to be executed if the expression evaluates to true. A statement block is a series of statements to be executed that are surrounded by curly braces:
if (expression){ statement1 statement2 statementn }

The statement block is shown in bold. If statements always contain a statement or statement block. A statement that contains other statements is also called a compound statement.

Doing Something or Other


Often we want to do something if an expression evaluates to true and something else if the expression evaluates to false. Here is a simple example:

<HTML> <HEAD> <TITLE>Example of using a Date object and an if else statement.</TITLE> </HEAD> <BODY> <PRE> This script provides an example of using the Date object to obtain the hour of the day. The hour is used to write out a Good Morning greeting if the time of day is before noon(12 hours) otherwise a generic welcome message is written into the page. <SCRIPT Language="JavaScript"> now = new Date() hour = now.getHours() //create a Date object named: now //hours range from 0 to 23.

if (hour < 12) document.writeln("Good Morning.") else document.writeln("Welcome.") </SCRIPT> </PRE> </BODY> </HTML>

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 49

This example uses an if else statement. This is a compound statement where the statement immediately after the expression is executed if the expression is true and the statement after the else keyword is executed if the expression is false. Here is a flowchart showing step-by-step how the script works.

Statement blocks may be used in place of either statement:


if (expression){ statement1 statement2 statementx }

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 50

else { statementa statementb statementn }

The positioning of the curly braces {} is designed to make the blocks visible and is one of many coding styles. While many styles are possible it is important to choose one style and stick with it to make your code readable.

Working with if Statements and Numbers


Exercises

This introduction and the exercise at the bottom of the page are designed to help you become more familiar with using:
if statements; if else statements;

comparison operators such as: <, <=, >, >=, ==, and != when used with numbers; and introduces the else if construct and the logical operators && and ||.

Comparison Operators
The following table provides some examples of what boolean value is returned ( true or false) when two numbers are compared. Unless, you are already familiar with C, C++, Perl, or Java operators take a moment to read through each table and assure yourself that the results makes sense. Note that if hour contains a string (and not a number) the JavaScript interpreter will attempt to convert it to a number before making the comparison. Less than ( < ) Statement
hour = 2 result = hour < 3 hour = 2 result = hour < 2 hour = 2 result = hour < 1

result
true

false

false

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 51

Less than or equal ( <= ) Statement


hour = 2 result = hour <= 3 hour = 2 result = hour <= 2 hour = 2 result = hour <= 1

result
true

true

false

Greater than ( > ) Statement


hour = 2 result = hour > 3 hour = 2 result = hour > 2 hour = 2 result = hour > 1

result
false

false

true

Greater than or equal ( >= ) Statement


hour = 2 result = hour >= 3 hour = 2 result = hour >= 2 hour = 2 result = hour >= 1

result
false

true

true

Equal ( == ) Statement
hour = 2

result
false

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 52

result = hour == 3 hour = 2 result = hour == 2 hour = 2 result = hour == 1 true

false

Not equal ( != ) Statement


hour = 2 result = hour != 3 hour = 2 result = hour != 2 hour = 2 result = hour != 1

result
true

false

true

Caveats
For the most part the comparison operators behave exactly as you might expect them to with numbers. There is one important caveat however. The following table gives a simple example of this: Decimal Places Expression 1 2 3 4 5 6 7 8
return = 4.9 == 5.0 return = 4.99 == 5.0 return = 4.999 == 5.0 return = 4.9999 == 5.0 return = 4.99999 == 5.0 return = 4.999999 == 5.0 return = 4.9999999 == 5.0 return = 4.99999999 == 5.0

Result
false false false false false false false false

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 53

9 10 11 12 13 14 15 16 17 18 19 20

return = 4.999999999 == 5.0 return = 4.9999999999 == 5.0 return = 4.99999999999 == 5.0 return = 4.999999999999 == 5.0 return = 4.9999999999999 == 5.0 return = 4.99999999999999 == 5.0 return = 4.999999999999999 == 5.0 return = 4.9999999999999999 == 5.0 return = 4.99999999999999999 == 5.0 return = 4.999999999999999999 == 5.0 return = 4.9999999999999999999 == 5.0

false false false false false false false true true true true

return = 4.99999999999999999999 == 5.0 true

It is possible for us to conceive of a number such as Pi that has an infinite number of decimals. However no one has ever written out all the decimal values of Pi because the task could never be completed and would take up an infinite amount of space to write down all the digits. Similarly computers must process operations on numbers quickly and store numbers in a limited amount of memory. JavaScript stores numbers using the standard 8 byte IEEE floating-point numeric format. This means that there are limits to the size and precision of numbers. Integer numbers will behave exactly as you expect if you want to compare integers or do integer math (calculate with integers and that result in integers) where the numbers and results of any calculations only range between -231 and -231 - 1. For the most part we can ignore problems of precision. The exceptions are when we use very small or very large numbers or when we must compare numbers that may have rounding errors or have lost precision because of size. In this case we cannot use a simple == test and must instead test numbers to see if they are adequately close to each other.

Greetings for Different Times of Day


On the previous page
now = new Date() hour = now.getHours() if (hour < 12) document.writeln("Good Morning.")

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 54

was used to produce a greeting that would only be visible in the morning. If we, somewhat arbitrarily, define the following times of day (by the hour) we can provide a slightly more complete greeting: Time of Day Morning Afternoon Evening Hours 0 ~ 11 12 ~ 17 18 ~ 23

If we try to write out a separate greeting for each time period in the day then writing out a greeting for the morning and evening is not a problem:
now = new Date() hour = now.getHours() //create a Date object named: now //hours range from 0 to 23. //0 is midnight to before 1 AM.

if (hour < 12) document.writeln("Good Morning.") if (hour > 17) document.writeln("Good Evening.")

However, writing out a greeting for the afternoon cannot be done in the same way with just the comparison operators. What is needed is some way to test for a time period that is not part of the ranges that have already been tested. There are different ways to do this. Here is one of them:
if (hour < 12) document.writeln("Good Morning.") else if (hour > 17) document.writeln("Good Evening.") else document.writeln("Good Afternoon.")

In this example the first else is followed by another if else statement. While the formatting above is the standard way to write if else if else... type constructions the following indentation shows better what is happening:
if (hour < 12) document.writeln("Good Morning.") else if (hour > 17) document.writeln("Good Evening.") else document.writeln("Good Afternoon.")

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 55

The first if else statement has two statements. The first one is executed if hour is less than 12. The second statement is executed if hour is not less than 12. This statement is another if else statement. It in turn tests if the hour is greater than 17. If it is, the evening message is written into the document, and if it is not, the afternoon message is written out. Since the afternoon message is only written out if all the if tests return false it will be written out at the correct time of day. Here is the same code with curly brackets so that you will recognize the else if construction with statement blocks. Even though the curly brackets only contain one statement the code is still legal. Each bracket could contain many statements if necessary:
if (hour < 12) { document.writeln("Good Morning.") } else if (hour > 17) { document.writeln("Good Evening.") } else { document.writeln("Good Afternoon.") }

Logical Operators
Another way to determine if it is the afternoon would be to do the following:
if (hour > 11 && hour < 18) document.writeln("Good Afternoon.")

The logical and operator && returns true if the values on both sides of it are true. Otherwise it returns false. In this case hour > 11 must evaluate to true as must hour < 18 for the and operator to return true. In JavaScript the comparison operators are always evaluated before the logical operators so that this works properly. Here is a table showing the possibilities: Statement
hour = 2 if (hour > 11 && hour < 18) document.writeln("Good Afternoon.") hour = 14 if (hour > 11 && hour < 18) document.writeln("Good Afternoon.") hour = 19 if (hour > 11 && hour < 18) document.writeln("Good Afternoon.") hour > 11 hour < 18 hour > 11 && hour < 18

false

true

false

true

true

true

True

false

false

When both hour > 11 and when hour < 18 evaluate to true the && operator returns true. In the other cases it returns false. While it does take more comparisons than the previous example that used the else if construct, the same script could be written: Success is not the result of spontaneous combustion. You must set yourself on fire . Page 56

if (hour < 12) document.writeln("Good Morning.") if (hour > 11 && hour < 18) document.writeln("Good Afternoon.") if (hour > 17) document.writeln("Good Evening.")

The logical or operator || is often used in a similar way to the && operator except that it returns true if either expression returns true. Here is a table of values: Statement
(true || false) (false || true) (true || true)

result
true true true

(false || false) false

Finally, even though we may remember the significance of the numbers 12, 11, 18, and 17 as parts of the day, it is not likely that someone returning to this script in the future would. These values are basically constants. They do not change throughout the life of the script. To make the script more readable we might consider creating some new variables to hold some of these values:
morning = 0 noon = 12 evening = 18 //Morning begins at midnight? //Afternoon begins at noon. //Evening begins at 6 PM.

Here is a complete example:


<HTML> <HEAD> <TITLE>Examples of using a Date object and the if and if else statements.</TITLE> </HEAD> <BODY> <PRE> This script provides examples of using the Date object to obtain the hour of the day. The hour is used to print different messages at different times during the day. <SCRIPT Language="JavaScript"> now = new Date() //create a Date object named: now

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 57

hour = now.getHours() noon = 12 evening = 18

//hours range from 0 to 23. //0 is midnight to before 1 AM.

//Afternoon begins at noon. //Evening begins at 6 PM.

if (hour < noon) document.writeln("Good Morning.") else if (hour < evening) document.writeln("Good Afternoon.") else document.writeln("Good Evening.") </SCRIPT> </PRE> </BODY> </HTML>

Note: the morning = 0 variable was not needed and that since we have excluded the hours 0 through 11 in the first if statement we do not have to excluded them again by using: if (hour > 11 && hour < 18) in the second if statement.

Exercise
Given the arbitrary labeling of the following periods in a day: Time of Day Night Morning Afternoon Evening Hours 0~5 6 ~ 11 12 ~ 17 18 ~ 23

1. Extend the script above to correctly handle the time periods listed. 2. While less efficient, write a second version of the script that uses if statements without any if else statements. You will need to make extensive use of the && operator. 3. Test your scripts carefully. To do this add a line right after the line hour = now.getHours() where you set hour to a test value. For example: hour = 2. Change the test value you set hour to, and run the script. Make sure that the script works correctly under every possible condition by setting hour to different values. Consider testing with values such as 0, 2, 5, 6, 8, 11, 12, 15, 17, 18, 20 and 23. Are these numbers likely to provide a good test? Why? Finally, don't forget to remove (or comment out) the test line so that the script does what it is supposed to do.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 58

Loops: Repeating Statement Execution


Every programming language provides a method to do things repeatedly. For example when checking for valid user data, it may be necessary to examine every character of a string, one character at a time, until the end of the string is reached. Typically this is done inside a loop statement of some sort using a variable as a counter to keep track of which character is to be checked. The counter variable may be incremented by one, each time through, so that the first character is examined the first time through the loop, the second character the second time, and so forth. Being able to repeatedly execute a statement or compound statement is an essential feature of programming. The simplest loop statement is probably the while statement:
while(expression) statement

As long as the JavaScript expression inside the round brackets evaluate to true the statement is executed. More typically while loops contain a block or compound statement often (also referred to as the loop body) shown here in bold:
while(expression){ statement statement statement }

Before the compound statement or loop block is executed, the expression in the round brackets is evaluated. If it is true the block is executed. When the block is finished executing, the expression is reevaluated. If it is true the block is executed again. This process continues until the expression evaluates to false. At that point the loop block is not executed, the while loop is complete, and the next statement after the loop can be executed. The following is a very simple while loop:
<HTML> <HEAD> <TITLE>Simple While Loop with Counter Variable</TITLE> </HEAD> <BODY> <PRE>Output from a simple while loop with a counter variable: <SCRIPT Language="JavaScript"> <!-counter = 0 while (counter < 5){ document.writeln(counter) counter++ } // -->

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 59

</SCRIPT> </PRE> </BODY> </HTML>

Controlling the Loop


In this example, the Loop is controlled by the counter variable. It is part of the expression: counter < 5. Here is the script again:
counter = 0 while (counter < 5){ document.writeln(counter) counter++ }

The following describes how this particular while loop works:


counter = 0

Before executing the loop statement the counter variable is set to zero. This insures the loop body will be executed at least once because zero is less than 5.
while (counter < 5)

The expression counter < 5 is evaluated. Since zero is less than five, the expression evaluates to true, and the loop block will be executed.
document.writeln(counter)

Inside the loop block the first statement is executed, writing out the current value of the counter variable.
counter++

The counter variable is incremented by 1. In other words if it was zero when before this statement is executed, it will be equal to one afterwards. As this is the last statement in the block the while expression will be reevaluated. And since, 1 is less than 5 the loop block will be executed again. This loop ends when the counter variable is incremented to five. At that point it is no longer less than five and the loop block will not be executed again.

Flow Charts
While flow charts have fallen out of fashion as higher level languages have become popular, the following flow chart below is provided to help make clear each step in the while loop example. By following the arrows and remembering the current value of counter the looping mechanism may become more obvious. If you are at all unsure how loops work, try "walking through" the flow chart one step at a time. Keep track of the value of counter and see how many times you loop until the script is done.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 60

The cycle in the flow chart where the expression is true, the document is written to, the counter incremented, and the expression is evaluated again..., forms a sort of visual "loop" in the flow chart. Hence the name.

Infinite Loops
It is all too easy to create a loop that will go on forever executing the loop block. Whether done by accident or deliberately the result is that the Web page will never complete loading, the browser's controls/buttons may freeze, or the browser may crash altogether. Here is an example of an infinite loop that was likely created by mistake:
counter = 0 while (counter < 10){ document.writeln(counter) }

Since the counter variable is never changed inside the loop it will always be less than ten. The counter++ statement or something similar was forgotten. If you try this in a document you may Success is not the result of spontaneous combustion. You must set yourself on fire . Page 61

have to use your operating system to shut down your browser. Here is an infinite loop that has been written on purpose:
while (true){ document.writeln("Some message..") }

Note that the test expression is simply the true value.

Checking Every Character in a String


While validating text strings is described elsewhere on this site, here is a short example that prints out each character of a string on a separate line. Note the test in the while loop uses the length property of the string object. Also, as the counter goes through values 0, 1, 2, etc. it is used in the charAt() method of the string object to retrieve the character in that position in the string. The character is stored in the chr variable and written out to the document in the next line. In this example the string is Hello World which has a length of 11 characters in positions 0 through 10. Since counter is initially set to 0 and is incremented by one at the end of each loop, counter will be set to the values 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10 and the body of the loop will be executed. However, afert counter is set to 11 the test counter < str.length will fail and the loop body will not be executed again.
<HTML> <HEAD> <TITLE>Examining Every Character in a String</TITLE> </HEAD> <BODY> <PRE>Examining every character in a string: <SCRIPT Language="JavaScript"> <!-str = "Hello World" counter = 0 while (counter < str.length){ chr = str.charAt(counter) document.writeln(chr) counter++ } // --> </SCRIPT> </PRE> </BODY> </HTML>

The chr variable contains a one character string - unlike languages like C where a single character is a different datatype. A small embellishment to this script might be to write out the value of the counter variable and the character at the same time. For completeness, the length of Success is not the result of spontaneous combustion. You must set yourself on fire . Page 62

the string is written out when the loop ends. Output from this script shows the position of each character in the string and then the strings length:
<HTML> <HEAD> <TITLE>Examining Every Character in a String</TITLE> </HEAD> <BODY> <PRE>Examining every character in a string: <SCRIPT Language="JavaScript"> <!-str = "Hello World" counter = 0 while (counter < str.length){ chr = str.charAt(counter) document.writeln("Character in position " + counter + ": " + chr) counter++ } document.writeln("The string length is: " + str.length) // --> </SCRIPT> </PRE> </BODY> </HTML>

Perl (Practical Extraction and Report Language)


Perl is an acronym, short for Practical Extraction and Report Language It was designed by Larry Wall as a tool for writing programs in the UNIX environment and is continually being updated and maintained by him. Perl has the power and flexibility of a high-level programming language such as C. In fact, as you will see, many of the features of the language are borrowed from C. Like shell script languages, Perl does not require a special compiler and linker to turn the programs you write into working code. Instead, all you have to do is write the program and tell Perl to run it. This means that Perl is ideal for producing quick solutions to small programming problems, or for creating prototypes to test potential solutions to larger problems. Perl provides all the features of the script languages sed and awk, plus features not found in either of these two languages. Perl also supports a sed-to-Perl translator and an awk-to-Perl Success is not the result of spontaneous combustion. You must set yourself on fire . Page 63

translator. Statements and Tokens When the Perl interpreter sees a statement, it breaks the statement down into smaller units of information. In this example, the smaller units of information are $inputline, =, <STDIN>, and ;. Each of these smaller units of information is called a token. Tokens and White Space Tokens can normally be separated by as many spaces and tabs as you like. For example, the following statements are identical in Perl: $inputline = <STDIN>; The chop Library Function This function assumes that a line of text is stored in the variable passed to it; chop's job is to delete the character at the right end of the line of text. Consider this example: $line = "This is my line"; chop ($line); After chop is called, the value of $line becomes This is my lin

In Perl, a floating-point scalar value consists of all of the following: An optional minus sign (-) A sequence of digits, optionally containing a decimal point An optional exponent The optional exponent tells the Perl interpreter to multiply or divide the scalar value by a power of ten. An exponent consists of all of the following: The letter e (E is also acceptable) An optional + or A one-, two-, or three-digit number

Using Octal and Hexadecimal Notation So far, all the integer scalar values you've seen have been in what normally is called base 10 or decimal notation. Perl also enables you to use two other notations to represent integer scalar values: Base 8 notation, or octal Base 16 notation, or hexadecimal (sometimes shortened to hex) To use octal notation, put a zero in front of your integer scalar value: $result = 047; This assigns 47 octal, or 39 decimal, to $result . To use hexadecimal notation, put 0x in front of your integer scalar value, as follows: Success is not the result of spontaneous combustion. You must set yourself on fire . Page 64

$result = 0x1f; This assigns 1f hexadecimal, or 31 decimal, to $result. Perl accepts either uppercase letters or lowercase letters as representations of the digits a through f: $result = 0xe; $result = 0xE; Both of the preceding statements assign 14 (decimal) to $result. Character strings that are enclosed in double quotes accept escape sequences for special characters. These escape sequences consist of a backslash (\) followed by one or more characters. The most common escape sequence is \n, which represents the newline character as shown in this example: $text = "This is a string terminated by a newline\n"; Table 3.1 lists the escape sequences recognized in double-quoted strings.

\a Bell (beep) \b Backspace \cn The Ctrl+n character \e Escape \E Ends the effect of \L, \U or \Q \f Form feed \l Forces the next letter into lowercase \L All following letters are lowercase \n Newline \r Carriage return \Q Do not look for special pattern characters \t Tab \u Force next letter into uppercase \U All following letters are uppercase \v Vertical tab A backslash also enables you to include a $ character in a string. $result = 14; print("The value of \$result is $result.\n");

In Perl, the comparison operators are divided into two classes: Comparison operators that work with numbers Comparison operators that work with strings Integer-Comparison Operators Table 4.1 defines the integer-comparison operators available in Perl. Table 4.1. Integer-comparison operators. Operator Description < Less than Success is not the result of spontaneous combustion. You must set yourself on fire . Page 65

> Greater than == Equal to <= Less than or equal to >= Greater than or equal to != Not equal to <=> Comparison returning 1, 0, or -1 Here are simple examples of each of the first six operators in Table 4.1: $x < 10 # true if the value of $x is less than 10 $x > 10 # true if $x is greater than 10 $x == 10 # true if $x is equal to 10 $x <= 10 # true if $x is less than or equal to 10 $x >= 10 # true if $x is greater than or equal to 10 $x != 10 # true if $x is not equal to 10 Each of these operators yields one of two values: l True, or nonzero l False, or zero The <=> operator is a special case. Unlike the other integer comparison operators, <=> returns one of three values: l 0, if the two values being compared are equal l 1, if the first value is greater l -1, if the second value is greater For example, consider the following statement: $y = $x <=> 10; These are the possible results: l If $x is greater than 10, the first value in the comparison is greater, and $y is assigned 1. l If $x is less than 10, the second value in the comparison is greater, and $y is assigned -1. l If $x is equal to 10, $y is assigned 0.

Integer Comparisons and Readability In any given statement, it's best to use the comparison that can be most easily read. For example, consider the following: if (3.2 < $x) { # conditionally executed stuff goes here } Although the expression 3.2 < $x< is perfectly valid, it isn't easy to read because variables usually appear first in comparisons. Instead, it would be better to use if ($x >= 3.2) { ... because this is easier to understand. I'm not sure exactly why this is true; I think it's related to the way the English language is spoken. (Normally, we say, "If I had five dollars, I'd buy some milk," instead of, "If five dollars had I, I'd buy some milk," eventhough both are correct.) Success is not the result of spontaneous combustion. You must set yourself on fire . Page 66

String-Comparison Operators For every numeric-comparison operator, Perl defines an equivalent string-comparison operator. Table 4.2 displays each string-comparison operator, the comparison it performs, and the equivalent numeric-comparison operator. String- and numeric-comparison operators. String operator Comparison operation Equivalent numeric operator lt Less than < gt Greater than > eq Equal to == le Less than or equal to <= ge Greater than or equal to >= ne Not equal to != cmp Compare, returning 1, 0,or -1 Perl compares strings by determining their places in an alphabetical order. For example, the string aaa is less than the string bbb, because aaa appears before bbb when they are sorted alphabetically.

Here are some examples of string-comparison operators in action: $result = "aaa" lt "bbb"; # result is true $result = "aaa" gt "bbb"; # result is false $result = "aaa" eq "bbb"; # result is false $result = "aaa" le "aaa"; # result is true $result = "aaa" ge "bbb"; # result is false $result = "aaa" ne "aaa"; # result is false $result = "aaa" cmp "bbb"; # result is -1 If you are familiar with the C programming language, you might have noticed that the behavior of the cmp operator is identical to that of the C function strcmp(). String Comparison Versus Integer Comparison You might be thinking: If strings and integers are equivalent in Perl, why do we need two kinds of comparison operators? To answer this, consider the strings 123 and 45. The result when these two strings are compared depends on whether a string or integer comparison is being performed. $result = "123" < "45"; $result = "123" lt "45"; In the first statement, the strings 123 and 45 are converted to integers, and 123 is compared to 45. The result is false and $result is assigned 0, because 123 is not less than 45. In the second statement, 123 is alphabetically compared to 45. Because 123 is alphabetically less than 45, the result in this case is true, and $result is assigned a nonzero value. Because these results are different, you must ensure that you are using the proper Success is not the result of spontaneous combustion. You must set yourself on fire . Page 67

comparison operator every time. If you don't, your program can contain errors that are not easy to spot. For instance, consider the following: $var1 = "string 1"; $var2 = "string 2"; $result = $var1 == $var2; # this statement is bad

Using the Assignment Operators the assignment operator = associates, or assigns, a value to a variable. For example, the statement $result = 42; assigns the value 42 to the variable $result. The = operator can appear more than once in a single statement . For example, in the statement $value1 = $value2 = "a string"; the character string a string is assigned to both $value1 and $value2. Perl also supports other assignment operators, each of which combines an assignment with another operation. For example, suppose that you want to add a value to a scalar variable and assign the result to the following variable: $var = $var + 1; Another way to write this is with the += assignment operator: $var += 1; This statement adds the value 1 to the existing value of $var. An assignment operator exists for just about every bitwise operator and arithmetic operator that Perl supports. Table 4.3. The assignment operators. Operator Operations performed = Assignment only += Addition and assignment -= Subtraction and assignment *= Multiplication and assignment /= Division and assignment %= Remainder and assignment **= Exponentiation and assignment &= Bitwise AND and assignment |= Bitwise OR and assignment ^= Bitwise XOR and assignment Table 4.4 shows examples of the assignment operators, along with equivalent statements that use operators you've seen earlier.

Table 4.4. Examples of assignment operators. Success is not the result of spontaneous combustion. You must set yourself on fire . Page 68

Statement using Equivalent Perl assignment operator statement $a = 1; none (basic assignment) $a -= 1; $a = $a - 1; $a *= 2; $a = $a * 2; $a /= 2; $a = $a / 2; $a %= 2; $a = $a % 2; $a **= 2; $a = $a ** 2; $a &= 2; $a = $a & 2; $a |= 2; $a = $a | 2; $a ^= 2; $a = $a ^ 2; Assignment Operators as Subexpressions Any expression that contains an assignment operator can appear on the left side of another assignment operator. The following is an example: ($a = $b) += 3; In cases such as this, the assignment enclosed in parentheses is performed first. This assignment is then treated as a separate subexpression whose value is the variable to which it is being assigned. For example, $a = $b has the value $a. This means that the statement shown previously is equivalent to the following two statements: $a = $b; $a += 3; Using File-Test Operators with File Variables You can use file-test operators on file variables as well as character strings. In the following example the file-test operator -z tests the file represented by the file variable MYFILE: if (-z MYFILE) { print ("This file is empty!\n"); }

Opening a File Before you can read from or write to a file, you must first open the file. This operation tells the operating system that you are currently accessing the file and that no one else can change it while you are working with it. To open a file, call the library function open. The syntax for the open library function is open (filevar, filename); When you call open, you must supply two arguments: l filevar represents the name you want to use in your Perl program to refer to the file. l filename represents the location of the file on your machine. Success is not the result of spontaneous combustion. You must set yourself on fire . Page 69

The File Mode When you open a file, you must decide how you want to access the file. There are three different file-access modes (or, simply, file modes) available in Perl: readmode Enables the program to read the existing contents of the file but does not enable it to write into the file write mode Destroys the current contents of the file and overwrites them with the output supplied by the program append mode Appends output supplied by the program to the existing contents of the file By default, open assumes that a file is to be opened in read mode. To specify write mode, put a > character in front of the filename that you pass to open , as follows: open (OUTFILE, ">/u/jqpublic/outfile"); This opens the file /u/jqpublic/outfile for writing and associates it with the file variable OUTFILE. To specify append mode, put two > characters in front of the filename , as follows: open (APPENDFILE, ">>/u/jqpublic/appendfile"); This opens the file /u/jqpublic/appendfile in append mode and associates it with the file variable APPENDFILE Available File-Test Operators Table 6.1 provides a complete list of the file-test operators available in Perl. In this table, name is a placeholder for the name of the operand being tested. Table 6.1. The file-test operators. Operator Description -b Is name a block device? -c -d -e -f -g -k -l -o -p -r -s -t -u Is name a character device? Is name a directory? Does name exist? Is name an ordinary file? Does name have its setgid bit set? Does name have its "sticky bit" set? Is name a symbolic link? Is name owned by the user? Is name a named pipe? Is name a readable file? Is name a non-empty file? Does name represent a terminal? Does name have its setuid bit set? Page 70

Success is not the result of spontaneous combustion. You must set yourself on fire .

-w -x -z -A -B -C -M -O -R -S -T -W -X

Is name a writable file? Is name an executable file? Is name an empty file? How long since name accessed? Is name a binary file? How long since name's inode accessed? How long since name modified? Is name owned by the "real user" only?* Is name readable by the "real user" only?* Is name a socket? Is name a text file? Is name writable by the "real user" only?* Is name executable by the "real user" only?*

PATTERN MATCHING How pattern matching works The pattern-matching operators Special characters supported in pattern matching Pattern-matching options Pattern substitution Translation Extended pattern-matching features Perl supports a variety of special characters inside patterns, which enables you to match any of a number of character strings. ^ or \A Match at beginning of string only $ or \Z Match at end of string only \b Match on word boundary \B Match inside word Pattern-matching options g Change all occurrences of the pattern i Ignore case in pattern e Evaluate replacement string as expression m Treat string to be matched as multiple lines o Evaluate only once s Treat string to be matched as single line x Ignore white space in pattern The Translation Operator Perl also provides another way to substitute one group of characters for another: the tr translation operator. This operator uses the following syntax: Success is not the result of spontaneous combustion. You must set yourself on fire . Page 71

tr/string1/string2/ Here, string1 contains a list of characters to be replaced, and string2 contains the characters that replace them. The first character in string1 is replaced by the first character in string2, the second character in string1 is replaced by the second character in string2, and so on.

JavaScript Dynamic Document Creation


JavaScript came out at the same time that the Microsoft Script language, VBScript, did, and allows flexible and more powerful Web sites to be designed. There is very little actual difference in programming power between JavaScript and VBScript, but I have written these articles for JavaScript. I suppose that at a later date I might translate them into VBScript. This article explores the JavaScript Dynamic Document Creation (DDC) capabilities. Sounds very complicated, and is. Dynamic Document Creation is the creation of a Web document from within the JavaScript. It may be created while an HTML document is being displayed, and may be influenced by features of the current Web page. As a technique, it is very useful for displaying information from Web pages and creating new HTML documents. DDC rapidly takes you into frames, new windows, variable expressions and using DHTML to access the DOM, and these topics will be covered later, in detail, in future articles. This article concentrates on explaining the principles of DDC, and is simple enough for a beginner to progress from the simple through to the advanced concepts of DDC. The basic components of DDC are the JavaScript functions 'write()', 'writeln()', 'open()' and 'close()'. 'write()' writes the string it contains to the document referenced. 'writeln()' does the same, except it adds a carriage return character after writing its string. 'open()' and 'close()' open and close documents. They don't have any relevance to this article, and will be discussed in a later one. There are two basic levels of implementation of DDC, the first is to create a fresh document from the current document, and the second is to create a document inside a new window. Creating a new window involves a detailed knowledge of the first type of DDC, and so I will begin with the first type. To dynamically create a new document, you must place the necessary code in the HTML document as JavaScript. The most common method to achieve this is to place the JavaScript inside a <SCRIPT> element inside the <HEAD> element. A simple DDC example is : <HTML> <HEAD> <TITLE>DDC in Action</TITLE> <SCRIPT> document.write('Hello World, '); document.write('from DDC in Action.'); Success is not the result of spontaneous combustion. You must set yourself on fire . Page 72

</SCRIPT> </HEAD> </HTML> This code, with no <BODY> element at all, writes 'Hello Word, from DDC in Action' to the page. Its <BODY> equivalent would be to add the text between the open and close tags of a <BODY> element. So, although with this example there have been no savings, having the line of text implemented form JavaScript, where it may be a variable, does increase our control over the Web page. Next, I have demonstrated the difference between write and writeln next, virtually completely replicating the previous example, except for changing the write's to writeln's, and changing the text so that it is correctly formatted. <HTML> <HEAD> <TITLE>DDC in Action2</TITLE> <SCRIPT> document.writeln('Hello World.'); document.writeln('From DDC in Action2.'); </SCRIPT> </HEAD> </HTML> So you can see the difference between write and writeln, with the inclusion of a space after 'Hello World.'. Note that the last writeln is unnecessary in this example, as nothing it written after it the carriage return is invisible. This isn't a design feature though - if you were to add any further text, the difference would become visible again. To write the two lines of text on separate lines, we have to write an HTML element to the document. Because write writes to a document, which is then parsed as an HTML document, we can pass it tags. <HTML> <HEAD> <TITLE>DDC in Action3</TITLE> <SCRIPT> document.write('Hello World.'); document.write('<BR>'); document.writeln('From DDC in Action3.'); </SCRIPT> </HEAD> </HTML> which places the <BR> element between the two lines of text, and causes them to be on different lines. At this point, we have developed the theory only at the most basic level. To add excitement and Success is not the result of spontaneous combustion. You must set yourself on fire . Page 73

complexity to DDC, we develop the techniques further, and a good example of this is in the use of functions. Functions are pieces of code that perform calculations over a certain range of variables, and are generally called a lot, normally from different sections of a program. We can use functions in JavaScript to great effect, and so I have briefly explained them and their implementation. If we wish to define a function called 'ButtonPress' and this takes a parameter 'buttonnumber', we would define this like : <HTML> <HEAD> <TITLE>Blank Function Code</TITLE> <SCRIPT> function ButtonPress(buttonnumber) { code } </SCRIPT> </HEAD> </HTML> The function is defined within a <SCRIPT> tag. This raises the issue of which JavaScript is interpreted. On a first run, any non-function JavaScript will be executed. Functions are only interpreted when called for the first time. If you run this program, it will not produce an error. This is because 'code' is never reached. Although this program doesn't do anything, it has given our HTML document a JavaScript function, which we can call later. The curly braces {} will enclose the function's content. Note that functions do not have to take a parameter, we could have equally defined ButtonPress(). Now I add a few buttons to the Web page, and define the function, instead of the potentially dangerous 'code'. <HTML> <HEAD> <TITLE>DDC Buttons</TITLE> <SCRIPT> function ButtonPress(buttonnumber) { document.write('You pressed button number : '+buttonnumber); } </SCRIPT> </HEAD> <BODY> <BUTTON onclick="ButtonPress(1);">Button 1</BUTTON> <BUTTON onclick="ButtonPress(2);">Button 2</BUTTON> <BUTTON onclick="ButtonPress(3);">Button 3</BUTTON> </BODY> </HTML> Success is not the result of spontaneous combustion. You must set yourself on fire . Page 74

This code displays three buttons and then tells you which one you pressed, hence demonstrating the use of variables inside the write command. JavaScript uses a loose typing of variables, e.g. x can any of a string, integer or floating-point. The statement within the write command is a concatenation of a string and variable, which the JavaScript interpreter reads as a variable, converts to the variables value, and converts the value to a string. These two strings are then added together. To press a different button to get a different result, you need to press 'Back' on your browser. There is a problem in this area. We cannot add content to an existing Web page, we can only create a new one. We can add to a document that we have dynamically created, which can be useful. Advanced DHTML techniques do allow you to dynamically alter content, and there are methods to alleviate this as a problem within JavaScript, namely writing to a frame in the same window, and writing to a new window. Writing to a new window, as I have already said, is complicated. You need a full working knowledge of DDC to do this, and then you are faced with the task of tracking at least two windows rather than just one. I have covered this in the next article in this series, 'Dynamic Document Creation in a New Window.' <HTML> <HEAD> <TITLE>DDC Creating HTML documents</TITLE> <SCRIPT> document.write('<BUTTON onclick="ButtonPress(1);">Button 1</BUTTON>'); document.write('<BUTTON onclick="ButtonPress(2);">Button 2</BUTTON>'); document.write('<BUTTON onclick="ButtonPress(3);">Button 3</BUTTON>'); function ButtonPress(buttonnumber) { document.write('You pressed button number : '+buttonnumber); } </SCRIPT> </HEAD> </HTML> This again demonstrates writing HTML elements to a new document. This code behaves exactly as the code before it, but you will notice again has no <BODY> element. A further trick here is to index the button writing code through a for loop, saving time, keeping the code tidy, and slightly increasing our control over the Web page development again. Change : document.write('<BUTTON onclick="ButtonPress(1);">Button 1</BUTTON>'); document.write('<BUTTON onclick="ButtonPress(2);">Button 2</BUTTON>'); document.write('<BUTTON onclick="ButtonPress(3);">Button 3</BUTTON>'); to : for (index=1;index<=3;index++) document.write('<BUTTON onclick="ButtonPress('+index+');">Button '+index+'</BUTTON>'); Success is not the result of spontaneous combustion. You must set yourself on fire . Page 75

This is starting to get awkward. Great care needs to exercised when tracking the type and depth of quotes, and avoid getting confused with string/number combinations. We need to dip in and out of the 'write' string several times to get our desired effect. The write command is very literal in its behaviour, it just writes what you tell it to, and the result is as if you had typed the code in yourself through Windows NotePad. If you break the example down, the statement : document.write('<BUTTON onclick="ButtonPress('+index+');">Button '+index+'</BUTTON>'); has to be interpreted very carefully. The document.write command expects to be passed a string. So the first expression is : document.write('<BUTTON onclick="ButtonPress(' This writes the string '<BUTTON onclick="ButtonPress(' to the document. The variable expression : +index+ uses index as a number, e.g. index=1. When added to a string, index='1', and the string becomes : '<BUTTON onclick="ButtonPress(1'. So this code does not write the string 'index' to the current string, but converts it first to a number and then to the string of that number. ');">Button ' does a similar thing, and our string is now : '<BUTTON onclick="ButtonPress(1);">Button '. Another numerated index : +index+ is added to the string, and we finalise it : '</BUTTON>'); creates our desired string :'<BUTTON onclick="ButtonPress(1);">Button 1</BUTTON>'. This is repeated for all iterated values of index, which creates three buttons. Document.write writes these to a fresh HTML document, and the viewer will see three buttons, labelled Button 1, Button 2 and Button 3, and each one associated with an event handler to the function ButtonPress, with each buttons index as a parameter for the benefit of the function. The hardest part about doing this is in nesting the strings, and making sure the entry and exit points for the string are correct. It would be very easy to be reading the string 'index', rather than the variable index. To keep the document in the same window, without having to lose visibility of our initial document, we must use frames. For this example, I have created a frames document first, and give it two frames : Success is not the result of spontaneous combustion. You must set yourself on fire . Page 76

<HTML> <HEAD> <TITLE>Frames for DDC</TITLE> </HEAD> <FRAMESET rows="100,*"> <FRAME NAME="information"> <FRAME SRC="ButtonsforFrames.htm" NAME="buttons"> </FRAMESET> </HTML> We also need a 'Buttons' Web page. The 'Information' Web page is dynamically created from the Buttons document, and so we do not need to supply a SRC attribute for its frame element definition. <HTML> <HEAD> <TITLE>Buttons Revisited</TITLE> <SCRIPT> for (index=1;index<=3;index++) document.write('<BUTTON onclick="ButtonPress('+index+');">Button '+index+'</BUTTON>'); function ButtonPress(buttonnumber) { parent.information.document.write('<LI>You pressed button number : '+buttonnumber+'</LI>'); } </SCRIPT> </HEAD> </HTML> This code should be saved in the same folder as 'FramesforDDC.htm', and as 'ButtonsforFrames.htm'. There is a significant development with this example, which is to navigate successfully through the window frame hierarchy, to be able to name the frame we intend to write to. As we are in frame 'Buttons', its parent is 'Window', which has two frames, 'Buttons' and 'Information'. We need the frame 'information', and so this has the relative reference parent.information. This is a reference to a window, and so we access the document part of it. I have put the recorded button presses in a list to maintain order.

UNIT- IV
http://www.roseindia.net/servlets/HolisticCounterInServlet.shtml Success is not the result of spontaneous combustion. You must set yourself on fire . Page 77

Introduction to Java Servelets Programming


What is Java Servlets? Servlets are server side components that provide a powerful mechanism for developing server side programs. Servlets provide component-based, platform-independent methods for building Web-based applications, without the performance limitations of CGI programs. Unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), servlets are server as well as platform-independent. This leaves you free to select a "best of breed" strategy for your servers, platforms, and tools. Using servlets web developers can create fast and efficient server side application which can run on any servlet enabled web server. Servlets run entirely inside the Java Virtual Machine. Since the Servlet runs at server side so it does not checks the browser for compatibility. Servlets can access the entire family of Java APIs, including the JDBC API to access enterprise databases. Servlets can also access a library of HTTP-specific calls, receive all the benefits of the mature java language including portability, performance, reusability, and crash protection. Today servlets are the popular choice for building interactive web applications. Third-party servlet containers are available for Apache Web Server, Microsoft IIS, and others. Servlet containers are usually the components of web and application servers, such as BEA WebLogic Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System Application Server and others. Servlets are not designed for a specific protocols. It is different thing that they are most commonly used with the HTTP protocols Servlets uses the classes in the java packages javax.servlet and javax.servlet.http. Servlets provides a way of creating the sophisticated server side extensions in a server as they follow the standard framework and use the highly portable java language. HTTP Servlet typically used to:

Priovide dynamic content like getting the results of a database query and returning to the client. Process and/or store the data submitted by the HTML. Manage information about the state of a stateless HTTP. e.g. an online shopping car manages request for multiple concurrent customers.

Methods of Servlets
A Generic servlet contains the following five methods:

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 78

init() public void init(ServletConfig config) throws ServletException The init() method is called only once by the servlet container throughout the life of a servlet. By this init() method the servlet get to know that it has been placed into service. The servlet cannot be put into the service if

The init() method does not return within a fix time set by the web server. It throws a ServletException

Parameters - The init() method takes a ServletConfig object that contains the initialization parameters and servlet's configuration and throws a ServletException if an exception has occurred. service() public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException Once the servlet starts getting the requests, the service() method is called by the servlet container to respond. The servlet services the client's request with the help of two objects. These two objects javax.servlet.ServletRequest and javax.servlet.ServletResponse are passed by the servlet container. The status code of the response always should be set for a servlet that throws or sends an error. Parameters - The service() method takes the ServletRequest object that contains the client's request and the object ServletResponse contains the servlet's response. The service() method throws ServletException and IOExceptions exception.

getServletConfig() public ServletConfig getServletConfig() This method contains parameters for initialization and startup of the servlet and returns a ServletConfig object. This object is then passed to the init method. When this interface is implemented then it stores the ServletConfig object in order to return it. It is done by the generic class which implements this inetrface. Returns - the ServletConfig object getServletInfo() public String getServletInfo() Success is not the result of spontaneous combustion. You must set yourself on fire . Page 79

The information about the servlet is returned by this method like version, author etc. This method returns a string which should be in the form of plain text and not any kind of markup. Returns - a string that contains the information about the servlet destroy() public void destroy() This method is called when we need to close the servlet. That is before removing a servlet instance from service, the servlet container calls the destroy() method. Once the servlet container calls the destroy() method, no service methods will be then called . That is after the exit of all the threads running in the servlet, the destroy() method is called. Hence, the servlet gets a chance to clean up all the resources like memory, threads etc which are being held.

Life cycle of Servlet


The life cycle of a servlet can be categorized into four parts: 1. Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute <loadon-startup> of web.xml file. If the attribute <load-on-startup> has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet. 2. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet. The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet. 3. Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object. 4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection. Success is not the result of spontaneous combustion. You must set yourself on fire . Page 80

Features of Servlets
In this tutorial you will learn the new features added in Servlet 2.4. 1. Upgraded supports for Http, J2SE, and J2EE: Servlet 2.4 depends on Http1.1 and J2SE 1.3. 2. Additional ServletRequest methods : In Servlet 2.4 four new methods are added in the ServletRequest o getRemotePort(): It returns the IP source port of the client. o getLocalName(): It returns the host name on which the request was recieved. o getLocalAddr(): It returns the IP address on which the request was recieved. o getLocalPort(): It returns the IP port number. 3. New Support for Internationalization and charset choice: To provide support of internationization, Servlet 2.4 has added two new methods in the ServletResponse interface. o setCharacterEncoding(String encoding): The purpose of this method is to set the response's character encoding. This method helps us to pass a charset parameter to setContentType(String) or passing a Locale to setLocale(Locale). We can now avoid setting the charset in the setContentType("text/html;charset=UTF-8") as setCharacterEncoding() method pairs with the pre-existing getCharacterEncoding() method to manipulate and view the response's character encoding. getContentType(): It is responsible for returning the response's content type. The content type can be dynamically set with a combination of setContentType(), setLocale(), and setCharacterEncoding() calls, and the method getContentType() provides a way to view the generated type string. 4. New features has been added in RequestDispatcher: In Servlet 2.4 five new request attributes has been added for providing extra information during a RequestDispatcher Success is not the result of spontaneous combustion. You must set yourself on fire .
o

Page 81

forward() call. This features has been added is Servlet 2.4 to know the true original request URI. The following request attributes are: o javax.servlet.forward.request_uri o javax.servlet.forward.context_path o javax.servlet.forward.servlet_path o javax.servlet.forward.path_info o javax.servlet.forward.query_string

5. SingleThreadModel interface has been deprecated: In Servlet 2.4 the SingleThreadModel interface has been deprecated. 6. HttpSession details and interaction with logins has been clarified: The new method HttpSession.logout() has been added in Servlet 2.4. Now session allows zero or negative values in the <session-timeout> element to indicate sessions should never time out. If the object in the session can't be serialize in a distributed environment then it must throw an IllegalArgumentException. 7. Welcome file behavior and Classloading has been clarified: In servlet 2.4 welcome file can be a servlet. 8. The web.xml file now uses XML Schema: Version 2.4 servers must still accept the 2.2 and 2.3 deployment descriptor formats, but all new elements are solely specified in Schema.

Features of Servlet 2.5


This version has been released on September 26, 2005 by the Sun MicroSystems. It is not necessary that all web servers and application servers support the features of Servlet 2.5. Still most of the popular containers like Tomcat 5.5 and JBoss 4.0 support Servlet 2.4. The list of the added features is given below: 1. Dependency on J2SE 5.0: The minimum platform requirement for Servlet 2.5 is JDK 1.5. Servet 2.5 can't be used in versions below than JDK1.5. All the available features of JDK1.5 like generics, autoboxing, an improved for loop etc are guaranteed available to Servlet 2.5 programmers. 2. Support For annotations: Annotations provide a mechanism for decorating java code constructs (classes, methods, fields, etc.) with metadata information. Annotations are mark code in such a way that code processors may alter their behavior based on the metadata information. 3. Several web.xml convenience: Servlet 2.5 introduces several small changes to the web.xml file to make it more convenient to use. For example while writing a <filtermapping>, we can now use an asterisk in a <servlet-name> which will represent all servlets as well as JSP. Previously we used to do <filter-mapping> Success is not the result of spontaneous combustion. You must set yourself on fire . Page 82

<filter-name>FilterName</filter-name> <servlet-name>FilterName</servlet-name> </filter-mapping> Now, <filter-mapping> <filter-name>FilterName</filter-name> <servlet-name>*</servlet-name> </filter-mapping> Previously in <servlet-mapping> or <filter-mapping> there used to be only one <urlpattern>, but now we can have multiple <url-pattern>, like <servlet-mapping> <servlet-name>abc</servlet-name> <url-pattern>/abc/*</url-pattern> <url-pattern>/abc/*</url-pattern> </servlet-mapping> Apart from these changes, many more facilities added in web.xml. 4. A Handful of removed restrictions: Servlet 2.5 removed a few restrictions around error handling and session tracking. Now it has removed the restriction that the <error-page> could not call the setStatus() method to alter the error code that triggered them. In session tracking, Servlet 2.5 eased a rule that a servlet called by RequestDispatcher include() couldn't set response headers. 5. Some edge case clarifications: The servlet 2.4 specification says that before calling request.getReader() we must call request.setCharacterEncoding(). However there is no such clarification given why it is so.

Advantages of Java Servlets


1. 2. 3. 4. 5. 6. 7. Portability Powerful Efficiency Safety Integration Extensibilty Inexpensive Page 83

Success is not the result of spontaneous combustion. You must set yourself on fire .

Each of the points are defined below: Portability As we know that the servlets are written in java and follow well known standardized APIs so they are highly portable across operating systems and server implementations. We can develop a servlet on Windows machine running the tomcat server or any other server and later we can deploy that servlet effortlessly on any other operating system like Unix server running on the iPlanet/Netscape Application server. So servlets are write once, run anywhere (WORA) program. Powerful We can do several things with the servlets which were difficult or even impossible to do with CGI, for example the servlets can talk directly to the web server while the CGI programs can't do. Servlets can share data among each other, they even make the database connection pools easy to implement. They can maintain the session by using the session tracking mechanism which helps them to maintain information from request to request. It can do many other things which are difficult to implement in the CGI programs. Efficiency As compared to CGI the servlets invocation is highly efficient. When the servlet get loaded in the server, it remains in the server's memory as a single object instance. However with servlets there are N threads but only a single copy of the servlet class. Multiple concurrent requests are handled by separate threads so we can say that the servlets are highly scalable. Safety As servlets are written in java, servlets inherit the strong type safety of java language. Java's automatic garbage collection and a lack of pointers means that servlets are generally safe from memory management problems. In servlets we can easily handle the errors due to Java's exception handling mechanism. If any exception occurs then it will throw an exception. Integration Servlets are tightly integrated with the server. Servlet can use the server to translate the file paths, perform logging, check authorization, and MIME type mapping etc. Extensibility The servlet API is designed in such a way that it can be easily extensible. As it stands today, the servlet API support Http Servlets, but in later date it can be extended for another type of servlets. Inexpensive There are number of free web servers available for personal use or for commercial purpose. Web servers are relatively expensive. So by using the free available web servers you can add servlet support to it .

Introduction to Server Side Programming


Success is not the result of spontaneous combustion. You must set yourself on fire . Page 84

All of us (or most of us) would have started programming in Java with the ever famous ?Hello World!? program. If you can recollect, we saved this file with a .java extension and later compiled the program using javac and then executed the class file with java. Apart from introducing you to the language basics, the point to be noted about this program is that ? ?It is a client side program?. This means that you write, compile and also execute the program on a client machine (e.g. Your PC). No doubt, this is the easiest and fastest way to write, compile and execute programs. But, it has little practical significance when it comes to real world programming. 1. Why Server Side Programming?

Though it is technically feasible to implement almost any business logic using client side programs, logically or functionally it carries no ground when it comes to enterprise applications (e.g. banking, air ticketing, e-shopping etc.). To further explain, going by the client side programming logic; a bank having 10,000 customers would mean that each customer should have a copy of the program(s) in his or her PC which translates to 10,000 programs! In addition, there are issues like security, resource pooling, concurrent access and manipulations to the database which simply cannot be handled by client side programs. The answer to most of the issues cited above is ? ?Server Side Programming?. Figure-1 illustrates Server side architecture in the simplest terms.

2. Advantages of Server Side Programs The list below highlights some of the important advantages of Server Side programs. i. All programs reside in one machine called the Server. Any number of remote machines (called clients) can access the server programs. ii. New functionalities to existing programs can be added at the server side which the clients? can advantage without having to change anything from their side. iii. Migrating to newer versions, architectures, design patterns, adding patches, switching to new databases can be done at the server side without having to bother about clients? hardware or software capabilities. iv. Issues relating to enterprise applications like resource management, concurrency, session management, security and performance are managed by service side applications.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 85

v.

They are portable and possess the capability to generate dynamic and user-based content (e.g. displaying transaction information of credit card or debit card depending on user?s choice).

3. Types of Server Side Programs i. Active Server Pages (ASP) ii. Java Servlets iii. Java Server Pages (JSPs) iv. Enterprise Java Beans (EJBs) v. PHP
To summarize, the objective of server side programs is to centrally manage all programs relating to a particular application (e.g. Banking, Insurance, e-shopping, etc). Clients with bare minimum requirement (e.g. Pentium II, Windows XP Professional, MS Internet Explorer and an internet connection) can experience the power and performance of a Server (e.g. IBM Mainframe, Unix Server, etc) from a remote location without having to compromise on security or speed. More importantly, server programs are not only portable but also possess the capability to generate dynamic responses based on user?s request.

Introduction to Java Servlets


Java Servlets are server side Java programs that require either a Web Server or an Application Server for execution. Examples for Web Servers include Apache?s Tomcat Server and Macromedia?s JRun. Web Servers include IBM?s Weblogic and BEA?s Websphere server. Examples for other Server programs include Java Server Pages (JSPs) and Enterprise Java Beans (EJBs). In the forthcoming sections, we will get acquainted with Servlet fundamentals and other associated information required for creating and executing Java Servlets. 1. Basic Servlet Structure

As seen earlier, Java servlets are server side programs or to be more specific; web applications that run on servers that comply HTTP protocol. The javax.servlet and javax.servlet.http packages provide the necessary interfaces and classes to work with servlets. Servlets generally extend the HttpServlet class and override the doGet or the doPost methods. In addition, other methods such as init, service and destroy also called as life cycle methods might be used which will be discussed in the following section. The skeleton of a servlet is given in Figure

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 86

A Servlet?s Life Cycle

The first time a servlet is invoked, it is the init method which is called. And remember that this is called only once during the lifetime of a servlet. So, you can put all your initialization code here. This method next calls the service method. The service method in turn calls the doGet or doPost methods (whichever the user has overridden). Finally, the servlet calls the destroy method. It is in a sense equivalent to the finally method. You can reset or close references / connections done earlier in the servlet?s methods (e.g. init, service or doGet /doPost). After this method is called, the servlet ceases to exist for all practical purposes. However, please note that it is not mandatory to override all these methods. More often than not, it is the doGet or doPost method used with one or more of the other life cycle methods.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 87

A Servlet Program

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 88

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 89

Output Screens To appreciate the execution of the servlet life cycle methods, keep refreshing the browser (F5 in Windows). In the background, what actually happens is ? with each refresh, the doGet method is called which increments i?s value and displays the current value. Find below the screen shots (Figures 5 through 7) captured at random intervals. The procedure to run the servlets using a Web Server will be demonstrated in the next section (1.3.).

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 90

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 91

Installation, Configuration and running Servlets


In this section, we will see as how to install a WebServer, configure it and finally run servlets using this server. Throughout this tutorial, we will be using Apache?s Tomcat server as the WebServer. Tomcat is not only an open and free server, but also the most preferred WebServer across the world. A few reasons we can attribute for its popularity is ? Easy to install and configure, very less memory footprint, fast, powerful and portable. It is the ideal server for learning purpose. 1. Installation of Tomcat Server and JDK As mentioned earlier, Apache?s Tomcat Server is free software available for download @ www.apache.org. The current version of Tomcat Server is 6.0 (as of November 2007). This Server supports Java Servlets 2.5 and Java Server Pages (JSPs) 2.1 specifications. In case of doubt or confusion, you can refer to the abundant documentation repository available on this site. Important software required for running this server is Sun?s JDK (Java Development Kit) and JRE (Java Runtime Environment). The current version of JDK is 6.0. Like Tomcat, JDK is also free and is available for download at www.java.sun.com. 2. Configuring Tomcat Server Success is not the result of spontaneous combustion. You must set yourself on fire . Page 92

Set JAVA_HOME variable - You have to set this variable which points to the base installation directory of JDK installation. (e.g. c:\program file\java\jdk1.6.0). You can either set this from the command prompt or from My Computer -> Properties -> Advanced -> Environment Variables. o Specify the Server Port ? You can change the server port from 8080 to 80 (if you wish to) by editing the server.xml file in the conf folder. The path would be something like this ? c:\program files\apache software foundation\tomcat6\conf\server.xml 3. Run Tomcat Server Once the above pre-requisites are taken care, you can test as whether the server is successfully installed as follows: Step 1 ? Go to C:\Program Files\Apache Software Foundation\Tomcat 6.0\bin and double click on tomcat6 OR ? Go to Start->Programs->Apache Tomcat 6.0 -> Monitor Tomcat. You will notice an icon appear on the right side of your Status Bar. Right click on this icon and click on Start service. Step 2 ? Open your Browser (e.g. MS Internet Explorer) and type the following URL : http://localhost/ (If you have changed to port # to 80) OR ? Open your Browser (e.g. MS Internet Explorer) and type the following URL : http://localhost:8080/ (If you have NOT changed the default port #) In either case, you should get a page similar to the one in Figure-8 which signifies that the Tomcat Server is successfully running on your machine. 4. Compile and Execute your Servlet This section through a step by step (and illustration) approach explains as how to compile and then run a servlet using Tomcat Server. Though this explanation is specific to Tomcat, the procedure explained holds true for other Web servers too (e.g. JRun, Caucho?s Resin). Step 1 ? Compile your servlet program The first step is to compile your servlet program. The procedure is no different from that Success is not the result of spontaneous combustion. You must set yourself on fire . Page 93

of writing and compiling a java program. But, the point to be noted is that neither the javax.servlet.* nor the javax.servlet.http.* is part of the standard JDK. It has to be exclusively added in the CLASSPATH. The set of classes required for writing servlets is available in a jar file called servlet-api.jar. This jar file can be downloaded from several sources. However, the easiest one is to use this jar file available with the Tomcat server (C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar). You need to include this path in CLASSPATH. Once you have done this, you will be able to successfully compile your servlet program. Ensure that the class file is created successfully. Step 2 ? Create your Web application folder The next step is to create your web application folder. The name of the folder can be any valid and logical name that represents your application (e.g. bank_apps, airline_tickets_booking, shopping_cart,etc). But the most important criterion is that this folder should be created under webapps folder. The path would be similar or close to this - C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps. For demo purpose, let us create a folder called demo-examples under the webapps folder.

Figure- depicts the same. Step 3 ? Create the WEB-INF folder The third step is to create the WEB-INF folder. This folder should be created under your web application folder that you created in the previous step. Figure-10 shows the WEB-INF folder being placed under the demo-examples folder.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 94

Figure ? WEB-INF folder inside web application folder Step 4 ? Create the web.xml file and the classes folder The fourth step is to create the web.xml file and the classes folder. Ensure that the web.xml and classes folder are created under the WEB-INF folder. Figure-11 shows this file and folder being placed under the WEB-INF folder.

Figure ? web.xml file and the classes folder Note ? Instead of creating the web.xml file an easy way would be to copy an existing web.xml file (e.g. C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\examples\WEBINF) and paste it into this folder. You can later edit this file and add relevant information to your web application. Step 5 ? Copy the servlet class to the classes folder We need to copy the servlet class file to the classes folder in order to run the servlet that we created. All you need to do is copy the servlet class file (the file we obtained from Step 1) to this folder. Figure-12 shows the servlet_lifecycle (refer section 1.2.3.) class being placed in the classes folder.

Figure ? servlet class file placed under classes folder Step 6 ? Edit web.xml to include servlet?s name and url pattern This step involves two actions viz. including the servlet?s name and then mentioning the url pattern. Let us first see as how to include the servlet?s name in the web.xml file. Open the web.xml file and include the servlet?s name as shown in Figure-13. Success is not the result of spontaneous combustion. You must set yourself on fire . Page 95

Figure? Include servlet?s name using the <servlet> </servlet> tag Note ? The servlet-name need not be the same as that of the class name. You can give a different name (or alias) to the actual servlet. This is one of the main reasons as why this tag is used for. Next, include the url pattern using the <servlet-mapping> </servlet-mapping> tag. The url pattern defines as how a user can access the servlet from the browser. Figure-14 shows the url pattern entry for our current servlet.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 96

Figure ? Include url-pattern using the <servlet-mapping> </servlet-mapping> tag Note ? Please remember that the path given in the url-pattern is a relative path. This means that this path is w.r.t. your web applications folder (demo-examples in this case). Step 7 ? Run Tomcat server and then execute your Servlet This step again involves two actions viz. running the Web Server and then executing the servlet. To run the server, follow the steps explained in Section 1.3.3. After ensuring that the web server is running successfully, you can run your servlet. To do this, open your web browser and enter the url as specified in the web.xml file. The complete url that needs to be entered in the browser is: http://localhost/demo-examples/servlet_lifecycle

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 97

Figure ? Our servlet?s output! Eureka! Here?s the output of our first servlet. After a long and pain staking effort, we finally got an output! As mentioned in Section 1.2.3. you can keep refreshing the browser window and see for yourself as how i value is incremented (a proof that the doGet is called every time you reinvoke a servlet).

How to Run a Servlet


To run a servlet one should follow the steps illustrated below:

Download and Install the tomcat server: Install the tomcat server in a directory in which you want to install and set the classpath.for the variable JAVA_HOME in the environment variable. To get details about the installation process and setting the classpath click the link Tomcat installation. Set the class for the jar file: Set the classpath of the servlet-api.jar file in the variable CLASSPATH inside the environment variable by using the following steps. For Windows XP, Go to Start->Control Panel->System->Advanced->Environment Variables->New button and Set the values as Variable Name: CLASSPATH Variable Value: C:\Program Files\Java\Tomcat 6.0\lib\servlet-api.jar For Windows 2000 and NT Go to Start->Settings->Control Panel->System->Environment Variables->New button and Set the values as Variable Name: CLASSPATH Variable Value: C:\Program Files\Java\Tomcat 6.0\lib\servlet-api.jar

Create a java source file and a web.xml file in a directory structure. Compile the java source file, put the compiled file (.class file) in the classes folder of your application and deploy the directory of your application in the webapps folder inside the tomcat directory. Start the tomcat server, open a browser window and type the URL http://localhost:8080/directory (folder name of your application) name/servler name and press enter. If everything is correct your servlet will run.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 98

Writing Servlet Hello World


We should start understanding the servlets from the beginning. Lets start by making one program which will just print the "Hello World" on the browser. Each time the user visits this page it will display "Hello World" to the user. As we know that the our servlet extends the HttpServlet and overrides the doGet() method which it inherits from the HttpServlet class. The server invokes doGet() method whenever web server recieves the GET request from the servlet. The doGet() method takes two arguments first is HttpServletRequest object and the second one is HttpServletResponse object and this method throws the ServletException. Whenever the user sends the request to the server then server generates two obects, first is HttpServletRequest object and the second one is HttpServletResponse object. HttpServletRequest object represents the client's request and the HttpServletResponse represents the servlet's response. Inside the doGet(() method our servlet has first used the setContentType() method of the response object which sets the content type of the response to text/html. It is the standard MIME content type for the Html pages. After that it has used the method getWriter() of the response object to retrieve a PrintWriter object. To display the output on the browser we use the println() method of the PrintWriter class. The code the program is given below: 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{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<html>"); pw.println("<head><title>Hello World</title></title>"); pw.println("<body>"); pw.println("<h1>Hello World</h1>"); pw.println("</body></html>"); } }

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 99

web.xml file for this program:


<?xml version="1.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> </web-app>

The output of the program is given below:

Displaying Date in Servlet


In this example we are going to show how we can display a current date and time on our browser. It is very easy to display it on our browser by using the Date class of the java.util package. As we know that the our servlet extends the HttpServlet and overrides the doGet() method which it inherits from the HttpServlet class. The server invokes doGet() method whenever web server recieves the GET request from the servlet. The doGet() method takes two arguments first is HttpServletRequest object and the second one is HttpServletResponse object and this method throws the ServletException. Whenever the user sends the request to the server then server generates two obects, first is HttpServletRequest object and the second one is HttpServletResponse object. HttpServletRequest object represents the client's request and the HttpServletResponse represents the servlet's response. Success is not the result of spontaneous combustion. You must set yourself on fire . Page 100

Inside the doGet(() method our servlet has first used the setContentType() method of the response object which sets the content type of the response to text/html. It is the standard MIME content type for the Html pages. The MIME type tells the browser what kind of data the browser is about to receive. After that it has used the method getWriter() of the response object to retrieve a PrintWriter object. To display the output on the browser we use the println() method of the PrintWriter class. The code the program is given below:
import import import import java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

public class DisplayingDate extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ PrintWriter pw = response.getWriter(); Date today = new Date(); pw.println("<html>"+"<body><h1>Today Date is</h1>"); pw.println("<b>"+ today+"</b></body>"+ "</html>"); } }

XML File for this program


<?xml version="1.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> --> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>DateDisplay</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/DateDisplay</url-pattern> </servlet-mapping> </web-app>

The output of the program is given below:

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 101

Simple Counter in Servlet


In this example we are going to know how we can make a program on counter which will keep track how many times the servlet has been accessed. To make this program firstly we have to make one class SimpleCounterInServlet. The name of the class should follow the naming convention. Remember to keep the name of the class in such a way that it becomes easy to understand what the program is going to do just by seeing the class name. After making a class define one variable counter which will keep record for how many times the servlet has been accessed. Now use method either doGet() or doPost() to write a logic of the program. Our program logic is simple. We have to just increment the value of the counter by 1. To display the output use the method getWriter() method of the response object which will in turn return the object of the PrintWriter class. Now display the value of the counter. The code of the program is given below:
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SimpleCounter extends HttpServlet{ int counter = 0; public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); counter++; pw.println("At present the value of the counter is " + counter); } }

The output of the program is given below:

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 102

Introduction to Applet Programming


Introduction
Applets This lesson provides a very brief introduction to the programming of Java Applets. Two Approaches To repeat some of what we said in an earlier lesson, Java programs can be written and executed in two ways:

Stand-alone application, run from the command line. Applet which runs under control of a Java-capable browser or the AppletViewer program.

A Third Approach Actually we said that with a little extra programming effort, it is also possible to run most applets as standalone programs. We will illustrate this at the end of this lesson. What About A Graphical User Interface (GUI)? Programming a simple applet in Java is significantly different from programming a simple application. This is particularly true when the application doesn't make use of a Graphical User Interface (GUI). When the application does make use of a GUI, the programming requirements for the two are more similar. When a simple graphical user interface is needed, applet programming can be easier than application programming. We will also illustrate this at the end of the lesson. Applet Execution Mode Applets are designed to be downloaded and executed on-line, under control of a Java-capable browser. A Java-Capable Browser What do we mean by a Java-Capable browser? We mean a browser that contains its own Java Virtual Machine, which (hopefully) is compatible with all the programming features included in your applet. As of August 1999, this compatibility issue continues to be a serious one, but not as serious as it was in past years.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 103

The Java Virtual Machine What do we mean by a Java Virtual Machine or JVM? A JVM is a program that is capable of extracting the bytecode data from the compiled class files and using them to cause the behavior of the computer to match what the Java programmer (hopefully) had in mind when she wrote the Java application or applet in the first place. Using a Different Language to Produce Bytecode Could you use another language (possibly one of your own design) to create applets? The answer is probably yes. All that would be necessary would be for your other language to create class files whose contents match the requirements of the JVM, although that may be much easier said than done. All the browser actually sees is the class files. It really doesn't know how they were created as long as they meet the specifications for the Java language and JVM. Special Security Procedures Apply Because applets are designed to be downloaded and executed on-line, special security procedures are implemented. Applet functionality is restricted by the browser in an attempt to prevent downloaded applets from damaging your computer or your data. Note that such restrictions are not a function of the Java language. Rather, they are imposed by a security manager that is a part of browser. In theory, you could write your own browser that would impose no such requirements on the execution of applets (but that might not be a wise thing to do). Security in JDK 1.1 Capabilities were designed into JDK 1.1 to allow the individual to decide the level of security restrictions that are to be imposed on applets when they are executed. However, as of August 1999, I don't believe that either the Netscape or Microsoft browser products are fully supporting this capability. New Security Requirements in JDK 1.2 Actually, security is a moving target. Major changes in the security area were introduced in JDK 1.2 in December 1998. However, the details are far too complex for an introductory course in Java. The topic of security will be discussed in more detail in a subsequent lesson on Advanced Java Programming. Is a main() Method Required? A stand-alone Java program (Java application) requires a method named main in its controlling class.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 104

An Applet does not require a main method, but we will show at the end of this lesson that it is technically all right to include a main() method in an applet to support standalone operation.

A Brief Word about Overriding Methods


In order to understand the program code for an applet, it is necessary to have some understanding of the concept of overriding methods. This topic will be covered in more detail later, so this is simply an introduction to help you understand the applet code that is presented later in this lesson. Runtime Polymorphism Overriding methods is an aspect of inheritance and results in a mode of behavior that we refer to as runtime polymorphism. (You should already know about inheritance and runtime polymorphism as a result of studying one of the early lessons in this series on Object-Oriented Programming.) Inheritance New classes can be defined by extending (inheriting from) existing classes. The new class is often referred to as the subclass and the class being extended is often referred to as the superclass. (Many other names are used as well as explained in the earlier lesson on ObjectOriented Programming.) When a new class extends an existing class, all the variables and methods which are members of the superclass (and which are members of all the ancestors of the superclass) become members of the subclass. This is an extremely important statement. Turn it over in your mind a few times to make sure that you realize the full impact of what I just said. Modifying Behavior In the event that the behavior specified by a method of the superclass (or one of its ancestors) is not appropriate for objects of the new type defined by the subclass, it is possible to rewrite the method in the subclass to cause it to impart different behavior for objects of the subclass type. This is another extremely important statement. Make certain that you think about it and understand what it means. It might also be worthwhile for you to go back and review the section on overriding methods in the earlier lesson on Object-Oriented programming. That section contains a small, but very important sample program illustrating the general behavior of overridden methods.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 105

Overriding a Method in Java Rewriting the method in the subclass is referred to as overriding the method. All that is required to override a method in Java is to use the same method signature in the subclass and then provide a different body for the method. Overriding a Method in C++ C++ programmers may recall that the procedure for overriding a method in C++ is a little more complicated, requiring among other things that the method being overridden be originally defined as a virtual method.

A Brief Word about the Java Class Hierarchy


The Object Class All classes automatically derive from a superclass named Object or from a direct or indirect subclass of Object. All classes in Java form a hierarchical pyramid with the Object class at the top of the pyramid. The Object class defines a number of methods that are inherited by and are available to all direct or indirect subclasses of the Object class. Similarly, in the standard Java class libraries, various direct and indirect subclasses of Object provide additional methods that are inherited by new subclasses that you define. All Classes are Direct or Indirect Subclasses of Object Whenever you define a new class, it is a subclass of Object by default. However, you will often want to take advantage of the functionality of existing subclasses of Object by extending one of those existing subclasses. That is the case when we define the class for and write the code for an applet. When Should You Override Methods? Sometimes, you will be content with leaving the inherited methods alone and either using them as defined, or ignoring them altogether. At other times, you will need to modify the behavior of certain inherited methods by overriding them in new classes that you define.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 106

The "Hello World" Applet


What Is an Applet? According to The Java Tutorial, by Mary Campione and Kathy Walrath, which at the time of this writing could be downloaded from http://java.sun.com:80/books/Series/Tutorial/index.html,
"... a Java Applet is a program that adheres to a set of conventions that allows it to run within a Java-compatible browser."

Three Ways to Execute an Applet There are at least two ways to execute a Java applet (actually three ways with a little extra programming effort). AppletViewer One way, and this is often the preferable way for testing, is to execute the applet using the AppletViewer program which is a standard part of the JDK. Java-Capable Browser A second way to execute a Java applet, and this is the way that you make applets available to others on your Web site, is to view it using a Java-capable browser program. In both cases, it is necessary to produce an HTML file containing tags that reference the applet. HTML files will be discussed briefly a little later. Running Applet in Standalone Mode The third way to execute an applet is to run it in a standalone mode. This does not require an HTML file. It does require that a main() method is contained in the controlling class for the applet. The "Hello World" Applet A sample applet that displays Hello World follows. Note that the controlling class for this applet

extends the Applet class, and overrides the paint() method.

The various parts of the applet are presented and discussed later in this lesson.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 107

/*Applet program hello3.java This is a Java applet that produces the same output as the application named hello1.java, except this program runs under a browser or the Applet Viewer. *********************************************************/ import java.applet.Applet;//see discussion on packages import java.awt.Graphics; public class hello3 extends Applet { //override the paint method public void paint(Graphics screen) { screen.drawString("Hello World",50,25); } } //End hello3 class. //End applet

A Brief Word about Packages


What is a Package? Packages are used in Java to group classes similar to the way libraries are used to group functions and classes in C++. Packages will be discussed in more detail in a subsequent lesson. Suffice it for now to say that a package is nothing more and nothing less than the specification of a directory on your hard drive that contains a group of (probably) related class files. Importing Classes The above program contains two import statements. Except for certain classes that are automatically imported (such as the System class) when a Java program is compiled, Java programs can import classes or packages containing classes in order to access the classes with minimal code. Doing it the Hard Way If we were to delete the import directives in the above program, we could still compile and run the program, but only if we made the modifications shown in boldface below. As you can see, this requires more typing effort on your part.
public class hello3 extends java.applet.Applet { public void paint(java.awt.Graphics screen) { screen.drawString("Hello World",50,25); } } //End hello3 class.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 108

Why Use Import Directives? The import directives are a convenience to the programmer making it possible to refer to the classes without the requirement to provide a fully qualified path name for every class. Importing Packages As an alternative to importing individual classes, you can import entire packages using a wildcard character as shown below. This may slow down compilation but will have no detrimental impact at runtime.
import java.applet.*; import java.awt.*;

The Default Package All classes are in packages, either the package specified when the class is defined, or in the default package. All of the classes within a package can refer to each other without using fully qualified path names. As mentioned above, packages will be discussed in more detail in a subsequent lesson.

A Brief Word about Inheritance and Applets


In both Java and C++, classes can inherit from other classes. (Inheritance will be discussed in more detail in a subsequent lesson.) In Java, a class which inherits from another class is called a subclass and the inheritance is accomplished using the keyword extends. (Inheritance syntax is much different in C++.) Applets Must Extend the Applet Class Every applet must inherit a subclass from the Applet class by extending the Applet class (which was imported in the above program). Furthermore, that subclass must be defined as public. What About main()? Applets do not need a main method (but may have one if you want to be able to run them in a standalone mode).

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 109

What Methods Must an Applet Override? An applet must override at least one of the following methods, and can override more than one.

init() start() paint().

Overridden paint() Method The overridden paint() method appears as shown in the following code fragment:
public void paint(Graphics screen) { screen.drawString("Hello World",50,25); }

Without going into detail at this point, the paint() method receives a reference to an object of type Graphics. This reference is known locally by the name screen. The Graphics class provides a method named drawString() that is used to "draw" a text string onto the Graphics object at a specified location. In this case, the Graphics object represents the computer's screen. That isn't always the case, but the exceptions are too advanced for an introductory course in Java. In this case, the string Hello World is drawn onto the Graphics object (and hence the screen) at a location of 50 pixels to the right and 25 pixels down from the top left-hand corner of the screen space occupied by the applet. Where Are These Methods Defined? init and start are methods of the Applet class. paint is a method of the component class that is inherited by several intermediate classes and is finally inherited by the Applet class. Why Override the Methods? There are some complex issues surrounding the overriding and use of these methods that will be discussed in subsequent lessons. Since this lesson is simply a brief introduction to applets, these issues will not be discussed further here.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 110

A Brief Word about the HTML Page


Where Does HTML come Into the Picture? Applets are intended to be included in HTML pages and downloaded from a Web site to a client computer. What is an <APPLET> Tag? You use the HTML <APPLET> tag to specify the location of the applet subclass (controlling class) and the dimensions of the onscreen display area. When the <APPLET> tag is encountered by a Java-capable browser, (or the AppletViewer program) it

reserves screen space, loads the specified subclass file, and instantiates an object of the subclass.

It then invokes one of the three methods listed above for the object causing the Applet to execute. These are Not Class Methods Unlike main(), the methods named init(), start() and paint() are not class methods. Therefore they cannot be invoked simply by joining the name of the method with the name of a class. These are instance methods and an object is required to invoke them. Creating HTML Files Instructions for creating simple HTML files can be obtained from a variety of sources, including several online locations on the Web. You can find links to hundreds of HTML resources at http://html.about.com/. (In fact, you can find hundreds of links to hundreds of different topics at http://about.com/.) A Sample HTML File There is no intention of providing a detailed discussion of HTML in this course of study. However, a minimum knowledge of HTML is required to work with applets. A sample HTML document that can be used to execute this Applet with the Applet Viewer or a Java-capable browser is shown below. Success is not the result of spontaneous combustion. You must set yourself on fire . Page 111

Appearance and Behavior of Applet As a word of caution, in some cases, the appearance and behavior of your applet will not be exactly the same when viewed with the AppletViewer and when viewed with a Java-capable browsers. Always test your applets using one or more browsers before publishing them on your Web page (the appearance and behavior may differ between different browsers as well).
<HTML> <HEAD> <title>Hello World Applet</title> </HEAD> <BODY> <applet code="hello3.class" width=300 height=100> </applet> </BODY> </HTML>

Running Applets in Standalone Mode


Earlier in this lesson I made the following statement: In some ways, when a graphical user interface is needed, applet programming is easier than application programming. I am now going to show you what I meant by that statement. The programs for most applets can be written so that can be run

under control of a Java-capable browser, under control of the AppletViewer program, or in a standalone mode.

Providing a Place for the Applet to Run For simple applets, all that is required to run an applet in a standalone mode is to provide a place for the applet to run (recall that the browser normally provides the place for it to run). Some additional code is required to provide that place when running the applet in a standalone mode. A main() Method in an Applet Although an applet doesn't require a main() method, there is no harm in providing one. If you provide an appropriate main() method, it can be invoked by the JVM to run the applet in a standalone mode. Unfortunately, the complexity of the main() method goes beyond what we have covered so far and it will be awhile before we cover enough material that you will be able to understand most of what you see in the following main() method. In fact, most of this material is not covered until the Intermediate Java Programming course.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 112

Sample Program
The following program will run

under control of a Java-capable browser (compatible with JDK 1.1.3 or later), under control of the AppletViewer program, or under control of the standalone JVM.

The comments pretty well explain what is going on. However, since we haven't covered any of the material involving the graphical user interface ( Frame, etc.), we won't discuss it in detail at this point. This program is provided simply to alert you to the possible dual nature of applet programs.
/*Applet program hello4.java This program illustrates that simple applets can run in a standalone mode as well as inside a browser or under the AppletViewer program. This is a Java applet which produces the same output as the applet named hello3, except that this program is capable of running either under AppletViewer or standalone. A main method is provided to support the running of the applet in the standalone mode. This program was tested using JDK 1.1.3 under Win95 */ import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class hello4 extends Applet { public void paint(Graphics screen) { screen.drawString("Hello World",50,25); }//end paint() //Provide a main method that can be used to run the // applet in a standalone mode. public static void main(String[] args){ //Create a Frame for the applet to run in Frame myFrame = new Frame( "Copyright 1997, R.G.Baldwin"); myFrame.setSize(300,100); //Instantiate a hello4 applet object. Applet myApplet = new hello4(); //Add the applet object to the Frame object myFrame.add(myApplet); //Make the whole thing visible myFrame.setVisible(true); //This code will terminate the program when the // user clicks the close button on the Frame

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 113

myFrame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0);}}); }//end main } //End hello4 class.

The following html file can be used to run this program under the AppletViewer program.
<HTML> <HEAD> <title>Hello World Applet</title> </HEAD> <BODY> <applet code="hello4.class" width=300 height=100> </applet> </BODY> </HTML>

Applet
What is an Applet?
An applet is a program written in java that can be included in an html page, much in the same way an image is included in a page. When we use a java-enabled browser to view a page that contains applet, the applet's code is downloaded to our web-browser and executed by browser's JVM.

Applet's development and execution


1. Writing the applet's code by extending java.applet.Applet class.
2. import java.awt.*; 3. import java.applet.*; 4. 5. public class myApplet extends Applet 6. { 7. public void paint(Graphics g) 8. { 9. g.drawString("simple applet"); 10. } }

Simple applet example. 11. Compile the code: javac myApplet.java 12. Writing the html code
13. <APPLET 14. code="myApplet.java" 15. width="480" 16. height="320">

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 114

</APPLET>

17. Execute the applet: appletviewer myWebpage.html

Parameters to applet
1. Include one or more <PARAM> tags in the <APPLET> tag.
2. <APPLET > 3. <PARAM 4. name = "parameterName" 5. value = "parameterValue"> 6. </PARAM> </APPLET>

7. Use the getParameter() method to receive the parameter.


8. 9. String parameter1; 10. 11. public void init() 12. { 13. parameter1 = getParameter("parameterName"); 14. if(parameter1==null) 15. parameter1 = "NO PARAMETER"; 16. } 17. 18. public void paint(Graphics g) 19. { 20. g.drawString("Paramter: "+parameter1); 21. }

Applet life cycle

Applet life cycle. Success is not the result of spontaneous combustion. You must set yourself on fire . Page 115

1. Born/Initialization state Applet enters the initialization state when it is first loaded. This is achieved by calling the init() method of applet class. At this stage, we may do initialization of various things. The initialization occurs only once in the applets life cycle. To initialization, we may override the init() method.
public void init() { // Initialization goes here. }

2. Running state Applet enters the running state when the system calls the start() method of applet class. This occurs automatically after the applet is initialized. Starting can also occur if the applet is already in idle state. For example, we may leave the web page containing the applet temporarly to another page and return back to the page. This again starts the applet running. The start() method may be called more than once. We have to override the start() method if we want to create thread to control the applet.
public void start() { // code goes here. }

paint() method may be invoked during running state in the following situation.

Applet enters into the running state. Applet is covered or uncovered by some other window. Applet is minimized and maximized

public void paint(Graphics g) { // Visual output operations go here. }

3. Idle state An applet become idle when it is stopped from running. Stopping occurs automatically when we leave the applet page. We can also do so by calling the stop() method.
public void stop() { // code goes here. }

4. Dead state An applet is said to be dead when it is removed from memory. This occurs automatically by invoking the destroy() method when we quit the browser. Like born state, dead state occurs only Success is not the result of spontaneous combustion. You must set yourself on fire . Page 116

once in the applets life cycle. We may override the destroy() method to clean up the previously allocated resources.
public void destroy() { // code goes here. }

Security restrictions
An applet is restricted from doing the following thinks.

load libraries or define native methods. access local file system. make network connections to the system other than it came from execute a program on the local file system. read certain system properties. initiate a print job or access system clipboard

A local applet may get freedom from some of the above restrictions.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 117

UNIT- V
Structure of Web Application
Overview of Web Applications A Web Application contains an application's resources, such as servlets, JavaServer Pages (JSPs), JSP tag libraries, and any static resources such as HTML pages and image files. A Web Application can also define links to outside resources such as Enterprise JavaBeans (EJBs). Web Applications deployed on WebLogic Server use a standard J2EE deployment descriptor file and a WebLogic-specific deployment descriptor file to define their resources and operating parameters. JSPs and HTTP servlets can access all services and APIs available in WebLogic Server. These services include EJBs, database connections via Java Database Connectivity (JDBC), JavaMessaging Service (JMS), XML, and more. A Web archive contains the files that make up a Web Application (WAR file). A WAR file is deployed as a unit on one or more WebLogic Servers. A Web archive on WebLogic Server always includes the following files:

At least one servlet or JSP page, along with any helper classes. A web.xml deployment descriptor, a J2EE standard XML document that describes the contents of a WAR file. A weblogic.xml deployment descriptor, an XML document containing WebLogic Serverspecific elements for Web applications.

A Web archive may also include HTML/XML pages and supporting files such as image and multimedia files. The WAR file can be deployed alone or packaged in an Enterprise Archive (EAR file) with other application components. If deployed alone, the archive must end with a .war extension. If deployed in an EAR file, the archive must end with an .ear extension. (Note: If you are deploying an entire directory, do not name the directory .ear, .war, .jar and so on.) Servlets Servlets are Java classes that execute in WebLogic Server, accept a request from a client, process it, and optionally return a response to the client. A GenericServlet is protocol independent and can be used in J2EE applications to implement services accessed from other Java classes. An HttpServlet extends GenericServlet with support for the HTTP protocol. An HttpServlet is most often used to generate dynamic Web pages in response to Web browser requests.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 118

JavaServer Pages JSP pages are Web pages coded with an extended HTML that makes it possible to embed Java code in a Web page. JSP pages can call custom Java classes, called taglibs, using HTML-like tags. The WebLogic JSP compiler, weblogic.jspc, translates JSP pages into servlets. WebLogic Server automatically compiles JSP pages if the servlet class file is not present or is older than the JSP source file. You can also precompile JSP pages and package the servlet class in the Web Archive to avoid compiling in the server. Servlets and JSP pages may depend upon additional helper classes that must also be deployed with the Web Application. Web Application Directory Structure Web Applications use a standard directory structure defined in the J2EE specification, and can be deployed as a collection of files that use this directory structure (this type of deployment is called exploded directory format) or as an archived file called a WAR file. Deploying a Web Application in exploded directory format is recommended primarily for use while developing your application. Deploying a Web Application as a WAR file is recommended primarily for production environments. Web Application components are assembled in a directory in order to stage the WAR file for the jar command. HTML pages, JSP pages, and the non-Java class files they reference are accessed beginning in the top level of the staging directory. The XML descriptors, compiled Java classes and JSP taglibs are stored in a WEB-INF subdirectory at the top level of the staging directory. Java classes include servlets, helper classes and, if desired, precompiled JSP pages. The entire directory, once staged, is bundled into a WAR file using the jar command. The WAR file can be deployed alone or packaged in an Enterprise Archive (EAR file) with other application components, including other Web Applications, EJB components, and WebLogic components. JSP pages and HTTP servlets can access all services and APIs available in WebLogic Server. These services include EJBs, database connections through Java Database Connectivity (JDBC), JavaMessaging Service (JMS), XML, and more.

Main Steps to Create a Web Application The following steps summarize the procedure for creating a Web Application. You may want to use developer tools included with WebLogic Server for creating and configuring Web Applications. For more information, see Web Application Developer Tools. Success is not the result of spontaneous combustion. You must set yourself on fire . Page 119

To create a Web Application: 1. Create the HTML pages and JSPs that make up the Web interface of the Web application. Typically, Web designers create these parts of a Web application. See Programming WebLogic JSP 2. Write the Java code for the servlets and the JSP taglibs referenced in JavaServer Pages (JSPs). Typically, Java programmers create these parts of a Web application. See Programming WebLogic HTTP Servlets. 3. Compile the servlets into class files. See "Preparing to Compile" in Developing WebLogic Server J2EE Applications. 4. Arrange the resources (servlets, JSPs, static files, and deployment descriptors) in the prescribed directory format. See Directory Structure. 5. Create the Web Application deployment descriptor (web.xml) and place the descriptor in the WEB-INF directory of the Web Application. In this step you register servlets, define servlet initialization parameters, register JSP tag libraries, define security constraints, and define other Web Application parameters. See Writing the web.xml Deployment Descriptor, and WebLogic Builder. You can edit Web Application deployment descriptors using various methods (see Tools for Editing Deployment Descriptors) 6. Create the WebLogic-specific deployment descriptor (weblogic.xml) and place the descriptor in the WEB-INF directory of the Web Application. In this step you define how WebLogic Server will define JSP properties, JNDI mappings, security role mappings, and HTTP session parameters. See Writing the WebLogic-Specific Deployment Descriptor (weblogic.xml), and WebLogic Builder. You can edit Web Application deployment descriptors using various methods (see Tools for Editing Deployment Descriptors) 7. Archive the Web Application files into a WAR file. (During development you may find it more convenient to update individual components of your Web Application in exploded directory format.) Use this command from the root directory of your Web Application: jar cv0f myWebApp.war . This command creates a Web Application archive file called myWebApp.war. Success is not the result of spontaneous combustion. You must set yourself on fire . Page 120

8. If you are deploying the Web Application as part of an enterprise application, bundle the WAR file into an Enterprise Application archive (EAR file). See Deploying Web Applications as Part of an Enterprise Application 9. Deploy the Web Application or Enterprise Application on WebLogic Server. This final step configures your application to service requests on WebLogic Server. See Deploying Web Applications.

Directory Structure Develop your Web Application within a specified directory structure so that it can be archived and deployed on WebLogic Server or another J2EE-compliant server. All servlets, classes, static files, and other resources belonging to a Web Application are organized under a directory hierarchy. The root of this hierarchy defines the document root of your Web Application. All files under this root directory can be served to the client, except for files under the special directory WEB-INF, located under the root directory. The name of your Web Application is used to resolve requests for components of the Web Application. Place private files in the WEB-INF directory, under the root directory. All files under WEB-INF are private, and are not served to a client. DefaultWebApp/ Place your static files, such as HTML files and JSP files in the directory that is the document root of your Web Application. In the default installation of WebLogic Server, this directory is called DefaultWebApp, under user_domains/mydomain/applications. DefaultWebApp/WEB-INF/web.xml The Web Application deployment descriptor that configures the Web Application. DefaultWebApp/WEB-INF/weblogic.xml The WebLogic-specific deployment descriptor file that defines how named resources in the web.xml file are mapped to resources residing elsewhere in WebLogic Server. This file is also used to define JSP and HTTP session attributes. DefaultWebApp/WEB-INF/classes Contains server-side classes such as HTTP servlets and utility classes. DefaultWebApp/WEB-INF/lib Contains JAR files used by the Web Application, including JSP tag libraries.

URLs and Web Applications Construct the URL that a client uses to access a Web Application using the following pattern: Success is not the result of spontaneous combustion. You must set yourself on fire . Page 121

http://hoststring/ContextPath/servletPath/pathInfo Where hoststring is either a host name that is mapped to a virtual host or hostname:portNumber. ContextPath is the context root of your Web Application, if one is specified in application.xml or weblogic.xml. If the context root is not specified, ContextPath is the name of the Web Application archive file (for example, myWebApp.war) or the name of the directory in which the Web Application was deployed. servletPath is a servlet that is mapped to the servletPath. pathInfo is the remaining portion of the URL, typically a file name. If you are using virtual hosting, you can substitute the virtual host name for the hoststring portion of the URL. For additional information, see How WebLogic Server Resolves HTTP Requests.

To develop an application using servlet or jsp make the directory structure like one given below and maintain the pages of your application according to this directory structure: Roseindia/ WEB-INF/ web.xml struts-config.xml classes/ Myservlet.class lib/ Myapp.jar Welcome.html Welcome.jsp

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 122

Tomcat and the Tomcat Web Application Directory Structure


ExerTran uses Apache Tomcat to dynamically generate web pages. The current system uses Tomcat 5. In a standard, or original, Tomcat installation, a web application, or webapp would be stored in the webapps directory of the Tomcat installation in a directory whose name defines the application's name. Instead of this the application directory is kept within the ExerTran directory structure and this directory is linked to Tomcat via an entry in the context file that is created for each coursework application: the context file tells Tomcat all about the application and this file is created and installed when a build of the coursework is performed.

Tomcat Web Application Directory Structure


The webapp directory is held in the coursework directory within the "courses" directory and is named after the coursework. If the coursework's name is D2, the coursework directory is "courses/D2Home" in the ExerTran installation directory, and the webapp directory is named "courses/D2Home/D2". The directory structure is as follows:jsp Success is not the result of spontaneous combustion. You must set yourself on fire . Page 123

This directory holds all the jsp files for the application, both system jsp files copied from the "src/jsp" directory (), but also question related jsp files from packages imported into the coursework or generated by the coursework lecturer (the chapter called Topic Packages). The directory structure of this directory is the same as that of the "src/jsp" directory, except that the "jsp/user/" directory also hold jsp files from the packages: with directories structured by package name. images This hold image files, primarily "gif", for particular questions. This directory is structured by package name. html This hold pure html files for particular questions. This directory is structured by package name. WEB-INF Tomcat hides the contents of this directory from users, and is the location where Java class files are stored as well as the Tomcat "web.xml" file which defines a number of parameters for the application in particular security information and the mapping of user requests, i.e. URIs, to servlets. The contents of this directory are as follows:web.xml This is a key file for running a Tomcat application and defines various features of the application. This file is created automatically during a coursework build from a template file, "web.tmpl", held in "src/templates", with substitution of parameters defined in the coursework definition file (the chapter called Coursework Definition File. The contents of this file are described in . classes This holds the Java classes for the application, both system jsp files compiled from the "src/java" directory (), but also from the question related java files from packages imported into the coursework or generated by the coursework lecturer (the chapter called Topic Packages). The directory structure of this directory is the same as that of the "src/java" directory, except that the "java/user/" directory also hold java files from the packages: with directories structured by package name. help This holds the help for the application, both system help files compied from the "src/help" directory (), but also from the question related help files from packages imported into the coursework or generated by the coursework lecturer (the chapter called Topic Packages). The structure of the help files is by question package, with the system help files in the directory "system". Success is not the result of spontaneous combustion. You must set yourself on fire . Page 124

logs This holds the log files produced from the execution of a coursework. There are 3 basic log files, usually called applicationlog.text, activitylog.txt, and mysqlLog.txt. The first of these logs debug messages from the coursework; the second logs user activity, particularly question attempts and marks awarded; the third error messages from the mysql database, which is the default database. When the coursework is re-started, these log files are compressed when they are larger then a set limit, and versions created. It may be necessary to change the compression to occur while the system is running, if regular closure of the application does not occur. A further log file is also created when the connection to the marks database fails and marks cannot be stored in the database. The marks are then recorded in a log file, from which they are read stored to the database when the coursework system is restarted: on successful storage of these marks, the log file is removed. lib This contains jar files needed by Tomcat to run the @systemname; application. These are copied from "src/lib" on a coursework build. images-xml This hold Xml files that define an image to be rendered by the "synDrawings" package: these images can be modified at run-time in response to user input. This directory is structured by package name. initParameters This holds files holding name-value pairs for use by jsp and java packages so that the ExerTran application can be varied without editing the program sources: see the chapter called initParameters: Initialisation parameters and . xml This holds Xml files with definitions of the database table columns. Changes to these files changes the structure of the database table on the next database write: note that this has only been tested for adding extra columns to a table not for removing columns. Note that the only database table that needs creating to start running a coursework is a "users" table, defined by "userd_def.xml" in the directory, with a manager user and password, all other tables can be created from the manager interface by saving to the database, even if there are no rows to save. files This is available for holding save files from the application, particularly csv files created from database tables. src/java/dynDrawings Success is not the result of spontaneous combustion. You must set yourself on fire . Page 125

Objects that handle the dynDrawing system for modifying diagrams on the fly in respnse to user actions.

Deploying Web Applications to Tomcat


In this article we are going to cover the deployment of web applications using Tomcat. We are performing a manual deployment to fully explain the steps involved when deploying a web application. The best way to describe the deployment process is to create a web application of our own that includes the important components found in most Java web applications; then package it for deployment. The following sections will take you through the steps involved in deploying a web application. The name of our web application will be onjava. . In this article, we

create the web application directory structure, create a web application ServletContext, add JSPs, add Servlets, add Tag Libraries, and create and deploy a WAR file.

Creating the Web Application Directory Structure


The first thing you need to do is create the directory structure that will contain the application. We discussed this structure in Part 1, Java Web Applications, and I include the relevant details in Table 1.

Table 1. The Web Application Directory Structure Directory


/onjava

Contains This is the root directory of the web application. All JSP and XHTML files are stored here. This directory contains all resources related to the application that are not in the document root of the application. This is where your web application deployment descriptor is located. Page 126

/onjava/WEB-INF

Success is not the result of spontaneous combustion. You must set yourself on fire .

Note that the WEB-INF directory is not part of the public document. No files contained in this directory can be served directly to a client.
/onjava/WEB-INF/classes /onjava/WEB-INF/lib

This directory is where servlet and utility classes are located. This directory contains Java Archive files that the web application depends upon. For example, this is where you would place a JAR file that contained a JDBC driver.

The name of our web application, onjava, is the root of our directory structure. While in development I suggest creating the directory directly in the Tomcat /webapps directory. When it comes time for deployment, you can package your web application into a WAR file and go though the production deployment process. The last step in creating the web application directory structure is adding a deployment descriptor. At this point you'll be creating a default web.xml file that contains only the DTD, describing the web.xml file, and an empty <webapp/> element. Listing 1 contains the source for a default web.xml file. Listing 1 web.xml
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd"> <web-app> </web-app>

Now copy this file to the TOMCAT_HOME/onjava/WEB-INF/ directory, and we'll begin adding web application components to it in the following sections.

Creating a Web Application ServletContext After you've created the web application directory structure, you must add a new ServletContext to Tomcat. The ServletContext defines a set of methods that are used by components of a web application to communicate with the servlet container. The ServletContext acts as a container for the web application. There is only one ServletContext per web application. We will discuss the relationship between a ServletContext and its web application in much more detail in Part 4, "Web Applications and the ServletContext."

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 127

To add a new ServletContext to Tomcat you need to add the following entry to the TOMCAT_HOME/conf/server.xml file, setting the values for the path and docBase to the name of your web application. Notice again that the name we are using is onjava. <Context path="/onjava" docBase="onjava" debug="0" reloadable="true" /> There are two things here we need to focus on. The first, path="/onjava", tells the servlet container that all requests with /onjava appended to the server's URL belong to the onjava web application. The second, docBase="onjava", tells the servlet container that the web application exists in the /onjava directory. Adding JSPs Now that you have created the web application directories and added ServletContext, you can add server-side Java components. The first components we are going to add are JSPs. The first JSP will include a simple login screen. Listing 2 contains the source for the login.jsp page. Listing 2 login.jsp
<html> <head> <title>OnJava Demo</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body bgcolor="#FFFFFF" onLoad="document.loginForm.username.focus()"> <table width="500" border="0" cellspacing="0" cellpadding="0"> <tr> <td> </td> </tr> <tr> <td> <img src="/onjava/images/monitor2.gif"></td> </tr> <tr> <td> </td> </tr> </table> <table width="500" border="0" cellspacing="0" cellpadding="0"> <tr> <td> <table width="500" border="0" cellspacing="0" cellpadding="0"> <form name="loginForm" method="post" action="servlet/com.onjava.login"> <tr> <td width="401"><div align="right">User Name: </div></td> <td width="399"><input type="text" name="username"></td>

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 128

</tr> <tr> <td width="401"><div align="right">Password: </div></td> <td width="399"><input type="password" name="password"></td> </tr> <tr> <td width="401"> </td> <td width="399"><br><input type="Submit" name="Submit"></td> </tr> </form> </table> </td> </tr> </table> </body> </html>

As you look at this JSP, you'll see nothing very special about it. The only thing you should pay attention to is the action of the form. It references a servlet in the package com.java named login. This servlet will retrieve the username-password parameters from the request and perform its own processing. There isn't much to deploying a JSP. You just copy it to the public directory of your web application, which in this case is TOMCAT_HOME/webapps/onjava/. Any images that it references should be placed in an images folder that you have created in the /onjava directory. To see this JSP in action, open the following URL in a browser: http://localhost:8080/onjava/login.jsp Print Subscribe to Newsletters ShareThis Java > Deploying Web Applications to Tomcat Pages: 1, 2, 3, 4, 5 If you changed the default HTTP port, as mentioned in Installing and Configuring Tomcat, you will need to request the URL from the appropriate port value. If everything was configured correctly, you should see an image similar to Figure 1.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 129

Figure 1. If everything is configured correctly, you'll see something like this. If you do not see a page similar to this image, make sure you have the correct entry in the server.xml file, as described in the section, "Creating a Web Application ServletContext."

The second JSP is the target JSP referenced by the servlet defined in the following section. This JSP will retrieve the request attribute USER that was added to the request with the following servlet. It will then output the String value of the attribute. Listing 3 contains the source for the target JSP. Listing 3 welcome.jsp
<html> <head> <title>OnJava Demo</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <table width="500" border="0" cellspacing="0" cellpadding="0"> <tr> <td> </td> </tr> <tr> <td> <img src="/onjava/images/monitor2.gif"></td> <td> <b>Welcome : <%= request.getAttribute("USER") %></b>

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 130

</td> </tr> <tr> <td> </td> </tr> </table> </body> </html>

As we stated earlier to deploy this JSP, you simply need to copy it to the public directory of your web application, which in this case is TOMCAT_HOME/webapps/onjava/. Adding Servlets The next component to add is a servlet. This servlet will be the action of login.jsp's form. It will retrieve the username and password values from HttpServletRequest, look up the associated user, and then forward the request to a target JSP. The source code for this servlet can be found in Listing 4. For our example the value of the USER is static. Normally you would perform a real lookup of some sort, but, to keep things simple, I'm just returning String Bob. Listing 4 com.onjava.login.java
package com.onjava; import import import import javax.servlet.*; javax.servlet.http.*; java.io.*; java.util.*;

public class login extends HttpServlet { private String target = "/welcome.jsp"; private String getUser(String username, String password) { // Just return a static name // If this was reality, we would perform a SQL lookup return "Bob"; } public void init(ServletConfig config) throws ServletException { super.init(config); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // If it is a get request forward to doPost() doPost(request, response);

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 131

} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get String // Get String the username from the request username = request.getParameter("username"); the password from the request password = request.getParameter("password");

String user = getUser(username, password); // Add the fake user to the request request.setAttribute("USER", user); // Forward the request to the target named ServletContext context = getServletContext(); RequestDispatcher dispatcher = context.getRequestDispatcher(target); dispatcher.forward(request, response); } public void destroy() { } }

To deploy a servlet as part of a web application you first need to compile the servlet and move it into the web application's /WEB-INF/classes directory. For this example, you should compile this servlet and move it to the /onjava/WEB-INF/classes/com/onjava/ directory. This class file is in the subdirectory com.onjava because of its package name.

The next step in deploying the login servlet is to add a servlet entry into the web application's web.xml file. An example <servlet> element can be found in the following code snippet.

It isn't necessary to add all servlets to the web.xml file; it's only necessary when the servlet requires additional information, such as initialization parameters. Example <servlet> Element
<servlet> <servlet-name>ExampleServlet</servlet-name> <servlet-class>packagename.ExampleServlet</servlet-class> <init-param> <param-name>parameter</param-name>

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 132

<param-value>value</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>

This servlet entry contains a simple servlet definition. A description of each of its parts can be found in Table 2. Table 2. The Sub-elements of a <servlet> Sub-element
<servlet-name>

Description The <servlet-name> element is simply the canonical of the deployed servlet. name

<servlet-class>

The <servlet-class> sub-element references the fully qualified class name of the servlet. The <init-parameter> sub-element is an optional parameter containing a name-value pair that is passed to the servlet on initialization. It contains two sub-elements, <param-name> and <param-value>, which contain the name and value, respectively, to be passed to the servlet. The <load-on-startup> sub-element indicates the order in which each servlet should be loaded. Lower positive values are loaded first. If the value is negative or unspecified, then the container can load the servlet at anytime during startup.

<init-param>

<load-on-startup>

To add our login servlet we need to make the following entry into the TOMCAT_ROOT/onjava/WEB-INF/web.xml file:
<servlet> <servlet-name>login</servlet-name> <servlet-class>com.onjava.login</servlet-class> </servlet>

That's all there is to it. To see your web application in action, restart the Tomcat server and open the following URL in your browser: http://localhost:8080/onjava/login.jsp You should see an image similar to Figure 1 (which was referred to above). Now enter a username and password and press the "Submit Query" button. If everything went according to plan, you should see an image similar to Figure 2.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 133

Figure 2. Results after pressing "Submit Query". If you didn't see an image similar to Figure 2, make sure that you have the servlet class in the appropriate directory and the entry in the web.xml file matches the code snippet referenced above. Adding Tag Libraries The final component that we're adding is a tag library. This library contains a single tag, HelloTag, that replaces every occurrence of the text <onjava:hello/> with the literal string "Hello". While this is a perfectly silly example of a tag library, it allows us to present a practical example of deploying a tag library. The source code for the tag handler can be found in Listing 5 and the source for the tld can be found in Listing 6. Listing 5 HelloTag.java
package com.onjava; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.tagext.TagSupport; public class HelloTag extends TagSupport { public void HelloTag() { } // Method called when the closing hello tag is encountered public int doEndTag() throws JspException { try { // We use the pageContext to get a Writer // We then print the text string Hello pageContext.getOut().print("Hello"); }

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 134

catch (Exception e) { throw new JspTagException(e.getMessage()); } // We want to return SKIP_BODY because this Tag does not support // a Tag Body return SKIP_BODY; } public void release() { // Call the parent's release to release any resources // used by the parent tag. // This is just good practice for when you start creating // hierarchies of tags. super.release(); } }

Listing 6 taglib.tld
<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <!-- a tag library descriptor --> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>onjava</shortname> <uri>/onjava</uri> <tag> <name>hello</name> <tagclass>com.onjava.HelloTag</tagclass> <bodycontent>empty</bodycontent> <info>Just Says Hello</info> </tag> </taglib>

To deploy this tag library, we need to make an entry to the web.xml file. The modified web.xml file can be found in Listing 7. Listing 7 web.xml
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/j2ee/dtds/web-app_2_3.dtd'> <web-app> <servlet>

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 135

<servlet-name>login</servlet-name> <servlet-class>com.onjava.login</servlet-class> </servlet> <taglib> <taglib-uri>/onjava</taglib-uri> <taglib-location>/WEB-INF/lib/taglib.tld</taglib-location> </taglib> </web-app>

The added <taglib> entry contains two elements. The first <taglib> element, <taglib-uri>, tells the container how the tag library is to be referenced. For this example we use the value /onjava, which is the way we'll reference the tag library in our JSPs. The second <taglib> element, <taglib-location>, defines the location of the tag library's descriptor (TLD). The TLD defines the tags contained in the library and the handlers that will process the defined tags. To complete your deployment, copy the compiled tag library and the taglib.tld into the TOMCAT_ROOT/onjava/WEB-INF/lib directory. To test you new tag library, you need to modify the welcome.jsp page, replacing the Welcome message with a reference to the <onjava:hello /> tag. You need to also add a taglib directive referencing the taglib.tld to the welcome.jsp file. The modified JSP is in Listing 7.

Listing 7 Modified welcome.jsp


<%@ taglib uri="/onjava" prefix="onjava" %> <html> <head> <title>Onjava Demo</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <table width="500" border="0" cellspacing="0" cellpadding="0"> <tr> <td> </td> </tr> <tr> <td> <img src="/onjava/images/monitor2.gif"></td> <td> <b><onjava:hello /> : <%= request.getAttribute("USER") %></b> </td> </tr> <tr> <td> </td> </tr> </table> </body> </html>

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 136

Now open the login.jsp page as described previously and run through the demo again. This time instead of Welcome: Bob, you should see the message Hello: Bob. Creating and Deploying a WAR File When your web application is ready for deployment, you need to package it for distribution. As we discussed previously in Java Web Applications, web applications are packaged in WAR files. The steps required to "WAR-up" your /onjava web application and deploy it are as follows: 1. Change to the root directory of your web application. In this case the root directory would be TOMCAT_HOME/webapps/onjava/. 2. Archive the web application:
jar cvf onjava.war .

3. Copy the resulting WAR file, onjava.war, to the TOMCAT_HOME/webapps directory. If you're deploying this WAR file to the Tomcat installation that you were developing in, then you will need to back up your development directory and remove it from the TOMCAT_HOME/webapps directory. 4. Add a new Context entry to the /TOMCAT_HOME/conf/server.xml file, referencing the onjava web application. 5. Restart Tomcat.

Success is not the result of spontaneous combustion. You must set yourself on fire .

Page 137

S-ar putea să vă placă și