You are on page 1of 132

Week-1 ----------------------------------------------------------------------------------------------------------AIM: Design the static web pages required for an online book store web site.

1) HOME PAGE DESCRIPTION: The static home page must contain three frames. Top frame : Logo and the college name and links to Home page, Login page, Registration page, Left frame : At least four links for navigation, which will display the catalogue of respective links. For e.g.: When you click the link CSE the catalogue for CSE 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 web site. PROGRAM: Homepage <head> <frameset rows="20 %,* "> <frame src="topframe.htm l"name="f1"> <frameset cols="20 %,* "> <frame src="leftframe.htm l"name="f2"> <frame src="right frame.htm l"name="f3"> </frameset> </frameset> </he ad>
1

OUTPUT:

Top frame: <htm l> <body> <p> <img src="C:\Documents Pictures\Sample he ight =100 "> <h1 align=cente r>Online book store</h1> </p> <br> and Settings\All Users\Docum ent s\My align=left width =10 0 Pictures\Winte r.jpg "

<p> <h2>&nbsp;nbsp;&nbsp;&nbsp; <a href="homepage.htm l" target=_parent> Home </a> &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; <a href="login.ht ml" target="f3"> login </a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="registration.htm l" target="f3"> registration </a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nbsp;&nbsp;&nbsp; <a href="catalogue .htm l" target="f3"> Catalogue </a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="cart.htm l" target="f3"> Cart </a> &nbsp; </h2> </p> </body> </htm l>

OUTPUT:

Leftframe: <htm l> <body> <a href=cse.htm l <a <a <a href=civil.htm l target="f3"> h3>Civil</h3> /a> < < 4 target="f3"> h3>CSE</h3> < href=ece.htm l href=eee.htm l

</a> br> br><br> br> br> < < < < target="f3"> h3>ECE</h3> /a> br> br><br> br> br> < < < < < < target="f3"> h3>EEE</h3> /a><br> br><br> br> br> < < < < <

</body> </htm l>

OUTPUT:

Right frame: <htm l> <body bg color="pink"> <p> <h2 align="cente r"> <font face="times new roman" color="gree n" >Online boo k stor e information </font> </h2>

<h3> corsiva"

&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<font face="monotyp e color=blue > This is the online boo k stor e developed

by students of pvpsit.It cont ains boo k catalogue of various branch es like cse,ece,eee ,civil </font ></h3> </p> </body> </htm l> OUTPUT:

2) LOGIN PAGE DESCRIPTION: The login page contains the user name and the password of the user to authenticate. PROGRAM:

<htm l> <head> <p style= position:absolute ; "> </he ad> <body backgroun d=E:\1.jpg > <for m action="index.jsp" method="get"> <label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font face="comic sans ms" color="gree n" size="5">Login </font> </label> &nbsp;&nbsp;&nbsp;&nbsp; <input typ e="text" '><br> br> br> < < <label> <font <input face="comic sans </label> size="20 " maxlength ="20 "> <input value ="submit">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input typ e="reset"> </form> </body> </htm l> OUTPUT: typ e="submit" ms" color="gree n" size="5">Pass word </fon t> type ="passwor d" size="20 " maxlength ="20 " value =' "backgroun d:yellow; top:10 0px; left:250 px;

<br> br> <br> &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;&nbsp; <

3) CATOLOGUE PAGE DESCRIPTION: The catalogue page should contain the details of all the books available in the web site 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. PROGRAM: <htm l> <body> <cente r> <table border=1> <tr> <th Boo k Preview </th> > <th Boo k Details </th> > <th Pri ce </th> > <th> Payment </th> </tr> <tr> <td> </img> </td> <td> <pre> <font face="comic sans ms" size=4 color="gree n" > book:XML Bible Auth or:winston Publishe r:Wiesley </font> </pre> </td> <td>&nbsp;$4 0 &nbsp; </td> <img src="C:\Do cuments and Settings\All users\My Docum ent s\My Pictures\xml.bmp" width =10 0 he ight =50 >

<td &nbsp; &nbsp; <a href="cart.htm l" target="_blank"> > <img src="C :\Do cuments </a > &nbsp; &nbsp; </td> </tr> <tr> <td> </img> </td> <td> <pre> <font face="comic sans ms" size=4 color="gree n" > boo k:Java 2 Auth or:Watson Publi sher:B PB pu blications </font> </pre> </td> <td>&nbsp; $4 0 &nbsp;</td> <td &nbsp; &nbsp; <a href="cart.htm l" target="_blank"> > <img src="C :\Do cuments </a > &nbsp; &nbsp; </td> </tr> </table> </cente r> </body> </htm l> OUTPUT: and Settings\All users\My Docum ent s\My Pictures\cart.bmp" width ="150 " he ight ="100 "> /img> < <img src="C:\Do cuments and Settings\All users\My Docum ent s\My Pictures\java.bmp" width =10 0 he ight =50 > and Settings\All users\My Docum ent s\My Pictures\cart.bmp" width ="150 " he ight ="100 "> /img> <

RESULT: Thus the home page, login page, catalogue page for the online book store are created successfully

Week-2 -

Date: 30-06-08

----------------------------------------------------------------------------------------------------------AIM: Design of the cart page and the registration page required for online book store. 4) CART PAGE DESCRIPTION: The cart page contains the details about the books which are added to the cart. PROGRAM: <htm l> <body> <cente r><br> br> br> < < <img src=E:\aa .jpg > <table bor de r=1 cellpadd ing=cente r> <thead> <tr> <th >Boo k name</th> <th >price</th> <th >quant ity</th> <th >amount </th> </tr> </the ad> <tr> <td>java 2</td> <td>$45 </td> <td>2</td> <td>$70 </td> </tr> <tr>

<td XML bible</td> > <td $20 </td> > <td 5</td> > <td $40 </td> > </tr> <th colspan=4>total amount =$110 > </th> </tr> </table> </cente r> </body> </htm l> OUTPUT:

5) REGISTRATION PAGE DESCRIPTION: Create a registration form with the following fields 1)Name(Textfield) 2) Password (password field) 3) E-mail id (text field) 4) Phone number (text field) 5) Sex (radio button) 6) Date of birth (3 select boxes) 7) Languages known (check boxes English, Telugu, Hindi, Tamil) 8) Address (text area) PROGRAM: <htm l> <body> <cente r> <img src=E:\aaa.jpg align=left> <form> <label>name</label> <input typ e="text" size="20 "> br> br> <br> < < <label>password</label> <input typ e="p asswor d" size="20 " maxsize="28 "> br> <br> <br> < <label>email</label> <input typ e="text" size="30 "> br> <br> <br> < <label>phone no</label> <input typ e="text" size="2"> <input typ e="text" size="6"> <input typ e="text" size="10 "> br> <br> <br> < <label>Sex</label>

<input typ e="radio" name="sex">m <input typ e="radio" name="sex">f <br> <br> <br> <label> date of birth </label> <select> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <select> <option>jan</option> <option>feb</option> <option>mar</option> <option> pr</option> a </select> <select> <option>1980 </option> <option>1981 </option> <option>1982 </option> <option>1983 </option> </select> <br> <br> <br> <label> Languages Known </label> &nbsp; &nbsp; <input typ e="chec kbox"> Engli sh &nbsp; &nbsp;&nbsp; <input typ e="chec kbox"> Telugu &nbsp; &nbsp; &nbsp; <input typ e="chec kbox"> Hindi &nbsp; &nbsp; &nbsp; <input typ e="chec kbox"> Tamil <br> <br> <br> <label> Add ress </label> <tex tarea ro ws= 5 cols=20 scrolling="yes"> </te xtarea> </cente r> </body>

</htm l>

OUTPUT:

RESULT: Thus the registration and cart pages for online book store pages are created successfully

Week-3 -

Date: 14-07-08

----------------------------------------------------------------------------------------------------------AIM: Write JavaScript to validate the following fields of the above registration page. 1. Name (Name should contains alphabets and the length should not be less than 6 characters). 2. Password (Password should not be less than 6 characters length). 3. E-mail id (should not contain any invalid and must follow the standard pattern name@domain.com) 4. Phone number (Phone number should contain 10 digits only). DESCRIPTION: JavaScript is a simple scripting language invented specifically for use in web browsers to make websites more dynamic. On its own, HTML is capable of outputting more-or-less static pages. Once you load them up your view doesn't change much until you click a link to go to a new page. Adding JavaScript to your code allows you to change how the document looks completely, from changing text, to changing colors, to changing the options available in a drop-down list. JavaScript is a client-side language. JavaScripts are integrated into the browsing environment, which means they can get information about the browser and HTML page, and modify this information, thus changing how things are presented on your screen. This access to information gives JavaScript great power to modify the browsing experience. They can also react to events, such as when the user clicks their mouse, or points to a certain page element. This is also a very powerful ability. Regular Expressions: One of the most common situations that come up is having an HTML form for users to enter data. Normally, we might be interested in the visitors name, phone number and email address, and so forth. However, even if we are very careful about putting some hints next to each required field, some visitors are going to get it wrong, either

accidentally or for malicious purposes. Heres where regular expressions come in handy. A regular expression is a way of describing a pattern in a piece of text. In fact, its an easy way of matching a string to a pattern. We could write a simple regular expression and use it to check, quickly, whether or not any given string is a properly formatted user input. This saves us from difficulties and allows us to write clean and tight code. A regular expression is a JavaScript object. There are multiple ways of creating them. They can be created statically when the script is first parsed or dynamically at run time. A static regular expression is created as follows: regx=/fish|fow1/; Dynamic patterns are created using the keyword to create an instance of the RegExp class: regx=new RegExp(fish|fow1); Functions: test(string)- Tests a string for pattern matches. This method returns a Boolean that indicates whether or not the specified pattern exists within the searched string. This is the most commonly used method for validation. It updates some of the properties of the parent RegExp object following a successful search. exec(string)- Executes a search for a pattern within a string. If the pattern is not found, exec() returns a null value. If it finds one or more matches it returns an array of the match results. It also updates some of the properties of the parent RegExp object PROGRAM: Valid.js function fun() { var userv=document.forms[0].user.value; var pwdv=document.forms[0].pwd.value; var emailv=document.forms[0].email.value; var phv=document.forms[0].ph.value; var userreg=new RegExp("^[a-zA-Z][a-zA-Z0-9]*$"); var emailreg=new RegExp("^[a-zA-Z][a-zA-Z0-9_.]*@[a-zA-Z][a-zA-Z0-9_.]*. [a-zA-Z][a-zA-Z0-9_.]{2}.[a-zA-Z][a-zA-Z0-9_.]{2}$|^[a-zA-Z][a-zA-Z0-9_.]*@[a-zAZ][a-zA-Z0-9_.]*.[a-zA-Z][a-zA-Z0-9_.]{3}$");

var phreg=new RegExp("^[0-9]{10}$"); var ruser=userreg.exec(userv); var remail=emailreg.exec(emailv); var rph=phreg.exec(phv); if(ruser && remail && rph && (pwdv.length > 6)) { alert("All values are valid"); return true; } else { if(!ruser) { alert("username invalid");document.forms[0].user.focus();} if(!remail) { alert("password invalid");document.forms[0].user.focus();} if(!rph) { alert("phone number invalid");document.forms[0].ph.focus();} if(pwdv.length < 6) { alert("password invalid");document.forms[0].pwd.focus();} return false; } } Register.html <html> <body> <center> <fieldset> <legend>Registration</legend> <form action="Database" method="get" onSubmit="return fun()"> <pre> Name :<input type="text" name="user" size="10"><br> Password :<input type="password" name="pwd" size="10"><br> E-mail :<input type="text" name="email" size="10"><br> Phone Number :<input type="text" name="ph" size="10"><br> <input type="submit" value="Register"> </pre> </form> </body> <script src="valid.js"></script> </html>

OUTPUT:

RESULT: Thus the home page, login page, catalogue page for the online book store are created successfully

Week-4 AIM:

Date: 21-07-08

-----------------------------------------------------------------------------------------------------------

Design a web page using CSS (Cascading Style Sheets) which includes the following: 1) Use different font, styles: In the style definition you define how each selector should work .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. 3) Control the repetition of the image with the background-repeat property DESCRIPTION: Cascading Style Sheets (CSS) is a stylesheet 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. 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 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 (;)

Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet by the following rules: 1. External style sheet 2. Internal style sheet (inside the <head> tag) 3. Inline style (inside an HTML element) An inline style (inside an HTML element) has the highest priority, which means that it will override a style declared inside the <head> tag, in an external style sheet, or in a browser (a default value). Syntax The CSS syntax is made up of three parts: a selector, a property and a value: selector {property: value} The selector is normally the HTML element/tag you wish to define, the property is the attribute you wish to change, and each property can take a value. The property and value are separated by a colon, and surrounded by curly braces: body {color: black} External Style Sheet An external style sheet is ideal when the style is applied to many pages. With an external style sheet, you can change the look of an entire Web site by changing one file. Each page must link to the style sheet using the <link> tag. The <link> tag goes inside the head section: <head> <link rel="stylesheet" type="text/css" href="mystyle.css" /> </head> The browser will read the style definitions from the file mystyle.css, and format the document according to it. Internal Style Sheet An internal style sheet should be used when a single document has a unique style. You define internal styles in the head section by using the <style> tag, <head>

<style> selector {property:value; property:value;..} </style> </head> Inline Styles An inline style loses many of the advantages of style sheets by mixing content with presentation. Use this method sparingly, such as when a style is to be applied to a single occurrence of an element. To use inline styles you use the style attribute in the relevant tag. The style attribute can contain any CSS property. <p style="color: sienna; margin-left: 20px"> This is a paragraph </p> PROGRAM: Cas.css: a:link{color:black;} a:visite d{color:pink;} a:active{color:red;} a:hover{color:gree n;} .right { te xt-align:cente r; te xt-decoration:un derline ; font -we ight :bold; color:blue; font -family:comic sans ms; font -size:30 ; } .image { te xt-align:left; font -family:"monotyp e corsiva";

font -we ight :10 ; } .image1 { backgroun d-image:url("C:\Docum ents and Settings\All Users\My Docum ent s\My Pictures\krishn a.jpg "); backgroun d-attachm ent :fixed; backgroun d-repeat:no-repeat; width:150 ; he ight :150; } table { align:cente r;border:10; border-style:ridge; border-color:yellow;} htm.html: <htm l> <head> <link rel="styleshe et" href="cas.css " typ e="te xt/css"> <style> .xlink{ te xt-decoration:none ;font-we ight :bold;cursor:cross hair;} .ylink{te xt-decoration:un derline ;font -we ight :bold;cursor:he lp;} </style> </he ad> <body class="image"> <p style="te xt-align:right ;"> <a Link</a>&nbsp;&nbsp; <a href="topframe.htm l" class="ylink"> He lp Link</a> </p> <p class="right ">PVPSIT</p> href="registration.htm l" class="xlink"> Reg

<div

style="position:relative;font -size:90 px;z-

index:5;color:purple;">PVPSIT</div> <div style="position:relative;font -size:50 px;z-index:1;top:-70 ; left:5;color:blue ;">CSE</div> <div style="position:relative;font -size:90 px;zindex:1;color:purple;">PVPSIT</div> <div style="position:relative;font -size:50 px;z-index:5;top:-70 ; left:5;color:blue ;">CSE</div> <table align="cente r" class="image1"> <tr> <td> Fruits</td> <td> Mango</td> </tr> </table> </body> </htm l> OUTPUT:

RESULT: Thus different style of CSS and different type of the properties are applied.

Week-5: Date: 28-07-08 ----------------------------------------------------------------------------------------------------------AIM: Write an XML file which will display the Book information. It includes the following: 1) Title of the book 2) Author Name 3) ISBN number 4) Publisher name 5) Edition 6) Price

Write a Document Type Definition (DTD) to validate the above XML file. Display the XML file as follows. The contents should be displayed in a table. The header of the table should be in 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. DESCRIPTION: DTD vs XML Schema The DTD provides a basic grammar for defining an XML Document in terms of the metadata that comprise the shape of the document. An XML Schema provides this, plus a detailed way to define what the data can and cannot contain. It provides far more control for the developer over what is legal, and it provides an Object Oriented approach, with all the benefits this entails. Many systems interfaces are already defined as a DTD. They are mature definitions, rich and complex. The effort in re-writing the definition may not be worthwhile. DTD is also established, and examples of common objects defined in a DTD abound on the Internet -- freely available for re-use. A developer may be able to use these to define a DTD more quickly than they would be able to accomplish a complete re-development of the core elements as a new schema. Finally, you must also consider the fact that the XML Schema is an XML document. It has an XML Namespace to refer to, and an XML DTD to define it. This is all overhead. When a parser examines the document, it may have to link this all in, interpret the DTD for the Schema, load the namespace, and validate the schema, etc., all before it can parse the actual XML document in question. If you're using XML as a protocol between two systems that are in heavy use, and need a quick response, then this overhead may seriously degrade performance. Write a Document Type Definition (DTD) to validate the XML file.

PROGRAM: XML document (bookstore.xml) <bookstore> <book> <title>web programming</title> <author>chrisbates</author> <ISBN>123-456-789</ISBN> <publisher>wiley</publisher> <edition>3</edition> <price>350</price> </book> <book> <title>internet worldwideweb</title> <author>ditel&amp;ditel</author> <ISBN>123-456-781</ISBN> <publisher>person</publisher> <edition>3</edition> <price>450</price> </book> </bookstore> XML document Validation using DTD DTD document (bookstore.dtd) <?xml version="1.0" encoding="UTF-8"?> <!ELEMENT bookstore (book+)> <!ELEMENT book (title,author,ISBN,publisher,edition,price)> <!ELEMENT title (#PCDATA)> <!ELEMENT author (#PCDATA)> <!ELEMENT ISBN (#PCDATA)> <!ELEMENT publisher (#PCDATA)> <!ELEMENT edition (#PCDATA)> <!ELEMENT price (#PCDATA)>

Bookstore.xml <!DOCTYPE bookstore SYSTEM "C:\Documents and Settings\Administrator\My Documents\bookstore.dtd"> <bookstore> <book> <title>web programming</title> <author>chrisbates</author> <ISBN>123-456-789</ISBN>

<publisher>wiley</publisher> <edition>3</edition> <price>350</price> </book> <book> <title>internet worldwideweb</title> <author>ditel&amp;ditel</author> <ISBN>123-456-781</ISBN> <publisher>person</publisher> <edition>3</edition> <price>450</price> </book> </bookstore>

XML document Validation using DTD XML Schema (bookstore.xsd) <?xml version="1.0" encoding="UTF-8"?> <xs:schema elementFormDefault="qualified" attributeFormDefault="unqualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="bookstore"> <xs:complexType> <xs:sequence> <xs:element name="book" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="title" type="xs:string"></xs:element> <xs:element name="author" type="xs:string"></xs:element> <xs:element name="ISBN" type="xs:string"></xs:element> <xs:element name="publisher" type="xs:string"></xs:element> <xs:element name="edition" type="xs:int"></xs:element> <xs:element name="price" type="xs:decimal"></xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>

Bookstore.xml <bookstore xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="C:\Documents and Settings\Administrator\My Documents\bookstore.xsd"> <book> <title>web programming</title> <author>chrisbates</author> <ISBN>123-456-789</ISBN> <publisher>wiley</publisher> <edition>3</edition> <price>350</price> </book> <book> <title>internet worldwideweb</title> <author>ditel&amp;ditel</author> <ISBN>123-456-781</ISBN> <publisher>person</publisher> <edition>3</edition> <price>450</price> </book> </bookstore> Display the XML file as follows. PROGRAM: XML: <?xml version="1.0"?> <?xml-styleshe et typ e="te xt/xsl" href="boo kstore.xsl"?> <boo kstore> <boo k> <title>Everyday Italian</title> <auth or>Giada De Laurent iis</auth or> <year>2005 </year> <price>30 .00 </price> </boo k> <boo k> <title>Harry Potte r</title>

<auth or>J K. Rowling</auth or> <year>2005 </year> <price>29 .99 </price> </boo k> <boo k> <title>Learning XML</title> <auth or>Erik T. Ray</auth or> <year>2003 </year> <price>39 .95 </price> </boo k> </boo kstore> XSL: <xsl:styleshe et xmlns:xsl="htt p:// www.w 3.org/199 9/XSL/Transform"> <xsl:te mplate match="/"> <htm l> <body> <h2> My Boo ks collection</h2> <table border="1"> <tr bg color="red"> <th align="left">title</th> <th align="left">auth or</th> </tr> <xsl:for-each select="boo kstore/boo k"> <tr> <td><xsl:value -of select="title"/> /td> < <xsl:ch oose> <xsl:whe n te st="price &gt; 30 "> <td bg color="yellow"> xsl:value -of select="auth or"/> /td> < < </xsl:whe n> <xsl:whe n te st="price &gt; 10 "> version="1.0"

<td bg color="magne ta"><xsl:value -of select="auth or"/> /td> < </xsl:whe n> <xsl:othe rwise> <td><xsl:value -of select="auth or"/> /td> < </xsl:othe rwise> </xsl:ch oose> </tr> </xsl:for-each> </table> </body> </htm l> </xsl:te mplate > </xsl:styleshe et> OUTPUT:

RESULT: Thus the XML stylesheets are successfully used to display the content in a table format. Week-6: Date: 04-08-08

----------------------------------------------------------------------------------------------------------VISUAL BEANS: AIM: 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 set to 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 for every mouse click. The color should also be changed if we change the color in the property window . DESCRIPTION: A Bean is a JavaBeans component. Beans are independent, reusable software modules. Beans may be visible objects, like AWT components, or invisible objects, like queues and stacks. A builder/integration tool manipulates Beans to create applets and applications. Beans consist of three things: Events An event allows your Beans to communicate when something interesting happens. There are three parts to this communication: EventObject Event Listener - (the sink) An Event Source (the Bean) The event source defines when and where an event will happen. Classes register themselves as interested in the event, and they receive notification when the event happens. A series of methods patterns represents the registration process: public synchronized void addListenerType(ListenerType l); public synchronized void removeListenerType( ListenerType l); Properties

Properties define the characteristics of the Bean. For instance, when examining an AWT TextField for its properties, you will see properties for the caret position, current text, and the echo character, among others. A property is a public attribute of the Bean, usually

represented by a non-public instance variable. It can be read-write, read-only, or writeonly. There are four different types of properties: Simple - As the name implies, simple properties represent the simplest of the four. To create a property, define a pair of set/get routines. Whatever name used in the pair of routines, becomes the property name Indexed - An indexed property is for when a single property can hold an array of values. The design pattern for these properties is: public void setPropertyName (PropertyType[] list) public void setPropertyName ( PropertyType element, int position) public PropertyType[] getPropertyName () public PropertyType getPropertyName (int position) Bound A bean that has the bound property generates an event when the property is changed. The event is of type propertyChangeEvent and is sent to objects that previously registered an interest in receiveing such notifications. In order for the notification to happen, you need to maintain a watch list for PropertyChangeEvents via the PropertyChangeSupport First, you have to create a list of listeners to maintain: private PropertyChangeSupport changes = new PropertyChangeSupport (this); And then, you have to maintain the list: public void addPropertyChangeListener ( PropertyChangeListener p) { changes.addPropertyChangeListener (p); } public void removePropertyChangeListener ( PropertyChangeListener p) { changes.removePropertyChangeListener (p); } Constrained - Constrained properties are similar to bound properties. In addition class.

to maintaining a list of PropertyChangeListeners, the Bean maintains a list of

VetoableChangeListeners. Then, prior to the Bean changing a property value, it asks the VetoableChangeListeners if its okay. If it isn't, the listener throws a PropertyVetoException, which you declare the set routine to throw. Methods Bean methods are available for anyone to call by just making each public. However, you can restrict which methods are visible to the Bean builder/integration tool by providing a getMethodDescriptors method along with your Bean's BeanInfo. Every Bean can provide a supporting BeanInfo class to customize a Bean's appearance to an integration tool. Procedural Steps to create a Java-Bean: 1) Creating a directory- Create a new directory in C:\beans\demo\sunw\demo with a new folder name colors 2) Create a java source file 3) Compile the java source file 4) Create a manifest file colors.mft in the directory called as C:\beans\demo 5) Create a jar file- to create a jar file type the following command in the command prompt jar cfm ..\jars\colors.jar colors.mft sunw\demo\colors\*.class 6) Start the BDK 7) Check whether the colors bean is placed in toolbox or not. PROGRAM: packa ge sunw. demo.colors; import java.awt.*; import java.awt.e vent.*; publi c class Color s exten ds Canv as { transient private Colo r color; private boo lean rectangular; publi c Colors()

{ add MouseListe ne r(ne w MouseAdapte r(){ publi c void mousePress ed(MouseEvent me){ ch ange(); } }); rectangular=false; setSize(100 ,100); change(); } publi c boo lean getRectangular() { retu rn rectangular; } publi c void setRectangular(boo lean flag) { this.rectangular=fla g; repaint( ); } publi c void change() { color=randomColor( ); repaint( ); } private Colo r randomColor() { int r=(int) (255 *Math. random()) ; int int } publi c void paint( Graphics g) g=(int) (255 *Math. random()) ; b=(int) (255 *Math. random()) ;

retu rn new Color(r,g,b);

{ Di men sion d=getSize(); int h=d.he ight; 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); } } } OUTPUT:

RESULT: Thus the colors bean is created successfully. Program 2: Visual Beans (program 2) Convert.java package sunw.demo.convert; import java.awt.*; import java.awt.event.*; public class convert extends Canvas { private double dollars=0.0; private double rupees=0.0; private double dollarvalue=0.0; public convert() { setSize(100,1000); } public double getDollars()

{ return dollars; } public void setDollars(double value) { this.dollars=value; } public void setRupees(double value) { this.rupees=value; } public double getRupees() { return rupees; } public void change() { dollarvalue= value(); repaint(); } private double value() { return rupees*dollars; } public void paint(Graphics g) { g.setColor(Color.red); g.drawString(String.valueOf(dollarvalue),10,10); } } Convert.mf Name: sunw/demo/convert/convert.class Java-Bean: True ( press Enter) (Carriage return compulsory)

Result Thus the convertion bean is created successfully Program 3: package sunw.demo.colors; import java.awt.*; import java.awt.event.*; public class mouseclick extends Canvas { public int count=0; public mouseclick() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { change(); } });

setSize(100,100); } public void change() { count++; repaint(); } public void paint(Graphics g) { Dimension d = getSize(); int h = d.height; int w = d.width; g.setColor(Color.red); g.fillRect(0,0,100,100); g.setColor(Color.blue); g.drawString(String.valueOf(count),50,50); } } Mouseclick.mft Name: sunw/demo/colors/mouseclick.class Java-Bean: True Output

Result Thus the Mouse Clicks bean is created successfully

Week-7: AIM: Install TOMCAT web server and APACHE.

Date: 11-08-08

-----------------------------------------------------------------------------------------------------------

While installation assign port number 8080 to APACHE. Make sure that these ports are available i.e., no other process is using this port.

DESCRIPTION: Set the JAVA_HOME Variable You must set the JAVA_HOME environment variable to tell Tomcat where to find Java. Failing to properly set this variable prevents Tomcat from handling JSP pages. This variable should list the base JDK installation directory, not the bin subdirectory. On Windows XP, you could also go to the Start menu, select Control Panel, choose System, click on the Advanced tab, press the Environment Variables button at the bottom, and enter the JAVA_HOME variable and value directly as: Name: JAVA_HOME Value: C:\jdk Set the CLASSPATH Since servlets and JSP are not part of the Java 2 platform, standard edition, you have to identify the servlet classes to the compiler. The server already knows about the servlet classes, but the compiler (i.e., javac) you use for development probably doesn't. So, if you don't set your CLASSPATH, attempts to compile servlets, tag libraries, or other classes that use the servlet and JSP APIs will fail with error messages about unknown classes. Name: JAVA_HOME Value: install_dir/common/lib/servlet-api.jar Turn on Servlet Reloading The next step is to tell Tomcat to check the modification dates of the class files of requested servlets and reload ones that have changed since they were loaded into the server's memory. This slightly degrades performance in deployment situations, so is turned off by default. However, if you fail to turn it on for your development server, you'll have to restart the server every time you recompile a servlet that has already been loaded into the server's memory.

To turn on servlet reloading, edit install_dir/conf/server.xml and add a DefaultContext subelement to the main Host element and supply true for the reloadable attribute. For example, in Tomcat 5.0.27, search for this entry:

<Host name="localhost" debug="0" appBase="webapps" ...>


and then insert the following immediately below it:

<DefaultContext reloadable="true"/>
Be sure to make a backup copy of server.xml before making the above change. Enable the Invoker Servlet The invoker servlet lets you run servlets without first making changes to your Web application's deployment descriptor. Instead, you just drop your servlet into WEBINF/classes and use the URL http://host/servlet/ServletName. The invoker servlet is extremely convenient when you are learning and even when you are doing your initial development. To enable the invoker servlet, uncomment the following servlet and
servlet- mapping

elements in install_dir/conf/web.xml. Finally, remember to make a

backup copy of the original version of this file before you make the changes. <servlet> <servlet-name>inv oker</servlet-name> <servlet-class> org.apache .catalina.servlets.Inv okerServlet </servlet-class> ... </servlet> ... <servlet-mapp ing> <servlet-name>inv oker</servlet-name> <url-patte rn>/servlet/*</url-patte rn> </servlet-mapp ing>

OUTPUT:

RESULT: Thus TOMCAT web server was installed successfully.

Week-7:

Date: 11-08-08

----------------------------------------------------------------------------------------------------------AIM: Access the developed static web pages for books web site, using these servers by putting the web pages developed in week-1 and week-2 in the document root.

OUTPUT

RESULT: Thus week-1 and week-2 pages are accessed using the TOMCAT web server successfully.

Week-8: AIM: User Authentication:

Date: 10-09-08

-----------------------------------------------------------------------------------------------------------

Assume four users user1, user2, user3 and user4 having the passwords pwd1, pwd2, pwd3 and pwd4 respectively. Write a servelet for doing the following. 1. Create a Cookie and add these four user ids and passwords to this Cookie. 2. Read the user id and passwords entered in the Login form (week1) and authenticate with the values (user id and passwords) available in the cookies. 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 web.xml and access them in the servlet by using the getInitParameters() method. DESCRIPTION: Servlet Life cycle: 1. 2. 3. 4. 5. Servlet class loading Servlet Instantiation call the init method call the service method call destroy method

Class loading and instantiation If you consider a servlet to be just like any other Java program, except that it runs within a servlet container, there has to be a process of loading the class and making it ready for requests. Servlets do not have the exact equivalent of a main method that causes them to start execution. When a web container starts it searches for the deployment descriptor (WEB.XML) for each of its web applications. When it finds a servlet in the descriptor it

will create an instance of the servlet class. At this point the class is considered to be loaded (but not initialized). The init method The HttpServlet class inherits the init method from GenericServlet. The init method performs a role slightly similar to a constructor in an ordinary Java program in that it allows initialization of an instance at start up. It is called automatically by the servlet container and as it causes the application context (WEB.XML) to be parsed and any initialization will be performed. It comes in two versions, one with a zero parameter constructor and one that takes a ServletConfig parameter. The servlet engine creates a request object and a response object. The servlet engine invokes the servlet service() method, passing the request and response objects. Once the init method returns the servlet is said to be placed into service. The process of using init to initialize servlets means that it is possible to change configuration details by modifying the deployment descriptor without having them hard coded in with your Java source and needing a re-compilation. void init(ServletConfig sc) Calling the service method The service() method gets information about the request from the request object, processes the request, and uses methods of the response object to create the client response. The service method can invoke other methods to process the request, such as doGet(), doPost(), or methods you write. The service method is called for each request processed and is not normally overridden by the programmer. The code that makes a servlet go is the. servlet void service(ServletRequest req,ServletResponse res) The destroy Method Two typical reasons for the destroy method being called are if the container is shutting down or if the container is low on resources. This can happen when the container keeps a pool of instances of servlets to ensure adequate performance. If no requests have come in for a particular servlet for a while it may destroy it to ensure resources are available for the servlets that are being requested. The destroy method is called only once, before a servlet is unloaded and thus you cannot be certain when and if it is called.

void destroy() ServletConfig


ServletConfig

Class object is used by the Servlet Container to pass information to class

the Servlet during it's initialization. Servlet can obtain information regarding initialization parameters and their values using different methods of ServletConfig initialization parameters are name/value pairs used to provide basic information to the Servlet during it's initialization like JDBC driver name, path to database, username, password etc. Methods of ServletConfig class

Following are the four methods of this class : getInitParameter(String paramName) Returns value of the given parameter. If value of parameter could not be found in web.xml file then a null value is returned. getInitParameterNames() Returns an Enumeration object containing all the names of initialization parameters provided for this Servlet. getServletContext() Returns reference to the ServletContext object for this Servlet. It is similar class. to
getServletContext()

method

provided by

HttpServlet

getServletName() Returns name of the Servlet as provided in the web.xml file or if none is provided then returns complete class path to the Servlet.

PROGRAM: cologin.html: <htm l> <head> <title> login Page </title> <p style= "backgroun d:yellow; top:100 px; left:250px; position:absolute ; "> </he ad>

<body> <for m ACTION="clogin"> <label> Login </label> <input typ e="text" nam ="u sr" size="20 "> <br> <br> e <label> Pa sswor d </label> <input typ e="p asswor d" nam ="pw d" size="20 "> <br> <br> e <input typ e="submit" value="submit"> </form> </body> </htm l> cologin1.html <htm l> <head> <title> login Page </title> <p style="backgroun d:yellow;top:100 px; left:250px;position:absolute ; "> </he ad> <body> <for m ACTION="clogin1"> <label> Login </label> <input typ e="text" nam ="u sr" size="20 "> <br> <br> e <label> Pa sswor d </label> <input typ e="p asswor d" nam ="pw d" size="20 "> <br> <br> e <input typ e="submit" value="submit"> </form> </body> </htm l>

Addcook.java: import javax.servlet.* ; import javax.servlet.htt p.*;

import java.io.*; publi c class Add cook exten ds Http Servlet { String user,pas; publi c void service(Http ServletReque st req,Http ServletResponse res) throws ServletException,IOException { res.setConte ntType("te xt/ht ml"); Pri ntWriter out =res.getWrite r(); Coo kie c1=new Cookie("usr1","suni"); Cookie p1=new Coo kie("pwd1","ani"); Cookie c2=new Coo kie("usr2","abc"); Cookie p2=new Coo kie("pwd2","123 "); Cookie c3=new Coo kie("usr3","def"); Cookie p3=new Coo kie("pwd3","456 "); Cookie c4=new Coo kie("usr4","mno"); Cookie p4=new Coo kie("pwd4","789 "); res.add Coo kie(c1); res.add Coo kie(p1); res.add Coo kie(c2); res.add Coo kie(p2); res.add Coo kie(c3); res.add Coo kie(p3); res.add Coo kie(c4); res.add Coo kie(p4); out. println( "COOKIE ADDED"); } } Clogin.java: import javax.servlet.* ; import javax.servlet.htt p.*;

import java.io.*; publi c class Clogin exten ds Http Servlet { String user,pas; publi c void service(Http ServletReque st req,Http ServletResponse res) throws ServletException,IOException { res.setConte ntType("te xt/ht ml "); Pri ntWriter out =res.getWrite r(); user=req.getParamete r("usr"); pas=req.getParamete r("pwd"); Cookie[] c=req.getCoo kies(); for (int i=0;i<c.length;i+ ) + { if((c[i].getName().equals("usr1")&&c[i+1].getName().equals("pwd1"))| | ( c[i].getName().equals("usr2") &&c[i+1].getName().equals("pwd2"))|| (c[i].getName().equals("usr3")&& { if((user.equals(c[i].getValue ()) pas.equals(c[i+1].getValue ())) ) { Reque stDispatche r rd=req.getReque stDispatche r("/cart.ht ml"); rd.forward(req,res); } else { out. println( "YOU ARE NOT AUTHORISED USER "); //res.sendRedirect("/coo kdemo/cologin.htm l"); } && c[i+1].getName().equals("pwd3"))|| (c[i].getName().equals("usr4")&& c[i+1].getName().equals("pwd4") ))

} } } } Web.xml: <we b-app > <servlet> <servlet-name>him</servlet-name> <servlet-class >Clogin</servlet-class> </servlet> <servlet> <servlet-name>him1</servlet-name> <servlet-class >Add coo k</servlet-class> </servlet> <servlet-mapp ing> <servlet-name>him</servlet-name> <url-patte rn>/clogin</url-patte rn> </servlet-mapp ing> <servlet-mapp ing> <servlet-name>him1</servlet-name> <url-patte rn>/clogin1</url-patte rn> </servlet-mapp ing> </we b-app >

OUTPUT:

2. Read the user id and passwords entered in the Login form (week1) and authenticate with the values (user id and passwords) available in the cookies. 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. home.html: <htm l> <head> <title>Authe nt ication</title> </he ad> <body> <for m action="ex1"> <label>Username </label> <input typ e="te xt"size="20 " name="user"><br> br> < pass word<input typ e="text" size="20 " name="pwd"> br> br> < < <input typ e="submit" value="submit"> </form> </body> </htm l> Example1.java import javax.servlet.*; import java.io.*; publi c class Example1 exten ds Gene ricServlet { private String user1,pwd1,user2,pwd2,user3,pwd3,user4,pwd4,user5,pwd5; publi c void init(Se rvletC onfig sc) { user1=sc.getInitParamete r("username1"); pwd1=sc.getInitParamete r("pass word1");

user2=sc.getInitParamete r("username2"); pwd2=sc.getInitParamete r("pass word2"); user3=sc.getInitParamete r("username3"); pwd3=sc.getInitParamete r("pass word3"); user4=sc.getInitParamete r("username4"); pwd4=sc.getInitParamete r("pass word4"); } Publi c void service(ServletReque st req,ServletResponse res)throws ServletException,IOException { res.setConte ntType("te xt/ht ml"); Pri ntWriter out =res.getWrite r(); user5=req.getParamete r("user"); pwd5=req.getParamete r("pwd"); if((user5.equals(user1)&&pwd5.equals(pwd1))|| (user5.equals(user2)&&pwd5.equals(pwd2))|| (user5.equals(user3)&&pwd5.equals(pwd3))|| (user5.equals(user4)&&pwd5.equals(pwd4))) out. print ln( "<p> we lcome to"+user5.toUpp erCase()); else out. print ln( "You are not auth orized user"); } }

web.xml: <we b-app > <servlet> <servlet-name>Example</servlet-name>

<servlet-class >Example1</servlet-class> <init-param> <param-name>username1</param-name> <param-value >pvpsit</param-value > </init-param> <init-param> <param-name>password1</param-name> <param-value >cse</param-value> </init-param> <init-param> <param-name>username2</param-name> <param-value >1234 </param-value> </init-param> <init-param> <param-name>password2</param-name> <param-value >4567 </param-value> </init-param> <init-param> <param-name>username3</param-name> <param-value >cse</param-value> </init-param> <init-param> <param-name>password3</param-name> <param-value >pvpsit</param-value > </init-param> <init-param> <param-name>username4</param-name> <param-value >w </param-value > t </init-param> <init-param> <param-name>password4</param-name>

<param-value >lab</param-value > </init-param> </servlet> <servlet-mapp ing> <servlet-name>Example</servlet-name> <url-patte rn>/ex1</url-patte rn> </servlet-mapp ing> </we b-app >

OUTPUT:

RESULT: Thus the user authentication is carried out for four users by using both cookies and getInitParameters successfully.

Week-9

Date: 22-09-08

-----------------------------------------------------------------------------------------------------------AIM: Install a database (Mysql or Oracle). Create a table which should contain at least the following fields: name, password, email-id, phone number (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 web site, whenever a new user clicks the submit button in the registration page (week2). DESCRIPTION: JDBC Driver Types There are four types of JDBC drivers in use: Type 1: JDBC-ODBC Bridge A Type 1 JDBC-ODBC Bridge provides application developers with a way to access JDBC drivers via the JDBC API. Type 1 JDBC drivers translate the JDBC calls into ODBC calls and then send the calls to the ODBC driver. Type 1 JDBC drivers are generally used when the database client libraries need to be loaded on every client machine. Type 2: Native API/Partly Java Driver A Type 2 Native API/Partly Java Driver is a partial Java driver because it converts JDBC calls into database specific calls. Type 2 Native API/Partly Java Driver communicates directly with the database server. Type 3: Pure Java Driver A Type 3 Pure Java Driver works in a three tiered architecture. The JDBC calls are passed via the network to the middle tier server. This server translates the calls to the database specific native interface to further request the server. JDBC drivers available from Simba are Type 3 drivers. Type 4: Native Protocol Java Driver

The type 4 driver is written completely in Java and is hence platform independent. It is installed inside the Java Virtual Machine of the client. It provides better performance over the type 1 and 2 drivers as it does not have the overhead of conversion of calls into ODBC or database API calls. Unlike the type 3 drivers, it does not need associated software to work.A Type 4 Native Protocol Java Driver converts JDBC calls into the database specific calls so that the client applications can communicate directly with the server. PROGRAM: Registration.html: <htm l> <head> <title>Registration page</title> </he ad> <body bg color="#00 FFFf"> <for m METHOD="POST" ACTION="registe r"> <CENTER> <table> <cente r> <tr> <td> Username </td> <td><input type ="text" name="u sr"> </td> </tr> <tr> <td> Passwor d </td> <td><input type ="p ass wor d" name="pw d"> </td> </tr> <tr><td>Age</td> <td><input type ="text" name="age"> </td> </tr> <tr> <td>Add ress </td> <td <input type ="text" name="add"> </td> </tr> > <tr> <td>email</td> <td <input type ="text" name="mail"> </td> </tr> > <tr> <td>Phone </td> <td <input type ="text" name="ph one"> </td> </tr> >

<tr>

<td

colspan=2

align=cente r>

<input

typ e="submit"

value ="submit"> </td> </tr> </cente r> </table> </form> </body> Login.html <htm l> <head> <title>Registration page</title> </he ad> <body bg color=pink> <cente r> <table> <for m METHOD="POST" ACTION="authe nt "> <tr> <td> Username </td> <td><input type ="text" name="u sr">< /td> </tr> <tr> <td> Passwor d </td> <td <input type ="p ass wor d" name="pw d"> </td> </tr> > <tr> <td align=cente r colspan="2"> input < typ e="submit" value ="submit"> /td> </tr> < </table> </cente r> </form> </body> </htm l> Ini.java: import javax.servlet.*; import java.sql.*; import java.io.*; publi c class Ini exten ds Gene ricServlet {

private String user1,pwd1,email1; publi c void service(ServletReque st req,ServletResponse res) throws ServletException,IOException { user1=req.getParamete r("user"); pwd1=req.getParamete r("pwd"); email1=req.getParamete r("email"); res.setConte ntType("te xt/ht ml"); Pri ntWriter out =res.getWrite r(); try { Class .forName("oracle.jdb c.driver.OracleDriver" ); Conne ction con=DriverManager.getConne ction( "jdb c:oracle:thin:@195 .10 0.101.15 8:1521 :cclab","scott","tiger"); Pr ep aredSt atem ent value s(?,?,?,? ,?,?)"); st.setString(1,user1); st.setString(2,pwd1); st.setString(3,"25 "); st.setString(4,"hy d"); st.setString(5,email1); st.setString(6,"21234 "); st.e xecute Update (); con.c lose(); } catch( SQLException s) { out. println( "not found "+s); } catch( ClassNotFoun dException c) st=con. prepareState ment( "insert into personal

{ out. print ln( "not found "+c); } }} web.xml: <we b-app > <servlet> <servlet-name>init1</servlet-name> <servlet-class >Ini</servlet-class> </servlet> <servlet-mapp ing> <servlet-name>init1</servlet-name> <url-patte rn>/regis</url-patte rn> </servlet-mapp ing> </we b-app > OUTPUT:

RESULT: Thus a table is created and the details are entered into the table using jdbc from the registration form successfully.

Week-10 AIM: Write a JSP which does the following job

Date: 29-09-08

-----------------------------------------------------------------------------------------------------------

Insert the details of the 3 or 4 users who register with the web site (week9) by using registration form. Authenticate the user when he submits the login form using the user name and password from the database (similar to week8 instead of cookies). DESCRIPTION: JSP Scripting Elements JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page. There are three forms: 1. Expressions of the form <%= expression %> that are evaluated and inserted into the output, 2. Scriptlets of the form <% code %> that are inserted into the servlet's service method, and 3. Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods. Each of these is described in more detail below.

JSP Expressions
A JSP expression is used to insert Java values directly into the output. It has the following form: <%= Java Expression %> The Java expression is evaluated, converted to a string, and inserted in the page. This evaluation is performed at run-time (when the page is requested), and thus has full access to information about the request. For example, the following shows the date/time that the page was requested: Current time: <%= new java.util.Date() %>

To simplify these expressions, there are a number of predefined variables that you can use. These implicit objects are discussed in more detail later, but for the purpose of expressions, the most important ones are:
request,

the HttpServletRequest; the HttpServletResponse; the HttpSession associated with the request (if any); and

response, session, out,

the PrintWriter (a buffered version of type JspWriter) used to send

output to the client. JSP Scriptlets If you want to do something more complex than insert a simple expression, JSP scriptlets let you insert arbitrary code into the servlet method that will be built to generate the page. Scriptlets have the following form: <% Java Code %> Scriptlets have access to the same automatically defined variables as expressions. So, for example, if you want output to appear in the resultant page, you would use the
out

variable.

<% String queryData = request.getQueryString(); out.println("Attached GET data: " + queryData); %> Note that code inside a scriptlet gets inserted exactly as written, and any static HTML (template text) before or after a scriptlet gets converted to print statements. This means that scriptlets need not contain complete Java statements, and blocks left open can affect the static HTML outside of the scriptlets. JSP Declarations A JSP declaration lets you define methods or fields that get inserted into the main body of the servlet class (outside of the service method processing the request). It has the following form: <%! Java Code %> Since declarations do not generate any output, they are normally used in conjunction with JSP expressions or scriptlets. For example, here is a JSP fragment that

prints out the number of times the current page has been requested since the server booted (or the servlet class was changed and reloaded): <%! private int accessCount = 0; %> PROGRAM: Login.html: <!--Home.htm l--> <htm l> <body> <cente r><h1>XYZ Comp any Ltd.</h1> /cente r> < <table bor de r="1" width ="100 % height ="100 %"> " <tr> <td valign="top" align="cente r"> br/> < <for m action="auth. jsp"> table> < <tr> <td colspan="2" align="cente r"> b>Login < Page</b></td> </tr> <tr> <td align="cente r"> b>&nbsp;</td> < </tr> <tr> <td>User Name</td> <td><input type ="text" name="user"/> /td> < </tr> <tr> <td>Pass word</td> <td> input < name="pwd"/> /td> < </tr> <tr> <td>&nbsp;</td> typ e="password" colspan="2"

<td>&nbsp;</td> </tr> <tr> <td colspan="2" align="cente r"> input typ e="submit" < value ="LogIN"/> /td> < </tr> </table> </form> </td> </tr> </table> </body> </htm l> Auth.jsp: <% p age import="java.sql.*;"% @ > <htm l> <head> <title> This is simple data base example in JSP</title> </title> </he ad> <body bg color="yellow"> <%! String un ame,pwd;% > <% un ame=reque st.getParamete r("user"); pwd=reque st.getParamete r("pwd"); try { Class.forName("oracle.jdb c.driver.OracleDriver");

Conne ction con=DriverManager.getConne ction( "jdb c:oracle:thin:@195 .10 0.101.15 8:1521 :CCLAB","scott","tiger"); Statem ent st=con.c reate Statement( ); ResultSet rs=st.e xecute Que ry("select name, pa sswor d from personal w re nam ='"+un ame+"' and password='"+pwd+"'"); he e if(rs.ne xt()) { out. println( "Aut horized person"); } else { out. pri ntln("UnAut hori zed person"); } con.c lose(); } catch(Ex cept ion e){out. print ln( ""+e);} % > </body> </htm l> OUTPUT:

RESULT: The user is authenticated when he submits the login form using the user name and password from the database. Week-11: AIM: Extract data from the tables and display them in the catalogue page using JDBC. DESCRIPTION: Create tables in the database which contain the details of items (books in our case like Book name, Price, Quantity, Amount)) of each category. Modify your catalogue page (week 2) 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: Retrieve.java: import javax.servlet.*; import javax.servlet.htt p.*; Date: 06-10-08 -----------------------------------------------------------------------------------------------------------

import java.sql.*; import java.io.*; import java.ut il.*; publi c class Retrieve exten ds Http Servlet { publi c void service(Http ServletReque st req,Http ServletResponse res) throws ServletException,IOException { res.setConte ntType("te xt/ht ml "); Pri ntWriter out =res.getWrite r(); try{ Class .forName("oracle.jdb c.driver.OracleDriver"); Conne ction con=DriverManager.getConne ction( "jdb c:oracle:thin:@195 .10 0.101.15 8:1521 :cclab","scott","tiger"); St atem ent s=con.c reate State ment( ); ResultSet r=s.execute Que ry("select * from cart"); out. println( "<cente r> <table border=1>"); out. println( "<the ad> <th> Boo k nam </th> <th> Pri ce </th> <th> e Quant ity </th> <th> Amount </th> </the ad>"); wh ile(r.ne xt()) { out. println( "<tr> <td "+r.getString(1)+"</td> "); > out. println( "<td> "+r.getString(2)+"</td> "); out. println( "<td> "+r.get Int( 3)+"</td> "); out. println( "<td> "+r.getString(4)+"</td> </tr>"); } out. println( "</table> /cente r>"); < con.c lose(); } catch( SQLException sq)

{ out. println( "sql exception"+sq); } catch( ClassNotFoun dException cl) { out. println( "class not foun d"+cl); } } } web.xml: <we b-app > <servlet> <servlet-name>set</servlet-name> <servlet-class >Carte nte r</servlet-class> </servlet> <servlet> <servlet-name>display</servlet-name> <servlet-class >Retrieve</servlet-class> </servlet> <servlet-mapp ing> <servlet-name>set</servlet-name> <url-patte rn>/ente rdata</url-patte rn> </servlet-mapp ing> <servlet-mapp ing> <servlet-name>display</servlet-name> <url-patte rn>/display1</url-patte rn> </servlet-mapp ing> </we b-app >

CREATE THE TABLE

AND INSERT VALUES

INTO

THE TABLE:

OUTPUT:

RESULT: The data is extracted from the tables and displayed in the catalogue page using JDBC

Week-12: -

Date: 18-10-08

----------------------------------------------------------------------------------------------------------AIM: Modify cart JSPpage to achieve the dynamism with the HTTP protocol and session management DESCRIPTION: HTTP is a stateless protocol. Session is required to maintain the state.

Methods of session Object:


There are numerous methods available for session Object. Some are:
getAttribute(String name) getAttributeNames isNew() getCreationTime getId invalidate() getLastAccessedTime getMaxInactiveInterval removeAttribute(String name) setAttribute(String, object)

The <jsp:include> element allows you to include either static and dynamic files in a JSP file.

Program :

Cart .java import java.util.*; import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class Cart extends HttpServlet {

public void init(ServletConfig config) throws ServletException { super.init(config); } public void service(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException { res.setContentType("text/html" ); PrintWriter pw=res.getWriter(); HttpSession hs=req.getSession(); ArrayList cart=(ArrayList)hs.getAttribute("cart"); if(cart==null) { pw.println("No items in your cart"); cart=new ArrayList(); hs.setAttribute("cart",cart); } String itemselected[]; String item; itemselected=req.getParameterValues("book"); if(itemselected!=null) { for(int i=0;i<itemselected.length;i++) { item=itemselected[i ]; cart.add(item); }} pw.println("Items in the cart<br>"); Iterator it=cart.iterator();

while(it.hasNext()) { pw.println("<br><b>"+it.next()+"</b>"); } } } Catalogue.java import java.util.*; import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class Catalogue extends HttpServlet { int itemcount=0; public void init(ServletConfig config) throws ServletException { super.init(config); } public void service(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException { res.setContentType("text/html" ); PrintWriter pw=res.getWriter(); HttpSession hs=req.getSession(); ArrayList cart=(ArrayList)hs.getAttribute("cart"); if(cart!=null) { itemcount=cart.size();

} pw.println("You have"+itemcount+"items in cart"); pw.println("<body><center><fieldset><legend>Catalogu e</legend><form action='cart' method='get'><input type='checkbox' value='Java2' name='book'>java2</input><br>"); pw.println("<input type='checkbox' name='book' value='web programming'>Web programming</input><br>"); pw.println("<input type='checkbox' name='book' value='Java2 Complete Reference'>Java2 Complete Reference</input><br>"); pw.println("<input type='checkbox' name='book' value='Internet & World wide web'>Internet & World wide web</input><br>"); pw.println("<input type='checkbox' name='book' value='Core servlets &JSP'>Core servlets &JSP</input><br>"); pw.println("<input type='checkbox' name='book' value='J2EE 3rd edition'>J2EE 3rd edition</input><br>"); pw.println("<input type='checkbox' name='book' value='Electronic Devices and circuits'>Electronic Devices and circuits</input><br>"); pw.println("<input type='checkbox' name='book' value='Software Engineering'>Software Engineering</input><br>"); pw.println("<input type='checkbox' name='book' value='software project management'>software project management</input><br>"); pw.println("<input type='checkbox' name='book' value='Computer networks'>Computer networks</input><br>");

pw.println("</fieldset></center>"); pw.println("<input type='submit' value='submit'>");

} } <web-app> <servlet> <servlet-name>Login</servlet-name> <servlet-class>Login</servlet-class> <init-param> <param-name>username</param-name> <param-value>syam</param-value> </init-param> <init-param> <param-name>password</param-name> <param-value>syam</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>/login.do</url-pattern> </servlet-mapping> <servlet> <servlet-name>cat</servlet-name> <servlet-class>Catalogue</servlet-class> </servlet> <servlet-mapping>

<servlet-name>cat</servlet-name> <url-pattern>/Cat</url-pattern> </servlet-mapping> <servlet> <servlet-name>cart</servlet-name> <servlet-class>Cart</servlet-class> </servlet> <servlet-mapping> <servlet-name>cart</servlet-name> <url-pattern>/cart</url-pattern> </servlet-mapping> </web-app>

Result : Thus the session management is successfully created using jsp

Week 13: Aim : Write a program to implement MVC architecture. Description :

Model-View-Controller Pattern
Model-View-Controller (MVC) is a classic design pattern often used by applications that need the ability to maintain multiple views of the same data. The MVC pattern

hinges on a clean separation of objects into one of three categories models for maintaining data, views for displaying all or a portion of the data, and controllers for handling events that affect the model or view(s). Because of this separation, multiple views and controllers can interface with the same model. Even new types of views and controllers that never existed before can interface with a model without forcing a change in the model design.
How It Works

The MVC abstraction can be graphically represented as follows.

Events typically cause a controller to change a model, or view, or both. Whenever a controller changes a models data or properties, all dependent views are automatically updated. Similarly, whenever a controller changes a view, for example, by revealing areas that were previously hidden, the view gets data from the underlying model to refresh itself. A Concrete Example We explain the MVC pattern with the help of a simple spinner component which consists of a text field and two arrow buttons that can be used to increment or decrement a numeric value shown in the text field. We currently do not have an element type that can directly represent a spinner component, but it easy is to synthesize a spinner using existing element types.

The spinners data is held in a model that is shared with the text field. The text field provides a view of the spinners current value. Each button in the spinner is an event source, that spawns an action event every time it is clicked. The buttons can be hooked up to trampolines that receive action events, and route them to an action listener that eventually handles that event. Recall that a trampoline is a predefined action listener that simply delegates action handling to another listener. Depending on the source of the event, the ultimate action listener either increments or decrements the value held in the model The action listener is an example of a controller. The trampolines that initially receive the action events fired by the arrow buttons, are also controllers However, instead of modifying the spinners model directly, they delegate the task to a separate controller (action listener). Multiple Controllers The MVC pattern allows any number of controllers to modify the same model. While we have so far focused only on the two arrow buttons as likely source of events, there is, in fact, a third event source in this example Whenever the text field has focus, hitting the enter key fires off an action event that may potentially be handled by a different action listener than the one handling action events from the buttons.

Program :

Eshop.jsp:
<% page session="true " % @ > <htm l> <head> <title>BOOK STORE</title> </he ad> <body bg color="#33 CCFF"> <font face="Times New Ro man,Ti me s" size="+3"> BOOK STORE </font> <hr> p> < <cente r> <for m name="shopp ingForm" action="ShoppingServlet" method="POST"> <b>BOOK:</b> <select name=BOOK> <opt io n> 1058 8 | Hans Bergste n | Java Se rver Pages | O'Reilly | 2 | 34 .95 </option> <opt ion> 105 89 | Deitel | Inte rne t |McGraw Hill | 4 | 44 .95 </option> <opt ion> 105 90 | Winston | XML BIBLE |Wiley | 2 | 14 .95 </option> </select> <b>Quant ity: value =1> <input type ="h idden" nam ="act ion" value ="ADD"> e <input typ e="submit" name="Submit" value ="Add to Cart"> </form> </cente r> <p> <jsp:inc lude page="Cart.jsp" flush="true " /> </body> </b><input type ="text" name="qty" SIZE="3"

</htm l>

Cart.jsp:
<% page session="true " import="java.ut il.*, shopp ing.BOOK" %> @ <% Vector buy list = (Vector) sess ion. getValue ("shopp ing.shoppingcart"); if (buy list != null && (buy list.size() > 0)) { % > <cente r> <table <tr> <td><b>ISBN</b> /td> < <td><b>AUTHOR</b> /td> < <td><b>TITLE</b> /td> < <td><b>PUBLISHER</b> /td> < <td><b>EDITION</b> /td> < <td><b>PRICE</b> /td> < <td><b>QUANTITY</b> /td> < <td></td> </tr> <% for (int index=0; index < buy list.size();index++) { BOOK anO der = (BOOK) buy list.e lementA t(index); r % > <tr> <td > b> % anOr de r.get isbn() %> /b></td> < < = < <td><b> %= anOr de r.getAut hor () %></b></td> < <td><b> %= anOrder.getTitle() %></b> /td> < < <td><b> %= anOrder.getPublishe r() %></b> /td> < < <td><b> %= anOrder.getEdition( ) %> /b></td> < < bor de r="0" cellpadd ing="0" width ="100 %" bg color="#FFFFFF">

<td > b> % anOrder.getPrice() %></b> /td> < < = < <td > b> % anOr de r.getQuant ity() %></b> /td> < < = < <td> <for m name="delete Form" action="ShoppingServlet" method="POST"> <input typ e="submit" value ="Delete "> <input type ="h idden" name= "delindex" value ='<% index %>'> = <input type ="h idden" name="act ion" value ="DELETE"> </form> </td> </tr> <% } % > </table> <p> <for m name="che ckoutF orm" action="ShoppingServlet" method="POST"> <input type ="h idden" name="act ion" value="CHECKOUT"> <input typ e="submit" name="Checkout" value ="Che ckout "> </form> </cente r> <% } %>

Checkout.jsp:
<% page session="true " import="java.ut il.*, shopp ing.BOOK" %> @ <htm l> <head> <title>BOOK STORE</title> </he ad> <body bg color="#33 CCFF"> <font face="Times New Ro man,Ti me s" size= 3> +

BOOK STORE CHECK OUT </font> <hr> p> < <cente r> <table <tr> <td><b>ISBN</b> /td> < <td><b>AUTHOR</b> /td> < <td><b>TITLE</b> /td> < <td><b>PUBLISHER</b> /td> < <td><b>EDITION</b> /td> < <td><b>PRICE</b> /td> < <td><b>QUANTITY</b> /td> < <td></td> </tr> <% Vector buy list = (Vector) session. getValue ("shopp ing.shopp ingcart"); String amount = (St ring) reque st.getAttribute ("amount "); for (int i=0; i < buy list.size();i+ ) { + BOOK anO der = (BOOK) buy list.e lementA t(i); r % > <tr> <td><b> %= anOr de r.get isbn() %></b></td> < <td><b> %= anOr de r.getAut hor () %></b></td> < <td><b> %= anOrder.getTitle() %></b> /td> < < <td><b> %= anOrder.getPublishe r() %></b> /td> < < <td><b> %= anOrder.getEdition( ) %> /b></td> < < <td><b> %= anOrder.getPrice() %></b> /td> < < <td><b> %= anOr de r.get Quant ity() %> /b> /td> < < < </tr> bor de r="0" cellpadd ing="0" width ="100 %" bg color="#FFFFFF">

<% } session.inv alidate (); % > <tr> <td > <td > </td> </td>

<td><b>TOTAL</b> /td> < <td><b>$<% amount %></b> /td> = < <td > </tr> </table> <p> <a href="Eshop.jsp">Shop som more! </a> e </cente r> </body> </htm l> </td>

Error.html: <html> <body> <h1> Sorry, there was an unrecoverable error ! <br> Plea se </h1> </body> </html> OUTPUT: try <a href="/examples/jsp/shopp ing/EShop.jsp">again</a>.

Web.xml:
<we b-app > <servlet> <servlet-name>Shopp ingServlet</servlet-name> <servlet-class >Shopp ingServlet</servlet-class> </servlet> <servlet-mapp ing> <servlet-name>Shopp ingServlet</servlet-name> <url-patte rn>/Shopp ingServlet</url-patte rn> </servlet-mapp ing> </we b-app>

ShoppingServlet.java:
import java.ut il.*; import java.io.*; import javax.servlet.*; import javax.servlet.htt p.*;

import shopp ing.BOOK; publi c class Shopp ingServlet exten ds Http Servlet { publi c voi d init(Se rvletC onfig conf) throws ServletException { super.init(conf); } publi c voi d d oPo st (Http ServletReque st req, Http ServletResponse res) throws ServletException, IOException { Http Sess ion session = req.getSession( false); if (sess ion == null) { res.sendRedirect("/error.htm l"); } Vector buy list=(Vector)sess ion. getValue ("shopp ing.shoppingcart"); String act ion = req.getParamete r("action"); if (!action.e quals("CHECKOUT")) { if (action.e quals("DELETE")) { String del = req.getParamete r("delindex"); int d = (new Inte ger(del)).intV alue (); buy list.removeElementA t(d); } else if (action.e quals("ADD")) { boo lean match=false; BOOK aCD = getBOOK(req); if (buy list==null) { buy list = new Vector(); //first order buy list. add Element( aCD); } else { // not first buy for (int i=0; i< buy list.size(); i++) { BOOK cd = (BOOK) buy list.e lementA t(i); if (cd.getTitle().equals(aCD.getTitle())) { cd.setQuant ity(cd.getQuant ity()+aCD.getQuant ity()) ; buy list.setElementA t(cd,i);

match = true ; } //end of if nam matche s e } // end of for if (!match) buy list. add Element( aCD); } } sess ion. putV alue ("shopp ing.shopp ingcart", buy list); String url="/Eshop.jsp"; // ServletConte xt sc = getServletConte xt(); Reque stDispatche r rd = req.getReque stDispatche r(url); rd. forward( req, res); } else if (action.e quals("CHECKOUT")) { float total =0; for (int i=0; i< buy list.size();i+ ) { + BOOK anO der = (BOOK) buy list.e lementA t(i); r float price= anOrder.getPrice(); int qty = anOrder.getQuant ity(); total += (price * qty ); } total += 0.00 5; String amount = new Float(total).toString(); int n = amount. indexOf('.'); amount = amount.s ubstring(0,n+3); req.setAttribute ("amount ",amount ); String url="/Che ckout. jsp"; ServletConte xt sc = getServletConte xt(); Reque stDispatche r rd = sc.getReque stDispatche r(url); rd.forward(req,res); }

} private BOOK getBOOK(Http ServletReque st req) { String myBOO K = req.getParamete r("BOOK"); String qty = req.getParamete r("qty "); St ringTo kenizer t = new StringTokenizer(myBOOK,"|"); String isbn= t.ne xtToken( ); String auth or = t.ne xtToken( ); String title = t.ne xtToken( ); String pu blishe r = t.ne xtToken( ); String Ed ition = t.ne xtToken( ); String price = t.ne xtToken( ); price = price.replace('$',' ').trim(); BOOK boo k = new BOOK(); boo k.setisbn( isbn) ; boo k.setAuth or(auth or); boo k.setTitle(title); boo k.setPublishe r(pu blishe r); boo k.setEdition( Edition) ; boo k.setPrice((ne w Float(price)).floatValue ()) ; boo k.setQuant ity((new Inte ger(qty )).intV alue ()) ; retu rn boo k; } }

book.java:
packa ge shopp ing; publi c class BOOK { String isbn; String auth or; String title; String pu blishe r;

String Edition; float price; int qu ant ity; pu blic BOOK() { isbn=""; auth or=""; title=""; pu blishe r=""; Edition=""; price=0; quant ity=0; } publi c void setPublishe r(String title1) { pu blishe r=title1; } publi c String getPublishe r() { retu rn pu blishe r; } publi c void setEdition( String group1 ) { Edition=group1; } publi c String getEdition( ) { retu rn Edition; } publi c void setisbn( String title) { isbn=title; } publi c String get isbn() { retu rn isbn; } publi c void setAuth or(String group) {

auth or=group; } publi c String getAuth or () { retu rn auth or; } publi c void setTitle(String cty) { title=cty; } publi c String getTitle() { retu rn title; } publi c void setPrice(float p) { price=p; } publi c float getPrice() { retu rn price; } publi c void setQuant ity(int q) { quant ity=q; } publi c int get Quant ity() { retu rn quant ity; } }

OUTPUT:

RESULT: Thus the cart page is dynamited with HTTP sessions and useBean concept.
Experiment :14 Aim : Write a program to implement custom tag libraries in JSP

Description : Program :

First.jsp
<%@ taglib uri="hello" prefix="examples"%> <html> <head>

<title>First Custom tags</title> </head> <body> <i><examples:hello/> </i> </body> </html> Web.xml <web-app> <taglib> <taglib-uri>hello</taglib-uri> <taglib-location>/WEB-INF/tlds/hello.tld</taglib-location> </taglib> </web-app> Create a folder called tlds

in WEB-INF directory.

Hello.tld
<taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <tag> <name>hello</name> <tag-class>tagext.HelloTag</tag-class> <body-content>JSP</body-content> </tag> </taglib>

HelloTag.java package tagext; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.TagSupport; import java.util.*; public class HelloTag extends TagSupport { public int doStartTag() { return EVAL_BODY_INCLUDE; } public int doEndTag() { Date date=new Date(); try { pageContext.getOut().write("HellOWorld"); pageContext.getOut().write("My it's"+date); }catch(Exception e){} return EVAL_PAGE; } } name is :"+getClass().getName()+"and

Output

Result : Thus the implementation of custom tag libraries in JSP is done. Experiment No : 14 Aim : Display Hello World NetBeans. Description: Apache Struts 2 is an elegant, extensible framework for creating enterprise-ready Java web applications. The framework is designed to streamline the full development cycle, from building, to deploying, to maintaining applications over time. using Struts Framework in

Apache Struts 2 was originally known as WebWork 2. After working independently for several years, the WebWork and Struts communities joined forces to create Struts2. This new version of Struts is simpler to use and closer to how Struts was always meant to be.

Implementation:
Step 1:

Step 2:

Step 3:

Step 4:

step 5:

step 6:

step 7:

step 8:

step 9:

Question & Answers


Q: Af ter I have edi te d an HTML fil e, I ca nn t vi ew th e re ult in o s m y br owse r. Why? A: Make sure that you have saved the file with a p roper name and exte nsion like "c :\myp age.htm". Also make sure that you use the same name when you open the file in your browser. Q: I have edi te d an HTML fil e, but th e changes don 't sho w in th e br owse r. Why? A: A browser caches pages so it doesn't have to read the same page twice. When you have modified a page, the browser doesn't know that. Use the bro wser's refresh/reload butt on to for ce the browser to reload the page. Q: W at br owse r shou ld I us ? h e A: You can do all the training with all of the we ll-known browsers, like Inte rne t Exp lor er, Firefox, Netscape, or Ope ra. Howeve r, some of the examples in our adv anced classes requ ire the late st versions of the browsers. Q: Doe s m c om ute r have to run Windows? W at ab ou t y p h a Mac? A: You can do all your training on a non-Windows computer like a Mac.

1. What is XML? (ans) XML is the Extensible Markup Language. It improves the functionality of the Web by letting you identify your information in a more accurate, flexible, and adaptable way. It is extensible because it is not a fixed format like HTML (which is a single, predefined markup language). Instead, XML is actually a metalanguagea language for describing other languageswhich lets you design your own markup languages for limitless different types of documents. XML can do this because it's written in SGML, the international standard metalanguage for text document markup (ISO 8879).

2.What

is a markup language?

(ans) A markup language is a set of words and symbols for describing the identity of pieces of a document (for example this is a paragraph, this is a heading, this is a list, this is the caption of this figure, etc). Programs can use this with a stylesheet to create output for screen, print, audio, video, Braille, etc. Some markup languages (eg those used in wordprocessors) only describe appearances

(this is italics, this is bold), but this method can only be used for display, and is not normally re-usable for anything else. XML is sometimes referred to as self-describing data because the names of the markup elements should represent the type of content they hold. 3. What is XML for (aka Where should I use XML)? (ans) Its goal is to enable generic SGML to be served, received, and processed on the Web in the way that is now possible with HTML. XML has been designed for ease of implementation and for interoperability with both SGML and HTML. SeeWhere's the spec? Despite early attempts, browsers never allowed other SGML, only HTML (although there were unknownplugins), and they allowed it (even encouraged it) to be corrupted or broken, which held development back for over a decade by making it impossible to program for it reliably. XML fixes that by making it compulsory to stick to the rules, and by making the rules much simpler than SGML. But XML is not just for Web pages: in fact it's very rarely used for Web pages on its own because browsers still don't provide reliable support for formatting and transforming it. Common uses for XML include: Information identification because you can define your own markup, you can define meaningful names for all your information items. Information storage because XML is portable and non-proprietary, it can be used to store textual information across any platform. Because it is backed by an international standard, it will remain accessible and processable as a data format. Information structure XML can therefore be used to store and identify any kind of (hierarchical) information structure, especially for long, deep, or complex document sets or data sources, making it ideal for an information-management back-end to serving the Web. This is its most common Web application, with a transformation system to serve it as HTML until such time as browsers are able to handle XML consistently. Publishing The original goal of XML as defined in the quotation at the start of this section. Combining the three previous topics (identity, storage, structure) means it is possible to get all the benefits of robust document management and control (with XML) and publish to the Web (as HTML) as well as to paper (as PDF) and to other formats (eg Braille, Audio, etc) from a single source document by using the appropriate stylesheets. Messaging and data transfer XML is also very heavily used for enclosing or encapsulating information in order to

pass it between different computing systems which would otherwise be unable to communicate. By providing a lingua franca for data identity and structure, it provides a common envelope for inter-process communication (messaging). Web services Building on all of these, as well as its use in browsers, machine-processable data can be exchanged between consenting systems, where before it was only comprehensible by humans (HTML). Weather services, e-commerce sites, blog newsfeeds, AJaX sites, and thousands of other data-exchange services use XML for data management and transmission, and the web browser for display and interaction. 4. What is SGML? (ans)SGML is the Standard Generalized Markup Language (ISO 8879:1986), the international standard for defining descriptions of the structure of different types of electronic document. There is an SGML FAQ from David Megginson at
http://math.albany.edu:8800/hm/sgml/cts-faq.htm

SGML is very large, powerful, and complex. It has been in heavy industrial and commercial use for nearly two decades, and there is a significant body of expertise and software to go with it. XML is a lightweight cut-down version of SGML which keeps enough of its functionality to make it useful but removes all the optional features which made SGML too complex to program for in a Web environment. 5. What is HTML? (ANS)HTML is the HyperText Markup Language (RFC 1866), which started as a small application of question A.4, SGML for the Web, originating with Tim BernersLee at CERN in 198990. It defines a very simple class of report-style documents, with section headings, paragraphs, lists, tables, and illustrations, with a few informational elements, but very few presentational elements [10], plus some hypertext and multimedia. See the question on extending HTML. The current recommendation is to use the XML version, XHTML. There is a HTML and XHTML FAQ maintained by Steven Pemberton at
http://www.w3.org/MarkUp/2004/xhtml-faq

6.Aren't XML, SGML, and HTML all the same thing? (ans) Not quite; SGML is the mother tongue, and has been used for describing thousands of different document types in many fields of human activity, from transcriptions of ancient Irish manuscripts to the technical documentation for stealth bombers, and from patients' medical and clinical records to musical notation. SGML is very large and complex, however, and probably overkill for most common office desktop applications. XML is an abbreviated version of SGML, to make it easier to use over the Web, easier

for you to define your own document types, and easier for programmers to write programs to handle them. It omits all the complex and less-used options of SGML in return for the benefits of being easier to write applications for, easier to understand, and more suited to delivery and interoperability over the Web. But it is still SGML, and XML files may still be processed in the same way as any other SGML file (see the question on XML software). HTML is just one of many SGML or XML applicationsthe one most frequently used on the Web. Technical readers will find it more useful to think of XML as being SGML rather than HTML++. 7.Who is responsible for XML? (ans) XML is a project of the World Wide Web Consortium (W3C), and the development of the specification is supervised by an XML Working Group. A Special Interest Group of co-opted contributors and experts from various fields contributed comments and reviews by email. XML is a public format: it is not a proprietary development of any company, although the membership of the WG and the SIG represented companies as well as research and academic institutions. The v1.0 specification was accepted by the W3C as a Recommendation on Feb 10, 1998. 8.Why is XML such an important development? (Ans) It removes two constraints which were holding back Web developments: dependence on a single, inflexible document type (HTML) which was being much abused for tasks it was never designed for; the complexity of full question A.4, SGML, whose syntax allows many powerful but hard-to-program options. XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary, persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web; and it removes the more complex options of SGML, making it easier to program for. 9.Why not just carry on extending HTML? (ans) HTML was already overburdened with dozens of interesting but incompatible inventions from different manufacturers, because it provides only one way of describing your information. XML allows groups of people or organizations to question C.13, create their own customized markup applications for exchanging information in their domain (music, chemistry, electronics, hill-walking, finance, surfing, petroleum geology, linguistics, cooking, knitting, stellar cartography, history, engineering, rabbit-keeping, question C.19, mathematics, genealogy, etc).

HTML is now well beyond the limit of its usefulness as a way of describing information, and while it will continue to play an important role for the content it currently represents, many new applications require a more robust and flexible infrastructure. 10.Why should I use XML? (aka What is XML for?) (ans) Here are a few reasons for using XML (in no particular order). Not all of these will apply to your own requirements, and you may have additional reasons not mentioned here (if so, please let the editor of the FAQ know!). XML can be used to describe and identify information accurately and unambiguously, in a way that computers can be programmed to understand your information (well, at least manipulate as if they could understand it). XML allows documents which are all the same type to be created and handled consistently and without structural errors, because it provides a standardised way of describing, controlling, or allowing/disallowing particular types of document structure. [Note that this has absolutely nothing whatever to do with formatting, appearance, or the actual text or data content of your documents, only the structure of them. If you want styling or formatting, see question C.24, How do I control formatting and appearance?.] XML provides a robust and durable format for information storage and transmission. Robust because it is based on a proven standard, and can thus be tested and verified; durable (persistent) because it uses plain-text file formats which will outlast proprietary binary ones. XML provides a common syntax for messaging systems for the exchange of information between applications. Previously, each messaging system had its own format and all were different, which made inter-system messaging unnecessarily messy, complex, and expensive. If everyone uses the same syntax it makes writing these systems much faster and more reliable. XML is free. Not just free of charge (free as in beer) but free of legal encumbrances (free as in speech). It doesn't belong to anyone, so it can't be hijacked or pirated. And you don't have to pay a fee to use it (you can of course choose to use commercial software to deal with it, for lots of good reasons, but you don't pay for XML itself). XML information can be manipulated programmatically (under machine control), so XML documents can be pieced together from disparate sources, or taken apart and re-used in different ways. They can be converted into any other format with no loss of information. XML lets you separate form (appearance) from content. Your XML file contains your document information (text, data) and identifies its structure: your formatting and other processing needs are identified separately in a stylesheet or processing system. The two are combined at output time to apply the required formatting to the text or data identified by its structure (location, position, rank, order, or whatever).

Any of the Design Goals listed in the XML Specification. 11. Where do I find more information about XML? (ans) Online, there's the XML Specification and the ancillary documentation available from the W3C; Robin Cover's SGML/XML Web pages with an extensive list of online reference material and links to software; and a summary and condensed FAQFPRIVATE Google or other search engine. For offline resources, see the lists of books, articles, and software for XML in Robin Cover's SGML and XML Web pages. That site should always be your first port of call. The events listed below are the ones I have been told about. Please mail me if you come across others: there are many other XML events around the world, and most of them are announced on the mailing lists and newsgroups. 12.Where can I discuss implementation and development of XML? (Ans) The two principal online support media are Usenet newsgroups and mailing lists. The IRC network is also used to some extent, and most individual projects and programs have their own topic-specific bulletin-boards on their web sites. For off-line support, see question A.11, Where do I find more information about XML? for details of conferences and summerschools. The Usenet newsgroups are comp.text.xml and to a certain extent comp.text.sgml. Ask your Internet Provider for access to these, or use a Web interface like Google Groups. If your browser or mailer doesn't provide newsreading facilities, install one that does, or (better) use a standalone newsreader. The general-purpose mailing list for public discussion is XML-L: to subscribe, visit the Web site and click on the link to join. For those developing software components for XML there is the xml-dev mailing list. You can subscribe by sending a 1line mail message to xml-devrequest@lists.xml.org saying just SUBSCRIBE. Note that this list is for those people actively involved in developing resources for XML. It is not for general information about XML (use the XML-L list above for that). The XSL-List is for for discussing XSL (both XSLT and XSL:FO). For details of how to subscribe, see http://www.mulberrytech.com/xsl/xsl-list. 13. What is the difference between XML and C or C++ or Java? (ans) C and C++ (and other languages like FORTRAN, or Pascal, or Visual Basic, or Java or hundreds more) are programming languages with which you specify calculations, actions, and decisions to be carried out in order:
mod curconfig[if left(date,6) = "01-Apr", t.put "April Fool!", f.put days('31102005','DDMMYYYY') days(sdate,'DDMMYYYY')

" more shopping days to Samhain"];

XML is a markup specification language with which you can design ways of describing information (text or data), usually for storage, transmission, or processing by a program. It says nothing about what you should do with the data (although your choice of element names may hint at what they are for):
<part num="DA42" models="LS AR DF HG KJ" update="2001-11-22"> <name>Camshaft end bearing retention circlip</name> <image drawing="RR98-dh37" type="SVG" x="476" y="226"/> <maker id="RQ778">Ringtown Fasteners Ltd</maker> <notes>Angle-nosed insertion tool <tool id="GH25"/> is required for the removal and replacement of this part.</notes> </part>

On its own, an SGML or XML file (including HTML) doesn't do anything. It's a data format which just sits there until you run a program which does something with it. See also the question about how to run or execute XML files.

: Are sessions created on the server side? A: A servlet session is created and stored on the server side. The servlet container
keeps track of all the sessions it manages and fulfils servlet API requests to get HttpSessions, manipulate object data stored with them and trigger event callbacks. To the maintain the session, Web clients must pass back a valid session identifier as a cookie header value or dynamically generated URL parameter. In this sense, the session is also stored by the client, but only as a token reference. Q: Can I create a session with GenericServlet?

A: There are no protocol-specific features in GenericServlet, which is an


implementation of the basic, general purpose Servlet interface. Servletbased

sessions are designed only for interactions using the HTTP protocol, which has two key features necessary for a servlet container to simulate continuous user sessions: cookies and URL-based navigation, which supports URL-rewriting. The servlet API therefore places the HttpSession interface in the javax.servlet.http package, and session references are only available through classes in this package. Q: How can I assemble data from multiple input forms?

A: First, it is best to use a single servlet to handle each form submission. A single
servlet for all input would be too complicated. Give each servlet responsibility to validate a single form input, and pass the error cases on to JSP documents that explain the problem and allow users to amend the input.

Servlet concepts
Q: What's the difference between applets and servlets? A: There are many fundamental differences between Applet and Servlet
classes, the Java API documentation for the two types will show you they have little in common. Applets are essentially graphical user interface (GUI) applications that run on the client side in a network environment, typically embedded in an HTML page. Applets are normally based on Abstract Windowing Toolkit components to maintain backward-compatibility with the widest range of browsers' Java implementations. The application classes are downloaded to the client and run in a Java Virtual Machine provided by the browser, in a restrictive security environment called a "sandbox". Servlets are used to dynamically generate HTTP responses and return HTML content to Web browsers on the server side. Servlets are often used to validate and process HTML form submissions and control a series of user interactions in what is known as a Web application. Servlets can be used to control all aspects of the request and response exchange between a Web browser and the server, called a servlet container. Q: How can I write a servlet using Javascript?

A: Java servlets is a server side technology that delivers dynamic content to Web
browsers and other clients. Javascript is also delivered by a Web server, but the code is only interpreted and executed after it has been downloaded by the Web browser. This means that it is not possible to write servlet code in Javascript. It is possible to include Javascript in the output of servlets and Java Server Pages, just like standard Web pages. It is also possible to dynamically generate

Javascript using a servlet and use it as the source for a script tag, though this is only advisable in rare cases. Q: How does the JVM execute a servlet compared with a regular Java class?

A: Servlets are standard Java classes and are executed by the Java Virtual
Machine in exactly the same way as any other. However, the environment or context in which servlets are executed is different. A servlet is not invoked directly through a main method, the class is loaded and run by a servlet container.

Can I include normal Java classes in servlets?

A: Any Java class can be used in a Web application, provided you make the
classes available to the servlet container at runtime. The Java API classes can be used directly by adding import statements to your servlet class. Other supporting classes can also be imported, but these classes must be added to the classes or lib directory of your application. If you need to configure the supporting classes, this can be done with standard servlet configuration features using the ServletConfig and ServletContext objects available to the init(ServletConfig) method. Q: How can I tell when a servlet is instantiated?

A: A servlet must be instantiated before it is brought into service by the servlet


container, so one way to check is to make a request to the servlet and check the response. If you need to check indirectly, you can override the init(ServletConfig) method and add log(String) statements to it. This method is called after the servlet container has instantiated the servlet before it is brought into service.

Q: What is URL-rewriting? A: URL-rewriting is a way of maintaining a session between an HTTP client and
a servlet container which does not use cookies. Rather than exchange a session ID in a cookie, the servlet container includes it in the hyperlink URLs it generates for servlets and JSP.

: Are servlets multi-threaded? A: Yes, servlets are normally multi-threaded. The servlet container allocates a
thread for each new request for a single servlet without any special programming. Each thread of your servlet runs as if a single user were accessing it alone, but

you can use static variables to store and present information that is common to all threads, like a hit counter for instance. How can I pass values between JSPs without using sessions?

A: There are four main alternatives to full session-based transfer of data values,
two of them use features of the session tracking API: cookies and URL-rewriting, detailed below. What is JavaServer Pages technology? JavaServer Pages (JSP) technology provides a simplified, fast way to create web pages that display dynamically-generated content. The JSP specification, developed through an industry-wide initiative led by Sun Microsystems, defines the interaction between the server and the JSP page, and describes the format and syntax of the page. How does the JavaServer Pages technology work? JSP pages use XML tags and scriptlets written in the Java programming language to encapsulate the logic that generates the content for the page. It passes any formatting (HTML or XML) tags directly back to the response page. In this way, JSP pages separate the page logic from its design and display. JSP technology is part of the Java technology family. JSP pages are compiled into servlets and may call JavaBeans components (beans) or Enterprise JavaBeans components (enterprise beans) to perform processing on the server. As such, JSP technology is a key component in a highly scalable architecture for web-based applications. JSP pages are not restricted to any specific platform or web server. The JSP specification represents a broad spectrum of industry input. What is a servlet? A servlet is a program written in the Java programming language that runs on the server, as opposed to the browser (applets). Detailed information can be found at http://java.sun.com/products/servlet. Why do I need JSP technology if I already have servlets? JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-based applications. However, JSP technology was designed to simplify the process of creating pages by separating web presentation from web content. In many applications, the response sent to the client is a combination of template data and dynamically-generated

data. In this situation, it is much easier to work with JSP pages than to do everything with servlets. Where can I get the most current version of the JSP specification? The JavaServer Pages 2.1 specification is available for download from here. How does the JSP specification relate to the Java Enterprise Edition 5 Platform? The JSP 2.1 specification is an important part of the Java EE 5 Platform. Using JSP and Enterprise JavaBeans technologies together is a great way to implement distributed enterprise applications with web-based front ends. Which web servers support JSP technology? There are a number of JSP technology implementations for different web servers. The latest information on officially-announced support can be found at http://java.sun.com/products/jsp/industry.html. Is Sun providing a reference implementation for the JSP specification? The GlassFish project is Sun's free, open-source Java EE 5 implementation. It includes an implementation of JSP technology version 2.1. You can download GlassFish builds from https://glassfish.dev.java.net/. How is JSP technology different from other products? JSP technology is the result of industry collaboration and is designed to be an open, industry-standard method supporting numerous servers, browsers and tools. JSP technology speeds development with reusable components and tags, instead of relying heavily on scripting within the page itself. All JSP implementations support a Java programming language-based scripting language, which provides inherent scalability and support for complex operations. Where do I get more information on JSP technology? The first place to check for information on JSP technology is http://java.sun.com/products/jsp/. This site includes numerous resources, as well as pointers to mailing lists and discussion groups for JSP technology-related topics.

You might also like