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 server’s 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.000 of 60. “Success is not the result of spontaneous combustion. which is accessible to the general public. You must set yourself on fire ”. Page 4 . 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 :.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.) and :. These interconnected computers work by transmitting data through a special type of packet switching which is known as the IP or the internet protocol.( get added Internet History Continued  1985 – first domain name – Symbolics.com  1986 – NSFNET  government support for major Internet backbone  1988 – Internet Worm affects 6.

chatting. 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.Internet is such a huge network of several different interlinked networks relating to the business. and the HTTP. or the World Wide Web. the biggest threat of the internet is in the pornography and the security threats. websites. You must set yourself on fire ”. the fiber optics and even the latest wireless connections. government. It is always mistaken said that the internet and the World Wide Web are both the same terms. the internet is the network of the several different computers which are connected through the linkage of the accessories like the copper wires. The internet has brought about the various different. With the introduction of the internet the global communication has become a matter of just the finger tips of the users. 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. as they provide the services of the internet. innovative communication means like the emailing. The security over the internet cannot be guaranteed due to the major hacking techniques and theories. These networks enable the internet to be used for various important functions which include the several means of communications like the file transfer. Actually there is a very significant difference between the two which has to be clear to understand both the terms. and media access which was never so easy before. therefore internet is known as the network of all the other networks. Page 5 . However. the online chat and even the sharing of the documents and web sites on the WWW. The internet and World Wide Web are both the networks yet. These are then linked by the website URLs and the hyperlinks. or are synonymous. There are other protocols that are the sub-classes of the IP itself. Everything has the negative aspect to it and so does the internet. like the TCP. even the interaction between the two strangers can lead to friendship and then serious “Success is not the result of spontaneous combustion. Advantages and Disadvantages of Internet Internet is undoubtedly the most crucial technology of the modern world. and the voice conversation system over the internet. the World Wide Web consists of the interlinked collection of the information and documents which are taken as the resource by the general public. Everyone is of course very well known that internet has the global advantages than just a few concentrated ones. These sites are easily accessible and attractive for the teenagers and young kids. Therefore World Wide Web is one of the services offered by the whole complicated and huge network of the internet. through different layers organization through the IP data packets. and even smaller domestic networks. academic. 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. The use of IP in the Internet is the integral part of the network. 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.

one can view web pages that may contain text. just publish the url • Don’t have to create a GUI – just create a web page • Browser runs on client. videos. wrote a proposal in March 1989 for what would eventually become the World Wide Web. 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. 2001 at 40 million web servers  Keys to success:  Client-server architecture • Users all over world can run programs on my computer • Don’t need to ship software. Using concepts from his earlier hypertext systems like ENQUIRE. a European research organization near Geneva situated on Swiss and French soil.cases of murders and serial killers plots which have become increasingly popular because of the internet launch. Berners-Lee and Belgian computer scientist Robert Cailliau proposed in 1990 to use “Success is not the result of spontaneous combustion. Page 6 . 2. At CERN. You must set yourself on fire ”. images. Students from Stanford  Peaks about Dec. now Director of the World Wide Web Consortium (W3C). and navigate between them via hyperlinks. With a web browser.D.000% growth rate in WWW Web History Continued  Yahoo – Yet Another Hierarchical Officious Oracle  2 Ph. and other multimedia. 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. British engineer and computer scientist Sir Tim Berners-Lee. Despite of a few major problems the Advantages of the Internet use clearly outweigh the few disadvantages.

[6] Mozilla M3..[7] Amaya 1997 1. Internet Explorer 3.0. not the versions released in that year.0. Netscape Navigator. You must set yourself on fire ”. video.0.0.0[6] 1998 iCab.0 4 7 10 21 16-40 36-74 70-119 147-186 248-279 “Success is not the result of spontaneous combustion. Netscape Navigator 4. presenting.[3] Lynx 2. Mozilla 1999 Amaya 2. in chronological order.5. Netscape Navigator 3.0.[4] Internet Explorer 2. they can also be used to access information provided by web servers in private networks or files in file systems. Opera. Note that Internet user data is related to the entire market. Opera 3. 1996 PowerBrowser 1. to link and access information of various kinds as a web of nodes in which the user can browse at will". A web browser can also be defined as an application software or program designed to enable users to access. See also: Timeline of web browsers This is a table of personal computer web browsers by year of release of major version. Opera 2.0. and traversing information resources on the World Wide Web. image. Amaya 0.0. see usage share of web browsers. Erwise.0 1994 IBM WebExplorer.9. 90% market share in 1997 would be roughly 60 million users. Cello. The major web browsers are Firefox. Google Chrome. Internet Explorer 5..0. UdiWWW. Hyperlinks present in resources enable users easily to navigate their browsers to related resources.0.0.[6] AWeb. For example. IBrowse. 3. but by the start of 2007 9% market share would equate to over 90 million users. Web Browsers A web browser is a software application for retrieving. Agora (Argo). retrieve and view documents and other resources on the Internet. and Safari Historical A rough estimate of usage share by percent of layout engines of web browsers as of Q2 2009.0.[5] Cyberdog. An information resource is identified by a Uniform Resource Identifier (URI) and may be a web page. and they publicly introduced the project in December. Although browsers are primarily intended to access the World Wide Web. with the approximate number of worldwide Internet users in millions.0. MacWeb. Arena.[1] Internet users (in millions) [2] Year Web browsers 1991 WorldWideWeb (Nexus) 1992 ViolaWWW. MacWWW (Samba) 1993 Mosaic. AMosaic 1. Grail Arachne 1. Internet Explorer. Netscape Navigator 2. Page 7 . 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. OmniWeb.hypertext ". Netscape Communicator 4. or other piece of content. SlipKnot 1. Minuet 1995 Internet Explorer 1. MidasWWW. Voyager Internet Explorer 4.

3.0.0. Internet Explorer 9. 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. Netscape Browser 8.0. while the actual server software remains unchanged. The former is primarily used for retrieving and/or modifying information from databases. They can also be found embedded in devices such as printers.0 SeaMonkey 1. Opera 10. 2005 Maxthon 1.[14] Firefox 3. commonly a web browser or web crawler.0[6] 2004 Firefox 1.0[6] 2002 Netscape 7. this function is used to create HTML documents dynamically ("on-the-fly") as opposed to returning static documents. or other scripting languages. Opera 11 Chrome 9-16. Safari 3.0. This means delivery of HTML documents and any additional content that may be included by a document. Sputnik 2007 Maxthon 2. Netscape 6. Firefox 3.5. Amaya 3.50. Opera 9. Web Servers The primary function of a web server is to deliver web pages on the request to clients.0.2. Opera 4. Amaya 10. Page 8 . iCab 3.[10] Amaya 5. Safari 3. 2011 Safari 5. Conkeror Konqueror 4. This usually means that no additional software has to be installed on the client computer. Flock 1. Opera 6.4. Phoenix 0.50. The web server may then be used as a part of a system for monitoring and/or administering the device in question. Avant 11. Safari 4.0. Chrome 4-8. Epiphany 1. routers. Many generic web servers also support server-side scripting using Active Server Pages (ASP). The resource is typically a real file on the server's secondary memory. a full implementation of HTTP also includes ways of receiving content from clients. OmniWeb 5. This means that the behaviour of the web server can be scripted in separate files. Firefox 2.1 361-393 513-494 587-673 719-783 817-909 1018-1021 1093-1146 1319-1357 1574-1586 1802 1971 2095 4. You must set yourself on fire ”. K-Meleon 1. Internet Explorer 7.[8] Opera 5. Galeon 1.1. Usually. Chrome 1.0.5. Mozilla 1.[9] K-Meleon 0. Amaya 9. Amaya 8. but this is not necessarily the case and depends on how the web server is implemented.0[6] 2001 Internet Explorer 6.0.[6] Amaya 4. While the primary function is to serve content.0[6] 2009 Internet Explorer 8.[15] SeaMonkey 2. Opera 11. Netscape Browser. Opera 8.[6] Amaya 7.0.0.8.0.0[6] 2003 Opera 7. Web servers are not always used for serving the World Wide Web.0. PHP. Links 2. A user agent. Camino 2.0.0.[12] Epiphany 1. Opera 2006 [13] 9. webcams and serving only a local network. including uploading of files.1-2. Firefox 3. Amaya 6.6. xxxterm. such as images. Amaya 2008 11.[11] Safari 1. Shiira 1. style sheets and scripts.0. Maxthon 3. Opera 10.0.0. Galeon 2.0. SeaMonkey 2. Chrome 2-3.0. “Success is not the result of spontaneous combustion.0. The latter is typically much faster and more easily cached.[6] AOL Explorer 1.0.[6] Flock 2.1. since only a web browser is required (which now is included with most operating systems).5 2010 K-Meleon 1.0. Firefox 4-8. Netscape Navigator 9.2000 Konqueror.[16] Safari 5.0. This feature is used for submitting web forms.0. NetSurf 1. Camino 1.0 Safari 2.

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

Python. Windows. URL URL.  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. The Sun Java System web server supports various languages. PHP. Java Servlets. Linux and Unix platforms. Though the server is free it is not open source. preceded by a double-slash (//). scripts and technologies required for Web 2. Perl. It is open source and free and can run on various platforms like Linux.II “Success is not the result of spontaneous combustion. Conventions already existed where server names could be prepended to complete file paths.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.Sun Java System Web Server This web server from Sun Microsystems is suited for medium and large web sites. Unix. Page 10 . The format combines the preexisting system of domain names (created in 1985) with file path syntax. runs on Windows. Ruby on Rails. Mac OS X Free BSD etc. 5. You must set yourself on fire ”. 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. where forward slashes are used to separate folder and file names.0 such as JSP. ASP and Coldfusion etc. It however. Jigsaw has been written in Java and can run CGI scripts and PHP programs.

preformatted text <h1> </h1> .1.URL=http:nextdoc.unnumbered list <li> first thing <li> second thing </ul> <ol> </ol> .ordered (numbered) list <p> </p> .italics “Success is not the result of spontaneous combustion.in 2 sec. Page 11 .html. You must set yourself on fire ”.html"> . 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. h6) <i> </i> .. tags"> Set keywords for the document.paragraph begin and end <br> .big heading (also h2 .information about  Meta document .line break <pre> </pre> . used by search engines to index your docume Basic HTML Tags <b> </b> .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.bold <ul> . </BODY> </HTML> Meta Document Information  “meta” . <META NAME="keywords" CONTENT="Web. redirect browser to nextdoc. HTML.

Cell 1 </TD> <TD> Row 2. Cell 2 </TD> </TR> <!-.non-blocking space Linking to Documents and Images Links to Documents and Images .end of first row definition --> <TR> <!-. While short.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. case sensitive &lt.unlike rest of HTML. This is the first paragraph.The displayed text is called the “anchor” <A HREF=“Presentation.greater than > &nbsp.less than < &gt. . it is still a paragraph! </P> <P>And this is the second paragraph. Cell 2 </TD> </TR> <!-. Page 12 .<center> </center> .uark. You must set yourself on fire ”.end of last row definition --> “Success is not the result of spontaneous combustion.csce.center <!-. Cell 1 </TD> <TD> Row 1.jpg" WIDTH=190 HEIGHT= 200> - Tables – Syntax <TABLE> <TR> <TD> Row 1.start of last row definition --> <TD> Row 2.edu/~sgauch"> Full path to a page</A> <img src="images/sgauch.ppt"> Document in same directory</A> <A HREF=“http://www. . . </P> </body> </html> Special Characters and Links Special Characters .

You must set yourself on fire ”. Cell 2 HTML Tables Tables are defined with the <table> tag. images. cell 2 row 2. etc. but most of the time. Page 13 . Cell 1 Row 2. cell 1 row 2. Sometimes this can be useful." and holds the content of a data cell. cell 1 row 1. Table Example <table border="1"> <tr> <td>row 1. other tables. A table is divided into rows (with the <tr> tag). lists. links. td stands for "table data. cell 1</td> <td>row 2. cell 2 HTML Tables and the Border Attribute If you do not specify a border attribute. Cell 1 Row 1. “Success is not the result of spontaneous combustion. forms. and each row is divided into data cells (with the <td> tag).end of table definition --> Tables – Output Row 1.</TABLE> <!-. A <td> tag can contain text. Cell2 Row 2. we want the borders to show. the table will be displayed without borders. cell 1</td> <td>row 1. cell 2</td> </tr> </table> How the HTML code above looks in a browser: row 1. cell 2</td> </tr> <tr> <td>row 2.

cell 2</td> </tr> </table> How the HTML code above looks in your browser: Header 1 Header 2 row 1. cell 2</td> </tr> </table> HTML Table Headers Header information in a table are defined with the <th> tag. You must set yourself on fire ”. “Success is not the result of spontaneous combustion. specify the border attribute: <table border="1"> <tr> <td>Row 1. cell 1 row 1.To display a table with borders. cell 2 HTML Unordered Lists An unordered list starts with the <ul> tag. <table border="1"> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>row 1. cell 2</td> </tr> <tr> <td>row 2. Each list item starts with the <li> tag. All major browsers display the text in the <th> element as bold and centered. cell 1</td> <td>row 2. cell 2 row 2. cell 1</td> <td>row 1. Page 14 . cell 1</td> <td>Row 1. cell 1 row 2.

Page 15 . Coffee 2. <ol> <li>Coffee</li> <li>Milk</li> </ol> How the HTML code above looks in a browser: 1. Each list item starts with the <li> tag. <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. The <dl> tag defines a definition list. The list items are marked with numbers.The list items are marked with bullets (typically small black circles). 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>. with a description of each item. Milk HTML Definition Lists A definition list is a list of items. You must set yourself on fire ”.black hot drink</dd> <dt>Milk</dt> “Success is not the result of spontaneous combustion.

The input element is used to select user information. fieldset. and label elements. The most used input types are described below. radio button. checkboxes. A form can also contain select lists. A form can contain input elements like text fields. checkbox. textarea. The <form> tag is used to create an HTML form: <form> . 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 ”.white cold drink HTML Forms HTML forms are used to pass data to a server. </form> HTML Forms .black hot drink Milk .The Input Element The most important form element is the input element. input elements . depending on the type attribute. and more. submit buttons and more. submit button. radio-buttons.<dd>. Page 16 . legend.white cold drink</dd> </dl> How the HTML code above looks in a browser: Coffee . An input element can vary in many ways. password. An input element can be of type text field.

You must set yourself on fire ”. 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). Page 17 . 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. Also note that the default width of a text field is 20 characters.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.

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. The file defined in the action attribute usually does something with the received input: <form name="input" action="html_form_action. and click the "Submit" button. <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.Checkboxes <input type="checkbox" /> defines a checkbox. 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.asp". HTML Frames With frames. Checkboxes let a user select ONE or MORE options of a limited number of choices. you can display more than one HTML document in the same browser window. 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. The page will show you the received input. the browser will send your input to a page called "html_form_action. Each HTML document is called a frame. and each frame is independent of the others. You must set yourself on fire ”.

Basic Notes . if you add a <noframes> tag containing some text for browsers that do not support frames. The web developer must keep track of more HTML documents The HTML frameset Element The frameset element holds one or more frame elements. To prevent a user from doing this.500"). “Success is not the result of spontaneous combustion.htm" is put into the first column.htm" /> </frameset> Note: The frameset column size can also be set in pixels (cols="200. and the document "frame_b. You must set yourself on fire ”. Each frame element can hold a separate document.htm" /> <frame src="frame_b. (Printing the entire page is difficult). The HTML frame Element The <frame> tag defines one particular window (frame) within a frameset. Note: Add the <noframes> tag for browsers that do not support frames. 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. and HOW MUCH percentage/pixels of space will occupy each of them.75%"> <frame src="frame_a. Important: You cannot use the <body></body> tags together with the <frameset></frameset> tags! However. you will have to enclose the text in <body></body> tags! See how it is done in the first example below. you can add noresize="noresize" to the <frame> tag.  Frames are difficult to use. with an asterisk (cols="25%.*"). In the example below we have a frameset with two columns. The document "frame_a. and one of the columns can be set to use the remaining space. the user can resize it by dragging the border.Useful Tips Tip: If a frame has visible borders. The frameset element states HOW MANY columns or rows there will be in the frameset.htm" is put into the second column: <frameset cols="25%. Page 19 .

The specified section is made with <a name="C10"> in the "link.htm) to the left contains a list of links with the second frame (link. The file called "tryhtml_contents.htm" target ="showframe">Frame c</a> The second frame will show the linked document. Frameset with noresize="noresize" How to use the noresize attribute. Jump to a specified section with frame navigation Two frames.htm#C10" target ="showframe">Link with Anchor</a>.htm" target ="showframe">Frame a</a><br> <a href ="frame_b. Navigation frame How to make a navigation frame. Page 20 . One of the links in the navigation frame is linked to a specified section in the target file.htm" target ="showframe">Frame b</a><br> <a href ="frame_c. Jump to a specified section within a frame Two frames. The navigation frame (content.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.htm) as a target. and how to mix them in rows and columns.htm" target ="showframe">Link without Anchor</a><br><a href ="link. 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.htm" contains three links. The HTML code in the file "content.htm" file. The navigation frame contains a list of links with the second frame as the target. You must set yourself on fire ”.htm" looks like this: <a href ="link. The second frame shows the linked document. Move the mouse over the borders between the frames and notice that you cannot move the borders. The source code of the links: <a href ="frame_a. One of the frames has a source to a specified section in a file.

Each page must link to the style sheet using the <link> tag.How to Use Styles When a browser reads a style sheet. you can change the look of an entire Web site by changing one file. To use inline styles. by using the <style> tag.css" /> </head> Internal Style Sheet An internal style sheet can be used if one single document has a unique style. 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. The <link> tag goes inside the <head> section: <head> <link rel="stylesheet" type="text/css" href="mystyle. With an external style sheet. use the style attribute in the relevant tag. like this: <head> <style type="text/css"> body {background-color:yellow. The style attribute can contain any CSS property.} </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. You must set yourself on fire ”.} p {color:blue. it will format the document according to it. Page 21 . 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. Internal styles are defined in the <head> section of an HTML page.

ca/JavaScript/lectures/contents.ryerson.margin-left:20px.html The Basic of java Script JavaScript Introduction JavaScript is a scripting language designed and first implemented by Netscape (with help from Sun Microsystems).">This is a paragraph. visit our CSS tutorial. JavaScript can be used to:  validate user input in an HTML form before sending the data to a server. . The interpreter was an extra software component in the browser that was capable of interpreting JavaSript source code inside an HTML document.</p> To learn more about style sheets. 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. You must set yourself on fire ”. Page 22 “Success is not the result of spontaneous combustion. Netscape first introduced a JavaScript interpreter in Navigator 2. 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.<p style="color:blue. For example.

Netscape Plugins such as Flash. open and close new Netscape windows or frames. doing this is can be a complex and labour intensive process. and complex programming are often better done using animated GIFs. You must set yourself on fire ”. The language is very new and still evolving. You can do things with 20 lines of JavaScript that will significantly reduce the load on your server. Microsoft's support for JavaScript (they call it Jscript) in Internet Explorer has been evolving at a different pace than Netscape's. new features have been added to the language and have been supported by later versions of Netscape's browsers. even the same version of Netscape may behave differently depending on the operating system it is run on. However. programmers are discovering new and exciting things they can do with JavaScript and Web pages. From a scripter's perspective this situation is quite discouraging.) to process it are still evolving. JavaScript is also an easy language to get started using. Few software development tools exist to help you write and debug your scripts. And while you can do a lot with JavaScript. 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.. Since then. Advantages of JavaScript JavaScript gives web authors an unprecedented degree of control over the behaviour of Netscape and the behaviour of their documents. Different versions of Netscape will behave differently depending on the language features you use. With little more than a text editor a few helpful websites and some interest it is possible to produce some but useful scripts. Unfortunately. 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.02.     build forms that respond to user input without accessing a server. change the appearance of HTML documents and dynamically write HTML into separate Windows. Page 23 . and others issue new versions of their browsers. build small but complete client side programs. scrolling/animated banners and notices. give the user better feed back. Microsoft. The definition of the JavaScript language and the ability of the Netscape browser (and others. some things like animation. and allowing the user to drag them around a browser window. It is possible to write JavaScript programs that use advanced JavaScript features but do not cause problems (JavaScript errors) on older browsers. Disadvantages of JavaScript The first browser that reliably implemented JavaScript was Netscape 2. and enhance the appearance of your web pages. 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. moving. To make matters more complicated. As the language grows. JavaScript is often the most efficient solution to many Web authoring problems. manipulate HTML "layers" including hiding. or Java applets. and Netscape.

Writing a function is part of the language.com/tech/javascript/index. One is learning the JavaScript language itself. anyone who can write HTML can. Of all the ones I have read. For example.ch/ecma1/STAND/ECMA-262. Learning to program in JavaScript requires learning two things at once. Microsoft has documented their implementation of JavaScript. Microsoft's site: http://msdn. Here are their addresses: 1.com/scripting/default. if you want to write a function that checks some user input in an HTML form. from O'Reilly and “Success is not the result of spontaneous combustion. most complete. Page 24 . You must set yourself on fire ”. with a certain amount of effort. Learning JavaScript Netscape and others have claimed that JavaScript can be learned by anyone who can write HTML. most of this information is being copied over to the Sun/Netscape alliance site called iPlanet. There are a number of books on JavaScript. since the early days the language has undergone a standardization process under the auspices of a european standards association (ECMA).htm?/scripting/jscript/techinfo/jsdocs.html.ecma. The ECMA standard is available as a downloadable PDF or Postscript file: http://www.microsoft. you usually need to do two things: first. and the other aspects of the language. Writing code to have it called by Netscape is part of working with the HTML page and the browser.netscape. I can only recommend one of them. looping and conditional branching constructs.HTM. While this is probably true. Finding Information on JavaScript For a long time the best. is learning to write scripts that interact with HTML objects and the Web browser. Also bad is the fact that so many of the different browser versions have serious bugs in how Javascript interacts with HTML objects. Also.html However. Documenting these and working out code work arounds could easily occupy a small group of people full time. 2. learning to program in JavaScript is not as simple as creating HTML documents. documentation on JavaScript came from Netscape.com/library/documentation/javascript.: http://developer. The Sun/Netscape Alliance site has JavaScript Documentation: http://developer. 3rd Edition. have your function called by Netscape when a user enters something into a field in the form. The second part of learning JavaScript. 3. When you learn to program in JavaScript you are usually learning to do both things at the same time. On the other hand. Even programmers who are new to event-driven programming find learning JavaScript often requires a significant investment of time. including things like how to declare functions. The Definitive Guide.iplanet. learn to incorporate and modify prewritten JavaScript functions into their pages.on the Web completely support the standard. David Flanagan's JavaScript. you must write a segment of code to correctly check data (a function) and second. The Netscape site was at.htm. Finally.

You must set yourself on fire ”.write("<P>Script tags will be ignored by ") document. <HTML> <HEAD> <TITLE>The Script Tag 1</TITLE> <SCRIPT> document. A Simple Script Placing JavaScript Statements inside HTML Documents JavaScript programing statements (source code) may only be placed in certain locations within HTML documents. Inc.write("browsers that do not understand them.write("in the Head of an HTML document.Associates.</P> <SCRIPT> document.</P>") </SCRIPT> </BODY> </HTML> “Success is not the result of spontaneous combustion. When a browser with a JavaScript interpreter reads the JavaScript code it can interpret and execute it so that some scripting task is completed.write("<P>Script tags can be placed ") document. Page 25 .</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. The simple document below shows JavaScript source code placed within HTML <SCRIPT></SCRIPT> tags. It is not a gentle introduction to programming or the language but is a thorough and well written book and makes an excellent reference.

write("in the Head of an HTML document.</P>") write some text. 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. Page 26 . and what text is JavaScript source code to be interpreted and executed. A browser that knows how to interpret JavaScript will attempt to interpret text inside the script tags while reading and displaying HTML elements correctly. You must set yourself on fire ”. into the Web page being loaded by the browser. Script tags are most often placed inside the head or body tags but may also be placed inside other elements.write("<P>Script tags can be placed ") document. The first statement writes the first half of the paragraph and the second writes the last “Success is not the result of spontaneous combustion. JavaScript Statements and Source Code The JavaScript text is often referred to as "source code" or just "code" and is made up of statements. Not every version of every browser correctly interprets JavaScript code when script tags are placed inside other HTML elements such as table data cells. In the example above these two JavaScript statements: document. consisting of an HTML paragraph.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 provides methods for displaying HTML output to the user. The first thing it will do is evaluate the right hand part of the statement after the " = ". Introducing the Document Object One of JavaScript's strengths is its ability to work with objects. On its own. In the JavaScript documentation the information about an object is referred to as its properties.half. Statements can be more complicated and we will often need to look closely at the expressions within them. “Success is not the result of spontaneous combustion. This is the expression 2 + 3 which the interpreter will evaluate to the number 5. Page 27 . But it does give an example of a simple JavaScript statement that contains a simple expression. Some of the properties of the document object can be changed others are read only. The next thing it will do is place the number 5 in the variable named a." Here is a simple example broken down into four parts: document.</P> part of the HTML document. 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. 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. objects are a way to group or package together information and methods of working with this information in a convenient way. adding two plus three to get five and storing this number in a storage location named a is not very exciting. You must set yourself on fire ”.write("<P>Hello World</P>") document An application object that contains information about the document loaded into a frame or window. 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. In object-oriented programming and scripting languages. Use the View Page button above to see what happens when you load a page containing this script into a Web browser.

For example the background colour and the URL the document was retrieved from are attributes of an HTML document. “Success is not the result of spontaneous combustion.contains the URL for the current document document. and Date objects. Many objects have methods such as document.bgColor . Any JavaScript expression can be placed inside the round brackets.makes it possible to get or set the background colour of the document document.will be written into the current Web page. Some of the basic properties and methods of the document object are introduced below using simple JavaScript statements. Working with the Document Object JavaScript provides a number of application objects such as the document. The round brackets following the word write are required. window. string.lastModified . The dot operator allows you to access information (object properties) and methods for working with that information in an object. write() will output a string of text to the document. The method or property of an object are on the right side of the dot and the object is on the left side. to text to be written into the current Web page. the dot notation. "<P>Hello World</P>" The double quoted text is a "literal" string of text including HTML markup.The dot between the document object and the write() method is significant. You must set yourself on fire ”. information about the document that contains the script is available using the document object.location . For example. Properties Properties are the attributes of an object.write() that give the object significant functionality. In the examples below various properties of the document object are accessed using the dot operator and assigned to a variable called result.the actual series of text characters . Information about the object often called the attributes of the object are stored in variables called "properties" of the object. Page 28 . The expression will be evaluated and the result converted. Each object has properties that can be read and sometimes set in JavaScript statements. and the names of properties of the document object: document. In this case the literal text .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. if necessary.

result = document. The JavaScript expression inside the round brackets will be evaluated and the result (whatever it is) written out to the HTML page. You must set yourself on fire ”. writeln is a convenient method to use when writing out data from short test programs within <PRE></PRE> tags.bgColor = "#800080" Methods Methods are a way of asking an object to do something more complicated than changing a property. So while it does not make sense to be able to change the location where the document came from. Setting the Properties of an Object It is also possible to assign values to some object properties.location result will contain the URL of the document.Getting the Properties of an Object result = document. For example: document. Calling write() is like asking a document to append HTML to itself. you can change the background colour of the document this way: document.bgColor result will contain the background colour of the document.02) “Success is not the result of spontaneous combustion.write( JavaScript expression ) write() is a method (a function) that belongs to the document object. result = document.lastModified result will contain the date of the last time the document was modified. Here are some more methods for the document object: document. Page 29 .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.clear() Clears the document (doesn't appear to do anything in Netscape 2. Here are some more methods for the document object: document.

so will your ability to read code. 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 are text that is not interpreted by the JavaScript interpreter. formatting code so it is easier to read. document. how it can be used. However. and other information the writers of the script thought important to note. These include using descriptive variable names.close() "Closes the output stream and forces data sent to layout to display.document. for correctly adapting other people's code for your own uses. There are a number of things you should do to make understanding your code easier." In Netscape 2. As your facility with a language improves.open() "Opens a stream to collect the output of write or writeln methods. Page 30 . You must set yourself on fire ”. 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 ." Comments . JavaScript. even trying to understand your own code after being away from it for some months may be quite challenging. It is important    to help understand how other people have solved problems by reading their code.02 it is not required to display the last ouput.Making Notes Inside Scripts Introduction Learning to read and understand source code is an important skill that takes some time and practice to develop. like other languages. that documents how the script works. //Single Line Comments Two forward slashes // begin a comment that begins with the // and goes to the end of the line. for modifying and extending your own code as needed. For example: “Success is not the result of spontaneous combustion.even painful. Comments Comments are notes. and documenting what you have done. To exclude comments from being interpreted. usually written by the authors of a script. they must be preceded by special characters or enclosed in special characters.

Adding comments as the script progresses is a good practice perhaps something like cleaning while you cook . Comments are particularly essential for scripts where numerous sections of code must work together and where more complex tasks are being performed. * The function expects one numeric parameter to be passed to it. If not it returns false.answer) return true else return false } While developing a script. The method keeps track of the number of * user guesses by incrementing a counter in the question object. **/ function checkAnswer(choice){ this. Page 31 . var firstQuestion = 0 //Change this to any number from 0 to (maxQuestions 1). You must set yourself on fire ”. comments are often left to the end to add to a source file. Here are some examples: /* Global Variables for Quiz */ var maxQuestions = 12 /*Change this value if you want to allow more questions.the comments will be more complete and writing them may help in clarifying what was being attempted as the work progresses.*/ var firstQuestion = 0 /*Change this to to any number from 0 to one less than maxQuestions. //Do Not edit code from this point on! /*Multiline or Bracketed Comments*/ The /* and */ characters can be used to enclose a comment.guesses++ if (choice == this. Working with JavaScript Exercises “Success is not the result of spontaneous combustion. This is an unfortunate practice as it increases the probability that few comments will ever be added to a script as it nears completion.//Global Variables for the Quiz var maxQuestions = 12 //Change this value if you want to allow more questions.*/ /* 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.

and then press the Choose File button to find the file and load it into the browser. You must set yourself on fire ”. Load the document into the text editor. Then open your browser and load the same file into it. in the pop up menu.. Your screen should look something like this: “Success is not the result of spontaneous combustion.Working with JavaScript requires little more than a simple text editor and a Web browser. To download the source code right click on the icon and select Save Link As. In Netscape 4.write(document.write("</P>") // --> </SCRIPT> </BODY> </HTML> Once you have downloaded the file.. The easiest way to do this is to download them. Here is some code you should download now.write("<P>The background colour is ") document. The only way to learn to write scripts is to begin by experimenting with them. <HTML> <HEAD> <TITLE>Hello World</TITLE> <SCRIPT Language="JavaScript"> <!-document. make some changes. You may have noticed the little document icon at the upper left of source code listings: . bring them into a text editor. and then load the page into a browser to see what happens. Open Page. Page 32 . open your favourite text editor (it must be able to read and write plain ASCII text files).X choose File.bgColor) document.write("<H1>Hello World!</H1>") // --> </SCRIPT> </HEAD> <BODY> <SCRIPT Language="JavaScript"> <!-document.

“Success is not the result of spontaneous combustion. Page 33 . In this case document. However. in the previous line no double quotes are used: document.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. In this example the double quotes are used inside the write() method when a string.bgColor inside the brackets is not literal text to be written into the page. or sequence. As JavaScript is a relatively high-level language. of text characters are to be written into the document. For example: document. 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. which is a string of text in the format #FFFFFF.bgColor returns the background property of the document object. This text is then written into the document by the write method. press the reload (or refresh) button in you browser to see the affects your changes have had.write("</P>").write(document. Then. It is a JavaScript expression that must first be evaluated. it is not necessary to know most of the details of how information is stored in memory by a JavaScript interpreter. In this case the document. You must set yourself on fire ”.bgColor).

A variable may hold a number. Java. and symbols that have some meaning in JavaScript. if a variable named x does not already exist it is created. or lower level languages such as C. Here is a very short example showing how the assignment operator ( = ) is used to assign a value to a variable: x = 3. break the text into three parts called tokens. In short. In the statement above the tokens are: x = 3. the number 3. You must set yourself on fire ”. or C++.4 is to be assigned to a variable. string or other values at different times. just by writing x = 3. 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. the value stored in y is being assigned to x. 4.4 as a number value. The JavaScript interpreter will copy the value in y into x. 5. Here are a few lines of code: x = 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.4 a variable named x is both created and has a value stored in it. Tokens are the separate words. Strings may also be enclosed in single quotes. The 3.JavaScript provides for the automatic creation of variables whenever values are assigned to them. JavaScript is a "loosely typed" language. In those languages a variable may only hold a certain type of data.4 A JavaScript interpreter will read this single line of code and do something like this: 1.4 2. The = indicates that the string following it should be stored in the variable y. determine the centre token is the assignment operator and that the value 3. 3. evaluate the right most token 3. “Success is not the result of spontaneous combustion. this can be a little confusing. Note the single quote inside the double quotes in this example is treated as a literal character. names.4 y = "Let's go for lunch!" x = y In the last line of this example.4 is stored in the variable named x. 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. Page 34 . For example an integer or a string but not either at different times.

Literal number values must begin with a number. The letters can be any upper or lower case letter. variable names may also contain numbers. while. Usually. and import. as a result. Array. or a + or . How do we know false is not a variable name? It is a reserved word. 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.5 x3 = -24e3 The e is another allowed character in a number that permits writing numbers in scientific notation. Page 35 . when the interpreter "reads" a line of code it breaks it into separate pieces called tokens based on these types of rules. 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?). There are many words that cannot be used for variable names because they have a special meaning in JavaScript. = is the assignment operator. for.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. 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. How does the interpreter tell the number 3. this. expressions are evaluated to produce a value of true or false and an action is taken. And since variable names are not allowed to start with a quote character. or not taken. there is no problem. Variables can store two other types of simple values: the two boolean values true or false and the special null value. Other reserved words you can't use for variable names include: var.14159 is a numeric value.14159 x2 = . Variable names must start with a letter or underscore _ character. -24e3 is that same as -24 × 103 or -24000. The actual literal Boolean values true and false are not always seen in scripts. “Success is not the result of spontaneous combustion. After the first character. Since a variable name cannot contain an = character the assignment operator is recognized as an operator by the JavaScript interpreter. The line x1 = 3. and 3. new.14159 has three tokens: x1 is a variable.followed by a number or decimal point followed by a number. If a is not less than 10 it will not. If a is less than 10 the true value will be returned and the alert dialog will appear. There are many others. As mentioned. You must set yourself on fire ”. Here are a few examples: x1 = 3. function. a decimal point followed by a number.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.

In other words it's contents are undefined. string. Why? Because of the typing error. Here are some errors you may run into as a result of JavaScript's loose typing. Unfortunately. Typos Can Create New Variables var x1 = 'He said "be seeing you" as he left. then. Problems with Variables A loosely typed language may seem easier to use and more convenient than a strongly typed language. x has been typed once in each example by mistake.Finally. Leaving the 1 off the variable name resulted in a new variable being created.write(x1) The intention here was to display two messages. x1 is supposed to be assigned a different message which will also be written into the page. the first message will show up twice in the document. Instead of typing x1. You must set yourself on fire ”.write(x1) x = "New Message" document. Page 36 . the two Boolean values and null. 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. This is useful in avoiding all sorts of errors because software tools (compilers and syntax aware editors) can catch many coding errors very easily. Strongly typed languages require that every variable is declared as capable of holding only one type of primitive value before it can be used. 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. First x1 is assigned a message that is written into a Web page. 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. Since the string "New Message" was assigned to the “Success is not the result of spontaneous combustion. 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. 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. These two short examples involve a simple typing error. strings. The x = "New Message" creates a new variable named x when what was intended was to assign another string to x1.' 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.' document.

"special key word denoting a null value" x = null “Success is not the result of spontaneous combustion.wrong variable. a browser running this script will stop executing the script and report the error: "Error: 'x' is undefined. You must set yourself on fire ”.write(x) This causes a runtime error.7343 //floating point x = -4.' document.3e-3 //same as 4." Since x was never declared and never had a value assigned to it.3 × 103 x = 4. Page 37 . JavaScript Data Types Numbers       "no explicit distinction between integers and real" numbers though integers may be stored differently than floating point or real numbers.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 . That is.3e3 //same as -4. Accessing Undefined Variables var x1 = 'He said "be seeing you" as he left. Here are some literal numbers being assigned to a variable (not a complete sampling): x=8 //integer x = . x1 still contains the original string which will be written into the document a second time. it does not exist and so cannot contain a value that can be written into the document.

Depending on how a number is assigned to a variable and the operations performed on it. On the far left are statements that assign the value that results from a simple expression using an operator. For example in C/C++/Java the following statements: int result.JavaScript Numbers Working with Numbers JavaScript is a loosely typed language.5 0.5 would be assigned to the variable result. Please take a minute to read through this table. does the following:   a variable named result is created that can only hold an integer number such as 1 .5 and the variable result can only hold an integer. Programmers used to strongly typed languages such as Pascal. however. result = 5/10. 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. Any variable can be assigned any datatype. five is divided by ten.5) is thrown away. since the result is 0. Here are some other examples of working with JavaScript numbers. 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. In JavaScipt there are no explicit integers or floating point numbers.it cannot hold a number with a fractional part such as 1. or Java will find this difficult to get used to when working with numbers. C++.5. You must set yourself on fire ”. 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. . The fractional part (the . C programmers are used to integer division where the decimal part of the result is truncated. it is assigned the value 0.

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. 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. Whenever a string is involved the number is converted to text and concatenated with the string to form a longer text string. 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. So the remainder is 0.5 2 Number Number Number Number 5 Number Remainder Note: 10 divides evenly into five (2 times). result = 5 .5 + "Hello" Note: a number and a string are being "added" together. You must set yourself on fire ”. .

writeln(5 + 10) document.10 = ") document.write("5 + \"Hello\" = ") document.write("5 + 10 = ") document.writeln(5%10) “Success is not the result of spontaneous combustion.writeln(5 * 10) document.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.write("5 % 10 = ") document.write("5 * 10 = ") document.writeln(5 / 10) document.write("5 / 10 = ") document. 5 Number Post Decrement 4 Number Pre Decrement Subtract one from the value in x and use 4 the new value in the expression.writeln(5 .10) document. Page 40 . 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.writeln(5 + "Hello") document. 6 Number Post Decrement Subtract one from the value in x after using current value of x in the expression.writeln(10/5) document. You must set yourself on fire ”.write("5 .write("10 / 5 = ") document.

writeln("x = 5") x = 5 document.writeln() // --> </SCRIPT> </PRE> </BODY> </HTML> “Success is not the result of spontaneous combustion. You must set yourself on fire ”.writeln(x) document.writeln(5 > 10) document.writeln(5 <= 10) document.writeln(5 < 10) document.write("x-.writeln(++x) document.write("x = ") document.write("5 > 10 = ") document.write("5 >= 10 = ") document.write("x++ = ") document.writeln(5 == 10) document.write("5 < 10 = ") document.writeln("x = 5") x = 5 document.write("5 <= 10 = ") document.write("10 % 5 = ") document.writeln() document.writeln("x = 5") x = 5 document.write("5 != 10 = ") document.writeln(x--) document.= ") document.writeln("x = 5") x = 5 document.writeln(5 != 10) document.writeln(x++) document.write("x = ") document.writeln(5 >= 10) document.writeln(--x) document.writeln(10 % 5) document.writeln() document.writeln() document.write("5 == 10 = ") document.write("++x = ") document. Page 41 .document.writeln() document.writeln(x) document.write("--x = ") document.

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 aàáâãäåæbcçdeè 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

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. . It also reduces the number of comparisons by forcing the extension extracted from the path to lower case.lastIndexOf(".JPEG.substring(start. Page 45 . You must set yourself on fire ”. This short demonstration script writes a report into the document if the extension is correct or not.writeln(errorMsg) } else{ start++ //the first character of the extension is the one after the . document. <HTML> <HEAD> <TITLE>Using lastIndexOf.and there are more of them than listed here .writeln(errorMsg) } } //--> </SCRIPT> //if “Success is not the result of spontaneous combustion.jpeg extension.writeln("The extension is correct.change this and rerun the script errorMsg = "Invalid File Name.jpg or . the script uses if else statements to make decisions .JPG. length.jpeg. 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 . path.length).jpg" //sample file name for testing .jpg." //standard error message start = path. Finally. or . File must have a .these are described later.") //find the last period character in the string if (start == -1){ //if there isn't one report the problem document. substring.") } else{ //otherwise report the error document.toLowerCase() //force the rest of the string to lower case if ((extension == "jpg") || (extension == "jpeg")){ extension is jpg or jpeg then it's ok. path = "C:\pictures\mmProject11\assembly3. 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.Using string methods together The string methods .are often used together to perform useful functions. . extension = path.

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

It contains three tokens:   hour is the variable that contains the hour . If the expression is true then the statement following the expression is executed. getHours()returns the hour of the time stored in the now variable. If it is not. If you try running this script before twelve and again after noon you will see this.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 first numeric value is less than the last one the operator returns a true value. The sample line creates a Date object named now that contains the date and time when the now Date was created. 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 Date object however is designed to provide a way to create Date objects for a given date or time. Here is a flow chart that shows each step in the execution of this script. if (hour < 12) document. Page 47 . No Good Morning message will occur from noon on . The less than operator compares the numeric values on either side of it.JavaScript provides a Date object that makes dealing with dates and times relatively easy.getHours() Just one of the useful methods provided by the Date object is the getHours() method. You must set yourself on fire ”. This is a little different from how objects have been used in the examples up until now. < is the less than operator. If the first value is not less than the last one then false is returned. Like the String. the expression being evaluated is hour < 12. “Success is not the result of spontaneous combustion.that is. In the example. document.") will be executed. and Math objects the Date object provides numerous useful methods for working with dates and times. In this line a new Date object named now is created using the new object creation operator. 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 the time was between noon and less than 1 PM (13 hours) getHours() will return 12. provided the system time is correct on your computer. then the statement is NOT executed. If the hour is between 0 and 11 then these values are less than 12 and the statement document.writeln("Good Morning.any integer value from 0 through 23. The document and Math objects are created by the browser and interpreter environments and are ready to use by any script executed by them. hour = now. The hour is between 0 (midnight) and 23 (11 PM).

Style Simple if statements can be written in either of the following formats. The indentation is to make the script easier to read by anyone who has to work on it in the future. 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. “Success is not the result of spontaneous combustion. You must set yourself on fire ”. Page 48 . While it is not necessary for the JavaScript interpreter it is necessary to make the code human readable.

if (hour < 12) document. Page 49 . You must set yourself on fire ”. 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. If statements always contain a statement or statement block.getHours() //create a Date object named: now //hours range from 0 to 23.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.writeln("Welcome. 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. 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.writeln("Good Morning. <SCRIPT Language="JavaScript"> now = new Date() hour = now.") else document.") </SCRIPT> </PRE> </BODY> </HTML> “Success is not the result of spontaneous combustion. A statement that contains other statements is also called a compound statement.

Page 50 . Statement blocks may be used in place of either statement: if (expression){ statement1 statement2 statementx } “Success is not the result of spontaneous combustion.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. You must set yourself on fire ”.

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. or Java operators take a moment to read through each table and assure yourself that the results makes sense. You must set yourself on fire ”. Perl. >. and introduces the else if construct and the logical operators && and ||. and != when used with numbers. 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. Unless. if else statements. While many styles are possible it is important to choose one style and stick with it to make your code readable.else { statementa statementb statementn } The positioning of the curly braces {} is designed to make the blocks visible and is one of many coding styles. you are already familiar with C. Page 51 . C++. Comparison Operators The following table provides some examples of what boolean value is returned ( true or false) when two numbers are compared. 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. <=. ==. comparison operators such as: <. >=.

Page 52 .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 ”.

You must set yourself on fire ”.9999999 == 5.0 return = 4.0 return = 4. The following table gives a simple example of this: Decimal Places Expression 1 2 3 4 5 6 7 8 return = 4. There is one important caveat however.0 return = 4.999999 == 5.999 == 5.0 return = 4.0 return = 4.99 == 5. Page 53 .9 == 5.99999 == 5.0 return = 4.9999 == 5.0 return = 4.99999999 == 5.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.0 Result false false false false false false false false “Success is not the result of spontaneous combustion.

999999999 == 5.0 return = 4. In this case we cannot use a simple == test and must instead test numbers to see if they are adequately close to each other.0 return = 4.0 return = 4. 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.9999999999999999 == 5.9999999999 == 5.9 10 11 12 13 14 15 16 17 18 19 20 return = 4. JavaScript stores numbers using the standard 8 byte IEEE floating-point numeric format.0 true It is possible for us to conceive of a number such as Pi that has an infinite number of decimals.1.getHours() if (hour < 12) document.writeln("Good Morning. Greetings for Different Times of Day On the previous page now = new Date() hour = now.0 return = 4.") “Success is not the result of spontaneous combustion.999999999999999 == 5.99999999999999999 == 5.0 return = 4.0 return = 4.0 return = 4.99999999999 == 5. This means that there are limits to the size and precision of numbers.99999999999999 == 5. Similarly computers must process operations on numbers quickly and store numbers in a limited amount of memory. 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. Page 54 .0 return = 4. You must set yourself on fire ”.9999999999999 == 5.9999999999999999999 == 5.999999999999999999 == 5.999999999999 == 5.99999999999999999999 == 5.0 return = 4. 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 . For the most part we can ignore problems of precision.0 return = 4.0 false false false false false false false true true true true return = 4.

if (hour < 12) document.") In this example the first else is followed by another if else statement.writeln("Good Evening. //0 is midnight to before 1 AM. type constructions the following indentation shows better what is happening: if (hour < 12) document.getHours() //create a Date object named: now //hours range from 0 to 23.") However.writeln("Good Afternoon.writeln("Good Morning.writeln("Good Afternoon. Page 55 . While the formatting above is the standard way to write if else if else.") “Success is not the result of spontaneous combustion. Here is one of them: if (hour < 12) document.") if (hour > 17) document.writeln("Good Evening. somewhat arbitrarily. What is needed is some way to test for a time period that is not part of the ranges that have already been tested. If we. You must set yourself on fire ”.writeln("Good Morning.. 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.") else document.") else if (hour > 17) document.") else document.writeln("Good Evening.writeln("Good Morning. There are different ways to do this.. writing out a greeting for the afternoon cannot be done in the same way with just the comparison operators.") else if (hour > 17) document.was used to produce a greeting that would only be visible in the morning.

and if it is not. It in turn tests if the hour is greater than 17.writeln("Good Afternoon.writeln("Good Afternoon. In this case hour > 11 must evaluate to true as must hour < 18 for the and operator to return true. Here is the same code with curly brackets so that you will recognize the else if construction with statement blocks.writeln("Good Afternoon. In JavaScript the comparison operators are always evaluated before the logical operators so that this works properly.writeln("Good Afternoon. the afternoon message is written out.The first if else statement has two statements.") } else { document. Here is a table showing the possibilities: Statement hour = 2 if (hour > 11 && hour < 18) document. You must set yourself on fire ”. In the other cases it returns false. Otherwise it returns false. the same script could be written: “Success is not the result of spontaneous combustion.") The logical and operator && returns true if the values on both sides of it are true.writeln("Good Morning. While it does take more comparisons than the previous example that used the else if construct. This statement is another if else statement.") hour = 14 if (hour > 11 && hour < 18) document.") hour = 19 if (hour > 11 && hour < 18) document.writeln("Good Evening. The second statement is executed if hour is not less than 12. The first one is executed if hour is less than 12. the evening message is written into the document. Each bracket could contain many statements if necessary: if (hour < 12) { document.") } Logical Operators Another way to determine if it is the afternoon would be to do the following: if (hour > 11 && hour < 18) document.") 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. Even though the curly brackets only contain one statement the code is still legal. If it is.") } else if (hour > 17) { document. Page 56 . 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.writeln("Good Afternoon.

") if (hour > 17) document.") The logical or operator || is often used in a similar way to the && operator except that it returns true if either expression returns true.writeln("Good Evening.writeln("Good Afternoon. Page 57 . These values are basically constants.") if (hour > 11 && hour < 18) document.</TITLE> </HEAD> <BODY> <PRE> This script provides examples of using the Date object to obtain the hour of the day. They do not change throughout the life of the script. it is not likely that someone returning to this script in the future would. You must set yourself on fire ”.if (hour < 12) document. Here is a complete example: <HTML> <HEAD> <TITLE>Examples of using a Date object and the if and if else statements.writeln("Good Morning. //Evening begins at 6 PM. 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. 18. and 17 as parts of the day. Here is a table of values: Statement (true || false) (false || true) (true || true) result true true true (false || false) false Finally. 11. <SCRIPT Language="JavaScript"> now = new Date() //create a Date object named: now “Success is not the result of spontaneous combustion. even though we may remember the significance of the numbers 12. The hour is used to print different messages at different times during the day.

For example: hour = 2. 8. if (hour < noon) document. 11.hour = now. You will need to make extensive use of the && operator.writeln("Good Morning. 2. Consider testing with values such as 0.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. 6. 18. You must set yourself on fire ”.writeln("Good Afternoon.getHours() where you set hour to a test value. write a second version of the script that uses if statements without any if else statements. and run the script.") else if (hour < evening) document. 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. don't forget to remove (or comment out) the test line so that the script does what it is supposed to do. 2. Test your scripts carefully.getHours() noon = 12 evening = 18 //hours range from 0 to 23. Are these numbers likely to provide a good test? Why? Finally. 17. //0 is midnight to before 1 AM. Extend the script above to correctly handle the time periods listed. To do this add a line right after the line hour = now. While less efficient. 15. “Success is not the result of spontaneous combustion.") else document. 12. //Evening begins at 6 PM. 20 and 23. Page 58 . Make sure that the script works correctly under every possible condition by setting hour to different values. 3. //Afternoon begins at noon. Change the test value you set hour to. 5.

and the next statement after the loop can be executed. For example when checking for valid user data. If it is true the block is executed. so that the first character is examined the first time through the loop. the while loop is complete. and so forth. If it is true the block is executed again. the expression in the round brackets is evaluated. each time through. one character at a time.writeln(counter) counter++ } // --> “Success is not the result of spontaneous combustion. it may be necessary to examine every character of a string. the second character the second time. the expression is reevaluated. 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 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. The counter variable may be incremented by one. Page 59 . You must set yourself on fire ”.Loops: Repeating Statement Execution Every programming language provides a method to do things repeatedly. 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. Being able to repeatedly execute a statement or compound statement is an essential feature of programming. At that point the loop block is not executed. When the block is finished executing. until the end of the string is reached. 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. This process continues until the expression evaluates to false.

Keep track of the value of counter and see how many times you loop until the script is done. while (counter < 5) The expression counter < 5 is evaluated. You must set yourself on fire ”. it will be equal to one afterwards. document. By following the arrows and remembering the current value of counter the looping mechanism may become more obvious. the expression evaluates to true. writing out the current value of the counter variable. try "walking through" the flow chart one step at a time. In other words if it was zero when before this statement is executed. Flow Charts While flow charts have fallen out of fashion as higher level languages have become popular. counter++ The counter variable is incremented by 1.writeln(counter) Inside the loop block the first statement is executed. “Success is not the result of spontaneous combustion. 1 is less than 5 the loop block will be executed again.</SCRIPT> </PRE> </BODY> </HTML> Controlling the Loop In this example. It is part of the expression: counter < 5. the following flow chart below is provided to help make clear each step in the while loop example. At that point it is no longer less than five and the loop block will not be executed again. And since. Here is the script again: counter = 0 while (counter < 5){ document. If you are at all unsure how loops work. This loop ends when the counter variable is incremented to five. and the loop block will be executed. Since zero is less than five. As this is the last statement in the block the while expression will be reevaluated.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. the Loop is controlled by the counter variable. Page 60 .

.The cycle in the flow chart where the expression is true. the document is written to. the counter incremented. the browser's controls/buttons may freeze. forms a sort of visual "loop" in the flow chart. Hence the name. Whether done by accident or deliberately the result is that the Web page will never complete loading. Page 61 . 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.writeln(counter) } Since the counter variable is never changed inside the loop it will always be less than ten. Infinite Loops It is all too easy to create a loop that will go on forever executing the loop block. Here is an example of an infinite loop that was likely created by mistake: counter = 0 while (counter < 10){ document.. You must set yourself on fire ”. and the expression is evaluated again. or the browser may crash altogether..

here is a short example that prints out each character of a string on a separate line. 1. Also. 9. the length of “Success is not the result of spontaneous combustion. etc.unlike languages like C where a single character is a different datatype.. 5. A small embellishment to this script might be to write out the value of the counter variable and the character at the same time. 1. 7.length will fail and the loop body will not be executed again.writeln(chr) counter++ } // --> </SCRIPT> </PRE> </BODY> </HTML> The chr variable contains a one character string . 4. Note the test in the while loop uses the length property of the string object.charAt(counter) document. Checking Every Character in a String While validating text strings is described elsewhere on this site. 8. 2. 2. and 10 and the body of the loop will be executed. In this example the string is Hello World which has a length of 11 characters in positions 0 through 10. afert counter is set to 11 the test counter < str. as the counter goes through values 0. <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.") } Note that the test expression is simply the true value. You must set yourself on fire ”.length){ chr = str. 6. it is used in the charAt() method of the string object to retrieve the character in that position in the string. For completeness. counter will be set to the values 0.writeln("Some message. Page 62 .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. However. Since counter is initially set to 0 and is incremented by one at the end of each loop. 3. The character is stored in the chr variable and written out to the document in the next line.

Page 63 .the string is written out when the loop ends. as you will see. plus features not found in either of these two languages. Like shell script languages. Instead. 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. In fact. 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.writeln("Character in position " + counter + ": " + chr) counter++ } document. Perl also supports a sed-to-Perl translator and an awk-to-Perl “Success is not the result of spontaneous combustion. all you have to do is write the program and tell Perl to run it.length) // --> </SCRIPT> </PRE> </BODY> </HTML> Perl (Practical Extraction and Report Language) Perl is an acronym.charAt(counter) document. Perl does not require a special compiler and linker to turn the programs you write into working code. Perl provides all the features of the script languages sed and awk. You must set yourself on fire ”.length){ chr = str. many of the features of the language are borrowed from C. This means that Perl is ideal for producing quick solutions to small programming problems. Perl has the power and flexibility of a high-level programming language such as C.writeln("The string length is: " + str. or for creating prototypes to test potential solutions to larger problems.

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. or 39 decimal. An exponent consists of all of the following: The letter e (E is also acceptable) An optional + or A one-. or three-digit number Using Octal and Hexadecimal Notation So far. Consider this example: $line = "This is my line". Page 64 . put a zero in front of your integer scalar value: $result = 047. the smaller units of information are $inputline. For example. the following statements are identical in Perl: $inputline = <STDIN>. Tokens and White Space Tokens can normally be separated by as many spaces and tabs as you like. as follows: “Success is not the result of spontaneous combustion. and . all the integer scalar values you've seen have been in what normally is called base 10 or decimal notation. put 0x in front of your integer scalar value. or hexadecimal (sometimes shortened to hex) To use octal notation. =.translator. Perl also enables you to use two other notations to represent integer scalar values: Base 8 notation. chop ($line). chop's job is to delete the character at the right end of the line of text. or octal Base 16 notation. To use hexadecimal notation. The chop Library Function This function assumes that a line of text is stored in the variable passed to it. to $result . Each of these smaller units of information is called a token. After chop is called. two-. a floating-point scalar value consists of all of the following: An optional minus sign (-) A sequence of digits. This assigns 47 octal. You must set yourself on fire ”. it breaks the statement down into smaller units of information. Statements and Tokens When the Perl interpreter sees a statement. In this example. <STDIN>.. the value of $line becomes This is my lin In Perl.

or 31 decimal.$result = 0x1f. Table 3. \a Bell (beep) \b Backspace \cn The Ctrl+n character \e Escape \E Ends the effect of \L.1. print("The value of \$result is $result. Page 65 .1 lists the escape sequences recognized in double-quoted strings. $result = 14. \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. Integer-comparison operators. Table 4.1 defines the integer-comparison operators available in Perl. Operator Description < Less than “Success is not the result of spontaneous combustion. You must set yourself on fire ”. The most common escape sequence is \n. In Perl. Character strings that are enclosed in double quotes accept escape sequences for special characters. This assigns 1f hexadecimal. Perl accepts either uppercase letters or lowercase letters as representations of the digits a through f: $result = 0xe.\n"). to $result. These escape sequences consist of a backslash (\) followed by one or more characters. Both of the preceding statements assign 14 (decimal) to $result. 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. $result = 0xE. which represents the newline character as shown in this example: $text = "This is a string terminated by a newline\n".

. <=> returns one of three values: l 0. if the second value is greater For example.2 < $x) { # conditionally executed stuff goes here } Although the expression 3. because this is easier to understand.) “Success is not the result of spontaneous combustion. (Normally. I'd buy some milk. consider the following statement: $y = $x <=> 10. or -1 Here are simple examples of each of the first six operators in Table 4. it's best to use the comparison that can be most easily read.2 < $x< is perfectly valid. I'm not sure exactly why this is true. the first value in the comparison is greater. Page 66 . $y is assigned 0. or nonzero l False. Unlike the other integer comparison operators. "If I had five dollars.2) { . "If five dollars had I. For example." instead of. l If $x is equal to 10. or zero The <=> operator is a special case. l If $x is less than 10. 0. we say.> Greater than == Equal to <= Less than or equal to >= Greater than or equal to != Not equal to <=> Comparison returning 1. if the two values being compared are equal l 1. I'd buy some milk. and $y is assigned -1.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. You must set yourself on fire ”. and $y is assigned 1.. it would be better to use if ($x >= 3. the second value in the comparison is greater. it isn't easy to read because variables usually appear first in comparisons." eventhough both are correct. consider the following: if (3. These are the possible results: l If $x is greater than 10. if the first value is greater l -1. Integer Comparisons and Readability In any given statement. Instead. I think it's related to the way the English language is spoken.

or -1 Perl compares strings by determining their places in an alphabetical order. Table 4. Because these results are different. In the first statement. 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. the strings 123 and 45 are converted to integers.and numeric-comparison operators. 123 is alphabetically compared to 45. The result when these two strings are compared depends on whether a string or integer comparison is being performed. and 123 is compared to 45. and the equivalent numeric-comparison operator. the string aaa is less than the string bbb. # result is true $result = "aaa" gt "bbb". because aaa appears before bbb when they are sorted alphabetically. consider the strings 123 and 45. 0.String-Comparison Operators For every numeric-comparison operator. Page 67 . Here are some examples of string-comparison operators in action: $result = "aaa" lt "bbb". why do we need two kinds of comparison operators? To answer this. # result is -1 If you are familiar with the C programming language. # result is false $result = "aaa" cmp "bbb". # result is false $result = "aaa" eq "bbb". the result in this case is true. # result is true $result = "aaa" ge "bbb". You must set yourself on fire ”. you must ensure that you are using the proper “Success is not the result of spontaneous combustion. Perl defines an equivalent string-comparison operator. Because 123 is alphabetically less than 45. The result is false and $result is assigned 0. String Comparison Versus Integer Comparison You might be thinking: If strings and integers are equivalent in Perl. For example.2 displays each string-comparison operator. # result is false $result = "aaa" ne "aaa". In the second statement. the comparison it performs. String. # result is false $result = "aaa" le "aaa". $result = "123" lt "45". $result = "123" < "45". because 123 is not less than 45. you might have noticed that the behavior of the cmp operator is identical to that of the C function strcmp(). returning 1. and $result is assigned a nonzero value.

For example. Another way to write this is with the += assignment operator: $var += 1. Table 4. For example.comparison operator every time. An assignment operator exists for just about every bitwise operator and arithmetic operator that Perl supports. Perl also supports other assignment operators. For example. The = operator can appear more than once in a single statement . # this statement is bad Using the Assignment Operators the assignment operator = associates. assigns the value 42 to the variable $result. Table 4.4. This statement adds the value 1 to the existing value of $var. “Success is not the result of spontaneous combustion. If you don't. your program can contain errors that are not easy to spot. along with equivalent statements that use operators you've seen earlier. the statement $result = 42. 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. or assigns. Examples of assignment operators. $result = $var1 == $var2. suppose that you want to add a value to a scalar variable and assign the result to the following variable: $var = $var + 1. the character string a string is assigned to both $value1 and $value2. Page 68 . a value to a variable.3. in the statement $value1 = $value2 = "a string". each of which combines an assignment with another operation. $var2 = "string 2".4 shows examples of the assignment operators. consider the following: $var1 = "string 1". You must set yourself on fire ”. For instance.

$a = $a / 2. 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"). filename). $a = $a . “Success is not the result of spontaneous combustion.Statement using Equivalent Perl assignment operator statement $a = 1. For example. 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. l filename represents the location of the file on your machine. Using File-Test Operators with File Variables You can use file-test operators on file variables as well as character strings. $a |= 2. Page 69 . none (basic assignment) $a -= 1. The following is an example: ($a = $b) += 3. To open a file. $a **= 2.1. This assignment is then treated as a separate subexpression whose value is the variable to which it is being assigned. $a = $a % 2. $a = $a ^ 2. You must set yourself on fire ”. $a ^= 2. you must supply two arguments: l filevar represents the name you want to use in your Perl program to refer to the file. $a += 3. call the library function open. $a = $a ** 2. $a %= 2. Assignment Operators as Subexpressions Any expression that contains an assignment operator can appear on the left side of another assignment operator. $a *= 2. the assignment enclosed in parentheses is performed first. $a &= 2. you must first open the file. $a = $a & 2. $a = $b has the value $a. } Opening a File Before you can read from or write to a file. In cases such as this. $a /= 2. When you call open. This means that the statement shown previously is equivalent to the following two statements: $a = $b. $a = $a | 2. The syntax for the open library function is open (filevar. $a = $a * 2.

simply.1. put two > characters in front of the filename . You must set yourself on fire ”. There are three different file-access modes (or. 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. put a > character in front of the filename that you pass to open . 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. . To specify append mode. In this table. ">>/u/jqpublic/appendfile"). as follows: open (APPENDFILE. To specify write mode. This opens the file /u/jqpublic/outfile for writing and associates it with the file variable OUTFILE. name is a placeholder for the name of the operand being tested. The file-test operators. Table 6.The File Mode When you open a file. as follows: open (OUTFILE. you must decide how you want to access the file. This opens the file /u/jqpublic/appendfile in append mode and associates it with the file variable APPENDFILE Available File-Test Operators Table 6. ">/u/jqpublic/outfile"). open assumes that a file is to be opened in read mode.1 provides a complete list of the file-test operators available in Perl.

You must set yourself on fire ”. which enables you to match any of a number of character strings.-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. Page 71 . ^ 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.

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

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

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

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

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

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

an online shopping car manages request for multiple concurrent customers. This leaves you free to select a "best of breed" strategy for your servers. including the JDBC API to access enterprise databases. Servlets are not designed for a specific protocols. HTTP Servlet typically used to:    Priovide dynamic content like getting the results of a database query and returning to the client. IBM WebSphere. Servlet containers are usually the components of web and application servers. without the performance limitations of CGI programs. Page 78 .g. Servlets can also access a library of HTTP-specific calls. reusability. Unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules). and others. platforms. Manage information about the state of a stateless HTTP.servlet. Sun Java System Application Server and others. Microsoft IIS. and tools. Sun Java System Web Server. and crash protection. e. Servlets can access the entire family of Java APIs. performance. platform-independent methods for building Web-based applications. such as BEA WebLogic Application Server.servlet and javax.http.Introduction to Java Servelets Programming What is Java Servlets? Servlets are server side components that provide a powerful mechanism for developing server side programs. Third-party servlet containers are available for Apache Web Server. Today servlets are the popular choice for building interactive web applications. You must set yourself on fire ”. receive all the benefits of the mature java language including portability. Process and/or store the data submitted by the HTML. Servlets run entirely inside the Java Virtual Machine. Using servlets web developers can create fast and efficient server side application which can run on any servlet enabled web server. It is different thing that they are most commonly used with the HTTP protocols Servlets uses the classes in the java packages javax. servlets are server as well as platform-independent. Since the Servlet runs at server side so it does not checks the browser for compatibility. Servlets provide component-based. Methods of Servlets A Generic servlet contains the following five methods: “Success is not the result of spontaneous combustion. 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.

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

check authorization. for example the servlets can talk directly to the web server while the CGI programs can't do. 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. 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. perform logging. 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. Safety As servlets are written in java. it remains in the server's memory as a single object instance. and MIME type mapping etc. If any exception occurs then it will throw an exception. However with servlets there are N threads but only a single copy of the servlet class. Integration Servlets are tightly integrated with the server. They can maintain the session by using the session tracking mechanism which helps them to maintain information from request to request. Java's automatic garbage collection and a lack of pointers means that servlets are generally safe from memory management problems. When the servlet get loaded in the server. Inexpensive There are number of free web servers available for personal use or for commercial purpose. Multiple concurrent requests are handled by separate threads so we can say that the servlets are highly scalable. Introduction to Server Side Programming “Success is not the result of spontaneous combustion. but in later date it can be extended for another type of servlets. Servlets can share data among each other. Servlet can use the server to translate the file paths. As it stands today. Extensibility The servlet API is designed in such a way that it can be easily extensible. Powerful We can do several things with the servlets which were difficult or even impossible to do with CGI. they even make the database connection pools easy to implement. servlets inherit the strong type safety of java language. Page 84 . So by using the free available web servers you can add servlet support to it . the servlet API support Http Servlets. So servlets are write once. run anywhere (WORA) program. In servlets we can easily handle the errors due to Java's exception handling mechanism. Web servers are relatively expensive.

000 programs! In addition. iii. compile and also execute the program on a client machine (e. we saved this file with a . iv. design patterns. switching to new databases can be done at the server side without having to bother about clients? hardware or software capabilities. All programs reside in one machine called the Server. If you can recollect. 1. Page 85 . e-shopping etc. the point to be noted about this program is that ? ?It is a client side program?. Apart from introducing you to the language basics. banking. i. concurrent access and manipulations to the database which simply cannot be handled by client side programs.All of us (or most of us) would have started programming in Java with the ever famous ?Hello World!? program.g. Any number of remote machines (called clients) can access the server programs. No doubt. concurrency. 2. Your PC). ii. adding patches. compile and execute programs. The answer to most of the issues cited above is ? ?Server Side Programming?. logically or functionally it carries no ground when it comes to enterprise applications (e. session management. Why Server Side Programming? Though it is technically feasible to implement almost any business logic using client side programs. But. This means that you write.java extension and later compiled the program using javac and then executed the class file with java. Figure-1 illustrates Server side architecture in the simplest terms. it has little practical significance when it comes to real world programming. this is the easiest and fastest way to write. 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. a bank having 10. resource pooling. You must set yourself on fire ”.g.). Migrating to newer versions. air ticketing. “Success is not the result of spontaneous combustion. Advantages of Server Side Programs The list below highlights some of the important advantages of Server Side programs. there are issues like security. going by the client side programming logic.000 customers would mean that each customer should have a copy of the program(s) in his or her PC which translates to 10. To further explain. Issues relating to enterprise applications like resource management. security and performance are managed by service side applications. architectures.

g. Insurance. Types of Server Side Programs i. Web Servers include IBM?s Weblogic and BEA?s Websphere server. e-shopping. PHP To summarize. MS Internet Explorer and an internet connection) can experience the power and performance of a Server (e. etc) from a remote location without having to compromise on security or speed. Active Server Pages (ASP) ii. IBM Mainframe. You must set yourself on fire ”. Examples for other Server programs include Java Server Pages (JSPs) and Enterprise Java Beans (EJBs). Enterprise Java Beans (EJBs) v. Unix Server. Introduction to Java Servlets Java Servlets are server side Java programs that require either a Web Server or an Application Server for execution. The javax.http packages provide the necessary interfaces and classes to work with servlets. Java servlets are server side programs or to be more specific. Examples for Web Servers include Apache?s Tomcat Server and Macromedia?s JRun.g.g. we will get acquainted with Servlet fundamentals and other associated information required for creating and executing Java Servlets. service and destroy also called as life cycle methods might be used which will be discussed in the following section. other methods such as init. More importantly. Java Server Pages (JSPs) iv. Servlets generally extend the HttpServlet class and override the doGet or the doPost methods. web applications that run on servers that comply HTTP protocol. Java Servlets iii. displaying transaction information of credit card or debit card depending on user?s choice). Windows XP Professional.g.v. Pentium II. Page 86 .servlet. In addition.servlet and javax. Clients with bare minimum requirement (e. 1. server programs are not only portable but also possess the capability to generate dynamic responses based on user?s request. Basic Servlet Structure As seen earlier. Banking. They are portable and possess the capability to generate dynamic and user-based content (e. In the forthcoming sections. the objective of server side programs is to centrally manage all programs relating to a particular application (e. The skeleton of a servlet is given in Figure “Success is not the result of spontaneous combustion. 3. etc).

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

You must set yourself on fire ”. Page 88 .A Servlet Program “Success is not the result of spontaneous combustion.

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

what actually happens is ? with each refresh. You must set yourself on fire ”.). the doGet method is called which increments i?s value and displays the current value. “Success is not the result of spontaneous combustion. Page 90 . The procedure to run the servlets using a Web Server will be demonstrated in the next section (1. keep refreshing the browser (F5 in Windows).3. In the background.Output Screens To appreciate the execution of the servlet life cycle methods. Find below the screen shots (Figures 5 through 7) captured at random intervals.

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

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

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

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

Figure ? servlet class file placed under classes folder Step 6 ? Edit web.xml file and the classes folder The fourth step is to create the web.g. All you need to do is copy the servlet class file (the file we obtained from Step 1) to this folder.xml file an easy way would be to copy an existing web. Figure-12 shows the servlet_lifecycle (refer section 1. You must set yourself on fire ”.0\webapps\examples\WEBINF) and paste it into this folder.3. Page 95 . You can later edit this file and add relevant information to your web application.xml file and the classes folder Note ? Instead of creating the web.xml file and the classes folder.xml file. “Success is not the result of spontaneous combustion. Figure ? web. Let us first see as how to include the servlet?s name in the web.2. C:\Program Files\Apache Software Foundation\Tomcat 6.) class being placed in the classes folder.xml file and include the servlet?s name as shown in Figure-13. Figure-11 shows this file and folder being placed under the WEB-INF folder. 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.xml to include servlet?s name and url pattern This step involves two actions viz.xml and classes folder are created under the WEB-INF folder. Ensure that the web.xml file (e.Figure ? WEB-INF folder inside web application folder Step 4 ? Create the web. Open the web. including the servlet?s name and then mentioning the url pattern.

You must set yourself on fire ”. include the url pattern using the <servlet-mapping> </servlet-mapping> tag. “Success is not the result of spontaneous combustion. You can give a different name (or alias) to the actual servlet. Page 96 . Next. Figure-14 shows the url pattern entry for our current servlet. The url pattern defines as how a user can access the servlet from the browser. This is one of the main reasons as why this tag is used for.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.

3. To run the server. To do this.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.3.t. Step 7 ? Run Tomcat server and then execute your Servlet This step again involves two actions viz. After ensuring that the web server is running successfully. you can run your servlet.xml file. your web applications folder (demo-examples in this case). running the Web Server and then executing the servlet. follow the steps explained in Section 1. open your web browser and enter the url as specified in the web. Page 97 . You must set yourself on fire ”.r. This means that this path is w. 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.

jar file in the variable CLASSPATH inside the environment variable by using the following steps. 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). For Windows XP.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. After a long and pain staking effort. open a browser window and type the URL http://localhost:8080/directory (folder name of your application) name/servler name and press enter. 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.2.xml file in a directory structure.jar    Create a java source file and a web. You must set yourself on fire ”.for the variable JAVA_HOME in the environment variable. we finally got an output! As mentioned in Section 1.0\lib\servlet-api. To get details about the installation process and setting the classpath click the link Tomcat installation.Figure ? Our servlet?s output! Eureka! Here?s the output of our first servlet. Set the class for the jar file: Set the classpath of the servlet-api. put the compiled file (. Page 98 . Compile the java source file. If everything is correct your servlet will run.3. Start the tomcat server. 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.class file) in the classes folder of your application and deploy the directory of your application in the webapps folder inside the tomcat directory. “Success is not the result of spontaneous combustion.

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

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.util package. As we know that the our servlet extends the HttpServlet and overrides the doGet() method which it inherits from the HttpServlet class.web.sun. Inc. You must set yourself on fire ”.3//EN" "http://java. first is HttpServletRequest object and the second one is HttpServletResponse object. Whenever the user sends the request to the server then server generates two obects. The server invokes doGet() method whenever web server recieves the GET request from the servlet.com/dtd/web-app_2_3. “Success is not the result of spontaneous combustion. Page 100 .xml file for this program: <?xml version="1.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems.//DTD Web Application 2. It is very easy to display it on our browser by using the Date class of the java. HttpServletRequest object represents the client's request and the HttpServletResponse represents the servlet's response. The doGet() method takes two arguments first is HttpServletRequest object and the second one is HttpServletResponse object and this method throws the ServletException.

println("<b>"+ today+"</b></body>"+ "</html>"). Page 101 .//DTD Web Application 2.*.io.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. Date today = new Date().http. It is the standard MIME content type for the Html pages. To display the output on the browser we use the println() method of the PrintWriter class. After that it has used the method getWriter() of the response object to retrieve a PrintWriter object. javax. You must set yourself on fire ”.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.getWriter(). Inc.*. public class DisplayingDate extends HttpServlet{ public void doGet(HttpServletRequest request.servlet. The code the program is given below: import import import import java. java. IOException{ PrintWriter pw = response.servlet.0" encoding="ISO-8859-1"?> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems.sun.3//EN" "http://java.*. pw.*. pw. HttpServletResponse response) throws ServletException. } } XML File for this program <?xml version="1.println("<html>"+"<body><h1>Today Date is</h1>"). The MIME type tells the browser what kind of data the browser is about to receive.util. javax.com/dtd/web-app_2_3.

servlet.servlet. The name of the class should follow the naming convention.io. PrintWriter pw = response.*. public class SimpleCounter extends HttpServlet{ int counter = 0. To make this program firstly we have to make one class SimpleCounterInServlet. We have to just increment the value of the counter by 1. Page 102 .println("At present the value of the counter is " + counter). counter++. After making a class define one variable counter which will keep record for how many times the servlet has been accessed. Now display the value of the counter.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.*. You must set yourself on fire ”.http. pw. HttpServletResponse response)throws ServletException. import javax. The code of the program is given below: import java. Our program logic is simple.setContentType("text/html"). public void doGet(HttpServletRequest request. Now use method either doGet() or doPost() to write a logic of the program.*. 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. import javax. IOException { response.getWriter(). } } The output of the program is given below: “Success is not the result of spontaneous combustion. To display the output use the method getWriter() method of the response object which will in turn return the object of the PrintWriter class.

Java programs can be written and executed in two ways:   Stand-alone application. “Success is not the result of spontaneous combustion. under control of a Java-capable browser. Two Approaches To repeat some of what we said in an earlier lesson. You must set yourself on fire ”. this compatibility issue continues to be a serious one. the programming requirements for the two are more similar. applet programming can be easier than application programming. run from the command line. which (hopefully) is compatible with all the programming features included in your applet. Page 103 . Applet which runs under control of a Java-capable browser or the AppletViewer program. We will also illustrate this at the end of the lesson. it is also possible to run most applets as standalone programs. As of August 1999. A Java-Capable Browser What do we mean by a Java-Capable browser? We mean a browser that contains its own Java Virtual Machine. When a simple graphical user interface is needed. Applet Execution Mode Applets are designed to be downloaded and executed on-line. but not as serious as it was in past years. We will illustrate this at the end of this lesson.Introduction to Applet Programming Introduction Applets This lesson provides a very brief introduction to the programming of Java Applets. When the application does make use of a GUI. This is particularly true when the application doesn't make use of a Graphical User Interface (GUI). What About A Graphical User Interface (GUI)? Programming a simple applet in Java is significantly different from programming a simple application. A Third Approach Actually we said that with a little extra programming effort.

You must set yourself on fire ”.2 in December 1998. 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 the browser actually sees is the class files. they are imposed by a security manager that is a part of browser. 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). However.1 Capabilities were designed into JDK 1. as of August 1999.2 Actually. Page 104 . Note that such restrictions are not a function of the Java language. New Security Requirements in JDK 1. However.1 to allow the individual to decide the level of security restrictions that are to be imposed on applets when they are executed. Major changes in the security area were introduced in JDK 1. special security procedures are implemented. All that would be necessary would be for your other language to create class files whose contents match the requirements of the JVM. Special Security Procedures Apply Because applets are designed to be downloaded and executed on-line. In theory. It really doesn't know how they were created as long as they meet the specifications for the Java language and JVM. security is a moving target. Rather. Applet functionality is restricted by the browser in an attempt to prevent downloaded applets from damaging your computer or your data. 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. Security in JDK 1. the details are far too complex for an introductory course in Java. although that may be much easier said than done.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. I don't believe that either the Netscape or Microsoft browser products are fully supporting this capability. The topic of security will be discussed in more detail in a subsequent lesson on Advanced Java Programming.

) When a new class extends an existing class. (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. This topic will be covered in more detail later. but very important sample program illustrating the general behavior of overridden methods. Runtime Polymorphism Overriding methods is an aspect of inheritance and results in a mode of behavior that we refer to as runtime polymorphism. This is an extremely important statement. That section contains a small. Turn it over in your mind a few times to make sure that you realize the full impact of what I just said. (Many other names are used as well as explained in the earlier lesson on ObjectOriented Programming. 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. it is possible to rewrite the method in the subclass to cause it to impart different behavior for objects of the subclass type. 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.An Applet does not require a main method. 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. Page 105 . The new class is often referred to as the subclass and the class being extended is often referred to as the superclass. “Success is not the result of spontaneous combustion. 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. so this is simply an introduction to help you understand the applet code that is presented later in this lesson.) Inheritance New classes can be defined by extending (inheriting from) existing classes. You must set yourself on fire ”. This is another extremely important statement. 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.

you will often want to take advantage of the functionality of existing subclasses of Object by extending one of those existing subclasses. 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. or ignoring them altogether. “Success is not the result of spontaneous combustion. That is the case when we define the class for and write the code for an applet. Similarly. requiring among other things that the method being overridden be originally defined as a virtual method. you will be content with leaving the inherited methods alone and either using them as defined. it is a subclass of Object by default.Overriding a Method in Java Rewriting the method in the subclass is referred to as overriding the method. You must set yourself on fire ”. you will need to modify the behavior of certain inherited methods by overriding them in new classes that you define. However. in the standard Java class libraries. Overriding a Method in C++ C++ programmers may recall that the procedure for overriding a method in C++ is a little more complicated. various direct and indirect subclasses of Object provide additional methods that are inherited by new subclasses that you define. At other times. When Should You Override Methods? Sometimes. Page 106 . All Classes are Direct or Indirect Subclasses of Object Whenever you define a new class. All classes in Java form a hierarchical pyramid with the Object class at the top of the pyramid. 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 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.

and this is the way that you make applets available to others on your Web site. The "Hello World" Applet A sample applet that displays Hello World follows. HTML files will be discussed briefly a little later. Page 107 . The various parts of the applet are presented and discussed later in this lesson.sun. by Mary Campione and Kathy Walrath. a Java Applet is a program that adheres to a set of conventions that allows it to run within a Java-compatible browser. This does not require an HTML file.. Note that the controlling class for this applet   extends the Applet class. is to view it using a Java-capable browser program.The "Hello World" Applet What Is an Applet? According to The Java Tutorial. AppletViewer One way. it is necessary to produce an HTML file containing tags that reference the applet. In both cases. is to execute the applet using the AppletViewer program which is a standard part of the JDK.com:80/books/Series/Tutorial/index. which at the time of this writing could be downloaded from http://java. and overrides the paint() method. and this is often the preferable way for testing. “Success is not the result of spontaneous combustion. ". Java-Capable Browser A second way to execute a Java applet.html.. It does require that a main() method is contained in the controlling class for the applet. You must set yourself on fire ”." 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). Running Applet in Standalone Mode The third way to execute an applet is to run it in a standalone mode.

java.drawString("Hello World". Doing it the Hard Way If we were to delete the import directives in the above program. Packages will be discussed in more detail in a subsequent lesson. public class hello3 extends Applet { //override the paint method public void paint(Graphics screen) { screen.Applet. but only if we made the modifications shown in boldface below. Page 108 . Importing Classes The above program contains two import statements. “Success is not the result of spontaneous combustion.awt. } } //End hello3 class.25). we could still compile and run the program.drawString("Hello World".50.awt. this requires more typing effort on your part. } } //End hello3 class. You must set yourself on fire ”. except this program runs under a browser or the Applet Viewer.applet. As you can see./*Applet program hello3.Graphics.50. Except for certain classes that are automatically imported (such as the System class) when a Java program is compiled.applet.Graphics screen) { screen.25). public class hello3 extends java. //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++.//see discussion on packages import java.Applet { public void paint(java. 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.java This is a Java applet that produces the same output as the application named hello1. *********************************************************/ import java. Java programs can import classes or packages containing classes in order to access the classes with minimal code.

A Brief Word about Inheritance and Applets In both Java and C++. import java. As mentioned above. either the package specified when the class is defined. “Success is not the result of spontaneous combustion.*. or in the default package. 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). packages will be discussed in more detail in a subsequent lesson. (Inheritance will be discussed in more detail in a subsequent lesson. classes can inherit from other classes.*.awt. All of the classes within a package can refer to each other without using fully qualified path names. The Default Package All classes are in packages. a class which inherits from another class is called a subclass and the inheritance is accomplished using the keyword extends. that subclass must be defined as public. Page 109 . (Inheritance syntax is much different in C++. you can import entire packages using a wildcard character as shown below.applet. Importing Packages As an alternative to importing individual classes. import java.) In Java.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. You must set yourself on fire ”. Furthermore. This may slow down compilation but will have no detrimental impact at runtime.) 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).

What Methods Must an Applet Override? An applet must override at least one of the following methods. 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. You must set yourself on fire ”. “Success is not the result of spontaneous combustion. and can override more than one. That isn't always the case. the paint() method receives a reference to an object of type Graphics. Since this lesson is simply a brief introduction to applets. In this case.25). 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. } Without going into detail at this point. the Graphics object represents the computer's screen. paint is a method of the component class that is inherited by several intermediate classes and is finally inherited by the Applet class.drawString("Hello World". In this case.    init() start() paint(). Page 110 .50. these issues will not be discussed further here. but the exceptions are too advanced for an introductory course in Java. Overridden paint() Method The overridden paint() method appears as shown in the following code fragment: public void paint(Graphics screen) { screen. Why Override the Methods? There are some complex issues surrounding the overriding and use of these methods that will be discussed in subsequent lessons. Where Are These Methods Defined? init and start are methods of the Applet class.

Creating HTML Files Instructions for creating simple HTML files can be obtained from a variety of sources. including several online locations on the Web. These are Not Class Methods Unlike main(). you can find hundreds of links to hundreds of different topics at http://about. You can find links to hundreds of HTML resources at http://html. (In fact. loads the specified subclass file. the methods named init(). “Success is not the result of spontaneous combustion. You must set yourself on fire ”. (or the AppletViewer program) it    reserves screen space.) A Sample HTML File There is no intention of providing a detailed discussion of HTML in this course of study. When the <APPLET> tag is encountered by a Java-capable browser.com/.com/. It then invokes one of the three methods listed above for the object causing the Applet to execute. a minimum knowledge of HTML is required to work with applets. 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.about. These are instance methods and an object is required to invoke them. However. 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. A sample HTML document that can be used to execute this Applet with the Applet Viewer or a Java-capable browser is shown below. Page 111 .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. and instantiates an object of the subclass.

A main() Method in an Applet Although an applet doesn't require a main() method.Appearance and Behavior of Applet As a word of caution. Unfortunately. 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. it can be invoked by the JVM to run the applet in a standalone mode. <HTML> <HEAD> <title>Hello World Applet</title> </HEAD> <BODY> <applet code="hello3. applet programming is easier than application programming. 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). You must set yourself on fire ”. or in a standalone mode. Page 112 . The programs for most applets can be written so that can be run    under control of a Java-capable browser.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. 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). In fact. 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 some cases. most of this material is not covered until the Intermediate Java Programming course. I am now going to show you what I meant by that statement. If you provide an appropriate main() method. under control of the AppletViewer program. when a graphical user interface is needed. Some additional code is required to provide that place when running the applet in a standalone mode. “Success is not the result of spontaneous combustion. Providing a Place for the Applet to Run For simple applets. there is no harm in providing one.

This program was tested using JDK 1.3 under Win95 */ import java. /*Applet program hello4.awt.Baldwin").1.*.setSize(300.awt. However. You must set yourself on fire ”. //This code will terminate the program when the // user clicks the close button on the Frame “Success is not the result of spontaneous combustion. Applet myApplet = new hello4().Sample Program The following program will run    under control of a Java-capable browser (compatible with JDK 1. under control of the AppletViewer program. import java. }//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.setVisible(true). Page 113 .add(myApplet). This program is provided simply to alert you to the possible dual nature of applet programs. etc. This is a Java applet which produces the same output as the applet named hello3. //Instantiate a hello4 applet object.drawString("Hello World". since we haven't covered any of the material involving the graphical user interface ( Frame. import java. R.1.applet. A main method is provided to support the running of the applet in the standalone mode.event.G. we won't discuss it in detail at this point.3 or later). myFrame.100). public class hello4 extends Applet { public void paint(Graphics screen) { screen. or under control of the standalone JVM.java This program illustrates that simple applets can run in a standalone mode as well as inside a browser or under the AppletViewer program.*. //Make the whole thing visible myFrame.50. except that this program is capable of running either under AppletViewer or standalone. //Add the applet object to the Frame object myFrame. The comments pretty well explain what is going on.Applet.).25).

2.*. Writing the html code 13. <APPLET 14. the applet's code is downloaded to our web-browser and executed by browser's JVM. 11. 5.drawString("simple applet"). } } Simple applet example.*. import java. Writing the applet's code by extending java.java 12. { 7. You must set yourself on fire ”. height="320"> “Success is not the result of spontaneous combustion. { 9. }//end main } //End hello4 class.Applet class. width="480" 16. Compile the code: javac myApplet. 3.java" 15.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. 10. code="myApplet. Page 114 .applet. When we use a java-enabled browser to view a page that contains applet. public void paint(Graphics g) 8.myFrame. Applet's development and execution 1. 4.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0). g.awt. import java. <HTML> <HEAD> <title>Hello World Applet</title> </HEAD> <BODY> <applet code="hello4. The following html file can be used to run this program under the AppletViewer program.}}).applet. public class myApplet extends Applet 6.

2. Use the getParameter() method to receive the parameter. 8. parameter1 = getParameter("parameterName"). public void paint(Graphics g) 19. public void init() 12. … 9. 21. <PARAM 4. } 17. parameter1 = "NO PARAMETER". </PARAM> </APPLET> 7. 14. String parameter1.html Parameters to applet 1. You must set yourself on fire ”. 10. “Success is not the result of spontaneous combustion. g. if(parameter1==null) 15.drawString("Paramter: "+parameter1).</APPLET> 17. <APPLET …> 3. 11. Execute the applet: appletviewer myWebpage. 16. 18. { 13. Page 115 . Include one or more <PARAM> tags in the <APPLET> tag. name = "parameterName" 5. { 20. value = "parameterValue"> 6. } … Applet life cycle Applet life cycle.

we may leave the web page containing the applet temporarly to another page and return back to the page. Stopping occurs automatically when we leave the applet page. public void start() { // code goes here. Applet is covered or uncovered by some other window. Applet is minimized and maximized public void paint(Graphics g) { // Visual output operations go here. } 4. This occurs automatically after the applet is initialized. dead state occurs only “Success is not the result of spontaneous combustion. For example. The start() method may be called more than once. Running state Applet enters the running state when the system calls the start() method of applet class. Page 116 . Idle state An applet become idle when it is stopped from running. This is achieved by calling the init() method of applet class. We have to override the start() method if we want to create thread to control the applet. Born/Initialization state Applet enters the initialization state when it is first loaded. You must set yourself on fire ”. public void stop() { // code goes here. We can also do so by calling the stop() method. This again starts the applet running. At this stage. Like born state. } 3. This occurs automatically by invoking the destroy() method when we quit the browser. To initialization. The initialization occurs only once in the applets life cycle. we may override the init() method. Starting can also occur if the applet is already in idle state.    Applet enters into the running state. } paint() method may be invoked during running state in the following situation. Dead state An applet is said to be dead when it is removed from memory. } 2.1. public void init() { // Initialization goes here. we may do initialization of various things.

access local file system.once in the applets life cycle. We may override the destroy() method to clean up the previously allocated resources. Page 117 . make network connections to the system other than it came from execute a program on the local file system. public void destroy() { // code goes here. “Success is not the result of spontaneous combustion. read certain system properties. You must set yourself on fire ”. } Security restrictions An applet is restricted from doing the following thinks. initiate a print job or access system clipboard A local applet may get freedom from some of the above restrictions.       load libraries or define native methods.

and more.ear. An HttpServlet extends GenericServlet with support for the HTTP protocol. . If deployed in an EAR file. and optionally return a response to the client. do not name the directory . A web. A Web Application can also define links to outside resources such as Enterprise JavaBeans (EJBs). “Success is not the result of spontaneous combustion. You must set yourself on fire ”.war. such as servlets. (Note: If you are deploying an entire directory. accept a request from a client. and any static resources such as HTML pages and image files. . process it. JavaMessaging Service (JMS). JavaServer Pages (JSPs). JSPs and HTTP servlets can access all services and APIs available in WebLogic Server.jar and so on. the archive must end with a . If deployed alone. 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.war extension. A WAR file is deployed as a unit on one or more WebLogic Servers. A weblogic. an XML document containing WebLogic Serverspecific elements for Web applications. These services include EJBs.xml deployment descriptor. A Web archive on WebLogic Server always includes the following files:    At least one servlet or JSP page. the archive must end with an .ear extension. JSP tag libraries. a J2EE standard XML document that describes the contents of a WAR file. A Web archive may also include HTML/XML pages and supporting files such as image and multimedia files. XML.V Structure of Web Application Overview of Web Applications A Web Application contains an application's resources.) Servlets Servlets are Java classes that execute in WebLogic Server.xml deployment descriptor. A Web archive contains the files that make up a Web Application (WAR file). The WAR file can be deployed alone or packaged in an Enterprise Archive (EAR file) with other application components. A GenericServlet is protocol independent and can be used in J2EE applications to implement services accessed from other Java classes. along with any helper classes.UNIT. Page 118 . An HttpServlet is most often used to generate dynamic Web pages in response to Web browser requests. database connections via Java Database Connectivity (JDBC).

JavaMessaging Service (JMS). precompiled JSP pages.JavaServer Pages JSP pages are Web pages coded with an extended HTML that makes it possible to embed Java code in a Web page. WebLogic Server automatically compiles JSP pages if the servlet class file is not present or is older than the JSP source file. The entire directory. and the non-Java class files they reference are accessed beginning in the top level of the staging directory. is bundled into a WAR file using the jar command. and more. including other Web Applications. XML. Deploying a Web Application as a WAR file is recommended primarily for production environments. Deploying a Web Application in exploded directory format is recommended primarily for use while developing your application. Servlets and JSP pages may depend upon additional helper classes that must also be deployed with the Web Application. helper classes and. Main Steps to Create a Web Application The following steps summarize the procedure for creating a Web Application. 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. EJB components. JSP pages and HTTP servlets can access all services and APIs available in WebLogic Server. You must set yourself on fire ”. using HTML-like tags. The WAR file can be deployed alone or packaged in an Enterprise Archive (EAR file) with other application components. “Success is not the result of spontaneous combustion. compiled Java classes and JSP taglibs are stored in a WEB-INF subdirectory at the top level of the staging directory. see Web Application Developer Tools. weblogic. Web Application Directory Structure Web Applications use a standard directory structure defined in the J2EE specification. For more information. You can also precompile JSP pages and package the servlet class in the Web Archive to avoid compiling in the server. once staged. translates JSP pages into servlets. Page 119 . called taglibs. The WebLogic JSP compiler. and WebLogic components. if desired. Web Application components are assembled in a directory in order to stage the WAR file for the jar command. Java classes include servlets. HTML pages. JSP pages can call custom Java classes. You may want to use developer tools included with WebLogic Server for creating and configuring Web Applications. These services include EJBs.jspc. JSP pages. The XML descriptors. database connections through Java Database Connectivity (JDBC).

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

xml The WebLogic-specific deployment descriptor file that defines how named resources in the web. If you are deploying the Web Application as part of an enterprise application. 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. located under the root directory. DefaultWebApp/WEB-INF/web. Page 121 . this directory is called DefaultWebApp. All servlets. 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. You must set yourself on fire ”. Deploy the Web Application or Enterprise Application on WebLogic Server. 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. such as HTML files and JSP files in the directory that is the document root of your Web Application. including JSP tag libraries. This file is also used to define JSP and HTTP session attributes.xml The Web Application deployment descriptor that configures the Web Application. All files under this root directory can be served to the client. The root of this hierarchy defines the document root of your Web Application. This final step configures your application to service requests on WebLogic Server. See Deploying Web Applications as Part of an Enterprise Application 9. DefaultWebApp/WEB-INF/classes Contains server-side classes such as HTTP servlets and utility classes. under the root directory.xml file are mapped to resources residing elsewhere in WebLogic Server. classes. under user_domains/mydomain/applications. static files. and are not served to a client. In the default installation of WebLogic Server. except for files under the special directory WEB-INF. bundle the WAR file into an Enterprise Application archive (EAR file). DefaultWebApp/ Place your static files. DefaultWebApp/WEB-INF/weblogic. and other resources belonging to a Web Application are organized under a directory hierarchy. All files under WEB-INF are private.8. DefaultWebApp/WEB-INF/lib Contains JAR files used by the Web Application. See Deploying Web Applications.

typically a file name. For additional information.xml classes/ Myservlet. see How WebLogic Server Resolves HTTP Requests.class lib/ Myapp.jar Welcome. pathInfo is the remaining portion of the URL.html Welcome. myWebApp.xml struts-config. servletPath is a servlet that is mapped to the servletPath. ContextPath is the context root of your Web Application. If you are using virtual hosting. you can substitute the virtual host name for the hoststring portion of the URL.xml or weblogic. You must set yourself on fire ”.war) or the name of the directory in which the Web Application was deployed.xml. If the context root is not specified. Page 122 . ContextPath is the name of the Web Application archive file (for example.jsp “Success is not the result of spontaneous combustion. if one is specified in application.http://hoststring/ContextPath/servletPath/pathInfo Where hoststring is either a host name that is mapped to a virtual host or hostname:portNumber. 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.

Page 123 . 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. or webapp would be stored in the webapps directory of the Tomcat installation in a directory whose name defines the application's name. The directory structure is as follows:jsp “Success is not the result of spontaneous combustion. and the webapp directory is named "courses/D2Home/D2". the coursework directory is "courses/D2Home" in the ExerTran installation directory. a web application. If the coursework's name is D2. In a standard. You must set yourself on fire ”. or original. The current system uses Tomcat 5. Tomcat installation.Tomcat and the Tomcat Web Application Directory Structure ExerTran uses Apache Tomcat to dynamically generate web pages. Tomcat Web Application Directory Structure The webapp directory is held in the coursework directory within the "courses" directory and is named after the coursework.

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

and versions created. even if there are no rows to save. files This is available for holding save files from the application. When the coursework is re-started. particularly question attempts and marks awarded. src/java/dynDrawings “Success is not the result of spontaneous combustion. application. It may be necessary to change the compression to occur while the system is running.txt.xml" in the directory. all other tables can be created from the manager interface by saving to the database. activitylog. Page 125 . This directory is structured by package name. These are copied from "src/lib" on a coursework build. You must set yourself on fire ”. usually called applicationlog. The first of these logs debug messages from the coursework. with a manager user and password. 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. the log file is removed. and mysqlLog. the second logs user activity. There are 3 basic log files. which is the default database. defined by "userd_def. xml This holds Xml files with definitions of the database table columns.txt. 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. A further log file is also created when the connection to the marks database fails and marks cannot be stored in the database. these log files are compressed when they are larger then a set limit.text. particularly csv files created from database tables. Note that the only database table that needs creating to start running a coursework is a "users" table. the third error messages from the mysql database. from which they are read stored to the database when the coursework system is restarted: on successful storage of these marks. lib This contains jar files needed by Tomcat to run the @systemname. if regular closure of the application does not occur.logs This holds the log files produced from the execution of a coursework. 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 . The marks are then recorded in a log file.

Creating the Web Application Directory Structure The first thing you need to do is create the directory structure that will contain the application. The following sections will take you through the steps involved in deploying a web application. . create a web application ServletContext.Objects that handle the dynDrawing system for modifying diagrams on the fly in respnse to user actions. The Web Application Directory Structure Directory /onjava Contains This is the root directory of the web application. Java Web Applications. We discussed this structure in Part 1. Deploying Web Applications to Tomcat In this article we are going to cover the deployment of web applications using Tomcat. Page 126 /onjava/WEB-INF “Success is not the result of spontaneous combustion. In this article. This directory contains all resources related to the application that are not in the document root of the application. we       create the web application directory structure. 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. and I include the relevant details in Table 1. Table 1. and create and deploy a WAR file. The name of our web application will be onjava. This is where your web application deployment descriptor is located. add Servlets. add Tag Libraries. add JSPs. You must set yourself on fire ”. We are performing a manual deployment to fully explain the steps involved when deploying a web application. All JSP and XHTML files are stored here.

/onjava/WEB-INF/classes /onjava/WEB-INF/lib This directory is where servlet and utility classes are located.Note that the WEB-INF directory is not part of the public document. Inc.xml <?xml version="1.xml file. No files contained in this directory can be served directly to a client. Page 127 . Creating a Web Application ServletContext After you've created the web application directory structure. For example. You must set yourself on fire ”. The ServletContext defines a set of methods that are used by components of a web application to communicate with the servlet container. The last step in creating the web application directory structure is adding a deployment descriptor. The name of our web application.3//EN" "http://java. and an empty <webapp/> element. describing the web.//DTD Web Application 2.com/j2ee/dtds/web-app_2_3. At this point you'll be creating a default web. The ServletContext acts as a container for the web application.dtd"> <web-app> </web-app> Now copy this file to the TOMCAT_HOME/onjava/WEB-INF/ directory. this is where you would place a JAR file that contained a JDBC driver. Listing 1 contains the source for a default web. and we'll begin adding web application components to it in the following sections. When it comes time for deployment. you can package your web application into a WAR file and go though the production deployment process. onjava. While in development I suggest creating the directory directly in the Tomcat /webapps directory. "Web Applications and the ServletContext.xml file. There is only one ServletContext per web application.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems. is the root of our directory structure. This directory contains Java Archive files that the web application depends upon.sun.xml file that contains only the DTD. We will discuss the relationship between a ServletContext and its web application in much more detail in Part 4. you must add a new ServletContext to Tomcat. Listing 1 web." “Success is not the result of spontaneous combustion.

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

5 If you changed the default HTTP port. The only thing you should pay attention to is the action of the form. Page 129 . as mentioned in Installing and Configuring Tomcat. 3.</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.java named login. you'll see nothing very special about it. 4. which in this case is TOMCAT_HOME/webapps/onjava/. 2. You must set yourself on fire ”. you should see an image similar to Figure 1. If everything was configured correctly. “Success is not the result of spontaneous combustion. This servlet will retrieve the username-password parameters from the request and perform its own processing. It references a servlet in the package com. There isn't much to deploying a JSP. 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. Any images that it references should be placed in an images folder that you have created in the /onjava directory. You just copy it to the public directory of your web application. you will need to request the URL from the appropriate port value.

If you do not see a page similar to this image. Listing 3 welcome. Listing 3 contains the source for the target JSP. you'll see something like this. Page 130 . "Creating a Web Application ServletContext. It will then output the String value of the attribute.jsp <html> <head> <title>OnJava Demo</title> <meta http-equiv="Content-Type" content="text/html. make sure you have the correct entry in the server.Figure 1. You must set yourself on fire ”." 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.gif"></td> <td> <b>Welcome : <%= request.getAttribute("USER") %></b> “Success is not the result of spontaneous combustion.xml file. If everything is configured correctly. 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. as described in the section.

} public void doGet(HttpServletRequest request.init(config). Listing 4 com. which in this case is TOMCAT_HOME/webapps/onjava/. you simply need to copy it to the public directory of your web application. to keep things simple. HttpServletResponse response) throws ServletException.</td> </tr> <tr> <td> </td> </tr> </table> </body> </html> As we stated earlier to deploy this JSP. response). and then forward the request to a target JSP.login.io.*. java. we would perform a SQL lookup return "Bob".*. I'm just returning String Bob. String password) { // Just return a static name // If this was reality. The source code for this servlet can be found in Listing 4. java.jsp". look up the associated user. public class login extends HttpServlet { private String target = "/welcome.util. Page 131 . You must set yourself on fire ”. } public void init(ServletConfig config) throws ServletException { super.java package com.*. import import import import javax. This servlet will be the action of login. javax. For our example the value of the USER is static. Adding Servlets The next component to add is a servlet. “Success is not the result of spontaneous combustion.onjava. IOException { // If it is a get request forward to doPost() doPost(request.onjava. but. private String getUser(String username.*.servlet.jsp's form.http.servlet. Normally you would perform a real lookup of some sort. It will retrieve the username and password values from HttpServletRequest.

getParameter("username"). user). You must set yourself on fire ”. This class file is in the subdirectory com. HttpServletResponse response) throws ServletException. It isn't necessary to add all servlets to the web. For this example.setAttribute("USER". such as initialization parameters. // Forward the request to the target named ServletContext context = getServletContext(). password). you should compile this servlet and move it to the /onjava/WEB-INF/classes/com/onjava/ directory. // Add the fake user to the request request. Page 132 . response). the password from the request password = request.getRequestDispatcher(target). IOException { // Get String // Get String the username from the request username = request.xml file. String user = getUser(username. RequestDispatcher dispatcher = context.forward(request. it's only necessary when the servlet requires additional information.getParameter("password").xml file. The next step in deploying the login servlet is to add a servlet entry into the web application's web. Example <servlet> Element <servlet> <servlet-name>ExampleServlet</servlet-name> <servlet-class>packagename.onjava because of its package name.} public void doPost(HttpServletRequest request. } 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. dispatcher.ExampleServlet</servlet-class> <init-param> <param-name>parameter</param-name> “Success is not the result of spontaneous combustion. An example <servlet> element can be found in the following code snippet.

xml file: <servlet> <servlet-name>login</servlet-name> <servlet-class>com. then the container can load the servlet at anytime during startup. If the value is negative or unspecified. “Success is not the result of spontaneous combustion. restart the Tomcat server and open the following URL in your browser: http://localhost:8080/onjava/login. to be passed to the servlet. you should see an image similar to Figure 2. Page 133 . Table 2. which contain the name and value. <param-name> and <param-value>. respectively. A description of each of its parts can be found in Table 2. Lower positive values are loaded first. The Sub-elements of a <servlet> Sub-element <servlet-name> Description The <servlet-name> element is simply the canonical of the deployed servlet. The <init-parameter> sub-element is an optional parameter containing a name-value pair that is passed to the servlet on initialization. The <load-on-startup> sub-element indicates the order in which each servlet should be loaded. If everything went according to plan. To see your web application in action.<param-value>value</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> This servlet entry contains a simple servlet definition. Now enter a username and password and press the "Submit Query" button.login</servlet-class> </servlet> That's all there is to it. It contains two sub-elements.jsp You should see an image similar to Figure 1 (which was referred to above). <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. name <servlet-class> The <servlet-class> sub-element references the fully qualified class name of the servlet.onjava. You must set yourself on fire ”.

make sure that you have the servlet class in the appropriate directory and the entry in the web. 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.java package com.servlet.servlet. import javax.Figure 2. While this is a perfectly silly example of a tag library.getOut().tagext. 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. that replaces every occurrence of the text <onjava:hello/> with the literal string "Hello".JspTagException. Results after pressing "Submit Query". Page 134 . it allows us to present a practical example of deploying a tag library.jsp. If you didn't see an image similar to Figure 2. import javax.onjava. Listing 5 HelloTag. import javax.xml file matches the code snippet referenced above.TagSupport. This library contains a single tag.jsp.servlet. } “Success is not the result of spontaneous combustion.print("Hello"). Adding Tag Libraries The final component that we're adding is a tag library.JspException.jsp. You must set yourself on fire ”. HelloTag.

You must set yourself on fire ”.catch (Exception e) { throw new JspTagException(e.//DTD JSP Tag Library 1.tld <?xml version="1.getMessage()).dtd'> <web-app> <servlet> “Success is not the result of spontaneous combustion.dtd"> <!-. Inc.sun.release(). } // We want to return SKIP_BODY because this Tag does not support // a Tag Body return SKIP_BODY.0</tlibversion> <jspversion>1. super.xml file can be found in Listing 7.1</jspversion> <shortname>onjava</shortname> <uri>/onjava</uri> <tag> <name>hello</name> <tagclass>com.com/j2ee/dtds/web-app_2_3. Inc.HelloTag</tagclass> <bodycontent>empty</bodycontent> <info>Just Says Hello</info> </tag> </taglib> To deploy this tag library. Listing 7 web.onjava. } } Listing 6 taglib.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC '-//Sun Microsystems.//DTD Web Application 2. // This is just good practice for when you start creating // hierarchies of tags.xml file. we need to make an entry to the web. } public void release() { // Call the parent's release to release any resources // used by the parent tag.a tag library descriptor --> <taglib> <tlibversion>1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems.1//EN" "http://java.3//EN' 'http://java. The modified web.xml <?xml version="1. Page 135 .sun.com/j2ee/dtds/web-jsptaglibrary_1_1.

<taglib-uri>.tld to the welcome.onjava. The TLD defines the tags contained in the library and the handlers that will process the defined tags.jsp page. 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. The second <taglib> element. You must set yourself on fire ”. you need to modify the welcome.<servlet-name>login</servlet-name> <servlet-class>com. <taglib-location>.gif"></td> <td> <b><onjava:hello /> : <%= request. Listing 7 Modified welcome.jsp file. defines the location of the tag library's descriptor (TLD).getAttribute("USER") %></b> </td> </tr> <tr> <td> </td> </tr> </table> </body> </html> “Success is not the result of spontaneous combustion. tells the container how the tag library is to be referenced.jsp <%@ taglib uri="/onjava" prefix="onjava" %> <html> <head> <title>Onjava Demo</title> <meta http-equiv="Content-Type" content="text/html.tld</taglib-location> </taglib> </web-app> The added <taglib> entry contains two elements. For this example we use the value /onjava.login</servlet-class> </servlet> <taglib> <taglib-uri>/onjava</taglib-uri> <taglib-location>/WEB-INF/lib/taglib. The first <taglib> element. copy the compiled tag library and the taglib. The modified JSP is in Listing 7.tld into the TOMCAT_ROOT/onjava/WEB-INF/lib directory. To complete your deployment. Page 136 . To test you new tag library. You need to also add a taglib directive referencing the taglib. which is the way we'll reference the tag library in our JSPs. replacing the Welcome message with a reference to the <onjava:hello /> tag.

to the TOMCAT_HOME/webapps directory. Archive the web application: jar cvf onjava. In this case the root directory would be TOMCAT_HOME/webapps/onjava/. referencing the onjava web application. you should see the message Hello: Bob. Creating and Deploying a WAR File When your web application is ready for deployment. Add a new Context entry to the /TOMCAT_HOME/conf/server. Page 137 . As we discussed previously in Java Web Applications. 2. you need to package it for distribution. web applications are packaged in WAR files.xml file. 4.Now open the login. Restart Tomcat. 3. The steps required to "WAR-up" your /onjava web application and deploy it are as follows: 1. If you're deploying this WAR file to the Tomcat installation that you were developing in. Copy the resulting WAR file.war .war.jsp page as described previously and run through the demo again. onjava. You must set yourself on fire ”. This time instead of Welcome: Bob. Change to the root directory of your web application. then you will need to back up your development directory and remove it from the TOMCAT_HOME/webapps directory. “Success is not the result of spontaneous combustion. 5.

Sign up to vote on this title
UsefulNot useful