You are on page 1of 236

ADVANCED JAVA AND WEB TECHNOLOGIES LAB RECORD

DEPARTMENT OF INFORMATION TECHNOLOGY

Submitted by

D.SUNITHA (Assistant Professor)

NARASARAOPETA ENGINEERING COLLEGE


DEPARTMENT OF INFORMATION TECHNOLOGY
NARASARAOPET, GUNTUR DIST-522 601.

INDEX
S.No 1 Name of Experiment Page Date Remarks

WEEK-1
Developing static WEBPAGES for an ONLINE BOOK STORE Introduction to HTML HOMEPAGE LOGIN PAGE 1 2 24 29

WEEK-2
Introduction to HTML FORMS CART PAGE REGISTRAION PAGE 37 41 43

WEEK-3
Introduction to DHTML with JavaScript VALIDATE THE REGISTRATION PAGE 49 58

WEEK-4
Introduction to CSS Use Different font, styles Set a Background image Control the repetition of the image

64 82 84 86 88 90

Define Styles for links Working with layers Add Customized Cursors

WEEK-5
Introduction to XML Implement an XML FILE For Book Information

94 102 106

PROCEDURE

WEEK-6
Introduction to JAVA BEANS Create a SIMPLE BEAN with a area filled with a COLOR. PROCEDURE 7 107 126 129

WEEK-7
Install TOMCAT web server and APCHE Access ONLINE BOOK SYSTEM WebPages from TOMCAT WEB SERVER. -133-142-

WEEK-8
Introduction to SERVLETS To Create Cookie To Read the user id and passwords entered (user id and passwords) available in the cookies. Validation of authentic users Use init-parameters to store USERNAMES and 148 164 170 172 175

PASSWORDS

WEEK-9
Introduction to JDBC Install a Database (Mysql or Orcle) Create table using above database(SQL) Practice JDBC connectivity through a JavaServlet Practice JDBC connectivity through a JSP 178 183 193 195 201

10

WEEK-10
Introduction to JSP Write JSP for Authenticate users using DATABASE 207 215

11

WEEK-11
Create tables in DatabaseandEXTRACTdata from tables and display them in CATALOGUE PAGE 219

WEEK-1

Date of Conduction: Date of Submission:

Date of Valuation Marks Awarded

: :

DEVELOPING STATIC WEBPAGES FOR AN ONLINE BOOK STORE


Signature of Staff Member

D.SUNITHA
AIM:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Design the Following Static WebPages Required for an Online Book Store website. 1. HOMEPAGE The Static Home Page must contain three frames. Top frame: Logo and the College name and links to home page, login page, Registation Page, Catalogue Page and Cart Page (The Description of these pages will be given below) Left Frame: At Least Four Links for Navigation, Which will display the catalogue of respective links. For e.g.: When you click the link IT the catalogue for IT books should be displayed in the Right Frame. Right Frame: The pages to the links in the Left Frame must be loaded here. Initially this page Contains Description of the Website.

LOGO HOME IT CSE ECE EEE CIVIL Login

WEBSITE NAME Registration Catalogue Cart

Description of the website

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

HTML
HTML, an initializes for Hypertext Mark-up Language, is the predominantmarkuplanguage for web pages. It provides a means to describe the structure of text-basedInformation in a documentby denoting certain text as links, headings, paragraphs, lists,etc.and to supplement that text with interactive forms embedded images, and otherObjects. HTML is written in the form of "tags" consisting minimally of "elements"Surrounded by angle brackets. HTML can also describe, to some degree, the appearanceAnd semantics of a document and can include embedded scripting language code (such asJavaScript) that can affect the behavior of Web browsers and other HTML processors.

HISTORY OF HTML
Origins In 1980, physicist Tim Berners-Lee, who was an independent contractor atproposed and prototyped ENQUIRE, a system for CERN researchers to use and sharedocuments. In 1989, Berners-Lee and CERN data systems engineer Robert Cailliau eachsubmitted separate proposals for an Internet-based hypertext system providing similarfunctionality. The following year, they collaborated on a joint proposal, theWorldwide Web (W3) project, which was accepted by CERN. In his personal notes from1990 he lists, "some of the many areas in which hypertext is used", and puts anencyclopedia first. First specifications The first publicly available description of HTML was a document called HTML Tags,first mentioned on the Internet by Berners-Lee in late 1991. It describes 22 elements comprising the initial, relatively simple design of HTML. Thirteen of these elements stillexist in HTML 4. HTML is a text and image formatting language used by web browsersto dynamically format web pages. The semantics of many of its tags can be traced toearly text formatting languages such as that used by the RUNOFF command developed inthe early 1960s for the CTSS (Compatible Time-Sharing System) operating system, andits formatting commands were derived from the commands used by typesetters tomanually format documents. Berners-Lee considered HTML to be, at the time, an application of SGML, but it was notformally defined as such until the mid-1993 publication, by the IETF, of the first proposalfor an HTML specification: Berners-Lee and Dan Connolly's "HypertextMarkupLanguage (HTML)" Internet-Draft, which included an SGML DocumentTypeDefinitionto define the grammar. The draft expired after six months, but was notable for itsacknowledgment of the NCSA Mosaic browser's custom tag for embedding inlineimages, reflecting the IETF's philosophy of basing standards on successful prototypes.Similarly, Dave Raggett's competing Internet-Draft, "HTML+ (Hypertext MarkupFormat)", from late 1993, suggested standardizing already-implemented features liketables and fill-out forms.
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 2

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

After the HTML and HTML+ drafts expired in early 1994, the IETF created an HTMLWorking Group, which in 1995 completed "HTML 2.0", the first HTML specification intended to be treated as a standard against which future implementations should bebased. Published as Request for Comments 1866, HTML 2.0 included ideas from theHTML and HTML+ drafts. There was no "HTML 1.0"; the 2.0 designation was intendedto distinguish the new edition from previous drafts. Further development under the auspices of the IETF was stalled by competing interests.Since 1996, the HTML specifications have been maintained, with input from commercialsoftware vendors, by the World Wide Web Consortium (W3C). However, in 2000,HTML also became an international standard (ISO/IEC 15445:2000). The last HTMLspecification published by the W3C is the HTML 4.01 Recommendation, published inlate 1999. Its issues and errors were last acknowledged by errata published in 2001. HTML version timeline November 1995 HTML 2.0 was published as IETF RFC 1866. Supplemental RFCs addedcapabilities: November 1995: RFC 1867 (form-based file upload) May 1996: RFC 1942 (tables) August 1996: RFC 1980 (client-side image maps) January 1997: RFC 2070 (internationalization)

In June 2000, all of these were declared obsolete/historic by RFC 2854. January 1997 HTML 3.2 was published as a W3C Recommendation. It was the first versiondeveloped and standardized exclusively by the W3C, as the IETF had closed itsHTML Working Group in September 1997.HTML 3.2 dropped math formulas entirely, reconciled overlap among various proprietary extensions, and adopted most of Netscape's visual markup tags. Netscapes blink element and Microsoft's marquee element were omitted due to a mutual agreement between the two companies. A markup for mathematical formulas similar to that in HTML wasn't standardized until 14 months later inMathML. December 1997 HTML 4.0 was published as a W3C Recommendation. It offers three "flavors":

Strict, in which deprecated elements are forbidden, Transitional, in which deprecated elements are allowed, Frameset, in which mostly only frame related elements are allowed.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Initially code-named "Cougar", HTML 4.0 adopted many browser-specific element types and attributes, but at the same time sought to phase out Netscapes visual markup features by marking them as deprecated in favor of style sheets. April 1998 HTML 4.0 was reissued with minor edits without incrementing the version number. December 1999 HTML 4.01 was published as a W3C Recommendation. It offers the same three flavors as HTML 4.0, and its last errata were published May 12, 2001. May 2000 ISO/IEC 15445:2000 ("ISO HTML", based on HTML 4.01 Strict) was published as an ISO/IEC international standard. As of mid-2008, HTML 4.01 and ISO/IEC 15445:2000 are the most recent versions ofHTML. Development of the parallel, XML-based language XHTML occupied the W3C'sHTML Working Group through the early and mid-2000s. October 1991 HTML Tags, an informal CERN document listing twelve HTML tags, was first mentioned in public. November 1992. July 1993 Hypertext Markup Language was published by the IETF as an Internet-Draft (a rough proposal for a standard). It expired in January 1994. November 1993 HTML+ was published by the IETF as an Internet-Draft and was a competingproposal to the Hypertext Markup Language draft. It expired in May 1994. April 1995 (authored March 1995) HTML 3.0 was proposed as a standard to the IETF, but the proposal expired fivemonths later without further action. It included many of the capabilities that were inRaggett's HTML+ proposal, such as support for tables, text flow aroundfigures, and the display of complex mathematical formulas. A demonstration appeared in W3C's own Arena browser. HTML 3.0 did not succeed forseveral reasons. The pace of browser development, as well as the number of interestedparties, had outstripped the resources of the IETF. Netscape continued to introduceHTML elements that specified the visual appearance of documents, contrary to the goalsof the newly-formed W3C, which sought to limit HTML to describing logical
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 4

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

structure.Microsoft, a newcomer at the time, played to all sides by creating its own tags,implementing Netscape's elements for compatibility, and supporting W3C features suchas Cascading Style Sheets. January 2008 HTML5 was published as a Working Draft by the W3C. Although its syntax closely resembles that of SGML, HTML 5 has abandoned any attempt to be an SGML application, and has explicitly defined its own "html" serialization, in addition to an alternative XML

XHTML VERSIONS

XHTML is a separate language that began as a reformulation of HTML 4.01 using XML 1.0. It continues to be developed: XHTML 1.0, published January 26, 2000 as a W3C Recommendation, later revised and republished August 1, 2002. It offers the same three flavors as HTML 4.0 and 4.01, reformulated in XML, with minor restrictions. XHTML 1.1, published May 31, 2001 as a W3C Recommendation. It is based on XHTML 1.0 Strict, but includes minor changes, can be customized, and is reformulated using modules from Modularization of XHTML, which was published April 10, 2001 as a W3C Recommendation. XHTML 2.0, is still a W3C Working Draft. XHTML 2.0 is incompatible withXHTML 1.x and, therefore, would be more accurate to characterize as aXHTMLinspired new language than an update to XHTML 1.x. XHTML5, which is an update to XHTML 1.x, is being defined alongside HTML5 in the HTML5 draft.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

The <DOCTYPE> element Its purpose is to declare to browsers exactly what version of HTML was used to create the document. The general DOCTYPE declaration for HTML 4.0 is

<! DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.0 // EN> The reason for the EN is that the HTML specification has not yet been developed in any language but English. If has not yet been developed in any language but English. If you are replacing the BODY element with FRAMESET, you should use the following DTD.

<! DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.0 FRAMESET // EN> There is another technique for supplying the DOCTYPE declaration. This is called the System Identifier DTD. A System Identifier DTD is declared as follows:

<! DOCTYPEHTMLSYSTEMhttp:// WWW.W3.Org/DTD/HTML 4 - strict.dtd> The difference in this approach is that the DTD is referenced not by name, but by specifying the URL where it is found.

The HTML Element It is the first and last thing in a web page, and its absence means that no web browser recognizes your work as an HTML page. HTML element must have both start and end tags in order to function properly. Thus, the document begins with <HTML> and ends with </HTML>. The HTML start tag can have three attributes. The first is version, and it takes a URL value. The URL points to a location that has the Document Type Definition (DTD) for the version of HTML in use on that page. The HTML start tag can also contain the Lang and dir attributes, which respectively, establish the human language in which the web page is written and the direction of the printing. <HTML> tag might look like:

<HTML version = http://www.w3.org/DTD/HTML4- strict.dtdlang=en dir=rtl> The HEAD Element The HEAD element is a container for an HTML documents header information. It contains one required element TITLE and several other optional attributes. The HEAD element has started and end tags, beginning with <HEAD> and ending with </HEAD>. A typical HEAD element look like this:
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 6

D.SUNITHA
<HEAD>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<TITLE> My Home Page </TITLE> </HEAD> The text between the TITLE tags is displayed in the title bar of a visitors web browser.

MetaData In addition to the title, a head element can contain other elements known as metadata. It is data that is not shown to the person viewing the page, but useful to user agents and search engines. The currently used elements in this category are: Base Link Meta Script Style The Base Element The base element establishes a base url from which relative URLs referenced in the html document can be calculated. Example,

<base href=http://www.test.org/> The result of this declaration is that any relative url in the html document is appended to this base url to achieve he full url. Thus, the relative url ashttp://www.test.org/index.html. index.html would be interpreted

The Link Element Its purpose is to establish relationships among different html documents. Used only in the head element. Link takes three main attributes in addition to href: rel, rev and title. Rel defines a forward relationship and rev defines a reverse one. Example,
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 7

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<link rev=previous href=chapter1.html <link rel=next href=chapter3.html> The title attribute simply gives a title to the document referenced by the url. Link types are:

Alternate - Points to an optional replacement for the current document Appendix - points to an appendix Bookmark - Points to a named anchor Chapter Points to a chapter Copyright - Points to a copyright statement Glossary - Points to s glossary of terms Help - Points to a help document Index - Points to an index Next - Points to the document that comes after the current one Previous - Points to the document that comes before the current one Start - Points to the beginning document The Meta Element When used with the name and content attributes, its main function is to establish metadata variable information for use by web search agents. For example,

<meta name=wt content=web technology> The script and style elements Used for including script and style sheet into an html document.

The body element The body element is where the displayable web page is found. A typical body in an html document looks like: link=0000FFvlink=FF8C00

<body background=bg.giftext=000000 alink=000000>Text, images, etc. are found here </body>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

HTML Elements Remember the HTML example from the previous page: <html> <head> <title>Title of page</title> </head> <body> This is my first homepage. <b>This text is bold</b> </body> </html> This is an HTML element: <b>This text is bold</b> The HTMLelementstartswithastarttag:<b> ThecontentoftheHTMLelementis:Thistext isbold The HTML element ends with an end tag: </b>

The purpose of the <b> tag is to define an HTML element that should be displayed asbold. This is also an HTML element: <body> This is my first homepage. <b>This text is bold</b> </body> This HTML element starts with the start tag <body>, and ends with the end tag </body>. The purpose of the <body> tag is to define the HTML element that contains the body of the HTML document.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

D.SUNITHA
Headings

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Headings are defined with the <h1> to <h6> tags. <h1> defines the largest heading. <h6>defines the smallest heading. <h1>This is a heading</h1> <h2>This is a heading</h2> <h3>This is a heading</h3> <h4>This is a heading</h4> <h5>This is a heading</h5> <h6>This is a heading</h6> HTML automatically adds an extra blank line before and after a heading. Paragraphs Paragraphs are defined with the <p> tag. <p>This is a paragraph</p> <p>This is another paragraph</p> HTML automatically adds an extra blank line before and after a paragraph. Dont Forget the Closing Tag You might have noticed that paragraphs can be written without end tags </p>: <p>This is a paragraph <p>This is another paragraph The example above will work in most browsers, but don't rely on it. Future version of HTML will not allow you to skip ANY end tags. Closing all HTML elements with an end tag is a future-proof way of writing HTML. It also makes the code easier to understand (read and browse) when you mark both where an element starts and where it ends. Line Breaks The <br> tag is used when you want to break a line, but don't want to start a new paragraph. The <br> tag forces a line break wherever you place it. <p>This<br> is a para<br>graph with line breaks</p>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 10

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

The <br> tag is an empty tag. It has no end tag like </br>, since a closing tag doesn't make any sense. Comments in HTML The comment tag is used to insert a comment in the HTML source code. A comment will be ignored by the browser. You can use comments to explain your code, which can help you when you edit the source code at a later date. <!-- This is a comment --> Note that you need an exclamation point after the opening bracket, but not before the closing bracket. HTML Tag Attributes HTML tags can have attributes. Attributes provide additional information to an HTML element. Attributes always come in name/value pairs like this: name="value". Attributes are always specified in the start tag of an HTML element. Attributes Example 1: <h1> defines the start of a heading. <h1 align="center"> has additional information about the alignment. Attributes Example 2: <body> defines the body of an HTML document. <body bgcolor="yellow"> has additional information about the background color. Attributes Example 3: <table> defines an HTML table. (You will learn more about HTML tables later) <table border="1"> has additional information about the border around the table. Use Lowercase Attributes Attributes and attribute values are case-insensitive. However, the World Wide Web Consortium (W3C) recommends lowercase attributes/attribute values in their HTML 4 recommendation, and XHTML demands lowercase attributes/attribute values.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

11

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Text Formatting Tags

Tag <b> <big> <em> <i> <small> <strong> <sub> <sup> <ins>

Description Defines bold text Defines big text Defines emphasized text Defines italic text Defines small text Defines strong text Defines subscripted text Defines superscripted text Defines inserted text

"Computer Output" Tags Tag <code> <kbd> <samp> <tt> <var> <pre> <listing> <plaintext> <xmp> Description Defines computer code text Defines keyboard text Defines sample computer code Defines teletype text Defines a variable Defines preformatted text Deprecated. Use <pre> instead Deprecated. Use <pre> instead Deprecated. Use <pre> instead

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

12

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Citations, Quotations, and Definition Tags

Tag <abbr> <acronym> <address> <bdo> <blockquote> <q> <cite> <dfn> <del> <s> <strike> <u>

Description Defines an abbreviation Defines an acronym Defines an address element Defines the text direction Defines a long quotation Defines a short quotation Defines a citation Defines a definition term Defines deleted text Deprecated. Use <del> instead Deprecated. Use <del> instead Deprecated. Use styles instead

Character Entities Some characters have a special meaning in HTML, like the less than sign (<) that defines the start of an HTML tag. If we want the browser to actually display these characters we must insert character entities in the HTML source. A character entity has three parts: an ampersand (&), an entity name or # and an entity number, and finally a semicolon (;). To display a less than sign in an HTML document we must write: &lt; or &#60; The advantage of using a name instead of a number is that a name is easier to remember. The disadvantage is that not all browsers support the newest entity names, while the support for entity numbers is very good in almost all browsers. Note that the entities are case sensitive. This example lets you experiment with character entities: Character Entities

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

13

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Non-breaking Space The most common character entity in HTML is the non-breaking space. Normally HTML will truncate spaces in your text. If you write 10 spaces in your text HTML will remove 9 of them. To add spaces to your text, use the &nbsp; character entity. The Most Common Character Entities: Result Description non-breaking space < > & " ' less than greater than Ampersand quotation mark apostrophe Entity Name &nbsp; &lt; &gt; &amp; &quot; &apos; (does not work in IE) Entity Number &#160; &#60; &#62; &#38; &#34; &#39;

Some Other Commonly Used Character Entities: Result Description Cent Pound Yen Euro Section Copyright registered trademark multiplication Division Entity Name &cent; &pound; &yen; &euro; &sect; &copy; &reg; &times; &divide; Entity Number &#162; &#163; &#165; &#8364; &#167; &#169; &#174; &#215; &#247;

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

14

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Anchor Tag and the Href Attribute HTML uses the <a> (anchor) tag to create a link to another document. An anchor can point to any resource on the Web: an HTML page, an image, a sound file, a movie, etc. The syntax of creating an anchor: <a href="url">Text to be displayed</a> The <a> tag is used to create an anchor to link from, the href attribute is used to address the document to link to, and the words between the open and close of the anchor tag will be displayed as a hyperlink. This anchor defines a link to W3Schools: <a href="http://www.w3schools.com/">Visit W3Schools!</a> The line above will look like this in a browser: Visit W3Schools! The Target Attribute With the target attribute, you can define where the linked document will be opened. The line below will open the document in a new browser window: <a href="http://www.w3schools.com/" Target="_blank">Visit W3Schools!</a> The Anchor Tag and the Name Attribute The name attribute is used to create a named anchor. When using named anchors we can create links that can jump directly into a specific section on a page, instead of letting the user scroll around to find what he/she is looking for. Below is the syntax of a named anchor: <a name="label">Text to be displayed</a> The name attribute is used to create a named anchor. The name of the anchor can be any text you care to use. The line below defines a named anchor: <a name="tips">Useful Tips Section</a> You should notice that a named anchor is not displayed in a special way.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

15

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

To link directly to the "tips" section, add a # sign and the name of the anchor to the end of a URL, like this: <a href="http://www.w3schools.com/html_links.asp#tips"> Jump to the Useful Tips Section</a> A hyperlink to the Useful Tips Section from WITHIN the file "html_links.asp" will look like this: <a href="#tips">Jump to the Useful Tips Section</a>

Frames
With frames, you can display more than one HTML document in the same browser window. Each HTML document is called a frame, and each frame is independent of the others. The disadvantages of using frames are: The web developer must keep track of more HTML documents It is difficult to print the entire page

The Frameset Tag The <frameset> tag defines how to divide the window into frames Each frameset defines a set of rows or columns The values of the rows/columns indicate the amount of screen area each row/column will occupy

The Frame Tag The <frame> tag defines what HTML document to put into each frame

In the example below we have a frameset with two columns. The first column is set to 25% of the width of the browser window. The second column is set to 75% of the width of the browser window. The HTML document "frame_a.htm" is put into the first column, and the HTML document "frame_b.htm" is put into the second column: <frameset cols="25%,75%"><frame src="frame_b.htm"></frameset> src="frame_a.htm"><frame

Note: The frameset column size value can also be set in pixels (cols="200,500"), and one of the columns can be set to use the remaining space (cols="25%,*"). Self Check - Useful Tips If a frame has visible borders, the user can resize it by dragging the border. To prevent a user from doing this, you can add noresize="noresize" to the <frame> tag. Add the <noframes> tag for browsers that do not support frames.
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 16

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Important: You cannot use the <body></body> tags together with the <frameset></frameset> tags! However, if you add a <noframes> tag containing some text for browsers that do not support frames, you will have to enclose the text in <body></body> tags! See how it is done in the first example below. Frame Tags

Tag <frameset> <frame>

Description Defines a set of frames Defines a sub window (a frame)

<noframes> Defines a noframe section for browsers that do not handle frames <iframe> Defines an inline sub window (frame)

Tables
Tables are defined with the <table> tag. A table is divided into rows (with the <tr> tag), and each row is divided into data cells (with the <td> tag). The letters td stands for "tabledata," which is the content of a data cell. A data cell can contain text, images, lists, paragraphs, forms, horizontal rules, tables, etc. <table border="1"> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> </tr> </table>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

17

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

How it looks in a browser: Row 1, cell 1 row 1, cell 2 Row 2, cell 1 row 2, cell 2 Tables and the Border Attribute If you do not specify a border attribute the table will be displayed without any borders. Sometimes this can be useful, but most of the time, you want the borders to show. To display a table with borders, you will have to use the border attribute: <table border="1"> <tr> <td>Row 1, cell 1</td> <td>Row 1, cell 2</td> </tr> </table> Headings in a Table Headings in a table are defined with the <th> tag. <table border="1"> <tr> <th>Heading</th> <th>Another Heading</th> </tr> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 18

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<td>row 2, cell 2</td> </tr> </table> How it looks in a browser:

Heading

Another Heading

row 1, cell 1 row 1, cell 2 row 2, cell 1 row 2, cell 2 Empty Cells in a Table Table cells with no content are not displayed very well in most browsers. <table border="1"> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td></td> </tr> </table> How it looks in a browser:

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

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

19

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Note that the borders around the empty table cell are missing (NB! Mozilla Firefox displays the border). To avoid this, add a non-breaking space (&nbsp;) to empty data cells, to make the borders visible: <table border="1"> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>&nbsp;</td> </tr> </table> How it looks in a browser: row 1, cell 1 row 1, cell 2 row 2, cell 1

Basic Notes - Useful Tips The <thead>,<tbody> and <tfoot> elements are seldom used, because of bad browser support. Expect this to change in future versions of XHTML. If you have Internet Explorer 5.0 or newer, you can view a working example in our XML tutorial.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

20

D.SUNITHA
Table Tags

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Tag <table> <th> <tr> <td> <caption> <colgroup> <col> <thead> <tbody> <tfoot>

Description Defines a table Defines a table header Defines a table row Defines a table cell Defines a table caption Defines groups of table columns Defines the attribute values for one or more columns in a table Defines a table head Defines a table body Defines a table footer

Unordered Lists
An unordered list is a list of items. The list items are marked with bullets (typically small black circles). An unordered list starts with the <ul> tag. Each list item starts with the <li> tag. <ul> <li>Coffee</li> <li>Milk</li> </ul> Here is how it looks in a browser: Coffee Milk

Inside a list item you can put paragraphs, line breaks, images, links, other lists, etc.

Ordered Lists
An ordered list is also a list of items. The list items are marked with numbers. An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 21

D.SUNITHA
<ol> <li>Coffee</li> <li>Milk</li> </ol>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Here is how it looks in a browser: 1. Coffee 2. Milk Inside a list item you can put paragraphs, line breaks, images, links, other lists, etc.

Definition Lists
A definition list is not a list of items. This is a list of terms and explanation of the terms. A definition list starts with the <dl> tag. Each definition-list term starts with the <dt> tag. Each definition-list definition starts with the <dd> tag. <dl> <dt>Coffee</dt> <dd>Black hot drink</dd> <dt>Milk</dt> <dd>White cold drink</dd> </dl> Here is how it looks in a browser: Coffee Black hot drink Milk White cold drink Inside a definition-list definition (the <dd> tag) you can put paragraphs, line breaks, images, links, other lists, etc.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

22

D.SUNITHA
List Tags

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Tag <ol> <ul> <li> <dl> <dt> <dd> <dir> <menu>

Description Defines an ordered list Defines an unordered list Defines a list item Defines a definition list Defines a definition term Defines a definition description Deprecated. Use <ul> instead Deprecated. Use <ul> instead

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

23

D.SUNITHA
HOMEPAGE: Home.html <html>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<frameset rows=20,8,72> <frameset cols=15,85> <frame src="1.html"> <frame src="2.html"> </frameset> <frameset cols=15,15,25,25,20> <frame src="3.html"> <frame src="4.html"> <frame src="5.html"> <frame src="6.html"> <frame src="7.html"> </frameset> <frameset cols=15,85> <frame src="8.html"> <frame src="9.html" name=f1> </frameset> </html>

1.html <html> <body> <imgsrc="logo.png" height=105 width=110></img> </body> </html>


INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 24

D.SUNITHA
2.html <html>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<body bgcolor=blue> <p> <h1 align=center><br>Online Book Shop</h1> </p> </body> </html>

3.html <html> <body> <h3 align=center> <a href="9.html" target=f1>Home</a> </h3> </body> </html>

4.html <html> <body> <h3 align=center> <a href="login.html" target=f1>Login</a> </h3> </body> </html>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

25

D.SUNITHA
5.html <html> <body>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<h3 align=center> <a href="registration.html" target=f1>Registration</a> </h3> </body> </html>

6.html <html> <body> <h3 align=center> <a href="catalogue.html" target=f1>Catalogue</a> </h3> </body> </html>

7.html <html> <body> <h3 align=center> <a href="cart.html" target=f1>Cart</a> </h3> </body> </html>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

26

D.SUNITHA
8.html <html> <body>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<h2 align=center><br><br> <a href="cse.html" target=f1>it</a><br><br><br> <a href="cse.html" target=f1>CSE</a><br><br><br> <a href="ece.html" target=f1>ECE</a><br><br><br> <a href="eee.html" target=f1>EEE</a><br><br><br> </h2> </body> </html>

9.html <html> <body> <p align=center> Description of the website </p> </body> </html>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

27

D.SUNITHA
OUTPUT:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

28

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

2.LOGIN PAGE The Page Looks Like Below. LOGO HOME IT CSE ECE EEE CIVIL Login WEBSITE NAME Registration Catalogue Cart

Login: Password:

SUBMIT

RESET

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

29

D.SUNITHA
login.html <html> <body>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<br><br><br><br><br> <p align=center> Login : <input type=text name=txt><br><br> Password :<input type=password name=pwd><br><br> <input type=submit value=Submit name=sub> <input type=reset value=Reset name=sub> </p> </body> </html>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

30

D.SUNITHA
OUTPUT:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

31

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

3) CATALOGUE PAGE: The Catalogue Page Should contains the details of all the books available in the website in a table. The Details should contain the following: 1. Snap shot of Cover Page. 2. Author Name. 3. Publisher 4. Price. 5. Add to cart Button.

LOGO HOME CSE ECE EEE CIVIL Login

WEBSITE NAME Registration Book: Author: Publications: Catalogue $4.05


ADD TO CART

Cart

Book: Author: Publications:

$63

ADD TO CART

Book: Author: Publications:

$35.5

ADD TO CART

Book: Author: Publications:

$50

ADD TO CART

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

32

D.SUNITHA
Catalogue.html <html> <body>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<table border=1 align=center bgcolor=grey> <tr> <td><imgsrc="Sunset.jpg" height=60 width=70></img></td> <td> Book:<br> Author:<br> Publications:<br> </td> <td>$40.5</td> <td><input type=button value="Add to cart"<td> </tr> <tr> <td><imgsrc="Sunset.jpg" height=60 width=70></img></td> <td> Book:<br> Author:<br> Publications:<br> </td> <td>$63</td> <td><input type=button value="Add to cart"<td> </tr> <tr> <td><imgsrc="Sunset.jpg" height=60 width=70></img></td> <td>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 33

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Book:<br> Author:<br> Publications:<br> </td> <td>$35.5</td> <td><input type=button value="Add to cart"<td> </tr> <tr> <td><imgsrc="Sunset.jpg" height=60 width=70></img></td> <td> Book:<br> Author:<br> Publications:<br> </td> <td>$50</td> <td><input type=button value="Add to cart"<td> </tr> </table> </body> </html>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

34

D.SUNITHA
OUTPUT:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

35

WEEK-2

Date of Conduction: Date of Submission:

Date of Valuation Marks Awarded

: :

AIM:

Signature of Staff Member

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

A HTML Program to Implement the CART PAGE and REGISTRATION PAGE. 4) CART PAGE: The Cart page contains the details about the books which are added to the cart. The cart page look likes: WEBSITE NAME LOGO HOME IT CSE ECE EEE CIVIL Login Registration Catalogue Cart

BOOK NAME JAVA 2 XML bible

Price $35.5 $40.5

Quantity 2 1

Amount $70 $13.5 $130.5

TOTAL AMOUNT

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

36

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

HTML FORMS
A form is an area that can contain form elements. Form elements are elements that allow the user to enter information (like text fields, textarea fields, drop-down menus, radio buttons, checkboxes, etc.) in a form. A form is defined with the <form> tag. <form> <input> <input> </form> Input The most used form tag is the <input> tag. The type of input is specified with the type attribute. The most commonly used input types are explained below. Text Fields Text fields are used when you want the user to type letters, numbers, etc. in a form. <form> First name: <input type="text" name="firstname"><br> Last name: <input type="text" name="lastname"> </form> How it looks in a browser:

First name: Last name:


Note that the form itself is not visible. Also note that in most browsers, the width of the text field is 20 characters by default. Radio Buttons Radio Buttons are used when you want the user to select one of a limited number of choices.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

37

D.SUNITHA
<form>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<input type="radio" name="sex" value="male"> Male <br> <input type="radio" name="sex" value="female"> Female </form> How it looks in a browser: o Male o Female Note that only one option can be chosen. Checkboxes Checkboxes are used when you want the user to select one or more options of a limited number of choices. <form> I have a bike: <input type="checkbox" name="vehicle" value="Bike"><br> I have a car: <input type="checkbox" name="vehicle" value="Car"> <br> I have an airplane: <input type="checkbox" name="vehicle" value="Airplane"> </form>

How it looks in a browser:

I have a bike: I have a car: I have an airplane:


The Form's Action Attribute and the Submit Button When the user clicks on the "Submit" button, the content of the form is sent to another file. The form's action attribute defines the name of the file to send the content to. The file defined in the action attribute usually does something with the received input.
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 38

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<form name="input" action="html_form_action.asp" method="get"> Username: <input type="text" name="user"> <input type="submit" value="Submit"> </form> How it looks in a browser:

Username:
Submit

Submit

If you type some characters in the text field above, and click the "Submit" button, you will send your input to a page called "html_form_action.asp". That page will show you the received input. More Examples Checkboxes This example demonstrates how to create check-boxes on an HTML page. A user can select or unselect a checkbox. Radio buttons this example demonstrates how to create radio-buttons on an HTML page. Simple drop down box This example demonstrates how to create a simple drop-down box on an HTML page. A drop-down box is a selectable list. Another drop down box This example demonstrates how to create a simple drop-down box with a pre-selected value. Textarea This example demonstrates how to create a text-area (a multi-line text input control). A user can write text in the text-area. In a text-area you can write an unlimited number of characters. Create a button This example demonstrates how to create a button. On the button you can define your own text. Fieldset around data This example demonstrates how to draw a border with a caption around your data.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

39

D.SUNITHA
Form Examples

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Form with input fields and a submit button This example demonstrates how to add a form to a page. The form contains two input fields and a submit button. Form with checkboxes this form contains three checkboxes, and a submit button. Form with radio buttons this form contains two radio buttons, and a submit button. Send e-mail from a form this example demonstrates how to send e-mail from a form. Form Tags Tag <form> <input> <textarea> <label> <fieldset> <legend> <select> <optgroup> <option> <button> <isindex> Description Defines a form for user input Defines an input field Defines a text-area (a multi-line text input control) Defines a label to a control Defines a fieldset Defines a caption for a fieldset Defines a selectable list (a drop-down box) Defines an option group Defines an option in the drop-down box Defines a push button Deprecated. Use <input>instea

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

40

D.SUNITHA
CART PAGE: Cart.html <html> <body>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<br><br><br><br><br> <table border=4 align=center bgcolor=grey> <tr> <th>Book name</th> <th>Price</th><th>Quantity</th><th>Amount</th> </tr> <tr> <td>Java 2</td> <td>$35.5</td><td>2</td> <td>$70</td> </tr> <tr> <td>XML</td> <td>$40.5</td><td>1</td> <td>$40.5</td> </tr> <tr> <th></th><th></th><th>total amount</th> <td>$130.5</td> </tr> </table> </body> </html>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 41

D.SUNITHA
OUTPUT:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

42

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

5) REGISTRATION PAGE: Create A REGISTRATION PAGE with the following fields. 1) 2) 3) 4) 5) 6) 7) 8) NAME Password E-mail id Phone Number Sex Date Of Birth Languages Known Address (Text Field) (Password Field) (Text Field) (Text Field) (Radio Button) (3 select boxes) (Check Boxes-English,Telugu,Hindi,Tamil) (Text area)

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

43

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Registration.html <html> <body> <form name=f ><br><br> <table align=center bgcolor=grey> <tr> <td align=right>Name : <td><input type=text name=n> </tr>

<tr> <td align=right>Password : <td><input type=password name=p> </tr>

<tr> <td align=right>E-mail id : <td><input type=text name=e> </tr> <tr> <td align=right>Phone number : <td><input type=text maxlength=10 name=ph> </tr>

<tr> <td align=right>Sex : <td><input type=radio name=g>Male


INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 44

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<input type=radio name=g>Female </tr> <tr> <td align=right>Date of Birth : <td><select> <option>1<option>2<option>3<option>4<option>5<option>6<option>7<option>8<option> 9<option>10<option>11<option>12<option>13<option>14<option>15<option>16<option>1 7<option>18<option>19<option>20<option>21<option>22<option>23<option>24<option>2 5<option>26<option>27<option>28<option>29<option>30<option>31 </select> <select> <option>Jan<option>Feb<option>Mar<option>Apr<option>May<option>Jun<option>Jul<o ption>Aug<option>Sep<option>Oct<option>Nov<option>Dec </select> <select> <option>1980<option>1981<option>1982<option>1983<option>1984<option>1985<option >1986<option>1987<option>1988<option>1989<option>1990<option>1991<option>1992< option>1993<option>1994 </select> </tr> <tr> <td align=right>Languages : <td> <input type=checkbox >English <input type=checkbox >Telugu <input type=checkbox >Hindi <input type=checkbox >Tamil </tr> <tr>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 45

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<td align=right>Address : <td><textarea cols=18 rows=5></textarea> </tr> <tr> <td> <td><input type=button value=submit > </tr> </table> </form> </body> </html>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

46

D.SUNITHA
OUTPUT:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

47

WEEK-3

Date of Conduction: Date of Submission:

Date of Valuation Marks Awarded

: :

AIM:
A

HTML Program to Validate the Registration Page. Signature of Staff Member

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

VALIDATION: Write a JavaScript to Validate the Following fields of the above Registration Page. Name (Name should contain alphabets and the length should not be less than 6 characters). Password (Password should not be less than 6 characters length). E-mail id (should not contain any invalid and must follow the standard patternname@domain.com). Phone Number (Phone Number should contain 10 digits only). Note: You can also validate the login page with these parameters. Use PHP to Connect with database to store the above details.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

48

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Dynamic HTML with JavaScript


A number of technologies are present that develops the static web page, but we require a language that is dynamic in nature to develop web pages a client side. Dynamic HTML is a combination of content formatted using HTML, cascading stylesheets, a scripting language and DOM. JavaScript originates from a language called LiveScript. The idea was to find a language which can be used at client side, but not complicated as Java. JavaScript is a simple language which is only suitable for simple tasks. Benefits of JavaScript Following are some of the benefits that JavaScript language possess to make the web site dynamic. It is widely supported in browser It gives easy access to document object and can manipulate most of them. JavaScript can give interesting animations with many multimedia datatypes. Special plug-in are not required to use JavaScript JavaScript is secure language JavaScript code resembles the code of C language, The syntax of both the language is very close to each other. The set of tokens and constructs are same in both the language. Features of JavaScript JavaScript program contains variables, objects and functions. Each line is terminated by a semicolon. Blocks of code must be surrounded by curly brackets. Functions have parameters which are passed inside parenthesis Variables are declared using the keyword var. Script does not require main function and exit condition. Variables Variables are like storage units. You can create variables to hold values. It is ideal to name a variable something thatis logical, so that you'll remember what you are using it for. For example, if you were writing a program to divide 2 numbers, it could be confusing if you called your variables numberOne, numberTwo, numberThree because you may forget which one is the divisor, which one is the dividend, and which one is the quotient. A more logical approach would be to name them just that: divisor, dividend, quotient. It is important to know the proper syntax to which variables must conform: They must start with a letter or underscore ("_") Subsequent characters can also be digits (0-9) or letters (A-Z and/or a-z). Remember, JavaScript is case-sensitive. (That means that MyVariable and myVariable are two different names to JavaScript, because theyhave different capitalization.) Some examples of legal names are Number_hits, temp99, and _name. When you declare a variable by assignment outside of a function, it is called a global variable, because it is available everywhere in the current document. When you declare a variable within a function, it is called a local variable, because it is available only within the function. Using var is
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 49

1. 2. 3. 4. 5.

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

optional, but you need to use it if you have a variable that has been declared global and you want to re-declare it as a local variable inside a function. Variables can store all kinds of data (see below, Values of Variables, section 3.2). To assign a value to a variable, you use the following notation: dividend = 8; divisor = 4; myString = "I may want to use this message multiple times"; message = myString; Values of Variables JavaScript recognizes the following types of values: o o o o Numbers, such as 42 or 3.14159 Logical (Boolean) values, either true or false Strings, such as "Howdy!" null, a special keyword which refers to nothing

This relatively small set of types of values, or data types, enables you to perform useful functions with yourapplications. There is no explicit distinction between integer and realvalued numbers. Data Type Conversion JavaScript is a loosely typed language. That means you do not have to specify the data type of a variable when youdeclare it, and data types are converted automatically as needed during script execution. So, for example, youcould define a variable as follows: var answer = 42 And later, you could assign the same variable a string value, for example, answer = "Thanks for all the fish..." Because JavaScript is loosely typed, this assignment does not cause an error message. However, this is not goodcoding! You should create variables for a specific type, such as an integer, string, or array, and be consistent in thevalues that you store in the variable. This prevents confusion when you are writing your program.In expressions involving numeric and string values, JavaScript converts the numeric values to strings. For example, consider the following statements: x = "The answer is " + 42 y = 42 + " is the answer." (The + sign tells JavaScript to concatenate, or stick together, the two strings. For example, if you write:message = "Hello" + "World"...then the variable message becomes the string "Hello World")In the first statement, x becomes the string "The answer is 42." In the second, y becomes the string "42 is theanswer."

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

50

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Literals You use literals to represent values in JavaScript. These are fixed values, not variables, thatyou literally provide inyour script. Examples of literals include: 1234, "This is a literal," and true. Integers Integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base 8). A decimal integer literalconsists of a sequence of digits without a leading 0 (zero). A leading 0 (zero) on an integer literal indicates it is inoctal; a leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-fand A-F. Octal integers can include only the digits 0-7.Some examples of integer literals are: 42, 0xFFF, and -345. Floating-point literals A floating-point literal can have the following parts: a decimal integer, a decimal point ("."), a fraction (anotherdecimal number), an exponent, and a type suffix. The exponent part is an "e" or "E" followed by an integer, whichcan be signed (preceded by "+" or "-"). A floatingpoint literal must have at least one digit, plus either a decimalpoint or "e" (or "E").Some examples of floating-point literals are 3.1415, -3.1E12, .1e12, and 2E-12 Boolean literals The Boolean type has two literal values: true and false. String literals A string literal is zero or more characters enclosed in double (") or single (') quotation marks. A string must bedelimited by quotation marks of the same type; that is, either both single quotation marks or double quotationmarks. The following are examples of string literals: "blah" 'blah' In addition to ordinary characters, you can also include special characters in strings, as shown in the last element inthe preceding list. The following table lists the special characters that you can use in JavaScript strings. Character Meaning
\b \f \n \r \t backspace form feed new line carriage return tab

Escaping characters For characters not listed in the preceding table, a preceding backslash is ignored, with the exception of a quotationmark and the backslash character itself.You can insert quotation marks inside strings by preceding them with a backslash. This is known as escaping the quotation marks. For example, var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service." document.write(quote)
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 51

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

The result of this would be He read "The Cremation of Sam McGee" by R.W. Service. To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following: var home = "c:\\temp" Arrays An Array is an object which stores multiple values and has various properties. When you declare an array, you mustdeclare the name of it, and then how many values it will need to store. It is important to realize that each value isstored in one of the elements of the array, and these elements start at 0. This means that the first value in the arrayis really in the 0 element, and the second number is really in the first element. So for example, if I want to store 10values in my array, the storage elements would range from 0-9. The notation for declaring an array looks like this: myArray = new Array(10); foo = new Array(5); Initially, all values are set to null. The notation for assigning values to each unit within the array looks like this: myArray[0] = 56; myArray[1] = 23; myArray[9] = 44; By putting the element number in brackets [ ] after the array's name, you can assign a value to that specificelement. Note that there is no such element, in this example, as myArray[10]. Remember, the elements begin at myArray[0] and go up to myArray[9]. In JavaScript, however, an array's length increases if you assign a value to an element higher than the current length of the array. The following code creates an array of length zero, then assigns a value to element 99. Thischanges the length of the array to 100. colors = new Array(); colors[99] = "midnightblue"; Be careful to reference the right cells, and make sure to reference them properly! Because arrays are objects, they have certain properties that are pre-defined for your convenience. For example, you can find out how many elements myArray has and store this value in a variable called numberOfElementsbyusing: numberOfElements = myArray.length;

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

52

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Operators JavaScript has many different operators, which come in several flavors, including binary. Selected assignment operators An assignment operator assigns a value to its left operand based on the value of its right operand. The basicassignment operator is equal (=), which assigns the value of its right operand to its left operand. The otheroperators are shorthand for standard operations. Find an abridged list of shorthand operators below:
x += y x -= y x *= y x /= y x=x+y x=x-y x=x*y x=x/y

Note that the = sign here refers to assignment, not "equals" in the mathematical sense. So if x is 5 and y is 7, x = x + y is not a valid mathematical expression, but it works in JavaScript. It makes x the value of x + y (12 in this case). EXAMPLES: If x = 10 and y = 2, x += y would mean x = x + y, hence x's new value would be the sum of x's previousvalue plus y's previous value. Upon executing x = x + y = 10 + 2, x's new value becomes 12, while y's new valueremains equal to its old value. Similarly, x -= y would change x's value to 8. Calculate x *= y and x /= y to get a betteridea of how these operators work. Comparison operators A comparison operator compares its operands and returns a logical value based on whether the comparison is trueor not. The operands can be numerical or string values. When used on string values, the comparisons are based onthe standard lexicographical ordering. They are described in the following table.
Operator Equal (= =) Not equal (!=) Greater than (>) Greater than or equal (>=) Less than (<) Less than or equal (<=) Description Evaluates to true if the operands are equal. Evaluates to true if the operands are not equal. Evaluates to true if left operand is greater than right operand. Evaluates to true if left operand is greater than or equal to right operand. Evaluates to true if left operand is less than right operand. Evaluates to true if left operand is less than or equal to right operand. Example x == y evaluates to true if x equals y. x != y evaluates to true if x is not equal to y. x > y evaluates to true if x is greater than y. x >= y evaluates to true if x is greater than or equal to y. x < y evaluates to true if x is less than y. x <= y evaluates to true if x is less than or equal to y.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

53

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

EXAMPLES: 5 == 5 would return TRUE. 5 != 5 would return FALSE. (The statement 'Five is not equal to five.' is patently false.) 5 <= 5 would return TRUE. (Five is less than or equal to five. More precisely, it's exactly equal to five,but JavaScript could care less about boring details like that.) Selected Arithmetic Operators Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), division (/)and remainder (%). These operators work as they do in other programming languages, as well as in standardalgebra. Since programmers frequently need to add or subtract 1 from a variable, JavaScript has shortcuts for doing this.myVar++ adds one to the value of myVar, while myVar-- subtracts one from myVar. EXAMPLES: Let x = 3. x++ bumps x up to 4, while x-- makes x equal to 2. Logical Operators Logical operators take Boolean (logical) values as operands and return a Boolean value. That is, they evaluatewhether each subexpression within a Boolean expression is true or false, and then execute the operation on therespective truth values. Consider the following table:
Operator Usage and (&&) or (||) not (!) expr1 && expr2 expr1 || expr2 !expr Description True if both logical expressions expr1 and expr2 are true. False otherwise. True if either logical expression expr1 or expr2 is true. False if both expr1 and expr2 are false. False if expr is true; true if expr is false.

EXAMPLES: Since we have now learned to use the essential operators, we can use them in conjunction with oneanother. See if you can work out why the following examples resolve the way they do: If x = 4 and y = 7, ((x + y + 2) == 13) && (((x + y) / 2) == 2) returns FALSE. If x = 4 and y = 7, ((y - x + 9) == 12) || ((x * y) == 2) returns TRUE. If x = 4 and y = 7, !((x/2 + y) == 9) || ((x * (y/2)) == 2) returns FALSE. Using JavaScript Objects When you load a document in your web browser, it creates a number of JavaScript objects with properties and capabilities based on the HTML in the document and other pertinent information. These objects exist in a hierarchy that reflects the structure of the HTML page itself. The pre-defined objects that are most commonly used are the window and document objects. The window has methods that allow you to create new windows with the open() and close() methods. It also allows you to create message boxes using alert(), confirm(), and prompt(). Each displays the text that you put between the parentheses. For example, the following code: alert("This is an alert box") ...pops up an alert box displaying the given message. Try it yourself by clicking on this link.
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 54

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

The document object models the HTML page. The document object contains arrays which store all the components constituting the contents of your web page, such as images, links, and forms. You can access and call methods on these elements of your web page through the arrays. The objects in this pre-defined hierarchy can be accessed and modified. To refer to specific properties, you must specify the property name and all its ancestors, spelling out the complete hierarchy until the document object. A period, '.', is used in between each object and the name of its property. Generally, a property / object get its name from the NAME attribute of the HTML tag. For example, the following refers to the value property of a text fieldname text1 in a form namedmyform in the current document. Document.myform.text1.valueForm elements can also be accessed through the aforementioned forms array of the document object. In the above example, if the form namedmyform was the first form on the page, and text1 was the third field in the form, the following also refers to that field's value property. document.forms[0].elements[2].value Functions (capabilities) of an object can similarly be accessed using the period notation. For example, the followinginstruction resets the 2nd form in the document. document.forms[2].reset(); Click on one of the objects below to view the Netscape documentation on the specific properties and methods that object has:

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

55

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Functions Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure -- a set of statements that performs a specific task. A function definition has these basic parts: The function keyword A function name A comma-separated list of arguments to the function in parentheses The statements in the function in curly braces: { }

Defining a Function When defining a function, it is very important that you pay close attention to the syntax. Unlike HTML, JavaScript is case sensitive, and it is very important to remember to enclose a function within curly braces { }, separate parameters with commas, and use a semi-colon at the end of your line of code. Its important to understand the difference between defining and calling a function. Defining the function names the function and specifies what to do when the function is called. You define a function within the <SCRIPT>...</SCRIPT> tags within the <HEAD>...</HEAD> tags. In defining a function, you mustalso declare the variables which you will be calling in that function. Heres an example of defining a function: functionpopupalert() { alert('This is an alert box.'); } Notice the parentheses after the function name. It is imperative that you include these parentheses, even if they are empty. If you want to pass a parameter into the function, you would include that parameter inside of the parentheses. A parameter is a bit of extra information that cn be different each time the function is run. It is stored in a variable and can be accessed just like any other variable. Here's an example of a function that takes a parameter: functionanotherAlert(word) { alert(word + ' is the word that you clicked on'); } When you call this function, you need to pass a parameter (such as the word that the user clicked on) into the function. Then the function can use this information. You can pass in a different word as a parameter each time you call the function, and the alert box will change appropriately. You'll see how to pass a parameter a little later on. You can pass in multiple parameters, by separating them with a comma. You would want to pass in a few parameters if you have more than one variable that you either want to change or use in your function. Here are two examples of passing in multiple parameters when you are defining the function:

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

56

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

functionsecondAlert(word,password) { confirm(word + ' is the word that you clicked on. The secret password is ' + password); } functionthirdAlert(word,password) { confirm(word + ' is the word you clicked on. Please take note of the password, ' + password); } You'll notice that the same parameters are passed into both of these functions. However, you can pass in whatever values you want to use (see this same example below in calling the function). Calling a Function Calling the function actually performs the specified actions. When you call a function, this is usually within the BODY of the HTML page, and you usually pass a parameter into the function. A parameter is a variable from outside of the defined function on which the function will act.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

57

D.SUNITHA
A

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

HTML Program to Validate the Registration Page.

PROGRAM: <html> <head> <script> function validate() { if((app.na.value=="")||(app.re.value=="")||(app.month.value=="")|| (app.day.value=="")) { alert("In complete Details"); } else if(app.re.value!=app.mail.value) { alert("Invalid E-Mail address"); } else if(app.repass.value!=app.pass.value) { alert("Invalid password"); } else { alert("successfully inserted"); } } function clear() { app.na.value=app.mail.value; } </script> </head> <body text="purple" > <center> <b><u><i>Registration</i></u></b> <form name=app> <table> <tr> <td style="font-family:script;color:tomato;font-size:20pt;"> Register Below. </td> </tr> <tr> <td>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 58

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Enter Name : </td> <td><input type=text name="na" size=20 maxlength=30> </td> </tr> <tr> <td> E=Mail Address : </td> <td> <input type=text name="mail" size=20 maxlength=30> </td> </tr> <tr> <td> RE-Type mail address: </td> <td> <input type=text name="re" size=20> </tr> <tr> <td> Birthday : </td> <td> <select size=1 name="maonth"> <option value=""></option> <option value="">January</option> <option value="">February</option> <option value="">March</option> <option value="">April</option> <option value="">May</option> <option value="">June</option> <option value="">July</option> <option value="">August</option> <option value="">September</option> <option value="">October</option> <option value="">November</option> <option value="">December</select> </select> <select size=1 name="day"> <option value=""></option> <option value="">1</option>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 59

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<option value="">2</option> <option value="">3</option> <option value="">4</option> <option value="">5</option> <option value="">6</option> <option value="">7</option> <option value="">8</option> <option value="">9</option> <option value="">10</option> <option value="">11</option> <option value="">12</option> <option value="">13</option> <option value="">14</option> <option value="">15</option> <option value="">16</option> <option value="">17</option> <option value="">18</option> <option value="">19</option> <option value="">20</option> <option value="">21</option> <option value="">22</option> <option value="">23</option> <option value="">24</option> <option value="">25</option> <option value="">26</option> <option value="">27</option> <option value="">28</option> <option value="">29</option> <option value="">30</option> <option value="">31</option> </select> </td> </tr> <tr> <td> Enter a new password: </td> <td><input type=password size=20 name="pass"> </td> </tr> <tr> <td>Re-enter password </td> <td><input type=password size=20 name="repass">
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 60

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

</td> </tr> <tr> <td colspan=2 align=center><input type=button value=continue onclick="validate()"> </tr> </table> </form> </center> </body> </html>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

61

D.SUNITHA
OUTPUT:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

62

WEEK-4

Date of Conduction: Date of Submission:

Date of Valuation Marks Awarded

: :

Signature of Staff Member

D.SUNITHA
AIM:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Design a web page using CSS(Cascading Style Sheets) which includes the following: 1) Use Different font, styles: In the style definition you define each selector should work (font, color etc.). Then, in the body of your pages, you refer to these selectors to activate the styles. 2) Set a Background image for both the page and single elements on the page. You can define the background image for the page like this: BODY{background-image:url(myimage.gif);} 3) Control the repetition of the image with background-repeat property. As background-repeat: repeat Tiles the image until the entire page is filled.just like an ordinary background image in plain HTML. 4) Define Styles for links as A:link A:visited A:active A:hover 5) Working with layers. 6) Add Customized Cursors.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

63

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

CSS
Cascading Style Sheets (CSS) is a simple mechanism for adding style (e.g. fonts, colors, and spacing) to Web documents. Cascading Style Sheets (CSS) is a style sheet language used to describe the presentation of a document written in a markup language. Its most common application is to style web pages written in HTML and XHTML, but the language can be applied to any kind of XML document, including SVG and XUL. CSS can be used locally by the readers of web pages to define colors, fonts, layout, and other aspects of document presentation. It is designed primarily to enable the separation of document content (written in HTML or a similar markup language) from document presentation (written in CSS). This separation can improve content accessibility, provide more flexibility and control in the specification of presentation characteristics, and reduce complexity and repetition in the structural content. CSS can also allow the same markup page to be presented in different styles for different rendering methods, such as on-screen, in print, by voice (when read out by a speech- based browser or screen reader) and on Braille-based, tactile devices. CSS specifies a priority scheme to determine which style rules apply if more than one rule matches against a particular element. In this so-called cascade, priorities or weights are calculated and assigned to rules, so that the results are predictable. The CSS specifications are maintained by the World Wide Web Consortium (W3C). Internet media type (MIME type) text/css is registered for use with CSS by RFC 2318 (March 1998).

Syntax
CSS has a simple syntax, and uses a number of English keywords to specify the names of various style properties. A style sheet consists of a list of rules. Each rule or rule-set consists of one or more selectors and a declaration block. A declaration-block consists of a list of semicolon- separated declarations in braces. Each declaration itself consists of a property, a colon (:), a value, then a semi-colon (;). In CSS, selectors are used to declare which elements a style applies to, a kind of match expression. Selectors may apply to all elements of a specific type, or only those elements which match a certain attribute; elements may be matched depending on how they are placed relative to each other in the markup code, or on how they are nested within the document object model. In addition to these, a set of pseudo-classes can be used to define further behavior. Probably the best-known of these is :hover, which applies a style only when the user 'points to' the visible element, usually by holding the mouse cursor over it. It is appended to a selector as in a: hover or #elementid:hover. Other pseudo-classes and pseudo- elements are, for example, first-line: visited or: before. A special pseudo-class is: Lang(c), "c".
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 64

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

A pseudo-class selects entire elements, such as: link or :visited, whereas a pseudo- element makes a selection that may consist of partial elements, such as :first-line or :first- letter. Selectors may be combined in other ways too, especially in CSS 2.1, to achieve greater specificity and flexibility Use of CSS Prior to CSS, nearly all of the presentational attributes of HTML documents were contained within the HTML markup; all font colors, background styles, element alignments, borders and sizes had to be explicitly described, often repeatedly, within the HTML. CSS allows authors to move much of that information to a separate style sheet resulting in considerably simpler HTML markup. Headings (h1 elements), sub-headings (h2), sub-sub-headings (h3), etc., are defined structurally using HTML. In print and on the screen, choice of font, size, color and emphasis for these elements is presentational. Prior to CSS, document authors who wanted to assign such typographic characteristics to, say, all h2 headings had to use the HTML font and other presentational elements for each occurrence of that heading type. The additional presentational markup in the HTML made documents more complex, and generally more difficult to maintain. In CSS, presentation is separated from structure. In print, CSS can define color, font, text alignment, size, borders, spacing, layout and many other typographic characteristics. It can do so independently for onscreen and printed views. CSS also defines non-visual styles such as the speed and emphasis with which text is read out by aural text readers. The W3C now considers the advantages of CSS for defining all aspects of the presentation of HTML pages to be superior to other methods. It has therefore deprecated the use of the entire original presentational HTML markup.

Sources
CSS information can be provided by various sources. CSS style information can be either attached as a separate document or embedded in the HTML document. Multiple style sheets can be imported, and alternative style sheets can be specified so that the user can choose between them. Different styles can be applied depending on the output device being used; for example, the screen version can be quite different from the printed version, so that authors can tailor the presentation appropriately for each medium. Author styles (style information provided by the web page author), in the form of external stylesheets, i.e. a separate CSS-file referenced from the document embedded style, blocks of CSS information inside the HTML document itself Inline styles, inside the HTML document, style information on a single element, specified using the "style" attribute. User style,
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 65

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

a local CSS-file specified by the user using options in the web browser, and acting as an override, to be applied to all documents. User agent style the default style sheet applied by the user agent, e.g. the browser's default presentation of elements.

One of the goals of CSS is also to allow users a greater degree of control over presentation; those who find the red italic headings difficult to read may apply other style sheets to the document. Depending on their browser and the web site, a user may choose from various stylesheets provided by the designers, may remove all added style and view the site using their browser's default styling or may perhaps override just the red italic heading style without altering other attributes. File highlightheaders.css containing: h1 {color: white; background: orange! important ;} h2 {color: white; background: green !important; } Such a file is stored locally and is applicable if that has been specified in the browser options. "!important" means that it prevails over the author specifications. CSS standard Style sheets are embedded directly into a page, or linked in from an external file, and provide web page developers the ability to redefine the appearance of all elements of a certain type, or one specific element. The following code is a simple style sheet, embedded into the head section of the web page.

<STYLE type=text/css> H1 { color: red;font-family: Arial; margin: 1.0in } </STYLE> With this style sheet setting, all H1 elements within the document are set to use the new style.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

66

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Including Style Sheets There are 4 different techniques to Include style sheet definitions 1. Including a style sheet in the documents head section. 2. Linking in a style sheet stored externally. 3. Importing in a style sheet stored externally. 4. Including an inline style sheet definition directly in an html element. The most common approach is to embed style sheets into the head of the web page and provide settings for all of the elements within the web page. <STYLE type=text/css> BODY { background-color: aqua; color: firebrick; margin: 0.5 in }</STYLE> A second technique is to link the style sheet into the web page using the link syntax: <HEAD> <TITLE> CSS Test Content </TITLE> <LINK rel=stylesheet type=text/css href=style.css> </HEAD> Another approach to incorporate style sheets into a page is to import the style sheet into the file. The code to import style sheet: <STYLE type=text/css> @import url(style.css); </STYLE> A last technique to include style sheet settings is to embed them directly into an element. The syntax for this is: <P style=color: yellow; font-style: italic>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

67

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Applying styles to Specific Groups of Elements Using the class name style sheet selector A class name is a way to apply style sheet settings to a group of named elements, using the following syntax:

<style type=text/css> P.someclass {color: red; margin-left: 1.5 in } .otherclass {color: green; font-size: 18 pt } </style> Example: <html> <head><title>css</title> <style type=text/css> P.someclass {color: red; margin-left: 1.5 in } .otherclass {color: green; background-color: yellow } </style></head> <body> <p class=someclass> text1. <p class=otherclass> text2 <h1 class = otherclass>This is heading1. </body> </html> Creating an overall look for the web page The body tag is the tag specifier to use when applying style sheets to an entire document page. Background-color and image and setting the page margins are the common attributes with the body tag.

Example <style type=text/css>


INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 68

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

body{ margin: 0.3 in; color: white; background-color: black; background-image: url(back1.jpg) background-repeat: repeat-x; background-attachment: fixed} The background, margin and color css attributes 1. Background 2. Background-color 3. Background-image 4. Background-repeat-repeat-x // repeat horizontally 5. Background-attachment -scroll // scroll with page 6. Background-position-top center 7. Color-white 8. Margin -20 px 10 px // top/bottom set to 20 pixels, left/right 9. Margin-left 10. Margin-right 11. Margin-top 12. Margin-bottom

Modifying Font and Text Appearance Font and text css properties Sample Value Italic bold 18pt arial times new roman Arial Larger 800 0.1 em 1.5em Underline Capitalize Center 10% normal | italic | oblique normal | small-caps
69

CSS attribute Font Font-family Font-size Font-weight Letter-spacing Word-spacing Text-decoration Text-transform Text-align Text-indent Font-style Font-variant

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Creating Borders Around Elements There are certain CSS attributes that impact the box that surrounds a block level Html element. Padding and border CSS attributes Value Thick groove yellow Yellow red blue Thin thick Inset 3px solid red (width,style,color) Yellow 5px solid Solid Ridge Double None groove #FFFF00

CSS attribute Border Border-color Border-width Border-style Border-top Border-right Border-bottom Border-left Border-top-style Border-bottom-style Border-left-style Border-right-style Border-top-color

CSS attribute Border-bottom-color Border-right-color Border-left-color Border-top-width Border-left-width Padding Padding-left Padding-right Padding-top Padding-bottom

Value Black #0000CC Blue Thin Thick 12% 18px 18 px 0.25 in 4% 5px

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

70

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Controlling the Appearance of Lists and other HTML elements The classifying and display CSS attributes Value None Pre Square outside Disc url(someimage.jpg) Inside 150 px 25%

CSS Attribute Display White-space List-style List-style-type List-style-image List-style-position Width Height

The display attribute can define that an element display as a list item or not at all.

display

The following example turns off the display of any element using the no display class:

<style type=text/css> .nodisplay{ display: none } </style> The Pseudo Elements and classes A pseudo element is an html element is in which some external factor influences the presentation of the element. Style settings can be applied based on this external factor. The following code demonstrates the use of this pseudo-class:

A:visited { color:red } A:unvisited { color: yellow} A:active { color: lime }

Using Tables for Organization and Layout What are the HTML Table Elements Html tables begin and end with the table tags, <table> and </table>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 71

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

They contain rows, defined with the row tags <tr> and </tr>. Cells defined with cell tags, <td> and </td> Captions for tables are created with the begin and end caption tags, <caption> and </caption>. Some cells can be designated as table row headers with the use of the <th> and </th> tags.

The basic Table Elements Attribute Description How table aligns with other elements. Align Background color for table Bgcolor Width of table Width Number of columns within table. Cols Width in pixels of frame around table. Border Which sides of the frame surrounding table are visible. Frame Which rules appear between table columns and rows Rules The space between cell border and table frame. Cellspacing The space between cell border and cell contents. Cellpadding The frame attribute has several values. i. ii. iii. iv. v. vi. vii. viii. ix. Void no frame Above top side only Below bottom side only Hsides horizontal sides Vsides vertical sides only Lhs left side only Rhs right side only Box all four sides Border all four sides

The acceptable values for the rules attribute

None no rules Groups rules appear only between groups Rows rules appear between rows Cols rules appear between columns
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 72

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

All rules appear between all elements. TH and TD element attributes Description Disbale automatic text wrapping Background color of cell Numbers of rows spanned by cell Number of columns spanned by cell.

Attribute Nowrap Bgcolor Rowspan Colspan

Column Grouping with COLGROUP and COL The columns of the table can be grouped by using the colgroup element. Once grouped, you can apply a width to all of the columns included within the group. A second element col, can also supply specific width and alignment information for one or more columns within the group. Example

<table border="1"> <colgroup span="3"> <col width="50"></col> <col width="100"></col> <col width="20"></col> </colgroup> <tr> <td>col 1</td> <td>col 2</td> <td>col 3</td> </tr> </table>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

73

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Row Grouping with thead, tfoot and tbody elements Each table has at least one row, and this becomes the default table body. However, the rows that make up the body can also be delimited with one or more tbody elements. The rows that make up the table head for a specific row grouping can be delimited with the thead element. The foot of the table row grouping can be delimited with the tfoot element. Example

<table width=60% frame=border border=8 rules=groups cols=3 cellspacing=3 cellpadding=5 align=center> <caption> This is an example table </caption> <thead align=left> <tr> <th></th> <th> second Value </th> <th> Third Value </th></tr> <tfoot> <tr><td> Month Two Subtotals </td> <td> 1446 </td> <td> 18889 </td> </tr> </tfoot> <tbody> <tr> <td rowspan=2> Month One Values: </td> <td> 0.5 </td> <td> .5 </td> </tr>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 74

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<tr><td> 4.4 </td> <td> 89.3 </td> </tr> <tfoot> <tr> <td> Month one Subtotals : </td> <td> 1 </td> <td>1 94</td> </tr> <tbody> <tr> <td rowspan=2> Month One Values: </td> <td> 1.444 </td> <td> .0005 </td> </tr> <tr><td> 1444.444 </td> <td> 18889.003 </td> </tr> </tbody> </table>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

75

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Combining the Use of HTML Tables and CSS Style Sheets <head> <style type=text/css> Thead{ background-color: red; color: yellow} Tbody {background-color:black ; color: yellow} Tfoot{background-color:lime; color: yellow} Table { border-style: groove; border-color:blue; color: darkgreen; Th{ font-family : fantasy } </style>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

76

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Using an html table to create a Layout for Links A popular use of html tables is to maintain the layout of a links page or a section of a page that contains resource links One column table used to control layout of a links list. Example

<html>

<body> <table width=80% cellpadding=10 cellspacing=15 border=5 frame=border rules=none align=center> <caption align=bottom> Internet Explorer Dynamic Html Links </caption> <tr><td><h1> My IE Dynamic Html Resources </h1></td></tr> <tr><td><a href="http://www.w3.org/pub/www/tr/wd-positioning"> W3C Positioning Draft </a></td></tr> <tr><td><a href="http://www.microsoft.com/ie/ie40"> Internet Explorer 4.0 Platform Preview </a></td></tr> </table>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 77

D.SUNITHA
</body> </html>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Creating Page Columns with a Table Another popular use of html tables is to create columns within a page.

<table width=100% cols=3 cellspacing =10> <colgroup span=3> <col width=30%> <col width=35%> <col width=35%> Controlling a Form Layout with a Table With a table, the form elements can be easily aligned. Example

Advanced Layout and Positioning with Style Sheets CSS positioning attributes Description Determines whether element is positioned explicitly or relative to the natural flow of web page document. Position of the left side of the rectangular area enclosing the element. Position of the left side of the rectangular area enclosing the element. Width of the rectangular area enclosing the element. Width of the rectangular area enclosing the element. The clipping shape and dimensions used to control what portion of the element displays. The portion of the element contents that exceeds the bounds of the rectangular area enclosing the element. The stacking order of the element if two or more elements are stacked on top of each other. Whether element is visible.

Attribute Position Left Top Width Height Clip Overflow Z-index Visibility

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

78

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Positioning images and other elements Images have some positioning capability, with the hspace and vspace IMG attributes, and can be aligned with the align attribute. One technique web developers did not have before IE 4.0 is the ability to layer text and other html elements on images, or to layer images themselves. Also, developers could not exactly position images or any other element. CSS positioning changes all of this. With CSS, the position attribute is set to a value of absolute, which means that the element is positioned exactly, regardless of how any other element is positioned. Using CSS positioning to position three images

<html><head><style type=text/css> Img{ position: absolute; width:90;height:90; top 100} #one { left:100} #two { left:200 } #three {left:300} </style> </head> <body> <img src=red.jpg id=one> <img src=yellow.jpg id=two> <img src=green.jpg id=three> </body></html> Using DIV blocks to position images

<html><head> <style type=text/css> DIV { position: absolute; top: 100} #one { left:100} #two { left:200 }
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 79

D.SUNITHA
#three {left:300} </style> </head> <body>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<div id=one><imgsrc=red.jpg></div> <div id=two><img src=yellow.jpg ></div> <div id=three><imgsrc=green.jpg></div> </body> </html> You can layer html elements, including placing text above images. One key to for using layers is to set the z-index CSS positioning attribute to a higher integer for the element you want to display at the top of the stack. Layering text and images with z-index ordering

<html><head> <style type=text/css> Body { font-family: arial; color:white; font-weight: bold} Div{ position: absolute } #one { top:25; left:20; z-index:1 } #two { top:125; left:20; z-index:1 } #three { top:225; left:20; z-index:1 } </style> </head> <body> <div style=top:50; left:40; z-index:2> Product <br>One </div> <div style=top:150; left:40; z-index:2> Product <br>two </div>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 80

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<div style=top:250; left:40; z-index:2> Product <br>Three </div> <div id=one><img src=red.jpg width=90 height=90></div> <div id=two><img src=yellow.jpg width=90 height=90></div> <div id=three><img src=green.jpg width=90 height=90></div> </body> </html>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

81

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Use Different font, styles: In the style definition you define each selector should work (font, color etc.). Then, in the body of your pages, you refer to these selectors to activate the styles. PROGRAM: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>embedded style sheets</title> <style> p{color:#cc6633;font-family:"Monotype Corsiva",Monotype,serif:align="right"} .s1{font-size:22px} .s2{word-spacing:8px} .s3{letter-spacing:4px} </style> </head> <body> <p class="s1 s2">welcome to wt lab</p> <p class="s3">embedded style sheets program</p> </body> </html>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

82

D.SUNITHA
OUTPUT:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

83

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Set a Background image for both the page and single elements on the page. You can define the background image for the page like this: BODY{background-image:url(myimage.gif);} Control the repetition of the image with background-repeat property. As background-repeat: repeat Tiles the image until the entire page is filled.just like an ordinary background image in plain HTML.

Program: <html> <head> <style type="text/css"> body { background-image:url('logo.png'); background-repeat:repeat; background-position:50%,50%; background-attachment:right; } </style> </body> </html>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

84

D.SUNITHA
OUTPUT:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

85

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Define Styles for links as A:link A:visited A:active A:hover Program: <html> <head> <link rel="style sheet"type="text/css"href="example.css"> </head> <body> <h1>this is a styel sheet for links</h1> <p>u canexp with the following link</p> <p><a href="http://www.google.co.in">this is a link</a></p> </body> </html>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

86

D.SUNITHA
OUTPUT:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

87

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Working with layers. Program: <html> <head> <style> </style> </head> <div style= "background-color:pink; width:80px; height:100px; position:relative; top:10px; left:80px; z-index:2;">layer1 </div> <div style="backgroundcolor:violet;width:80px;height:100px;position:relative;top:0px;left:35px;z-index:1;">layer2 </div> <body> </html>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

88

D.SUNITHA
OUTPUT:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

89

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Add Customized Cursors. Program: <html> <head> <title>customised cursors action demo</title> <style type="text/css"> .ink1{cursor:default} .link2{cursor:crooshair} .link3{cursor:pointer;cursor:hand} .link4{cursor:move} .link5{cursor:text} .link6{cursor:wait} .link7{cursor:help} .link8{cursor:n-resize} .link9{cursor:ne-resize} .link10{cursor:e-resize} .link11{cursor:se-resize} .link12{cursor:s-resize} .link13{cursor:sw-resize} .link14{cursor:w-resize} .link15{cursor:sw-resize} .link16cursor:progress} .link17{cursor:not-allowed} .link18{cursor:no-drop} .link19{cursor:vertical-text} .link20{cursor:all-scroll} .link21{cursor:col-scroll}
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 90

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

.link22{cursor:url} </style></head> <body><b> <a href="text.html"class="link1">this is the default cursor</a></br> <a href="text.html"class="link2">this is the crosshair cursor</a></br> <a href="text.html"class="link3">this is the hand cursor</a></br> <a href="text.html"class="link4">this is the move cursor</a></br> <a href="text.html"class="link5">this is the text cursor</a></br> <a href="text.html"class="link6">this is the wait cursor</a></br> <a href="text.html"class="link7">this is the help cursor</a></br> <a href="text.html"class="link8">this is the n-resize cursor</a></br> <a href="text.html"class="link9">this is the ne-resize cursor</a></br> <a href="text.html"class="link10">this is the e-resize cursor</a></br> <a href="text.html"class="link11">this is the se-resize cursor</a></br> <a href="text.html"class="link12">this is the s-resize cursor</a></br> <a href="text.html"class="link13">this is the sw-resize cursor</a></br> <a href="text.html"class="link14">this is the w-resize cursor</a></br> <a href="text.html"class="link15">this is the nw-resize cursor</a></br> <a href="text.html"class="link16">this is the not-allowed cursor</a></br> <a href="text.html"class="link17">this is the no-drop cursor</a></br> <a href="text.html"class="link18">this is the vertical-text cursor</a></br> <a href="text.html"class="link19">this is the all-scroll cursor</a></br> <a href="text.html"class="link20">this is the col-resize cursor</a></br> <a href="text.html"class="link21">this is the url cursor</a></br> </b> </body> </html>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 91

D.SUNITHA
OUTPUT:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

92

WEEK-5

Date of Conduction: Date of Submission:

Date of Valuation Marks Awarded

: :

Signature of Staff Member

D.SUNITHA
AIM:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

To Implement an XML file which will Display the Book information which includes the following? i) ii) iii) iv) v) vi) Title of the book Author Name ISBN number Publisher name Edition Price

Write a Document Type Definition to validate the above XML file. The Contents should be displayed in a table. The header of the table should be in a color GREY.and the Author names column should be displayed in one color and should be Capitalized and in bold.Use your own colors for remaining columns. Use XML schemas XSL and CSS for the above purpose. Note: Give at least for 4 books. It should be valid syntactically. Hint: You can use some xml editors like XML-spy

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

93

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB XML


(Extensible markup language)

The XML markup language developed to add structural and formatting information to data and which was designed to be simple enough to be included in any application that language is Standard Generalized Markup Language and was adopted as standard by International Organization for Standardization(ISO).Markup is nothing but instructions, which are often called as tags. There are many languages which show how the data is displayed but no one describes what the data is. This is the point at which XML enters. XML is a subset ofSGML. XML is used to describe the structure of a document not the way that is presented. XML is the recommendation of World Wide Consortium (W3C). The structure of basic XML is shown below which resembles HTML. The first line is the processing instruction which tells applications how to handle the XML. It is also serves as version declaration and says that the file is XML. Example Sample XML program <?xml version=1.0?> <college> <studdetail> <regno>05j0a1260</regno> <name> <firstname>karthik></firstname> <lastname>btech</lastname> </name> <country name="india"/> <branch>csit</branch></studdetail> </college> Valid an Well Formed XML XML documents may be either valid or well formed. A well formed document is one which follows all of the rules ofXML. Tags are matched and do not overlap, empty elements are ended properly, and the document contains anXML declaration. A valid XML document has its own DTD. XML should also conform the rules set out in the DTD. There are many XML parsers that checks the document and its DTD

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

94

D.SUNITHA
XML elements

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

XML documents are composed of three things i.e., elements, control information, and entities. Most of the markup in an XML document is element markup. Elements are surrounded by tags much as they are in HTML. Each document has a single root element which contains al of the other markup. Nesting tags: Even the simplest XML document has nested tags. Unlike HTML these must be properly nested and closed in the reverse of the order in which they were opened. Each XML tag has to have a closing tag, again unlikeHTML. Case Sensitive: XML is case sensitive and you must use lower case for your markup. Empty tags: Some tags are empty, they dont have content. Where the content of the tag is missing, it appears as <content/> Attributes: Sometimes it is important that elements have information associated with them without that information becoming a separate element. Control Information: There are three types of control information Comments processing instructions document type declaration.

Comments: XML comments are exactly same as HTML. They take the form as <!- -comment text - -> Processing Instructions: Processing Instructions are used to control applications. One ofthe processing instructions is <?xml version=1.0> Document Type Declarations: Each XML document has an associated DTD. The DTDis usually present in separate file, so that it can be used by many files. The statement that includes DTD in XML file is <?DOCTYPEcust SYSTEM customer.dtd> Entities Entities are used to create small pieces of data which you want to use repeatedly throughout your schema.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

95

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Example A Complete XML program <?xml version=1.0?> <!DOCTYPE stud S?YSTEM student.dtd> <college> <studdetail> <regno>05j0a1260</regno> <name> <firstname>feroz></firstname> <lastname>btech</lastname> </name> <country name="india"/> <branch>csit</branch> </studdetail> </college> Document Type Definition Document type definition has been successfully used in SGML applications for many year. DTD are document centric. They are well understood. There are plenty of tools that support DTD. <!ELEMENT college(studetail+)> <!ELEMENTstudetail(regno, name+, country, branch)> <!ELEMENTregno(#PCDATA)> <!ELEMENT name(firstname, lastname)> <!ELEMENTfirstname(#PCDATA)> <!ELEMENTlastname(#PCDATA)> <!ELEMENT country(#PCDATA)> <!ATTLIST country name CDATA #REQUIRED> <!ELEMENT branch(#PCDATA)>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

96

D.SUNITHA
XML Schema

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

W3C developed a technology called XML schema which they accepted as are commendation. XML schema is itself an XML application which means when you use it your only need a single grammar and can use your normal XML editor to create it. Example XML Schema for XML document shown in Example <?xml version =1.0 ?> <xsd:schemaxmlns = http://.........> <xsd:element name = college> <xsd:complexType> <xsd:sequence> <xsd:element name = studetail> <xsd:complexType> <xsd:sequence> <xsd:element name = regno type = xsd:string/> <xsd:element name = name> <xsd:complexType> <xsd:sequence> <xsd:element name = firstname type=xsd:string/> <xsd:element name= lastname type = xsd:string/> <xsd:element name = country> <xsd:complexType> <xsd:attribute name = India type= xsd:string/> </xsd:complexType> </xsd:element> xsd:element name = branch type = xsd:string/> </xsd:sequence> </xsd:complexType> </xsd:element>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 97

D.SUNITHA
</xsd:sequence>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

</xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema> Document Object Model XML parsers can handle documents in any way that their developers choose. There are two models commonly used for parsers i.e., SAX and DOM. SAX parsers are used when dealing with streams of data. This type of parsers is usually used with java. SAX-based parsers run quickly. DOM is and application program interface (API) for XML documents.

The DOM API specifies the logical structure of XML documents and the ways in which they can be accessed and manipulated. The DOM API is just a specification. DOM-complaint applications include all of the functionality needed to handle XML documents. They can build static documents, navigate and search through them, add new elements, delete elements, and modify the content of existing elements. The views XML documents trees. The DOM exposes the whole of the document to applications. It is also scriptable so applications can manipulate the individual nodes. Presenting XML XML documents are presented using Extensible Stylesheet which expresses stylesheets.XSL stylesheet are not the same as HTML cascading stylesheets. They create a style fora specific XML element, with XSL a template is created. XSL basically transforms onedata structure to another i.e., XML to HTML. Example Here is the XSL file for the XML document of Example This line must be included in the XML document which reference stylesheet <?xml:stylesheet type = text/xsl href = student.xsl?. Here goes the XSL file

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

98

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<xsl:stylesheetsmlns:xsl =uri:xsl. <xsl:template match=/> <html> <body> <h1> Student Database </h1. <xsl:for-each select = college> <xsl:for-each select = studetail> <xsl:value-of select = regno/> <xsl:for-each select = name> <xsl:value-of select = firstname/> <xsl:value-of select = lastname/> </xsl:for-each> <xsl:value-of select=country/@name /> <xsl:value-of select = branch/> </xsl:for-each> </xsl:for-each> </body> </xsl:template> </xsl:stylesheet> Evolution of the XML Parsing The combination of Java and XML has been one of the most attracting things which had happened in the field of software development in the 21st century. It has been mainly for two reasons - Java, arguably the most widely used programming language and XML, almost unarguably the best mechanism of data description and transfer. Since these two were different technologies and hence it initially required a developer to have a sound understanding of both of these before he can make the best use of the combination. Since then there have been a paradigm shift towards Java a few interesting technologies getting evolved to make this happen. Some of the mare:-

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

99

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

SAX - Simple API for XML Parsing It was the first to come on the scene and interestingly it was developed in the XMLDevmailing list. Evidently the people who developed this were XML gurus and it is quite visible in the usage of this API. You got to have a fairunderstanding of XML, but at least Java developers got something to combine the two worlds - Java and XML in a structured way. It instantly became a hit for the obvious reasons. Since this API does require to load the entire XML doc and also because it offers only a sequential processing of thedoc hence it is quite fast. Another reason of it being faster is that it does not allow modification of the underlyingXML data. DOM - Document Object Model The Java binding for DOM provided a tree-based representation of the XML documents allowing random accessand modification of the underlying XML data. Not very difficult to deduce that it would be slower as compared toSAX. The event-based callback methodology was replaced by an object-oriented in-memory representation of the XMLdocuments. Though, it differs from one implementation to another if the entire document or a part of it would be kept in the memory at a particular instant, but the Java developers are kept out of all the hassle and they get the entire tree readily available whenever they wish. JAXP - Java API for XML Parsing The creators and designers of Java realized that the Java developers should not be XML gurus to use the XML in Java applications. The first step towards making this possible was the evolution of JAXP, which made it easier to obtain either a DOM Document or a SAXcompliant parser via a factory class. This reduced the dependence of Java developers over the numerous vendors supplying the parsers of either type. Additionally, JAXP made sure that an interchange between the parsers required minimal code changes. Differences between DOM and SAX SAX v/s DOM Main differences between SAX and DOM, which are the two most popular APIs for processing XML documents in Java, are:Read v/s Read/Write: SAX can be used only for reading XML documents and not for the manipulation of the underlying XML data whereas DOM can be used for both read and write of the data in an XMLdocument. Sequential Access v/s Random Access: SAX can be used only for a sequential processing of an XMLdocument whereas DOM can be used for a random processing of XML docs. So what to do if you want arandom access to the underlying XML data while using SAX? You got to store and manage that informationso that you can retrieve it when you need.
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 100

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Call back v/s Tree: SAX uses call back mechanism and uses event-streams to read chunks of XML data intothe memory in a sequential manner whereas DOM uses a tree representation of the underlying XMLdocument and facilitates random access/manipulation of the underlying XML data. XML-Dev mailing list v/s W3C: SAX was developed by the XML-Dev mailing list whereas DOM wasdeveloped by W3C (World Wide Web Consortium). Information Set: SAX doesn't retain all the info of the underlying XML document such as commentswhereas DOM retains almost all the info. New versions of SAX are trying to extend their coverage ofinformation.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

101

D.SUNITHA
PROGRAM: book.xml

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="book.xsl"?> <bookdetails> <book> <title>XYZ</title> <author>ABC</author> <ISBN>22</ISBN> <publisher>XX</publisher> <price>25</price> <edition>2</edition> </book> <book> <title>MFG</title> <author>efg</author> <ISBN>23</ISBN> <publisher>YY</publisher> <price>$35</price> <edition>3</edition> </book> <book> <title>HIJ</title> <author>klm</author> <ISBN>22</ISBN> <publisher>ZZ</publisher> <price>45</price>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 102

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<edition>4</edition> </book> <book> <title>EFG</title> <author>nop</author> <ISBN>21</ISBN> <publisher>JS</publisher> <price>55</price> <edition>5</edition> </book> </bookdetails>

book.xsl <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <head></head> <body> <table border="1"> <tr> <thbgColor="grey">title</th> <thbgColor="grey">author</th> <thbgColor="grey">ISBN</th> <thbgColor="grey">publisher</th> <thbgColor="grey">price</th> <thbgcolor="grey">edition</th>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 103

D.SUNITHA
</tr>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<xsl:for-each select="bookdetails/book"> <tr> <td bgColor="blue"><b><xsl:value-of select="title"/></b></td> <td bgColor="blue"><b><xsl:value-of select="author"/></b></td> <td bgColor="blue"><b><xsl:value-of select="ISBN"/></b></td> <td bgColor="blue"><b><xsl:value-of select="publisher"/></b></td> <td bgColor="blue"><b><xsl:value-of select="price"/></b></td> <td bgColor="blue"><b><xsl:value-of select="edition"/></b></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>

PROCEDURE: XML documents are presented using Extensible Stylesheet which expresses stylesheets.XSL stylesheet are not the same as HTML cascading stylesheets. They create a style fora specific XML element, with XSL a template is created. XSL basically transforms onedata structure to another i.e., XML to HTML. This line must be included in the XML document which reference stylesheet <?xml:stylesheet type = text/xsl href = student.xsl?. So that to run the above xml we have to write a .XSL file for reference to xml file for presenting and defining the properties of elements used in xml file. So that we have to run .XSL file foe output;

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

104

D.SUNITHA
OUTPUT:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

105

WEEK-6

Date of Conduction: Date of Submission:

Date of Valuation Marks Awarded

: :

Signature of Staff Member

D.SUNITHA
AIM;

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

VISUL BEANS: Create a simple visual bean with a area filled with a color. The Shape of the area depends on the property shape. If it is true then the shape of the area is Square and it is Circle, if it is false the color of the area should be changed dynamically mouse click. The color should also be Changes if we the color in the Property windows.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

106

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Java Beans
A Java Beans is software component that has been designed to be reusable in variety ofdifferent environments. There is no restriction on the capability of a Bean. It may perform simple function, such as checking the spelling of a document, or complex function, such as forecasting the performance of a stock portfolio. A bean may be visible to an end user. One example of this is a button on a graphical user interface. A bean maybe designed to work autonomously on a users workstation or to work in cooperation witha set of other distributed components. Advantages of Java Beans A bean obtains all the benefits of Javas write once, run-anywhere paradigm. The properties, events and methods of a bean that are exposed to an application builder tool can be controlled. A bean may be designed to operate correctly in different locales, which makes it useful in global markets. Auxiliary software can be provided to help a person configure a bean. The configuration settings of a bean can be saved in persistent storage and restored at a later time. A bean may register to receive events from other objects and can generate events that are sent to other objects.

BDK Introspection Introspection is the process of analyzing a bean to determine its capabilities. This is avery important feature of Java Bean API, because it allows an application builder tool topresent information about a component to a software designer. Without introspection, thejava beans technology could not operate. One way exposed the properties, events andmethods of bean to application builder tool are using simple naming conventions. Design pattern for properties Property is a subset of a beans state. The values that are assigned to the properties determine the behavior andappearance of that component. Simple properties: A simple property has a single value. It can be identified by the following design patterns, where N is the name ofthe property and T is its type. Public T getN( ); Public void setN( );

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

107

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Boolean properties: A Boolean property has a value of true or false. It can be identified by the following design patterns, where N is name of the property. Public Boolean isN ( ); Public Boolean getN( ); Public void setN(Boolean value); indexed properties An indexed property consists of multiple values. It can be identified by the following design patterns, where N is the name of the property and T is its type. Public T getN(int index); Public void setN(int index, T value); Public T[ ] getN( ); Public void setN(T values[ ]); Using Bound Properties A bean that has a bound property generates an event when the property is changed. The event is of typePropertyChangeEvent and is sent to objects that previously registered an interest in receiving such notifications. Example : Application that uses TickTock bean to automatically control the Color bean Steps: 1. Go to menu bar of the bean box and select Edit | Events | propetyChange. We can see a line extending from thebutton to the cursor 2. Move the cursor so that it is inside the Colors bean display area, and click the left mouse button. See the EventTarget Dialog dialog box. dialog box allows to choose a method that should be invoked when this event occurs. Select the entry labeled change and click the Ok button.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

108

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Using BeanInfo Interface This interface defines several methods, including these: PropertyDescription[ ] getPropertyDescriptors( ) EventSetDescriptor[ ] getEventSetDescriptors( ) MethodDescriptor[ ] getMethodDescriptors( ) The above methods will return array of objects that provide information about the properties, events, and methodsof bean. SimpleBeanInfo is a class that provides default implementations of the BeanInfo interface, including thethreemethods .this class and override on or more of them. Constrained Properties A bean that has a constrained property generates an event when an attempt is made to change its value. The eventis of type PropertyChangeEvent. It is sent to objects that previously registered an interest in receiving suchnotifications. This capability allows a Bean to operate differently according to its run-time environment. Persistence Persistence is the ability to save a Bean to nonvolatile storage and retrieve it at a later time. The information that is particularly important are the configuration settings. Customizers A bean developer can provide a customizer that helps another developer configure this software. A customizer can provide a step-by-step guide through the process that must be followed to use the component in a specific context. Java Beans API Interface Description AppletInitializer Methods present in this interface are used to initialize Beans that are also applets BeanInfoThis interface allows a designer to specify information about the properties, events and methods of a Bean. Customizer this interface allows a designer to provide a graphical user interface through which a Bean may be configured. DesignMode Methods in this interface determine if a Bean is executing in design mode. PropertyChangeListener A method in this interface is invoked when a bound property is changed. Visibility Methods in this interface allow a bean to execute in environments where graphical user interface is not available.
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 109

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Class Description BeanDescriptor This class provides information about a Bean. Beans This class is used to obtain information about a Bean IntrospectionException An exception of this type is generated if a problem occurs when analyzing a bean. PropertyChangeEvent This event is generated when bound or constrained properties are changed. PropertyDescriptor Instances of this class describe a property of a Bean

Sun provides two Bean application builder tools. The first is the BeanBox, which is part of the Bean Developers Kit (BDK). The BDK is the original builder tool provided by Sun. The second is the new Bean Builder. Because BeanBuilder is designed to supplant the BeanBox, Sun has stopped development of the BDK and all new Beanapplications will be created using Bean Builder. Using the Bean Developer Kit (BDK) The Bean Developer Kit (BDK), available from the JavaSoft site, is a simple example of a tool that enables you tocreate, configure, and connect a set of Beans. There is also a set of sample Beans with their source code. Thissection provides step-by-step instructions for installing and using this tool. Starting the BDK

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

110

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

To start the BDK, follow these steps: 1. Change to the directory c:\bdk\beanbox. 2. Execute the batch file called run.bat. This causes the BDK to display the three windows shown in Figure .Toolbox lists all of the different Beans that have been included with the BDK.Bean Box provides an area to lay out andconnect the Beans selected from the ToolBox. Properties provide the ability to configure a selected Bean. You mayalso see a window called Method Tracer. Using the BDK First, the Molecule Bean displays a three-dimensional view of a molecule. It may be configured to present one of the following molecules: hyaluronic acid, benzene, buckminsterfullerene, cyclohexane, ethane, or water. Thiscomponent also has methods that allow the molecule to be rotated in space along its X or Y axis. Second, theOurButton Bean provides a push-button functionality. We will have one button labeled Rotate X torotate the molecule along its X axis and another button labeled Rotate Y to rotate the molecule along its Y axis. Create and Configure an Instance of the Molecule Bean

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

111

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Follow these steps to create and configure an instance of the Molecule Bean: 1. Position the cursor on the Toolbox entry labeled Molecule and clicks the left mouse button. You should see the cursor change to a cross. 2. Move the cursor to the BeanBox display area and click the left mouse button in approximately the area whereyou wish the Bean to be displayed. You should see a rectangular region appear that contains a 3-D display of a molecule. This area is surrounded by a hatched border, indicating that it is currently selected. 3. You can reposition the Molecule Bean by positioning the cursor over one of the hatched borders and dragging the Bean. 4. You can change the molecule that is displayed by changing the selection in the Properties window. Notice that the Bean display changes immediately when you change the selected molecule.

Create and Configure an Instance of the OurButton Bean Follow these steps to create and configure an instance of theOurButton Bean and connect it to the Molecule Bean: 1. Position the cursor on the ToolBox entry labeledOurButton and clicks the left mouse button. You should see thecursor change to a cross. 2. Move the cursor to the BeanBox display area and click the left mouse button in approximately the area whereyou wish the Bean to be displayed. You should see a rectangular region appear that contains a button. This area issurrounded by a hatched border indicating that it is currently selected. 3. You may reposition theOurButton Bean by positioning the cursor over one of the hatched borders and dragging the Bean. 4. Go to the Properties window and change the label of the Bean to Rotate X. The button appearance changes immediately when this property is changed. 5. Go to the menu bar of the BeanBox and select Edit | Events | action |action Performed. You should now see aline extending from the button to the cursor. Notice that one end of the line moves as the cursor moves. However, the other end of the line remains fixed at the button. 6. Move the cursor so that it is inside the Molecule Bean display area, and click the left mouse button. You should see the Event Target Dialog dialog box. 7. The dialog box allows you to choose a method that should be invoked when this button is clicked. Select theentry labeled rotateOnX and click the OK button. You should see a message box appear very briefly, stating thatthe tool is Generating and compiling adaptor
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 112

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

class.Test the application. Each time you press the button, the molecule should move a few degrees around one of itsaxes. Now create another instance of theOurButton Bean. Label it Rotate Y and map its action event to the rotateYmethod of the Molecule Bean. The steps to do this are very similar to those just described for the button labeledRotate X. Test the application by clicking these buttons and observing how the molecule moves. JAR Files Before developing your own Bean, it is necessary for you to understand JAR (Java Archive) files, because tools such as the BDK expect Beans to be packaged within JAR files. A JAR file allows you to efficiently deploy a set of classes and their associated resources. For example, a developer may build a multimedia application that uses various sound and image files. A set of Beans can control how and when this information is presented. All of these pieces can be placed into one JAR file.JAR technology makes it much easier to deliver and install software. Also, the elements in a JAR file a recompressed, which makes downloading a JAR file much faster than separately downloading several uncompressed files. Digital signatures may also be associated with the individual elements in a JAR file. This allows a consumer to be sure that these elements were produced by a specific organization or individual. The package java.util.zip contains classes that read and write JAR files. Manifest Files A developer must provide a manifest file to indicate which of the components in a JAR file Java Beans are. Anexample of a manifest file is provided in the following listing. It defines a JAR file that contains four .gif files and one.class file. The last entry is a Bean. Name: sunw/demo/slides/slide0.gif Name: sunw/demo/slides/slide1.gif Name: sunw/demo/slides/slide2.gif Name: sunw/demo/slides/slide3.gif Name: sunw/demo/slides/Slides.class Java-Bean: True A manifest file may reference several .class files. If a .class file is a Java Bean, its entry must be immediately followed by the line Java-Bean: True. The JAR Utility A utility is used to generate a JAR file. Its syntax is shown here:
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 113

D.SUNITHA
jar options files

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Creating a JAR File The following command creates a JAR file named Xyz.jar that contains all of the .class and .gif files in the current directory: jarcf Xyz.jar *.class *.gif If a manifest file such asYxz.mf is available, it can be used with the following command: jarcfm Xyz.jar Yxz.mf *.class *.gif The following command lists the contents of Xyz.jar: jartf Xyz.jar Introspection Introspection is the process of analyzing a Bean to determine its capabilities. This is an essential feature of the JavaBeans API, because it allows an application builder tool to present information about a component to a software designer. Without introspection, the Java Beans technology could not operate. There are two ways in which the developer of a Bean can indicate which of its properties, events, and methods should be exposed by an application builder tool. With the first method, simple naming conventions are used. These
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 114

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

allow the introspection mechanisms to infer information about a Bean. In the second way, an additional class is provided that explicitly supplies this information. Design Patterns for Properties A property is a subset of a Beans state. The values assigned to the properties determine the behavior and appearance of that component. This section discusses three types of properties: simple, Boolean, and indexed. Simple Properties A simple property has a single value. It can be identified by the following design patterns, where N is the name of the property and T is its type. public T getN( ); public void setN(Targ); A read/write property has both of these methods to access its values. A read-only property has only a get method. A write-only property has only a set method.

The following listing shows a class that has three read/write simple properties: public class Box { private double depth, height, width; public double getDepth( ) { return depth; } public void setDepth(double d) { depth = d; } public double getHeight( ) { return height; } public void setHeight(double h) { height = h;
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 115

D.SUNITHA
}

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

public double getWidth( ) { return width; } public void setWidth(double w) { width = w; } } Boolean Properties A Boolean property has a value of true or false. It can be identified by the following design patterns, where N is the name of the property: publicbooleanisN( ); publicbooleangetN( ); public void setN(boolean value); Either the first or second pattern can be used to retrieve the value of a Boolean property. However, if a class has both of these methods, the first pattern is used.

Indexed Properties An indexed property consists of multiple values. It can be identified by the following design patterns, where N is thename of the property and T is its type: public T getN(int index); public void setN(int index, T value); public T[ ] getN( ); public void setN(T values[ ]);

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

116

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Design Patterns for Events Beans use the delegation event model that was discussed earlier in this book. Beans can generate events and send them to other objects. These can be identified by the following design patterns, where T is the type of the event: public void addTListener(TListenereventListener); public void addTListener(TListenereventListener) throws TooManyListeners; public void removeTListener(TListenereventListener); These methods are used by event listeners to register an interest in events of a specific type. The first pattern indicates that a Bean can multicast an event to multiple listeners. The second pattern indicates that a Bean canunicast an event to only one listener. The third pattern is used by a listener when it no longer wishes to receive aspecific type of event notification from a Bean. The following listing outlines a class that notifies other objects when a temperature value moves outside a specific range. The two methods indicated here allow other objects that implement theTemperatureListener interface to receive notifications when this occurs. public class Thermometer { public void addTemperatureListener(TemperatureListenertl) { ... } public void removeTemperatureListener(TemperatureListenertl) { ... } } Methods Design patterns are not used for naming no property methods. The introspection mechanism finds all of the public methods of a Bean. Protected and private methods are not presented. Developing a Simple Bean Using the BDK The component is called the Colors Bean. It appears as either a rectangle or ellipse that is filled with a color. A color is chosen at random when the Bean begins execution. A public method can be invoked to change it. Each time the mouse is clicked on the Bean, another random color is chosen. There is oneboolean read/write propertythat determines the shape.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

117

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

The BDK is used to lay out an application with one instance of the Colors Bean and one instance of theOurButtonBean. The button is labeled Change. Each time it is pressed, the color changes. SOFTWARE DEVELOPMENTUSING JAVA

Create a New Bean 1. Create a directory for the new Bean. 2. Create the Java source file(s). 3. Compile the source file(s). 4. Create a manifest file. 5. Generate a JAR file. 6. Start the BDK. 7. Test. Create a Directory for the New Bean c:\bdk\demo\sunw\demo\colors. Then change to that directory. Create the Source File for the New Bean The source code for the Colors component is shown in the following listing. It is located in the file Colors.java.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

118

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

The import statement at the beginning of the file places it in the package namedsunw.demo.colors. this file must be located in a subdirectory namedsunw\demo\colors relative to the CLASSPATH environment variable. The color of the component is determined by the private Color variable color, and its shape is determined by the privateboolean variable rectangular.

// A simple Bean. packagesunw.demo.colors; importjava.awt.*; importjava.awt.event.*; public class Colors extends Canvas { transient private Color color; privateboolean rectangular; public Colors() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { change(); } }); rectangular = false; setSize(200, 100); change(); } publicbooleangetRectangular() { return rectangular; } public void setRectangular(boolean flag) {
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 119

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

this.rectangular = flag; repaint(); } public void change() { RE DEVELOPMENT color = randomColor(); repaint(); } private Color randomColor() { int r = (int)(255*Math.random()); int g = (int)(255*Math.random()); int b = (int)(255*Math.random()); return new Color(r, g, b); } public void paint(Graphics g) { Dimension d = getSize(); int h = d.height; int w = d.width; g.setColor(color); if(rectangular) { g.fillRect(0, 0, w-1, h-1); } else { g.fillOval(0, 0, w-1, h-1); } } }

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

120

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Compile the Source Code for the New Bean Compile the source code to create a class file. Type the following: javac Colors.java. Create a Manifest File switch to the c:\bdk\demo directory. This is the directory in which the manifest files for the BDK demos are located. Put the source code for your manifest file in the filecolors.mft. Name: sunw/demo/colors/Colors.class Java-Bean: True This file indicates that there is one .class file in the JAR file and that it is a Java Bean. TheColors.class file is in thepackagesunw.demo.colors and in the subdirectorysunw\demo\colors relative to the current directory. Generate a JAR File Beans are included in the ToolBox window of the BDK only if they are in JAR files in the directory c:\bdk\jars. Thesefiles are generated with the jar utility. Enter the following: jarcfm ..\jars\colors.jar colors.mftsunw\demo\colors\*.class This command creates the file colors.jar and places it in the directory c:\bdk\jars. Start the BDK Change to the directory c:\bdk\beanbox and type run. This causes the BDK to start. The ToolBox window should include an entry labeled Colors for your new Bean. Create an Instance of the ColorsBean .Test your new component by pressing the mouse anywhere within its borders. Its color immediately changes. Using the BeanInfo Interface Design patterns were used to determine the information that was provided to a Bean user. This sectiondescribes how a developer can use theBeanInfo interface to explicitly control this process. This interface defines several methods, including these: PropertyDescriptor[ ] getPropertyDescriptors( ) EventSetDescriptor[ ] getEventSetDescriptors( ) MethodDescriptor[ ] getMethodDescriptors( )

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

121

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Using Bound Properties


A Bean that has a bound property generates an event when the property is changed. The event is oftypePropertyChangeEvent and is sent to objects that previously registered an interest in receiving such notifications. The TickTock Bean is supplied with the BDK. It generates a property change event every N seconds. N is property of the Bean that can be changed via the Properties window of the BDK.The next example builds an application that uses the TickTock Bean to automatically control the Colors Bean. Figure shows how this application appears.

Steps
For this example, start the BDK and create an instance of the Colors Bean in the BeanBoxwindow.Create an instance of the TickTock Bean. The Properties window should show one property for thiscomponent. It is Interval and its initial value is 5. This represents the number of seconds that elapsebetween property change events generated by theTickTock Bean. Change the value to 1. Now you need to map events generated by theTickTock Bean into method calls on the Colors Bean. Follow these steps:
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 122

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

1. Go to the menu bar of the BeanBox and select Edit | Events | propertyChange | propertyChange. Youshould now see a line extending from the button to the cursor. 2. Move the cursor so that it is inside the Colors Bean display area, and click the left mouse button. Youshould see the Event Target Dialog dialog box. 3. The dialog box allows you to choose a method that should be invoked when this event occurs. Selectthe entry labeled change and click the OK button. You should see a message box appear very briefly,stating that the tool is Generating and compiling adaptor class. You should now see the color of your component changeevery second. Constrained Properties A Bean that has a constrained property generates an event when an attempt is made to change its value.The event is of typePropertyChangeEvent. It is sent to objects that previously registered an interest inreceiving such notifications. Those other objects have the ability to veto the proposed change. Thiscapability allows a Bean to operate differently according to its run-time environment. A full discussion ofconstrained Persistence Persistence is the ability to save a Bean to nonvolatile storage and retrieve it at a later time. Theinformation that is particularly important are the configuration settings. Customizers The Properties window of the BDK allows a developer to modify the properties of a Bean. However, thismay not be the best user interface for a complex component with many interrelated properties. Therefore, a Bean developer can provide a customizer that helps another developer configure thissoftware. A customizer can provide a step-by-step guide through the process that must be followed touse the component in a specific context. Online documentation can also be provided. The Java Beans API The Java Beans functionality is provided by a set of classes and interfaces in thejava.beans package. This section provides a brief overview of its contents. The Table lists the interfaces injava.beans and provides a brief description of their functionality.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

123

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

124

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

125

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Create a simple visual bean with a area filled with a color. PROGRAM: importjava.awt.*; importjava.awt.event.*; importjava.io.Serializable; public class Colors extends Canvas implements Serializable { transient private Color color; privateboolean rectangular; public Colors() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { change(); } }); rectangular = false; setSize(200,100); change(); } publicbooleangetRectangular() { return rectangular; } public void setRectangular(boolean flag)
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 126

D.SUNITHA
{

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

this.rectangular =flag; repaint(); } public void change() { color = randomColor(); repaint(); } private Color randomColor() { int r = (int)(255*Math.random()); int g = (int)(255*Math.random()); int b = (int)(255*Math.random()); return new Color(r,g,b); } public void paint(Graphics g) { Dimension d= getSize(); int h = d.height; int w =d.width; g.setColor(color); if (rectangular) { g.fillRect(0,0,w-1,h-1); } else
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 127

D.SUNITHA
{

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

g.fillOval(0,0,w-1,h-1); } } }

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

128

D.SUNITHA
PROCEDURE:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Create a simple visual bean with a area filled with a color. 1. Create a directory for the new colorsBean. 2. Create the Java source file(s). 3. Compile the source file(s). 4. Create a manifest file. 5. Generate a JAR file. 6. Start the BDK. 7. Test.

Create a Directory for the New Bean c:\bdk\demo\sunw\demo\colors. Then change to that directory. Create the Source File for the New Bean The source code for the Colors component is shown in the following listing. It is located in the file Colors.java. The import statement at the beginning of the file places it in the package namedsunw.demo.colors. this file must be located in a subdirectory namedsunw\demo\colors relative to the CLASSPATH environment variable. The color of the component is determined by the private Color variable color, and its shape is determined by the privateboolean variable rectangular. Compile the Source Code for the New colors Bean Compile the source code to create a class file. Type the following: javac Colors.java. Create a Manifest File Switch to the c:\bdk\demo directory. This is the directory in which the manifest files for the BDK demos arelocated. Put the source code for your manifest file in the filecolors.mft. Name: sunw/demo/colors/Colors.class Java-Bean: True
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 129

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

This file indicates that there is one .class file in the JAR file and that it is a Java Bean. TheColors.class file is in thepackagesunw.demo.colors and in the subdirectorysunw\demo\colors relative to the current directory. Generate a JAR File Beans are included in the ToolBox window of the BDK only if they are in JAR files in the directory c:\bdk\jars. Thesefiles are generated with the jar utility. Enter the following: jarcfm ..\jars\colors.jar colors.mftsunw\demo\colors\*.class This command creates the file colors.jar and places it in the directory c:\bdk\jars. Start the BDK Change to the directory c:\bdk\beanbox and type run. This causes the BDK to start. The ToolBox window should include an entry labeled Colors for your new Bean. Create an Instance of the ColorsBean .Test your new component by pressing the mouse anywhere within its borders. Its color immediately changes.

Steps
Start the BDK and create an instance of the Colors Bean in the BeanBoxwindow.Create an instance of the TickTock Bean. The Properties window should show one property for thiscomponent. It is Interval and its initial value is 5. This represents the number of seconds that elapsebetween property change events generated by theTickTock Bean. Change the value to 1. Now you need to map events generated by theTickTock Bean into method calls on the Colors Bean. Follow these steps: 1. Go to the menu bar of the BeanBox and select Edit | Events | propertyChange | propertyChange. Youshould now see a line extending from the button to the cursor. 2. Move the cursor so that it is inside the Colors Bean display area, and click the left mouse button. Youshould see the Event Target Dialog dialog box. 3. The dialog box allows you to choose a method that should be invoked when this event occurs. Selectthe entry labeled change and click the OK button. You should see a message box appear very briefly,stating that the tool is

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

130

D.SUNITHA
OUTPUT:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

131

WEEK-7

Date of Conduction: Date of Submission:

Date of Valuation Marks Awarded

: :

Signature of Staff Member

D.SUNITHA
AIM;

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

1. Install TOMCAT web server and APCHE. While installation assign port number 4040 to TOMCAT 8080 to APACHE. Make sure that these ports are available i.e., no other process is using this port number.

2. Access the above developed static web pages for books website using these servers by putting the webpage developed in week-1 and week-2 in the document root. Access the pages by using the http://localhost;4040/rama/books.html (for TOMCAT) http://localhost;8080/books.html (for APACHE)

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

132

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Apache Tomcat Server


Apache Tomcat (or Jakarta Tomcat or simply Tomcat) is an open source servlet container developed by theApacheSoftware Foundation (ASF). Tomcat implements the Java Servlet and the Java Server Pages (JSP) specifications fromOracle Corporation, and provides a "pure Java" HTTP web server environment for Java code to run. Apache Tomcat includes tools for configuration and management, but can also be configured by editing XML configuration files. Tomcat started off as a servlet reference implementation by James Duncan Davidson, a software architect at Sun Microsystems. He later helped make the project open source and played a key role in its donation by Sun to theApache Software Foundation. The Apache Ant software build automation tool was developed as a side-effect of thecreation of Tomcat as an open source project. Davidson had initially hoped that the project would become opensourced and, since many open source projects had O'Reilly books associated with them featuring an animal on the cover, he wanted to name the project after an animal. He came up with Tomcat since he reasoned the animal represented something that could fend for itself. Although the tomcat was already in use for another O'Reilly title, his wish to see an animal cover eventually came true when O'Reilly published their Tomcat book with a snow leopard on the cover.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

133

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Install TOMCAT web server and APCHE:. Steps to install the Tomcat Web Server: While installing the tomcat web server on our computer we can either make use of windows installer or we can download the package using zip or tar file. Let us discuss the first method using window installer. Step-1: If we click on the windows installer then the program will automatically install tomcat web server on our computer. When we start installation using this windows installer program initially following window will appear. The window name is welcome Apache Tomcat Setup Wizard.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

134

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Step-2: Next click on the Next button and following window will appear. The window name is License Agreement. In this we have to accept the terms by clicking the I agree button in the license agreement window.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

135

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Step-3: After clicking the I agree button the choose components window will appear. In this choose which features of apache tomcat we want to install. i.e., here we select the type of the choose components.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

136

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Step-4: Then click the Next button in the choose components window then we will get the installation part window in which the installation directory can be chosen. If you want to change the default path we can click the browse button and change the path.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

137

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Step-5: Then click the Next button in the choose install location window and we will get the configuration window. Here we can set the connector port number. By default the port number is 8080 for apache tomcat server. We can change port number to any other value except the first 1024 values (The first 1024 port numbers are reserved). In these we can also set the user name and password for administration login.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

138

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Step-6: Then click the Next button in configuration window. We will get the java virtual machine path selection window. Here we can select the jre folder in java.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

139

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Step-7: Then the installation process will start when we click the install button on the java virtual machine path selection.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

140

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Step-8: After the installation process is completed then we will get the window named Completed Apache Tomcat Setup Wizard. At the end click the finish button and the installation procedure get completed.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

141

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Access the above developed static web pages for books website using these servers by putting the webpage developed in week-1 and week-2 in the document root.

Step 1: First of all open some text editor like Notepad and type the code. Create a separate directory at the path C:\Program Files\Apache Software Foundation\Tomcat 5.5\web apps\jspexamples and store the code in this newly created directory. I have created a directory named Hello Demo in which stored the above program by the name hello.jsp. Note that while saving the file using Notepad editor with the program extension .jsp, you must select the all files option if you dont do that then the file may get saved as hello.jsp.txt because the default extension for the notepad files is .txt. Step 2: Start the Tomcat Web Server by typing the command Start at the command prompt.(OR) START->ALLPROGRAMS->APACHETOMCAT->CONFIGURE TOMCAT AFTER A WINDOW WILL BE DISPALYED IN THAT CLICK ON START BUTTON Step3: Open some suitable Web Browser like Firefox or Internet Explorer. Type the path for the page using the http://localhost:4040. Note that local host is the default DNS for Tomcat Web Server. As we have installed Tomcat on the port 4040 we have mentioned so. But the default port Tomcat Web Server is 4040.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

142

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

OUTPUT:

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

143

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

144

WEEK-8

Date of Conduction: Date of Submission:

Date of Valuation Marks Awarded

: :

Signature of Staff Member

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Before going to do the servlet programming we have to create classpath for java and for servlets. (JDK and Tomcat must their in system). Setting CLASS PATH: First go to My computer-PropertiesAdvanced Properties

Then click on Environment variables. then you redirected to a new window as given below

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

145

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Then click on new for setting new path then New User Variable windows has been open. For JAVA: Enter variable name as PATH Enter variable value as C:\Program Files\Java\jdk1.5.0_01\bin;

FOR TOMCAT: Enter variable name as CLASSPATH Enter variable value as C:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib\servlet-api.jar

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

146

D.SUNITHA
AIM:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

User Authentication: Assume four users user1, user2, user3, and user4 having the passwords pwd1, pwd2,pwd3 and pwd4 respectively. Write a Servlet for doing the following 1. Create Cookie and add these four user ids and passwords to this cookie. 2. Read the user id and passwords entered in the Login from (weel1) and authenticate with the values (user id and passwords) available in the cookies. 3. If he is a valid user (i.e., user-name and password match)you should welcome him by name(user-name)else you should display You are not an Authenticated user Use init-parameters to do this. Store the user-names and passwords in the WEBINF.xml and access them in the servlet by using the getInitParameters() method.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

147

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

SERVLETS
Servlets offer several advantages in comparison with CGI. First, performance is significantly better. Servlets execute within the address space of a web server. It is not necessary to create a separate process to handle each client request. Second, servlets are platform-independent because they are written in Java. Third, the Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. Finally, the full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, orother software via the sockets and RMI mechanisms that you have seen already. THE LIFE CYCLE OF A SERVLET Three methods are central to the life cycle of a servlet. These are init( ), service( ), and destroy( ).They are implemented by every servlet and are invoked at specific times by the server. Let us consider a typical user scenario to understand when these methods are called. First, assume that a user enters a Uniform Resource Locator (URL) to a web browser. The browser then generates an HTTP request for this URL. This request is then sent to the appropriate server. Second, this HTTP request is received by the web server. The server maps this request to a particular servlet. The servlet is dynamically retrieved and loaded into the address space of the server. Third, the server invokes theinit( ) method of the servlet. This method is invoked only when the servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet so it may configure itself. Fourth, the server invokes the service( ) method of the servlet. This method is called to process theHTTP request.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

148

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

The servlet remains in the servers address space and is available to process any other HTTP requests received from clients. The service( ) method is called for each HTTP request. Finally, the server may decide to unload the servlet from its memory. The algorithms by which this determination is made are specific to each server. The server calls thedestroy( ) method to relinquish any resources such as file handles that are allocated for the servlet. Important data may be saved to a persistent store. The memory allocated for the servlet and its objects can then be garbage collected. JSDK : JAVA SOFTWARE DEVELOPMENT KIT The JSWDK is the official reference implementation of the servlet 2.1 and JSP 1.0 specifications. It is used as a small stand-alone server for testing servlets and JSP pages before they are deployed to a full Web server that supports these technologies. It is free and reliable, but takes quite a bit of effort to install and configure. install_dir/webpages/WEB-INF/servlets Standard location for servlet classes. install_dir/classes Alternate location for servlet classes. install_dir/lib Location for JAR files containing classes. THE SERVLET API Two packages contain the classes and interfaces that are required to build servlets. These are javax.servletandjavax.servlet.http. They constitute the Servlet API. Keep in mind that these packages are not part of the Java core packages. Instead, they are standard extensions provided by Tomcat. Therefore, they are not included with Java SE6. The Servlet API has been in a process of ongoing development and enhancement.
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 149

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

THE JAVAX.SERVLET PACKAGE The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate. The following table summarizes the core interfaces that are provided in this package. The most significant of these is Servlet. All servlets must implement this interface or extend a class that implements the interface. The Servlet Request and Servlet Response interfaces are also very important. The Servlet Interface All servlets must implement the Servlet interface. It declares the init( ), service( ), and destroy( ) methods that are called by the server during the life cycle of a servlet. A method is also provided that allows a servlet to obtain any initializationparameters. Theinit( ), service( ), and destroy( ) methods are the life cycle methods of the servlet. These are invoked bythe server. The ServletConfig Interface The getServletConfig( ) method is called by the servlet to obtain initialization parameters. A servletdeveloper overrides the getServletInfo( ) method to provide a string with useful information (for example, author, version, date, copyright). This method is also invoked by the server. The ServletContext Interface The ServletContext interface enables servlets to obtain information about their environment. The ServletRequest Interface The ServletRequest interface enables a servlet to obtain information about a client request. The ServletResponse Interface The ServletResponse interface enables a servlet to formulate a response for a client.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

150

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

151

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

GenericServlet Class The GenericServlet class provides implementations of the basic life cycle methods for a servlet. GenericServletimplements the Servlet and ServletConfig interfaces. In addition, a method to append a string to the server logsfiles available. The signatures of this method are shown here: void log(String s) void log(String s, Throwable e) Here, s is the string to be appended to the log, and e is an exception that occurred.

The ServletInputStream Class The ServletInputStream class extends InputStream. It is implemented by the servlet container and provides an input stream that a servlet developer can use to read the data from a client request. It defines the default constructor. In addition, a method is provided to read bytes from the stream. It is shown here: intreadLine(byte[ ] buffer, int offset, int size) throws IOException

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

152

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Here, buffer is the array into which size bytes are placed starting at offset. The method returns the actual number of bytes read or 1 if an end-of-stream condition is encountered. The ServletOutputStream Class The ServletOutputStream class extends OutputStream. It is implemented by the servlet container and provides an output stream that a servlet developer can use to write data to a client response. A default constructor is defined. It also defines the print( ) and println( ) methods, which output data to the stream. The Servlet Exception Classes javax.servlet defines two exceptions. The first is ServletException, which indicates that a servlet problem has occurred. The second is UnavailableException, which extends ServletException. It indicates that a servlet is unavailable. READING SERVLET PARAMETERS The ServletRequest interface includes methods that allow you to read the names and values of parameters that areincluded in a client request. We will develop a servlet that illustrates their use. The example contains two files. Aweb page is defined in PostParameters.htm, and a servlet is defined in PostParametersServlet.java. The HTMLsource code for PostParameters.htm is shown in the following listing. It defines a table that contains twolabels and two text fields. One of the labels is Employee and the other is Phone. There is also a submit button.Notice that the action parameter of the form tag specifies a URL. The URL identifies the servlet to process the HTTPPOST request. <html> <body> <center> <form name="Form1" method="post" action="http://localhost:8080/servlets-examples/ servlet/PostParametersServlet"> <table> <tr><td><B>Employee</td><td><input value=""></td></tr> type=textbox name="e" size="25"

<tr><td><B>Phone</td><td><input type=textbox name="p" size="25" value=""></td></tr> </table> <input type=submit value="Submit"></body></html>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

153

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

The source code for PostParametersServlet.java is shown in the following listing. The service( ) method isoverridden to process client requests. The getParameterNames ( ) method returns an enumeration of theparameter names. These are processed in a loop. The parameter value is obtained via the getParameter ( ) method. import java.io.*; importjava.util.*; importjavax.servlet.*; public class PostParametersServlet extends GenericServlet { public void service(ServletRequestrequest, ServletException, IOException { // Get print writer. PrintWriter pw = response.getWriter(); // Get enumeration of parameter names. Enumeration e = request.getParameterNames(); // Display parameter names and values. while(e.hasMoreElements()) { String pname = (String)e.nextElement(); pw.print(pname + " = "); String pvalue = request.getParameter(pname); pw.println(pvalue); } pw.close(); } } Compile the servlet. Next, copy it to the appropriate directory, and update the web.xml file, perform these steps to test this example: 1. Start Tomcat (if it is not already running). 2. Display the web page in a browser.
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 154

ServletResponse

response)

throws

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

3. Enter an employee name and phone number in the text fields. 4. Submit the web page. THE JAVAX.SERVLET.HTTP PACKAGE The javax.servlet.http package contains a number of interfaces and classes that are commonly used by servlet developers. You will see that its functionality makes it easy to build servlets that work with HTTP requests and responses. The following table summarizes the core interfaces that are provided in this package:

The following table summarizes the core classes that are provided in this package. The most important of these isHttpServlet. Servlet developers typically extend this class in order to process HTTP requests.

The HttpServletRequest Interface The HttpServletRequest interface enables a servlet to obtain information about a client request. The HttpServletResponse Interface The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client. Several constants are defined. These correspond to the different status codes that can be assigned to an HTTP response. For example,SC_OK indicates that the HTTP request succeeded, and SC_NOT_FOUND indicates that the requested resource isnot available.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

155

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

The HttpSession Interface The HttpSession interface enables a servlet to read and write the state information that is associated with an HttpSession.. All of these methods throw an IllegalStateException if the session has already been invalidated. USING COOKIES & SESSION TRACKING The Cookie Class The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state information. Cookies are valuable for tracking user activities. A user visits an online store. Acookie can save the users name, address, andother information. The user does not need to enter this data each time he or she visits the store.Aservlet can write a cookie to a users machine via the addCookie ( ) method of the HttpServletResponseinterface.The data for that cookie is then included in the header of the HTTP response that is sent to the browser.The names and values of cookies are stored on the users machine. Some of the information that is saved for eachcookie includes the following: The name of the cookie The value of the cookie The expiration date of the cookie The domain and path of the cookie

The expiration date determines when this cookie is deleted from the users machine. If an expiration date is notexplicitly assigned to a cookie, it is deleted when the current browser session ends. Otherwise, the cookie is savedin a file on the users machine. The domain and path of the cookie determine when it is included in the header ofan HTTP request. If the user enters a URL whose domain and path match these values, the cookie is then supplied the Web server.

There is one constructor for Cookie. It has the signature shown here: Cookie (String name, String value) Here, the name and value of the cookie are supplied as arguments to the constructor.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

156

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

The HttpServlet Class The HttpServlet class extends GenericServlet. It is commonly used when developing servlets that receive andprocess HTTP requests. The HttpSessionEvent Class HttpSessionEvent encapsulates session events. It extends Event Object and is generated whena change occurs to the session. It defines this constructor: HttpSessionEvent(HttpSession session)
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 157

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Here, session is the source of the event. HttpSessionEvent defines one method, getSession ( ), which is shown here: HttpSessiongetSession( ) : It returns the session in which the event occurred. Example : AddCookie.htm Allows a user to specify a value for the cookie named MyCookie. AddCookieServlet.java Processes the submission of AddCookie.htm. GetCookiesServlet.java Displays cookie values.

The HTML source code for AddCookie.htm is shown in the following listing. This page contains a text field in which avalue can be entered. There is also a submit button on the page. When this button is pressed, the value in the text field is sent to AddCookieServlet via an HTTP POST request.

<html><body><center> <form name="Form1" method="post" action="http://localhost:8080/servlets-examples/servlet/AddCookieServlet"> <B>Enter a value for MyCookie:</B> <input type=textbox name="data" size=25 value=""> <input type=submit value="Submit"> </form></body></html>

The source code for AddCookieServlet.java gets the value of the parameter named data. It then creates a Cookie object that has the name MyCookie and contains the value of the data parameter. The cookie is then added to the header of the HTTP response via the addCookie( ) method. A feedback message is then written to the browser.

import java.io.*; importjavax.servlet.*; importjavax.servlet.http.*;

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

158

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

public class AddCookieServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get parameter from HTTP request. String data = request.getParameter("data"); // Create cookie. Cookie cookie = new Cookie("MyCookie", data); // Add cookie to HTTP response. response.addCookie(cookie); // Write output to browser. response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>MyCookie has been set to"); pw.println(data); pw.close(); } } The source code for GetCookiesServlet.java invokes the getCookies( ) method to read any cookies that are included in the HTTP GET request. The names and values of these cookies are then written to the HTTP response. getName() and getValue( ) methods are called to obtain this information.

import java.io.*; importjavax.servlet.*; importjavax.servlet.http.*;

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

159

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

public class GetCookiesServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException { // Get cookies from header of HTTP request. Cookie[] cookies = request.getCookies(); // Display these cookies. response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>"); for(inti = 0; i<cookies.length; i++) { String name = cookies[i].getName(); String value = cookies[i].getValue(); pw.println("name = " + name +"; value = " + value); } pw.close(); } }

Compile the servlets. Next, copy them to the appropriate directory, and update the web.xml file. Then, perform these steps to test this example: 1. Start Tomcat, if it is not already running. 2. Display AddCookie.htm in a browser. 3. Enter a value for MyCookie. 4. Submit the web page. Next, request the following URL via the browser: http://localhost:8080/servlets-examples/servlet/GetCookiesServlet
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 160

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Session Tracking HTTP is a stateless protocol. Each request is independent of the previous one. However, in some applications, it is necessary to save state information so that information can be collected from several interactions between a browser and a server. Sessions provide such a mechanism. A session can be created via the getSession( ) method ofHttpServletRequest. An HttpSession object is returned. This object can store a set of bindings that associate names with objects. The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods ofHttpSession manage these bindings. It is important to note that session state is shared among all the servlets that are associated with a particular client. The following servlet illustrates how to use session state. The getSession( ) method gets the current session. A new session is created if one does not already exist. The getAttribute( ) method is called to obtain the object that is bound to the name date. That object is a Date object that encapsulates the date and time when this page was last accessed. (Of course, there is no such binding when the page is first accessed.) A Date object encapsulating the current date and time is then created. The setAttribute( ) method is called to bind the name date to this object.

import java.io.*; importjava.util.*; importjavax.servlet.*; importjavax.servlet.http.*;

public class DateServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException { // Get the HttpSession object. HttpSessionhs = request.getSession(true); // Get writer. response.setContentType("text/html");
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 161

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

PrintWriter pw = response.getWriter(); pw.print("<B>"); // Display date/time of last access. Date date = (Date)hs.getAttribute("date"); if(date != null) { pw.print("Last access: " + date + "<br>"); } // Display current date/time. date = new Date(); hs.setAttribute("date", date); pw.println("Current date: " + date); } }

SECURITY ISSUES security has become one of the most important topics in web programming. Security is the science of keeping sensitive information in the hands of authorized users. On the web, this boils down to three important issues: Authentication : Being able to verify the identities of the parties involved Confidentiality : Ensuring that only the parties involved can understand the communication Integrity :Being able to verify that the content of the communication is not changed during transmission . A client wants to be sure that it is talking to a legitimate server (authentication), and it also want to be sure that any information it transmits, such as credit card numbers, is not subject to eavesdropping(confidentiality). The server is also concerned with authentication and confidentiality. If a company is selling a service or providing sensitive information to its own employees, it has a vested interest in making sure that nobody but an authorized user can access it. And both sides need integrity to make sure that whatever information they send gets to the other party unaltered. Authentication, confidentiality, and integrity are all linked by digital certificate technology. Digital certificates allow web servers and clients to use advanced cryptographic techniques to
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 162

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

handle identification and encryption in a secure manner. Thanks to Java's built-in support for digital certificates,servlets are an excellent platform for deploying secure web applications that use digital certificate technology. We'll be taking a closer look at them later. Security is also about making sure that crackers can't gain access to the sensitive data on your web server. Because Java was designed from the ground up as a secure, network-oriented language, it is possible to leverage the built-in security features and make sure that server add-ons from third parties are almost as safe as the ones you write yourself.

Running Servlets Securely


The Servlet Sandbox Servlets built using JDK 1.1 generally operate with a security model called the "servlet sandbox." Under this model, servlets are either trusted and given open access to the server machine, or they're untrustedand have their access limited by a restrictive security manager. The model is very similar to the "appletsandbox," where untrusted applet code has limited access to the client machine. A security manager is sub classed from java.lang.SecurityManager that is loaded by the Java environment to monitor all security-related operations: opening network connections, reading and writing files, exiting the program, and so on. Whenever an application, applet, or servlet performs an action that could cause a potential security breach, the environment queries the security manager to check its permissions. For a normal Java application, there is no security manager. When a web browser loads an untrusted appletover the network, however, it loads a very restrictive security manager before allowing the applet toexecute. Servlets can use the same technology, if the web server implements it. Local servlets can be trusted to run without a security manager, or with a fairly lenient one. For the Java Web Server 1.1, this is what happens when servlets are placed in the default servlet directory or another local source. Servlets loaded from a remote source, on the other hand, are by nature suspect and untrusted, so the Java Web Server forces them to run in a very restrictive environment where they can't access the local file system, establish network connections, and so on. All this logic is contained within the server and is invisible to the servlet,except that the servlet may see a SecurityException thrown when it tries to access a restricted resource. The servlet sandbox is a simple model, but it is already more potent than any other server extension technology to date.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

163

D.SUNITHA
Program:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

To Create Cookie

AddCookieServlet: import java.io.*; importjavax.servlet.*; importjavax.servlet.http.Cookie; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; public class AddCookieServlet extends HttpServlet { public void doPost(HttpServletRequestreq,HttpServletResponse IOException,ServletException { String cname,cvalue; cname=req.getParameter("n"); cvalue=req.getParameter("p"); Cookie c=new Cookie(cname,cvalue); res.addCookie(c); PrintWriter pw=res.getWriter(); pw.println("cookie added successfully"); } } res)throws

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

164

D.SUNITHA
Addc.html: <body>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<form name="f2" method="POST" action="./ac"> Name:<input type="text" name="n" value=" "><br> Password:<input type="password" name="p" value=""><br> <input type="submit" value="submit"> </form> <html>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

165

D.SUNITHA
PROCEDURE

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Saving the program: First we have to create a folder as servletsexin webapps folder as C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\

The servletsex contains WEB-INF folder and html files.

The WEB-INF folder having web.xml and classesfolder. Theclasses folder contains .class files of java servlet program. By this way we have to save the program.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

166

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Start Tomcat As explained, to start Tomcat, select Start Tomcat in the Startprogramsapache tomcatconfigure tomcat Then we have to start the tomcat at that window.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

167

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

After that we have to open TOMCAT MANAGER by Startprogramsapache tomcatTomcat manager

Start a Web Browser and Request the Servlet Start a Web browser and enter username and password. then you can go to servletsex in the list. a list of html files will open you have to click on addc.html

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

168

D.SUNITHA
OUTPUT:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

169

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

To Read the user id and passwords entered (user id and passwords)available in the cookies. GetCookieServlet: import java.io.*; importjavax.servlet.*; importjava.util.*; importjavax.servlet.http.Cookie; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; public class GetCookieServlet extends HttpServlet { public void doGet(HttpServletRequestreq,HttpServletResponse IOException,ServletException { res)throws

PrintWriter pw=res.getWriter(); Cookie[] c=req.getCookies(); for(inti=0;i<c.length;i++) { pw.println("Name is"+c[i].getName()); pw.println("Value is"+c[i].getValue()); } } }

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

170

D.SUNITHA
PROCEDURE:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Save the GetCookieServlet.classfile in classes folder. Start a Web browser and run the below URL for GetCookieServlet.classas http://127.0.0.1:8080/servletsex/GetCookieServlet

OUTPUT:

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

171

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

If he is a valid user (i.e., user-name and password match)you should welcome him by name(user-name)else you should display You are not an Authenticated user Validatelogin: importjavax.servlet.http.*; import java.io.*; importjavax.servlet.*; importjava.util.*; public class validatelogin extends HttpServlet { public void doPost(HttpServletRequestreq,HttpServletResponse IOException,ServletException { int t=0; String un,pw; un=req.getParameter("n"); pw=req.getParameter("p"); Enumeration e=getInitParameterNames(); while(e.hasMoreElements()) { String name=(String)e.nextElement(); String value=getInitParameter(name); Cookie c=new Cookie(name,value); res.addCookie(c); String name1=c.getName(); String value1=c.getValue(); if(un.equals(name1)&&pw.equals(value1)) t=1; }
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 172

res)throws

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

PrintWriter out=res.getWriter(); if(t==1) out.println("valid user!"); else out.println("Invalid User!"); out.close(); } }

Initlogc.html: <body> <form name="f2" method="POST" action="./clog"> Name:<input type="text" name="n" value=" "><br> Password:<input type="password" name="p" value=""><br> <input type="submit" value="submit"> </form> <html> PROCEDURE: Save the Validatelogin.classfile in classes folder.
C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\servletsex\WEB-INF\classes

Save the Insertreg.htmlinservletsexfolder.


C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\servletsex\

Start a Web browser and enter username and password. then you can go to servletsex in the list. a list of html files will open you have to click on Initlogc.html.itredirects tohttp://127.0.0.1:4040/servletsex/Validatelogin

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

173

D.SUNITHA
OUTPUT:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

174

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Use init-parameters to do this. Store the user-names and passwords in the WEBINF.xml and access them in the servlet by using the getInitParameters() method. (The below given web.xml file is common to all above three programs ie., for AddCooieServlet, GetCookieServlet and also for Validatelogin)

web.xml: <web-app> <servlet> <servlet-name>myservlet</servlet-name> <servlet-class>validatelogin</servlet-class> <init-param> <param-name>subbi</param-name> <param-value>sudha</param-value> </init-param> <init-param> <param-name>Mona</param-name> <param-value>Mona</param-value> </init-param> <init-param> <param-name>revanth</param-name> <param-value>kumar</param-value> </init-param> <init-param> <param-name>sanju</param-name> <param-value>jain</param-value> </init-param> </servlet> <servlet-mapping>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 175

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<servlet-name>myservlet</servlet-name> <url-pattern>/clog</url-pattern> </servlet-mapping> <servlet> <servlet-name>AddCookieServlet</servlet-name> <servlet-class>AddCookieServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AddCookieServlet</servlet-name> <url-pattern>/ac</url-pattern> </servlet-mapping>

<servlet> <servlet-name>GetCookieServlet</servlet-name> <servlet-class>GetCookieServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>GetCookieServlet</servlet-name> <url-pattern>/GetCookieServlet</url-pattern> </servlet-mapping> </web-app>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

176

WEEK-9

Date of Conduction: Date of Submission:

Date of Valuation Marks Awarded

: :

AIM;

Signature of Staff Member

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Install a Database (Mysql or Orcle). Create a table which should contain at least the following fields: name, password, email-id, phonenumber (these should hold the data from the registration form). Practice JDBC connectivity. Write a java Program/Servlet/JSP to connect to that database and extract data from the tables and display them. Experiment with various SQL queries. Insert the details of the users who register with the website, whenever a new user clicks the submit button in the registration page.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

177

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

DATABASE PROGRAMMING USING JDBC (Java database connectivity) Database programming has traditionally been a technological Tower Java is supposed to bring us the ability to"write once, compile once, and run anywhere," so it should bring it to us with database programming as well.Java's JDBC API gives us a shared language through which our applications can talk to database engines. Followingin the tradition of its other multi-platform APIs such as the AWT, JDBC provides us with a set of interfaces thatcreate a common point at which database applications and database engines can meet. What Is The JDBC? As I mentioned a moment ago, JDBC stands for Java Database Connectivity. What is this JDBC besides a nifty acronym? It refers to several things, depending on context: Its a specification for using data sources in Java applets and applications. Its an API for using low-level JDBC drivers. Its an API for creating the low-level JDBC drivers, which do the actual connecting/transacting with data sources. Its based on the X/Open SQL Call Level Interface (CLI) that defines how client/server interactions are implemented for database systems.

The Structure of JDBC JDBC accomplishes its goals through a set of Java interfaces, each implemented differently by individualvendors. The set of classes that implement the JDBC interfaces for a particular database engine is called aJDBC driver. In building a database application, you do not have to think about the implementation ofthese underlying classes at all; the whole point of JDBC is to hide the specifics of each database and letyou worry about just your application.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

178

D.SUNITHA
JDBC

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

JavaSoft developed a single API for database access--JDBC. As part of this process, they kept three main goals inmind: JDBC should be an SQL-level API. JDBC should capitalize on the experience of existing database APIs. JDBC should be simple.

An SQL-level API means that JDBC allows us to construct SQL statements and embed them inside Java API calls. Inshort, you are basically using SQL. But JDBC lets you smoothly translate between the world of the database and theworld of the Java application.JDBC attempts to remain as simple as possible while providing developers with maximum flexibility. A keycriterion employed by JavaSoft is simply asking whether database access applications read well. Thesimple and common tasks use simple interfaces, while more uncommon or bizarre tasks are enabledthrough extra interfaces. For example, three interfaces handle a vast majority of database access. JDBCnevertheless provides several other interfaces for handling more complex and unusual tasks.

. The architecture of the JDBC. Databases and and Drivers In putting together the examples in this book, I used both an mSQL database If you do not have a corporate pocketbook to back up your database purchase, mSQL is probably the most feasible solution. You should keep in mind, however, that mSQL does not allow you to abort transactions and does not support the stored procedures. Whatever your database choice, you must set up your database engine, create a database, and create the tables shown in the Chapter 3 data model before you can begin writingJDBC code. Once your database engine is installed and your database is all set up, you will need a JDBCdriver for that database engine.
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 179

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

The more commercial database engines like Oracle have commercialJDBC drivers. Driver categories: Type 1:JDBC-ODBC bridge These drivers use a bridging technology to access a database. The JDBC-ODBC bridge that comeswith the JDK 1.1 is a good example of this kind of driver. It provides a gateway to the ODBC API.Implementations of that API in turn do the actual database access. Bridge solutions generallyrequire software to be installed on client systems, meaning that they are not good solutions forapplications that do not allow you to install software on the client. Type 2:Native API connection driver The type 2 drivers are native API drivers. This means that the driver contains Java code that callsnative C or C++ methods provided by the individual database vendors that perform the databaseaccess. Again, this solution requires software on the client system. Type 3:Network connection driver Type 3 drivers provide a client with a generic network API that is then translated into databasespecific access at the server level. In other words, the JDBC driver on the client uses sockets to calla middleware application on the server that translates the client requests into an API specific tothe desired driver. As it turns out, this kind of driver is extremely flexible since it requires no codeinstalled on the client and a single driver can actually provide access to multiple databases. Type 4: Database Protocol driver Using network protocols built into the database engine, type 4 drivers talk directly to the database using Java sockets. This is the most direct pure Java solution. In nearly every case, this type of driver will come only from the database vendor. Alternatives to JDBC Without JDBC, only disparate, proprietary database access solutions exist. These proprietary solutions force the developer to build a layer of abstraction on top of them in order to create database independent code. Only after that abstraction layer is complete can the developer move to actually writing the application. In addition, the experience you have with that abstraction layer does not translate immediately to other projects or other employers who are almost certainly using their own abstraction layers to provide access to a variety of database engines. Connecting to the Database Any JDBC application we write needs to be able to run from start to finish without ever referencing a specific JDBC implementation. An application uses JDBC as an interface through which it passes all of its databases requests.
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 180

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

The JDBC Support Classes JDBC provides a handful of other classes and interfaces that support JDBC's core functionality. Many ofthem are more SQL-friendly extensions of java.util classes like java.sql.Date and java.sql.Numeric. Othersare exception classes that get thrown by JDBC calls. java.sql.Types The Types class provides constants that identify SQL data types. Each constant that represents anSQLdata type that is mapped to an integer is defined by the XOPEN SQL specification. You will see this classused extensively in the next chapter. java.sql.SQLException The SQLException class extends the general java.lang.Exception class that provides extra informationabout a database error. The information provided by a SQLException includes: The SQLState string describing the error according to the XOPEN SQLState conventions.Thedifferent values of this string are defined in the XOPEN SQL specification.The database-specific vendor error code. This code is usually some number that you have to lookup in the obscure reference section of your database's documentation. Fortunately, the errorshould be sufficiently described through the Java Exception class's getMessage() method.A chain of exceptions leading up to this one. This is one of the niftier features of this class.Specifically, if you get several errors during the execution of a transaction, you can chain them alltogether in this class. This is frequently useful when you have exceptions that you want to let theuser to know about, but you do not want to stop processing. try { Connection connection = DriverManager.getConnection(url, uid, pass); } catch( SQLExceptione ) { e.printStackTrace(); while( (e = e.getNextException()) != null ) { // while more exceptionse.printStackTrace(); } } java.sql.SQLWarning and java.sql.DataTruncation Depending on the driver you are using, non-fatal errors might occur that should not halt applicationprocessing. JDBC provides an extension to the SQLException class called SQLWarning. When a JDBCobject--like a ResultSet--encounters a warning situation internally, it creates a SQLWarning object andadds it to a list of warnings that it keeps. At any point, you can get the warnings for any JDBC object byrepeatedly calling the getWarnings() method until it returns null. The DataTruncation class is a special kind of warning that a JDBC implementation throws when JDBCunexpectedly truncates a data value. A DataTruncation object is chained as a warning on a read operationand thrown as an exception on a write.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

181

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

java.sql.Date, java.sql.Time, and java.sql.Timestamp Portable date handling among database engines can be very complex--each relational databasemanagement system (RDBMS) seems to have its own unique way of representing date information. Thesethree classes all extend the functionality of other Java objects to provide a portable representation oftheir SQL counterparts. The Date and Time classes represent different levels of granularity as well asdifferent means of expressing information already found in the java.util.Date class. The java.sql.Dateclass, for example, provides methods to express just the date, month, and year, while the Time classworks in terms of hours, minutes, and seconds. And finally the Timestamp class takes the java.util.Dateclass down to nanosecond granularity. java.sql.DriverPropertyInfo I can almost guarantee that you will never use this class. It is designed for Rapid Application Development(RAD) tools like Symantec VisualCafe and Borland JBuilder. In order to provide a graphical user interfacefor rapid prototyping, these tools need to know what properties are required by a given JDBCimplementation in order to connect to the database. Most drivers, for example, need to know the username and password of the user connecting to the database. That and anything else the driver needs inorder to connect to the database will be returned as an array of DriverPropertyInfo objects from thejava.sql. Driver getPropertyInfo() method. Development tools can call this method to find out whatinformation they should prompt the user for before connecting to the database. Connection to database: The DriverManager.getConnection method in the JDBC API uses this URL when attempting to start a connection. Remember that a valid driver must be registered with the JDBC DriverManager before attempting to create this connection (as I discussed earlier in the Registering and Calling JDBC Drivers section). The DriverManager.getConnection method can be passed in a Property object where the keys user, password, and even server are set accordingly. The direct way of using the getConnection method involves passing these attributes in the constructor. The following is an example of how to create a Connection object from the DriverManager.getConnection method. String url="jdbc:msql://mydatabaseserver.com:1112/databasename"; Name = "pratik"; password = ""; Connection con; con = DriverManager.getConnection(url, Name, password); // remember to register the driver before doing this!
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 182

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Install a Database (Mysql or Orcle). Step-1:

Step-2:

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

183

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Step-3:

Step-4:

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

184

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Step-5:

Step-6:

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

185

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Step-7:

Step-8:

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

186

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Step-9:

Step-10:

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

187

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Step-11:

Step-12:

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

188

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Step-13:

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

189

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Step-14:

For JDBC Connections we have to do the following:


To practice JDBC connections we have to do the following things.(This is for type-4 Driver).
1. Copy the Servlet-api.jarfile from the following path C:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib

Copy the above file and paste it on the following path


C:\Program Files\Java\jre1.5.0_01\lib\ext

And also select the ojdbc14_g.jar file from the following path C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib

Copy the above file and paste it in the following path


INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 190

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

C:\Program Files\Java\jre1.5.0_01\lib\ext

2. Copy the Servlet-api.jarfile from the following path C:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib

Copy the above file and paste it on the following path


C:\Program Files\Java\jdk1.5.0_01\lib And also select the ojdbc14_g.jar file from the following path C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib

Copy the above file and paste it in the following path


C:\Program Files\Java\jdk1.5.0_01\lib

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

191

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

3. Copy the Servlet-api.jarfile from the following path C:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib

Copy the above file and paste it on the following path C:\Program Files\Java\jdk1.5.0_01\jre\lib\ext
And also select the ojdbc14_g.jar file from the following path C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib

Copy the above file and paste it in the following path


C:\Program Files\Java\jdk1.5.0_01\jre\lib\ext

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

192

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Create a table which should contain at least the following fields: name, password, email-id, phonenumber (these should hold the data from the registration form).

Sql Commands: SQL>connect system/manager; Connected. SQL>create table reg( un varchar2(10),pwd varchar2(10),e varchar2(10),ph varchar2(10)); table created. SQL>descreg;
NameNull? Type ---------------------------VARCHAR2(10) VARCHAR2(10) VARCHAR2(10) VARCHAR2(1)

--------------------------------- -------UN PWD E PH

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

193

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

OUTPUT:

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

194

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Practice JDBC connectivity. Write a JavaServlet Program to connect to that database and extract data from the tables and display them. Experiment with various SQL queries.

Insert the details of the users who register with the website, whenever a new user clicks the submit button in the registration page.

PROGRAM:
Insertreg.java importjavax.servlet.*; import java.io.*; importjava.sql.*; importjavax.servlet.http.*; public class insertreg extends HttpServlet { public void doPost(HttpServletRequestreq,HttpServletResponse ServletException,IOException { PrintWriterpsw=res.getWriter(); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:XE","system","manag er"); PreparedStatementpstmt=con.prepareStatement("insert into reg values(?,?,?,?)"); res.setContentType("text/html"); String un=req.getParameter("txt"); String pw=req.getParameter("pwd"); String e=req.getParameter("email"); String ph=req.getParameter("num");
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 195

res)throws

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

pstmt.setString(1,un); pstmt.setString(2,pw); pstmt.setString(3,e); pstmt.setString(4,ph); int x=pstmt.executeUpdate(); if (x==1) psw.println("Information committed"); else psw.println("Could not commit"); pstmt.close(); con.close(); } catch(Exception ex) { psw.println(ex); } } } Insertreg1.html <html> <body bgcolor=lightblue> <div align="center"> <table cellspacing=10 > <form name=register method="post" action="./ireg"> <tr> <td>User name</td> <td><input type="text" name="txt"><br></td>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 196

D.SUNITHA
</tr> <tr>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<td>Password</td><td> <input type="password" name="pwd"></td> </tr> <tr> <td>E-mail id </td> <td><input type="text" name="email"></td> </tr> <tr> <td>Phone no.</td> <td><input type="text" name="num"></td> </tr>

<tr> <td>Submit the data:</td> <td><input type="submit" value="SUBMIT" > <input type="reset" value="RESET"></td> </tr> </form> </table> </div> </body> </html>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

197

D.SUNITHA
Web.xml <web-app> <servlet>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<servlet-name>jd</servlet-name> <servlet-class>insertreg</servlet-class> </servlet> <servlet-mapping> <servlet-name>jd</servlet-name> <url-pattern>/ireg</url-pattern> </servlet-mapping> </web-app> PROCEDURE: By using using the reg table information we are performing JDBC connections. the table reg will be created in Orcle10g as shown in the above SQL command line. Save the Insertreg.classfile in classes folder.
C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ jdbcsrvlts\WEB-INF\classes

Save the Insertreg.htmlin jdbcsrvlts folder.


C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\

Save the web.xml class file in WEB-INF folder.


C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ jdbcsrvlts\WEB-INF\

Start a Web browser and enter username and password. Then you can go to jdbcsrvlts in the list. a list of html files will open you have to click on Insertreg.html Enter the given details click on submit button. you are redirected to Information Commited window. Take a look on database and check the values of tables whether your given information is stored or not as using command: Select *from reg;

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

198

D.SUNITHA
OUTPUT:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

199

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

200

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Practice JDBC connectivity. Write a JSP Program to connect to that database and extract data from the tables and display them. Experiment with various SQL queries.

Insert the details of the users who register with the website, whenever a new user clicks the submit button in the registration page.

Program : Insertreg.jsp <%@ page language="java" import="java.sql.*"%> <% String un,pwd,e,ph; un=(String)request.getParameter("unm"); pwd=(String)request.getParameter("pwd"); e=(String)request.getParameter("email"); ph=(String)request.getParameter("num"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:XE","system","manag er"); Statement st=con.createStatement(); String sql=" insert into regvalues('"+un+"','"+pwd+"','"+e+"','"+ph+"')" ; int x=st.executeUpdate(sql); if(x==1) out.println("1 row inserted"); else out.println("not inserted"); st.close(); con.close();
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 201

D.SUNITHA
}

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

catch(SQLException se) { out.println("Error:"+se.toString()); } %> Insertreg.html <html> <body bgcolor=lightblue> <div align="center"> <table cellspacing=10 > <form method="GET" action="./insertreg.jsp"> <tr> <td>User name</td> <td><input type="text" name="unm"><br></td> </tr> <tr> <td>Password</td><td> <input type="password" name="pwd"></td> </tr> <tr> <td>E-mail id </td> <td><input type="text" name="email"></td> </tr> <tr> <td>Phone no.</td> <td><input type="text" name="num"></td>
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 202

D.SUNITHA
</tr> <tr>

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

<td>Submit the data:</td> <td><input type="submit" value="SUBMIT" > <input type="reset" value="RESET"></td> </tr> </form> </table> </div> </body> </html>

PROCEDURE: Save the Insertreg.jspfile in jdbcsrvltsfolder.


C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ jdbcsrvlts\

Save the Insertreg.htmlin jdbcsrvlts folder.


C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\jdbcsrvlts\

Start a Web browser and enter username and password. Then you can go to jdbcsrvlts in the list. a list of html files will open you have to click on Insertreg.html Enter the given details click on submit button. you are redirected to Information Commited window. Take a look on database and check the values of tables whether your given information is stored or not as using command: Select *from reg;

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

203

D.SUNITHA
OUTPUT:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

204

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

205

WEEK-10

Date of Conduction: Date of Submission:

Date of Valuation Marks Awarded

: :

Signature of Staff Member

D.SUNITHA
AIM;

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Write a JSP which does the following job: Insert the details of the 3 or 4 users who register with website (week-9)by using registration form. Authenticate the user when he submits the login form using the user and pass word from the database(similar to week-8 instead of cookies).

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

206

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB JSP

JavaServer Pages (JSP) technology enables you to mix regular, static HTML with dynamically generatedcontent. To simple write the regular HTML in the normal manner, using familiar Web-page-building tools.You then enclose the code for the dynamic parts in special tags, most of which start with <% and end with %>. We can think of servlets as Java code with HTML inside; you can think of JSP as HTML with Java codeinside. Now, neither servlets nor JSP pages are restricted to using HTML, but they usually do, and thisover-simplified description is a common way to view the technologies. Now, despite the large apparentdifferences between JSP pages and servlets, behind the scenes they are the same thing. JSP pages aretranslated into servlets, the servlets are compiled, and at request time it is the compiled servlets thatexecute. So, writing JSP pages is really just another way of writing servlets. Even though servlets and JSP pages are equivalent behind the scenes, they are not equally useful in allsituations. Separating the static HTML from the dynamic content provides a number of benefits overservlets alone, and the approach used in JavaServer Pages offers several advantages over competingtechnologies. Benefits of JSP JSP pages are translated into servlets. So, fundamentally, any task JSP pages can perform could also beaccomplished by servlets. However, this underlying equivalence does not mean that servlets and JSPpages are equally appropriate in all scenarios. The issue is not the power of the technology; it is theconvenience, productivity, and maintainability of one or the other. After all, anything you can do on aparticular computer platform in the Java programming language you could also do in assembly language.But it still matters which you choose. JSP provides the following benefits over servlets alone: It is easier to write and maintain the HTML. Your static code is ordinary HTML: no extra backslashes, no double quotes, and no lurking Java syntax. You can use standard Web-site development tools. For example, we use Macromedia Dreamweaver for most of the JSP pages in the book. Even HTML tools that know nothing about JSP can be used because they simply ignore the JSP tags. You can divide up your development team. The Java programmers can work on the dynamic code. The Web developers can concentrate on the presentation layer. On large projects, this division is very important. Depending on the size of your team and the complexity of your project, you can enforce a weaker or stronger separation between the static HTML and the dynamic content.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

207

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

THE ANATOMY OF JSP

The visible elements that make up a JSP page can include the following: Directive elements Template data Action Scripting elements

A JSP page does not need to have all of these visible elements, but you will very likely encounter all ofthem if you look into any moderately complex JSP project. The following sections briefly describe eachvisible element. Directives Unlike other JSP elements, directives are not used to generate output directly. Rather, they are used tocontrol some characteristics of a JSP page. Directives may be used to give special instructions to the JSPcontainer about what to do during the translation of the page. You can always tell a directive from otherelements because it is enclosed in a special set of braces:<%@ ... directive ... %> Three directives are allowed in JSP: page directive taglib directive include directive

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

208

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

XML-compatible syntax A directive for example, a taglib directive typically appears in a JSP as <%@ taglib .... %>The same element can also appear in a JSP as : <jsp:directive.taglib .... />This is an XMLcompatible syntax for expressing the JSP directive. There are many advantages toexpressing a JSP page in XML. For example, many developer tools can work with XML documentsdirectly. Enterprise technologies, such as Web services, also make extensive use of XML. The emergingnew XHTML standard is also XML-based. Because JSP works intimately with these technologies andthe standard <%@ ... %> syntax is not valid XML, this alternative notation is necessary.All professional JSP developers are trained in the <%@ ... %> notation. There are millions of lines ofexisting JSP code in this notation, so it will likely be supported for the foreseeable future. Template data Template data is static text. This static text is passed directly through the JSP container unprocessed. Forexample, it may be text that provides static HTML. The template data is the static HTML.Although most JSP pages are used in generating HTML pages, JSP is not specific to HTML generation.If a JSP page is expressed in XML syntax, typically contained in a .jspx file, the template data portionmay have characters that need to be escaped. For example, the characters < and > are not alloweddirectly in an XML document and must be expressed as &lt; and &gt;, respectively. Action Action elements are JSP elements that are directly involved in the processing of the request. In mostcases, action elements enable you to access data and manipulate or transform data in the generation ofthe dynamic output. For example, an online store may have a JSP page that displays a shopping cart. Thiscart JSP shows the products that you have purchased. Action elements may be used to generate thelisting of the products (dynamic content) on the page and to calculate the cost and shipping (dynamiccontent), while template data (static HTML) is used to display the logo and shipping policy statements.Action elements can be either standard or custom. A standard action is dependably available in every JSPcontainer that conforms to the JSP 2.0 standard.A custom action is an action created using JSPs tag extension mechanism. This mechanismenables developers to create their own set of actions for manipulating data or generating dynamic outputwithin the JSP page. Every XML tag has a name, optional attributes, and an optional body. For example, the standard <jsp:include> action can be coded as follows: <jsp:include page=news.jsp flush=false/> The name of this tag is jsp:include, the attributes are page and flush, and this <jsp:include>instance does not have a body. The XML empty notation is used.
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 209

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

An XML tag can also have a body containing other tags, of course: <jsp:include page=news.jsp flush=false> <jsp:param name=user value=$,param.username-/></jsp:include> In this tag, the name is still jsp:include and the attributes are still page and flush, but now the body is nolonger empty. Instead, the body contains a <jsp:param> standard action. After template data, actions arethe next most frequently used elements in JSP coding. Actions are synonymous with tags because everyaction is an XML tag. The terms are used interchangeably in this book, just as they are in the JSPdeveloper community. Scripting elements The practice of embedding code in another programming language within a JSP page is called scripting.Scripting elements are embedded code, typically in the Java programming language, within a JSP page. There are three different types of scripting elements: Declarations Scriptlets Expressions Declarations are Java code that is used to declare variables and methods. They appear as follows: <%! ... Java declaration goes here... %> The XML-compatible syntax for declarations is: <jsp:declaration> ... Java declaration goes here ... </jsp:declaration> Scriptlets are arbitrary Java code segments. They appear as follows: <% ... Java code goes here ... %> The XML-compatible syntax for scriptlets is: <jsp:scriptlet> ... Java code goes here ...</jsp:scriptlet> Expressions are Java expressions that yield a resulting value. When the JSP is executed, this value isconvertedto a text string and printed at the location of the scripting element. Expression scripting elements appear as:<%= ... Java expression goes here ... %> The XML-compatible syntax for expressions is: <jsp:expression> ... Java expression goes here ... </jsp:expression>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

210

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

JSP PROCESSING Just as a web server needs a servlet container to provide an interface to servlets, the server needs a JSPcontainer to process JSP pages. The JSP container is responsible for intercepting requests for JSP pages. Toprocess all JSP elements in the page, the container first turns the JSP page into a servlet (known as the JSPpage implementation class). The conversion is pretty straightforward; all template text is converted toprintln( ) statements similar to the ones in the hand coded servlet and all JSP elements are converted toJava code that implements the corresponding dynamic behavior. The container then compiles the servletclass. Converting the JSP page to a servlet and compiling the servlet form the translation phase. The JSPcontainer initiates the translation phase for a page automatically when it receives the first request for thepage. Since the translation phase takes a bit of time, the first user to request a JSP page notices a slightdelay. The translation phase can also be initiated explicitly; this is referred to asprecompilation of a JSPpage. Precompiling a JSP page is a way to avoid hitting the first user with this delay. The JSP container isalso responsible for invoking the JSP page implementation class (the generated servlet) to process eachrequest and generate the response. This is called the request processing phase. The two phases areillustrated inFigurebelow

As long as the JSP page remains unchanged, any subsequent request goes straight to the requestprocessing phase (i.e., the container simply executes the class file). When the JSP page is modified, it goesthrough the translation phase again before entering the request processing phase. The JSP container isoften implemented as a servlet configured to handle all requests for JSP pages. In fact, these twocontainers--a servlet container and a JSP container-are often combined in one package under the nameweb container. A JSP page is really just another way to write a servlet without having to be a Javaprogramming wiz. Except for the translation phase, a JSP page is handled exactly like a regular servlet: it'sloaded once and called repeatedly, until the server is shut down. By virtue of being an automaticallygenerated

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

211

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

servlet, a JSP page inherits all the advantages of a servlet as platform and vendorindependence, integration, efficiency, scalability, robustness, and security. JSP APPLICATION DESIGN WITH MVC JSP technology can play a part in everything from the simplest web application, such as an online phonelist or an employee vacation planner, to full-fledged enterprise applications, such as a human-resourceapplication or a sophisticated online shopping site. How large a part JSP plays differs in each case, ofcourse. In this section, I introduce a design model called ModelView-Controller (MVC), suitable for bothsimple and complex applications. MVC was first described by Xerox in a number of papers published in the late 1980s. The key point ofusing MVC is to separate logic into three distinct units: the Model, the View, and the Controller. In aserver application, we commonly classify the parts of the application as business logic, presentation, andrequest processing. Business logic is the term used for the manipulation of an application's data, such ascustomer, product, and order information. Presentation refers to how the application data is displayed tothe user, for example, position, font, and size. And finally, request processing is what ties the businesslogic and presentation parts together. In MVC terms, the Model corresponds to business logic and data,the View to the presentation, and the Controller to the request processing. MVC Architecture

An application data structure and logic (the Model) is typically the most stable part of an application,while the presentation of that data (the View) changes fairly often. Just look at all the face-lifts many websites go through to keep up with the latest fashion in web design. Yet, the data they present remains thesame. Another common example of why presentation should be separated from the business logic is thatyou may want to present the data in different languages or present different subsets of the data tointernal and external users. Access to the data through new types of devices, such as cell phones andpersonal digital assistants (PDAs), is the latest trend. Each client type requires its own presentationformat. It should come as no surprise, then, that separating business logic from the presentation makes iteasier to evolve an
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 212

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

application as the requirements change; new presentation interfaces can bedeveloped without touching the business logic.

JSP pages are used as both the Controller and the View, and JavaBeans components are used as theModel. A single JSP page that handles everything can use separate pages for the Controller and the Viewto make the application easier to maintain. Many types of real-world applications can be developed thisway, but what's more important is that this approach allows you to examine all the JSP features withoutgetting distracted by other technologies.

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

213

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Insert the details of the 3 or 4 users who register with website (week-9)by using registration form. The below output can be from week-9.By the Procedure of week-9 we can insert 3 users are i.e., USERNAME PASSWORD nec it mounica it suji sujitha

OUTPUT:

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

214

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Write JSP for Authenticate users using DATABASE PROGRAMS: Login.jsp <%@ page language="java" import="java.sql.*"%> <%@ page import="java.util.*"%> <%! String un,pw; inti=0; %> <% un=request.getParameter("txt"); pw=request.getParameter("pwd"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:XE","system","manag er"); Statement st=con.createStatement(); ResultSetrs=st.executeQuery("select * from login"); while(rs.next()) { String user=rs.getString("username"); String pass=rs.getString("password"); if(un.equals(user)&&pw.equals(pass)) { i++; out.println("Valid user!");
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 215

D.SUNITHA
break; } } if(i==0)

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

out.println("Invalid user!"); rs.close(); st.close(); con.close(); } catch(Exception ex) { out.println(ex); } %> login.html <html> <body> <form action="./login.jsp" method="POST"> username:<input type="text" name="txt"><br> password:<input type="password" name="pwd"><br> <input type="submit" value="submit"> </form> </body> </html>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

216

D.SUNITHA
PROCEDURE:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Create a jsj(created by user) folder in webapps.we have to maintain EMPTY folder as WEB-INF .it contains EMPTYclasses folder. Save the Login.jspfile in jsj folder.
C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ jsj\

Save the Insertreg.htmlinjsjfolder.


C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\jsj\

Start a Web browser and enter username and password. Then you can go to jsj in the list. a list of html files will open you have to click on login.html Enter the given details click on submit button. If you are a valid user you are redirected to valid user if not Invalid user! The validation of users based on the values which are stored in the table called as login. The details which are entered are in the database you are a valid user if not Invalid user!

OUTPUT:

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

217

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

218

WEEK-11

Date of Conduction: Date of Submission:

Date of Valuation Marks Awarded

: :

Signature of Staff Member

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

Create tables in the database which contain in the details of items (books in our ease like (Book name, Price, Quantity, Amount) of each category. Modify your catalogue page (week2) in such a way that you should connect to the database and extract data from the tables and display them in the catalogue page using JDBC. PROGRAM: Books.jsp <%@ page language="java" import="java.sql.*"%> <html> <body> <br><br><br><br> <table border=1 align=center> <tr> <th>bname</th> <th>price</th> <th>quantity</th> <th>amount</th> </tr> <% try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:XE","system","manag er"); Statement st=con.createStatement(); ResultSetrs=st.executeQuery("select * from bookdetails"); while(rs.next()) { String bname=rs.getString("bname");
INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE 219

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

String price=rs.getString("price"); String quantity=rs.getString("quantitiy"); String amount=rs.getString("amount"); %> <tr> <td><%=bname%></td> <td><%=price%></td> <td><%=quantity%></td> <td><%=amount%></td> <td><input type=submit value=addtocart></td>

</tr> <% } } catch(Exception e) { out.println(e); } %> </table> </body> </html>

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

220

D.SUNITHA
PROCEDURE:

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

First you have to create a Database using SQL.Name the Database table as bookdetails. The table contains BNANE,PRICE,QUANTITY,and AMOUNT. Insert data into bookdetails table. Insert into bookdetailsvalues(&bname,&price,&quntity,&amount); Write a JSP code for above table using JDBCand establish connection between that. Save the Books.jspfile in jsj folder.
C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\ jsj\

Start a Web browser and enter username and password. Then you can go to jsj in the list. a list of html files will open you have to click on Books.jsp OUTPUT:

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

221

D.SUNITHA

ADVANCED JAVA AND WEB TECHNOLOGIES LAB

INFORMATION TECHNOLOGY | NARASARAOPETA ENGINEERING COLLEGE

222