You are on page 1of 112

Week-1 Date: 23-06-08 ----------------------------------------------------------------------------------------------------------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.html"name="f1"> <frameset cols="20%,*"> <frame src="leftframe.html"name="f2"> <frame src="rightframe.html"name="f3"> </frameset> </frameset>

</head> Prasad V. Potluri Siddhartha Institute of Technology 1 OUTPUT: Top frame: <html> <body> <p> <img src="C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Winter.jpg" align=left width=100 height=100"> <h1 align=center>Online book store</h1> </p> <br> Prasad V. Potluri Siddhartha Institute of Technology 2 <p> <h2>&nbsp;nbsp;&nbsp;&nbsp; <a href="homepage.html" target=_parent> Home </a> &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; <a href="login.html" target="f3"> login </a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="registration.html" target="f3">

registration </a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nbsp;&nbsp;&nbsp; <a href="catalogue.html" target="f3"> Catalogue </a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="cart.html" target="f3"> Cart </a> &nbsp; </h2> </p> </body> </html> Prasad V. Potluri Siddhartha Institute of Technology 3 OUTPUT: Leftframe: <html> <body> <a href=cse.html target="f3"><h3>CSE</h3> </a><br><br><br><br><br> <a href=ece.html target="f3"><h3>ECE</h3></a><br><br><br><br><br> <a href=eee.html

&nbsp. &nbsp. Potluri Siddhartha Institute of Technology 4 </body> </html> OUTPUT: Right frame: <html> <body bgcolor="pink"> <p> <h2 align="center"> <font face="times new roman" color="green" >Online book store information </font> </h2> Prasad V. &nbsp. . Potluri Siddhartha Institute of Technology 5 <h3> &nbsp.ece.eee.html target="f3"><h3>Civil</h3></a> Prasad V.civil </font></h3> </p> </body> </html> OUTPUT: 2) LOGIN PAGE DESCRIPTION: The login page contains the user name and the password of the user to authenticate. &nbsp.target="f3"><h3>EEE</h3></a><br><br><br><br><br> <a href=civil.<font face="monotype corsiva" color=blue> This is the online book store developed by students of pvpsit.It contains book catalogue of various branches like cse.

&nbsp.&nbsp.PROGRAM: Prasad V.&nbsp.&nbsp.jsp" method="get"> <label> &nbsp.&nbsp.&nbsp. "> </head> <body background=”E:\1. position:absolute. Potluri Siddhartha Institute of Technology 6 <html> <head> <p style= "background:yellow. <input type="text" size="20" maxlength="20" value=' '><br><br><br> <label> <font face="comic sans ms" color="green" size="5">Password </font> </label> <input type="password" size="20" maxlength="20"> <br><br><br> &nbsp. left:250px. <input type="reset"> </form> </body> . <input type="submit" value="submit">&nbsp.&nbsp.&nbsp.&nbsp. &nbsp. &nbsp.&nbsp.&nbsp.&nbsp. <font face="comic sans ms" color="green" size="5">Login </font> </label> &nbsp.&nbsp.&nbsp.jpg”> <form action="index. &nbsp. &nbsp. top:100px.

The details should contain the following: 1. 5. Snap shot of Cover Page. 4. Prasad V. 3. Potluri Siddhartha Institute of Technology 7 3) CATOLOGUE PAGE DESCRIPTION: The catalogue page should contain the details of all the books available in the web site in a table. PROGRAM: <html> <body> <center> <table border=1> <tr> <th> Book Preview </th> <th> Book Details </th> <th> Price </th> <th> Payment </th> </tr> .</html> OUTPUT: Prasad V. Publisher. Price. Potluri Siddhartha Institute of Technology 8 2. Add to cart button. Author Name.

<tr> <td> <img src="C:\Documents and Settings\All users\My Documents\My Pictures\xml.$40 &nbsp. &nbsp. &nbsp. <a href="cart. Potluri Siddhartha Institute of Technology 9 <td> &nbsp.html" target="_blank"> <img src="C:\Documents and Settings\All users\My Documents\My Pictures\cart.bmp" width=100 height=50> . </td> Prasad V.bmp" width=100 height=50> </img> </td> <td> <pre> <font face="comic sans ms" size=4 color="green" > book:XML Bible Author:winston Publisher:Wiesley </font> </pre> </td> <td>&nbsp.bmp" width="150" height="100"></img> </a> &nbsp. </td> </tr> <tr> <td> <img src="C:\Documents and Settings\All users\My Documents\My Pictures\java.

&nbsp.bmp" width="150" height="100"></img> </a> &nbsp. </td> </tr> </table> </center> </body> </html> OUTPUT: Prasad V. Potluri Siddhartha Institute of Technology 11 RESULT: .html" target="_blank"> <img src="C:\Documents and Settings\All users\My Documents\My Pictures\cart. Potluri Siddhartha Institute of Technology 10 Prasad V. <a href="cart.</img> </td> <td> <pre> <font face="comic sans ms" size=4 color="green" > book:Java 2 Author:Watson Publisher:BPB publications </font> </pre> </td> <td>&nbsp. $40 &nbsp. &nbsp.</td> <td> &nbsp.

login page. Potluri Siddhartha Institute of Technology 12 Week-2 Date: 30-06-08 ----------------------------------------------------------------------------------------------------------AIM: Design of the cart page and the registration page required for online book store. catalogue page for the online book store are created successfully Prasad V.jpg”> <table border=1 cellpadding=center> <thead> <tr> <th>Book name</th> <th>price</th> <th>quantity</th> <th>amount</th> </tr> </thead> <tr> . 4) CART PAGE DESCRIPTION: The cart page contains the details about the books which are added to the cart. PROGRAM: <html> <body> <center><br><br><br> <img src=”E:\aa.Thus the home page.

<td>java 2</td> <td>$45</td> <td>2</td> <td>$70</td> </tr> <tr> Prasad V. Potluri Siddhartha Institute of Technology 13 <td> XML bible</td> <td> $20</td> <td> 5</td> <td> $40</td> </tr> <th colspan=4>total amount=$110> </th> </tr> </table> </center> </body> </html> OUTPUT: Prasad V. Potluri Siddhartha Institute of Technology 14 5) REGISTRATION PAGE DESCRIPTION: Create a “registration form “with the following fields 1)Name(Textfield) .

Potluri Siddhartha Institute of Technology 15 .jpg” align=”left”> <form> <label>name</label> <input type="text" size="20"><br><br> <br> <label>password</label> <input type="password" size="20" maxsize="28"><br> <br> <br> <label>email</label> <input type="text" size="30"><br> <br> <br> <label>phone no</label> <input type="text" size="2"> <input type="text" size="6"> <input type="text" size="10"><br> <br> <br> <label>Sex</label> Prasad V.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. Tamil) 8) Address (text area) PROGRAM: <html> <body> <center> <img src=”E:\aaa. Telugu. Hindi.

&nbsp. <input type="checkbox"> English &nbsp. &nbsp. . &nbsp.&nbsp. &nbsp. <input type="checkbox"> Telugu &nbsp.<input type="radio" name="sex">m <input type="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>apr</option> </select> <select> <option>1980</option> <option>1981</option> <option>1982</option> <option>1983</option> </select> <br> <br> <br> <label> Languages Known </label> &nbsp.

3. <input type="checkbox"> Tamil <br> <br> <br> <label> Address </label> <textarea rows=5 cols=20 scrolling="yes"> </textarea> </center> </body> Prasad V. Name (Name should contains alphabets and the length should not be less than 6 characters). Potluri Siddhartha Institute of Technology 16 </html> OUTPUT: RESULT: Thus the registration and cart pages for online book store pages are created successfully Prasad V.com) 4. Password (Password should not be less than 6 characters length). Potluri Siddhartha Institute of Technology 17 Week-3 Date: 14-07-08 ----------------------------------------------------------------------------------------------------------AIM: Write JavaScript to validate the following fields of the above registration page.<input type="checkbox"> Hindi &nbsp. Phone number (Phone number should contain 10 digits only). DESCRIPTION: JavaScript is a simple scripting language invented specifically for use in web . 2. &nbsp. &nbsp. 1. E-mail id (should not contain any invalid and must follow the standard pattern name@domain.

either Prasad V. They can be created statically when the script is first parsed or dynamically at run time. thus changing how things are presented on your screen. some visitors are going to get it wrong. and modify this information. from changing text. Here’s where regular expressions come in handy. A regular expression is a way of describing a pattern in a piece of text. This is also a very powerful ability. even if we are very careful about putting some hints next to each required field. phone number and email address. A regular expression is a JavaScript object. it’s an easy way of matching a string to a pattern. quickly. They can also react to events. Normally. JavaScripts are integrated into the browsing environment.browsers to make websites more dynamic. or points to a certain page element. This saves us from difficulties and allows us to write clean and tight code. Potluri Siddhartha Institute of Technology 18 accidentally or for malicious purposes. JavaScript is a client-side language. which means they can get information about the browser and HTML page. A static regular expression is created as follows: . HTML is capable of outputting more-or-less static pages. However. and so forth. Regular Expressions: One of the most common situations that come up is having an HTML form for users to enter data. Adding JavaScript to your code allows you to change how the document looks completely. whether or not any given string is a properly formatted user input. On its own. We could write a simple regular expression and use it to check. such as when the user clicks their mouse. This access to information gives JavaScript great power to modify the browsing experience. In fact. to changing the options available in a drop-down list. to changing colors. we might be interested in the visitor’s name. Once you load them up your view doesn't change much until you click a link to go to a new page. There are multiple ways of creating them.

user. exec() returns a null value. It updates some of the properties of the parent RegExp object following a successful search.]{3}$").ph. This method returns a Boolean that indicates whether or not the specified pattern exists within the searched string.]{2}$|^[a-zA-Z][a-zA-Z0-9_. [a-zA-Z][a-zA-Z0-9_.value.]*@[a-zAZ][ a-zA-Z0-9_.forms[0]. If the pattern is not found.value.forms[0].]*.forms[0]. Functions: test(string).value. var emailreg=new RegExp("^[a-zA-Z][a-zA-Z0-9_. var pwdv=document.forms[0].regx=/fish|fow1/.]{2}. This is the most commonly used method for validation.email.]*. Potluri Siddhartha Institute of Technology 19 . Prasad V.js function fun() { var userv=document.Executes a search for a pattern within a string.value. If it finds one or more matches it returns an array of the match results.[a-zA-Z][a-zA-Z0-9_. It also updates some of the properties of the parent RegExp object PROGRAM: Valid. var userreg=new RegExp("^[a-zA-Z][a-zA-Z0-9]*$").[a-zA-Z][a-zA-Z0-9_. var phv=document.Tests a string for pattern matches. Dynamic patterns are created using the keyword to create an instance of the RegExp class: regx=new RegExp(“fish|fow1”).pwd. var emailv=document.]*@[a-zA-Z][a-zA-Z0-9_. exec(string).

} } Register.user.} if(!rph) { alert("phone number invalid").focus().exec(emailv).} return false.document.} if(!remail) { alert("password invalid").focus().document.document. } else { if(!ruser) { alert("username invalid").length > 6)) { alert("All values are valid").exec(phv).document.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> .exec(userv).forms[0].ph.} if(pwdv.focus().forms[0].focus(). var ruser=userreg. var rph=phreg.var phreg=new RegExp("^[0-9]{10}$"). return true. if(ruser && remail && rph && (pwdv. var remail=emailreg.pwd.forms[0].forms[0].length < 6) { alert("password invalid").user.

Potluri Siddhartha Institute of Technology 22 Week-4 Date: 21-07-08 ----------------------------------------------------------------------------------------------------------AIM: Design a web page using CSS (Cascading Style Sheets) which includes the following: 1) Use different font. login page. styles: In the style definition you define how each selector should work . Potluri Siddhartha Institute of Technology 21 RESULT: Thus the home page. in the body of your pages. . you refer to these selectors to activate the styles.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. catalogue page for the online book store are created successfully Prasad V.js"></script> </html> OUTPUT: Prasad V.Then. Potluri Siddhartha Institute of Technology 20 Prasad V.

. in an external style sheet. or only those elements which match a certain attribute. or on how they are nested within the document object model A style sheet consists of a list of rules. or in a browser (a default value). which means that it will override a style declared inside the <head> tag. a colon (:). Each rule or rule-set consists of one or more selectors and a declaration block. External style sheet 2. a value. Inline style (inside an HTML element) An inline style (inside an HTML element) has the highest priority. Potluri Siddhartha Institute of Technology 23 Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet by the following rules: 1. Internal style sheet (inside the <head> tag) 3. 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. a kind of match expression.2) Set a background image for both the page and single elements on the page.) Prasad V. elements may be matched depending on how they are placed relative to each other in the markup code. selectors are used to declare which elements a style applies to. A declaration-block consists of a list of semicolon-separated declarations in braces. Each declaration itself consists of a property. but the language can be applied to any kind of XML document. In CSS. Its most common application is to style web pages written in HTML and XHTML. Selectors may apply to all elements of a specific type. then a semi-colon (.

<head> Prasad V.. Internal Style Sheet An internal style sheet should be used when a single document has a unique style. property:value. 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. the property is the attribute you wish to change. and format the document according to it.css.css" /> </head> The browser will read the style definitions from the file mystyle.} . You define internal styles in the head section by using the <style> tag. Potluri Siddhartha Institute of Technology 24 <style> selector {property:value. you can change the look of an entire Web site by changing one file. The property and value are separated by a colon. 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. a property and a value: selector {property: value} The selector is normally the HTML element/tag you wish to define. and each property can take a value. With an external style sheet.Syntax The CSS syntax is made up of three parts: a selector.

font-family:comic sans ms.css: a:link{color:black. The style attribute can contain any CSS property. text-decoration:underline. font-size:30. <p style="color: sienna. .image { text-align:left. } . margin-left: 20px"> This is a paragraph </p> PROGRAM: Cas.} a:hover{color:green.} a:visited{color:pink.</style> </head> Inline Styles An inline style loses many of the advantages of style sheets by mixing content with presentation.right { text-align:center. color:blue. such as when a style is to be applied to a single occurrence of an element.} a:active{color:red. Use this method sparingly. To use inline styles you use the style attribute in the relevant tag. font-weight:bold.} .

xlink{ text-decoration:none. background-attachment:fixed. width:150.html: <html> <head> <link rel="stylesheet" href="cas. background-repeat:no-repeat. height:150. Prasad V.font-weight:bold. Potluri Siddhartha Institute of Technology 25 font-weight:10. border-style:ridge.} htm. border-color:yellow. } table { align:center. } .jpg").} </style> </head> <body class="image"> <p style="text-align:right.image1 { background-image:url("C:\Documents and Settings\All Users\My Documents\My Pictures\krishna.css" type="text/css"> <style> ."> .cursor:help.font-weight:bold.font-family:"monotype corsiva".} .cursor:crosshair.ylink{text-decoration:underline.border:10.

. Potluri Siddhartha Institute of Technology 26 <div style="position:relative.font-size:90px.top:-70.font-size:50px.html" class="xlink"> Reg Link</a>&nbsp. Potluri Siddhartha Institute of Technology 27 RESULT: Thus different style of CSS and different type of the properties are applied.z-index:5.font-size:90px.top:-70.color:purple.">CSE</div> <table align="center" class="image1"> <tr> <td> Fruits</td> <td> Mango</td> </tr> </table> </body> </html> OUTPUT: Prasad V.">PVPSIT</div> <div style="position:relative. <a href="topframe.zindex: 1.html" class="ylink"> Help Link</a> </p> <p class="right">PVPSIT</p> Prasad V.">PVPSIT</div> <div style="position:relative.color:blue.<a href="registration.font-size:50px.">CSE</div> <div style="position:relative.z-index:1.&nbsp.zindex: 5.color:purple. left:5. left:5.color:blue.

The header of the table should be in color GREY. The contents should be displayed in a table. with all the benefits this entails. Display the XML file as follows. 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. And the Author names column should be displayed in one color and should be capitalized and in bold. Potluri Siddhartha Institute of Technology 28 Write a Document Type Definition (DTD) to validate the above XML file. . It includes the following: 1) Title of the book 2) Author Name 3) ISBN number 4) Publisher name 5) Edition 6) Price Prasad V. An XML Schema provides this. and it provides an Object Oriented approach. 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.Week-5: Date: 28-07-08 ----------------------------------------------------------------------------------------------------------AIM: Write an XML file which will display the Book information. Use XML schemas XSL and CSS for the above purpose. Use your own colors for remaining columns.

etc. and an XML DTD to define it. DTD is also established. Potluri Siddhartha Institute of Technology 29 PROGRAM: XML document (bookstore. · Write a Document Type Definition (DTD) to validate the XML file. then this overhead may seriously degrade performance. Finally. and examples of common objects defined in a DTD abound on the Internet -. and validate the schema. They are mature definitions. you must also consider the fact that the XML Schema is an XML document.. The effort in re-writing the definition may not be worthwhile. When a parser examines the document. load the namespace.Many systems interfaces are already defined as a DTD. interpret the DTD for the Schema. It has an XML Namespace to refer to. and need a quick response. rich and complex. Prasad V. it may have to link this all in.xml) <bookstore> <book> <title>web programming</title> <author>chrisbates</author> <ISBN>123-456-789</ISBN> <publisher>wiley</publisher> <edition>3</edition> . If you're using XML as a protocol between two systems that are in heavy 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. This is all overhead. all before it can parse the actual XML document in question.freely available for re-use.

author.0" encoding="UTF-8"?> <!ELEMENT bookstore (book+)> <!ELEMENT book (title.publisher.price)> <!ELEMENT title (#PCDATA)> <!ELEMENT author (#PCDATA)> <!ELEMENT ISBN (#PCDATA)> <!ELEMENT publisher (#PCDATA)> <!ELEMENT edition (#PCDATA)> <!ELEMENT price (#PCDATA)> Bookstore.edition.dtd"> .ISBN.dtd) <?xml version="1.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.<price>350</price> </book> <book> <title>internet worldwideweb</title> <author>ditel&amp.xml <!DOCTYPE bookstore SYSTEM "C:\Documents and Settings\Administrator\My Documents\bookstore.

<bookstore> <book> <title>web programming</title> <author>chrisbates</author> <ISBN>123-456-789</ISBN> Prasad V.0" encoding="UTF-8"?> <xs:schema elementFormDefault="qualified" attributeFormDefault="unqualified" xmlns:xs="http://www.xsd) <?xml version="1.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.org/2001/XMLSchema"> <xs:element name="bookstore"> . Potluri Siddhartha Institute of Technology 30 <publisher>wiley</publisher> <edition>3</edition> <price>350</price> </book> <book> <title>internet worldwideweb</title> <author>ditel&amp.w3.

w3.<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> Prasad V. Potluri Siddhartha Institute of Technology 31 Bookstore.xml <bookstore xmlns:xsi="http://www.xsd"> <book> <title>web programming</title> .org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="C:\Documents and Settings\Administrator\My Documents\bookstore.

PROGRAM: XML: <?xml version="1.<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.xsl"?> <bookstore> <book> <title>Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> .0"?> <?xml-stylesheet type="text/xsl" href="bookstore.

Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore> XSL: <xsl:stylesheet version="1. Rowling</author> <year>2005</year> <price>29.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body> <h2> My Books collection</h2> <table border="1"> <tr bgcolor="red"> .00</price> </book> <book> <title>Harry Potter</title> Prasad V.<price>30.0" xmlns:xsl="http://www.w3.99</price> </book> <book> <title>Learning XML</title> <author>Erik T. Potluri Siddhartha Institute of Technology 32 <author>J K.

<th align="left">title</th> <th align="left">author</th> </tr> <xsl:for-each select="bookstore/book"> <tr> <td><xsl:value-of select="title"/></td> <xsl:choose> <xsl:when test="price &gt. 10"> Prasad V. Potluri Siddhartha Institute of Technology 33 <td bgcolor="magneta"><xsl:value-of select="author"/></td> </xsl:when> <xsl:otherwise> <td><xsl:value-of select="author"/></td> </xsl:otherwise> </xsl:choose> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> . 30"> <td bgcolor="yellow"><xsl:value-of select="author"/></td> </xsl:when> <xsl:when test="price &gt.

Beans may be visible objects. The color of the area should be changed dynamically for every mouse click. Week-6: Date: 04-08-08 Prasad V. If it is set to true then the shape of the area is Square and it is Circle. Potluri Siddhartha Institute of Technology 34 ----------------------------------------------------------------------------------------------------------VISUAL BEANS: AIM: Create a simple visual bean with a area filled with a color. Beans consist of three things: An event allows your Beans to communicate when something interesting happens. or invisible objects. like AWT components. Beans are independent. reusable software modules. There are three parts to this communication: EventObject Event Listener .(the sink) An Event Source (the Bean) . The shape of the area depends on the property shape. A builder/integration tool manipulates Beans to create applets and applications. if it is false.OUTPUT: RESULT: Thus the XML stylesheets are successfully used to display the content in a table format. like queues and stacks. The color should also be changed if we change the color in the “property window “. DESCRIPTION: A Bean is a JavaBeans component.

and they receive notification when the event happens.The event source defines when and where an event will happen. among others. public synchronized void removeListenerType( ListenerType l). For instance. becomes the property name . read-only. The design pattern for these properties is: public void setPropertyName (PropertyType[] list) public void setPropertyName ( PropertyType element. The event is of type propertyChangeEvent and is sent to objects that previously registered an interest in receiveing such notifications. In . int position) public PropertyType[] getPropertyName () public PropertyType getPropertyName (int position) – A bean that has the bound property generates an event when the property is changed. define a pair of set/get routines. when examining an AWT TextField for its properties. A property is a public attribute of the Bean. Potluri Siddhartha Institute of Technology 35 represented by a non-public instance variable. To create a property. There are four different types of properties: . simple properties represent the simplest of the four. usually Prasad V. and the echo character.As the name implies. current text. Properties define the characteristics of the Bean.An indexed property is for when a single property can hold an array of values. Classes register themselves as interested in the event. A series of methods patterns represents the registration process: public synchronized void addListenerType(ListenerType l). Whatever name used in the pair of routines. you will see properties for the caret position. It can be read-write. or writeonly.

the listener throws a PropertyVetoException. Bean methods are available for anyone to call by just making each public. Then. it asks the VetoableChangeListeners if its okay. First. Potluri Siddhartha Institute of Technology 36 VetoableChangeListeners. } . the Bean maintains a list of Prasad V. } public void removePropertyChangeListener ( PropertyChangeListener p) { changes. which you declare the set routine to throw. Every .addPropertyChangeListener (p). And then. you can restrict which methods are visible to the Bean builder/integration tool by providing a getMethodDescriptors method along with your Bean's BeanInfo. you need to maintain a watch list for PropertyChangeEvents via the PropertyChangeSupport class.Constrained properties are similar to bound properties. However.removePropertyChangeListener (p).order for the notification to happen. you have to create a list of listeners to maintain: private PropertyChangeSupport changes = new PropertyChangeSupport (this). If it isn't. In addition to maintaining a list of PropertyChangeListeners. you have to maintain the list: public void addPropertyChangeListener ( PropertyChangeListener p) { changes. prior to the Bean changing a property value.

*.Bean can provide a supporting BeanInfo class to customize a Bean's appearance to an integration tool. PROGRAM: package sunw. Potluri Siddhartha Institute of Technology 37 { addMouseListener(new MouseAdapter(){ .awt.mft in the directory called as C:\beans\demo 5) Create a jar file. import java.event.\jars\colors. public class Colors extends Canvas { transient private Color color.class 6) Start the BDK 7) Check whether the colors bean is placed in toolbox or not. Procedural Steps to create a Java-Bean: 1) Creating a directory.demo.mft sunw\demo\colors\*. import java.awt.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.. public Colors() Prasad V.colors.jar colors. private boolean rectangular.*.to create a jar file type the following command in the command prompt jar cfm .

} public void setRectangular(boolean flag) { this. repaint(). } public boolean getRectangular() { return rectangular.random()). } public void change() { color=randomColor().random()). int g=(int)(255*Math. } private Color randomColor() { int r=(int)(255*Math. change().rectangular=flag. setSize(100.100). . rectangular=false.public void mousePressed(MouseEvent me){ change(). repaint(). } }).

w-1.height.h-1).w-1. Potluri Siddhartha Institute of Technology 39 RESULT: Thus the colors bean is created successfully.g.int b=(int)(255*Math.random()). } } } OUTPUT: Prasad V. } else { g. if(rectangular) { g.b).fillOval(0.0.fillRect(0.0.h-1). } public void paint(Graphics g) Prasad V. int h=d. int w=d.setColor(color). g. Program 2: . return new Color(r.width. Potluri Siddhartha Institute of Technology 38 { Dimension d=getSize().

import java.event. } public void setRupees(double value) { .demo.Visual Beans (program 2) Convert.0. import java.*.0.dollars=value. private double dollarvalue=0.java package sunw. } public void setDollars(double value) { this.*. public class convert extends Canvas { private double dollars=0.awt.convert.awt.1000). private double rupees=0.0. } public double getDollars() Prasad V. public convert() { setSize(100. Potluri Siddhartha Institute of Technology 40 { return dollars.

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

Potluri Siddhartha Institute of Technology 43 setSize(100. public class mouseclick extends Canvas { public int count=0.awt. import java.event.awt. } public void change() { count++.height. } public void paint(Graphics g) { Dimension d = getSize(). Potluri Siddhartha Institute of Technology 42 Result Thus the convertion bean is created successfully Program 3: package sunw. } }).demo.colors. Prasad V. int h = d.*. Potluri Siddhartha Institute of Technology 41 Prasad V. .Prasad V.100). repaint().*. import java. public mouseclick() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { change().

int w = d. g.100.blue).setColor(Color.0. Failing to properly set this variable prevents Tomcat from handling JSP pages.fillRect(0. g. no other process is using this port. g. g.100).valueOf(count).50). This variable should list the base JDK installation directory. . Make sure that these ports are available i.setColor(Color.e.red).drawString(String.class Java-Bean: True Output Prasad V. While installation assign port number 8080 to APACHE. }} Mouseclick.50. Potluri Siddhartha Institute of Technology 44 Result Thus the Mouse Clicks bean is created successfully Week-7: Date: 11-08-08 ----------------------------------------------------------------------------------------------------------AIM: Install TOMCAT web server and APACHE. not the bin subdirectory.mft Name: sunw/demo/colors/mouseclick.. Potluri Siddhartha Institute of Technology 45 DESCRIPTION: Set the JAVA_HOME Variable You must set the JAVA_HOME environment variable to tell Tomcat where to find Java.width. Prasad V.

if you fail to turn it on for your development server. press the Environment Variables button at the bottom. if you don't set your CLASSPATH. Name: JAVA_HOME Value: install_dir/common/lib/servlet-api. but the compiler (i. The server already knows about the servlet classes.xml and add a DefaultContext subelement to the main Host element and supply true for the reloadable attribute. Potluri Siddhartha Institute of Technology 46 To turn on servlet reloading. select Control Panel. 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.e.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.27.. search for this entry: .On Windows XP. so is turned off by default. For example. click on the Advanced tab. you could also go to the Start menu. However. you'll have to restart the server every time you recompile a servlet that has already been loaded into the server's memory. Prasad V. This slightly degrades performance in deployment situations. choose System. you have to identify the servlet classes to the compiler. or other classes that use the servlet and JSP APIs will fail with error messages about unknown classes. attempts to compile servlets. javac) you use for development probably doesn't. in Tomcat 5.0. tag libraries. So. edit install_dir/conf/server.

...xml before making the above change.> and then insert the following immediately below it: <DefaultContext reloadable="true"/> Be sure to make a backup copy of server. <servlet> <servlet-name>invoker</servlet-name> <servlet-class> org.xml. Enable the Invoker Servlet The invoker servlet lets you run servlets without first making changes to your Web application's deployment descriptor.InvokerServlet </servlet-class> .servlets. Finally.<Host name="localhost" debug="0" appBase="webapps" . The invoker servlet is extremely convenient when you are learning and even when you are doing your initial development. To enable the invoker servlet. </servlet> .. uncomment the following servlet and servletmapping elements in install_dir/conf/web.apache... remember to make a backup copy of the original version of this file before you make the changes.catalina. you just drop your servlet into WEBINF/ classes and use the URL http://host/servlet/ServletName. <servlet-mapping> <servlet-name>invoker</servlet-name> <url-pattern>/servlet/*</url-pattern> </servlet-mapping> . Instead.

pwd2. 2. . Potluri Siddhartha Institute of Technology 48 ----------------------------------------------------------------------------------------------------------AIM: Access the developed static web pages for books web site. 1. Write a servelet for doing the following.OUTPUT: Prasad V. 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. Potluri Siddhartha Institute of Technology 47 RESULT: Thus TOMCAT web server was installed successfully. Week-7: Date: 11-08-08 Prasad V. Create a Cookie and add these four user id’s and passwords to this Cookie. Potluri Siddhartha Institute of Technology 49 RESULT: Thus week-1 and week-2 pages are accessed using the TOMCAT web server successfully. user2. user3 and user4 having the passwords pwd1. using these servers by putting the web pages developed in week-1 and week-2 in the document root. OUTPUT Prasad V. Prasad V. Potluri Siddhartha Institute of Technology 50 Week-8: Date: 10-09-08 ----------------------------------------------------------------------------------------------------------AIM: User Authentication: Assume four users user1. pwd3 and pwd4 respectively.

e. Potluri Siddhartha Institute of Technology 51 will create an instance of the servlet class. The init method The HttpServlet class inherits the init method from GenericServlet. DESCRIPTION: Servlet Life cycle: 1. Store the user-names and passwords in the web.XML) for each of its web applications. call the init method 4.. When a web container starts it searches for the deployment descriptor (WEB. call destroy method Class loading and instantiation If you consider a servlet to be just like any other Java program. When it finds a servlet in the descriptor it Prasad V. Servlet Instantiation 3. Use init-parameters to do this. except that it runs within a servlet container. call the service method 5. there has to be a process of loading the class and making it ready for requests. user-name and password match) you should welcome him by name (user-name) else you should display “You are not an authenticated user “. The init method performs a role slightly similar to a constructor in an “ordinary” Java program in .If he is a valid user (i. At this point the class is considered to be loaded (but not initialized).xml and access them in the servlet by using the getInitParameters() method. Servlets do not have the exact equivalent of a main method that causes them to start execution. Servlet class loading 2.

This can happen when the container keeps a pool of instances of servlets to ensure adequate performance.XML) to be parsed and any initialization will be performed. void init(ServletConfig sc) Calling the service method The service() method gets information about the request from the request object. It is called automatically by the servlet container and as it causes the application context (WEB. Once the init method returns the servlet is said to be placed into service. such as doGet(). or methods you write. The code that makes a servlet “go” is the.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.that it allows initialization of an instance at start up. one with a zero parameter constructor and one that takes a ServletConfig parameter. The service method is called for each request processed and is not normally overridden by the programmer. servlet void service(ServletRequest req. 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 service method can invoke other methods to process the request. doPost(). and uses methods of the response object to create the client response. processes the request. 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. passing the request and response objects. The servlet engine creates a request object and a response object. The destroy method is called only . The servlet engine invokes the servlet service() method. It comes in two versions.

· getServletContext() Returns reference to the ServletContext object for this Servlet.xml file then a null value is returned. Potluri Siddhartha Institute of Technology 52 void destroy() ServletConfig Class ServletConfig object is used by the Servlet Container to pass information to the Servlet during it's initialization. Methods of ServletConfig class Following are the four methods of this class : · getInitParameter(String paramName) Returns value of the given parameter.once. Prasad V. Servlet can obtain information regarding initialization parameters and their values using different methods of ServletConfig class initialization parameters are name/value pairs used to provide basic information to the Servlet during it's initialization like JDBC driver name.html: <html> . username. It is similar to getServletContext() method provided by HttpServlet class. If value of parameter could not be found in web.xml file or if none is provided then returns complete class path to the Servlet. PROGRAM: cologin. password etc. · getServletName() Returns name of the Servlet as provided in the web. before a servlet is unloaded and thus you cannot be certain when and if it is called. path to database. · getInitParameterNames() Returns an Enumeration object containing all the names of initialization parameters provided for this Servlet.

<head> <title> login Page </title> <p style= "background:yellow; top:100px; left:250px; position:absolute; "> </head> Prasad V. Potluri Siddhartha Institute of Technology 53 <body> <form ACTION="clogin"> <label> Login </label> <input type="text" name="usr" size="20"> <br> <br> <label> Password </label> <input type="password" name="pwd" size="20"> <br> <br> <input type="submit" value="submit"> </form> </body> </html> cologin1.html <html> <head> <title> login Page </title> <p style= "background:yellow; top:100px; left:250px; position:absolute; "> </head> <body> <form ACTION="clogin1">

<label> Login </label> <input type="text" name="usr" size="20"> <br> <br> <label> Password </label> <input type="password" name="pwd" size="20"> <br> <br> <input type="submit" value="submit"> </form> </body> </html> Addcook.java: import javax.servlet.* ; import javax.servlet.http.*; Prasad V. Potluri Siddhartha Institute of Technology 54 import java.io.*; public class Addcook extends HttpServlet { String user,pas; public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter out=res.getWriter(); Cookie c1=new Cookie("usr1","suni"); Cookie p1=new Cookie("pwd1","ani"); Cookie c2=new Cookie("usr2","abc"); Cookie p2=new Cookie("pwd2","123");

Cookie c3=new Cookie("usr3","def"); Cookie p3=new Cookie("pwd3","456"); Cookie c4=new Cookie("usr4","mno"); Cookie p4=new Cookie("pwd4","789"); res.addCookie(c1); res.addCookie(p1); res.addCookie(c2); res.addCookie(p2); res.addCookie(c3); res.addCookie(p3); res.addCookie(c4); res.addCookie(p4); out.println("COOKIE ADDED"); } } Clogin.java: import javax.servlet.* ; import javax.servlet.http.*; Prasad V. Potluri Siddhartha Institute of Technology 55 import java.io.*; public class Clogin extends HttpServlet { String user,pas; public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException

getName().equals(c[i].i++) { if((c[i]. Cookie[] c=req. } .getParameter("pwd"). rd.equals("pwd4") )) { if((user.getValue())) ) { //RequestDispatcher rd=req.getRequestDispatcher("/cart.equals("usr3")&& c[i+1].i<c.length.equals("pwd2"))|| (c[i].equals(c[i+1].equals("pwd1"))|| c[i].sendRedirect("/cookdemo/cologin.println("YOU ARE NOT AUTHORISED USER "). //res.getParameter("usr"). } else { out.equals("usr4")&& c[i+1]. pas=req.equals("pwd3"))|| (c[i]. for(int i=0.html").getName().getName().equals("usr2") &&c[i+1].html"). user=req.{ res.getName().res).getName().getCookies(). PrintWriter out=res.getName().equals("usr1")&&c[i+1].getWriter().forward(req.getValue()) && pas.getName().setContentType("text/html").getName().

Prasad V. Potluri Siddhartha Institute of Technology 56 } } } } Web.xml: <web-app> <servlet> <servlet-name>him</servlet-name> <servlet-class>Clogin</servlet-class> </servlet> <servlet> <servlet-name>him1</servlet-name> <servlet-class>Addcook</servlet-class> </servlet> <servlet-mapping> <servlet-name>him</servlet-name> <url-pattern>/clogin</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>him1</servlet-name> <url-pattern>/clogin1</url-pattern> </servlet-mapping> </web-app> OUTPUT: .

xml and access them in the servlet by using the getInitParameters() method.java import javax.*.html: <html> <head> <title>Authentication</title> </head> <body> <form action="ex1"> <label>Username </label> <input type="text"size="20" name="user"><br><br> password<input type="text" size="20" name="pwd"><br><br> <input type="submit" value="submit"> </form> </body> </html> Example1.Prasad V. 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. user-name and password match) you should welcome him by name (user-name) else you should display “You are not an authenticated user “. Potluri Siddhartha Institute of Technology 59 2. home. Store the user-names and passwords in the webinf. Potluri Siddhartha Institute of Technology 57 Prasad V.e. Potluri Siddhartha Institute of Technology 58 Prasad V. If he is a valid user (i.servlet. . Use init-parameters to do this..

Prasad V.getInitParameter("username4").pwd5. user3=sc.getParameter("pwd").getInitParameter("password1").getInitParameter("password2"). pwd3=sc.pwd2. PrintWriter out=res.equals(user1)&&pwd5.equals(pwd1))|| . pwd5=req.getInitParameter("username2"). public class Example1 extends GenericServlet { private String user1. user4=sc.user4.getInitParameter("password3").setContentType("text/html").getWriter(). pwd4=sc.user2.pwd4.user5.ServletResponse res)throws ServletException.import java. user5=req.user3.pwd3.getParameter("user").io. public void init(ServletConfig sc) { user1=sc. Potluri Siddhartha Institute of Technology 60 user2=sc. pwd2=sc. if((user5.*.IOException { res.getInitParameter("username1").pwd1.getInitParameter("username3").getInitParameter("password4"). pwd1=sc. } Public void service(ServletRequest req.

equals(pwd4))) out.println("<p> welcome to"+user5.println("You are not authorized user"). else out.(user5.toUpperCase()).equals(pwd3))|| (user5.equals(pwd2))|| (user5. Potluri Siddhartha Institute of Technology 61 <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> .equals(user2)&&pwd5.equals(user4)&&pwd5.equals(user3)&&pwd5. } } web.xml: <web-app> <servlet> <servlet-name>Example</servlet-name> Prasad V.

Potluri Siddhartha Institute of Technology 62 <param-value>lab</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Example</servlet-name> .</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>wt</param-value> </init-param> <init-param> <param-name>password4</param-name> Prasad V.

Practice 'JDBC' connectivity. Insert the details of the users who register with the web site. Create a table which should contain at least the following fields: name. Type 1 JDBC drivers translate the JDBC calls . whenever a new user clicks the submit button in the registration page (week2). Potluri Siddhartha Institute of Technology 63 RESULT: Thus the user authentication is carried out for four users by using both cookies and getInitParameters successfully. Week-9 Date: 22-09-08 Prasad V. Experiment with various SQL queries. password. Potluri Siddhartha Institute of Technology 64 -----------------------------------------------------------------------------------------------------------AIM: Install a database (Mysql or Oracle). Write a java program/servlet/JSP to connect to that database and extract data from the tables and display them. 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. email-id.<url-pattern>/ex1</url-pattern> </servlet-mapping> </web-app> OUTPUT: Prasad V. phone number (these should hold the data from the registration form).

The JDBC calls are passed via the network to the middle tier server. JDBC drivers available from Simba are Type 3 drivers. Type 3: Pure Java Driver A Type 3 Pure Java Driver works in a three tiered architecture. 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. PROGRAM: Registration. It is installed inside the Java Virtual Machine of the client. Unlike the type 3 drivers.html: <html> <head> . 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.into ODBC calls and then send the calls to the ODBC driver. it does not need associated software to work. 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 communicates directly with the database server.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. Type 4: Native Protocol Java Driver Prasad V. This server translates the calls to the database specific native interface to further request the server. Potluri Siddhartha Institute of Technology 65 The type 4 driver is written completely in Java and is hence platform independent.

<title>Registration page</title> </head> <body bgcolor="#00FFFf"> <form METHOD="POST" ACTION="register"> <CENTER> <table> <center> <tr> <td> Username </td> <td><input type="text" name="usr"> </td> </tr> <tr><td> Password </td> <td><input type="password" name="pwd"> </td> </tr> <tr><td>Age</td> <td><input type="text" name="age"> </td> </tr> <tr> <td>Address</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="phone"> </td> </tr> Prasad V. Potluri Siddhartha Institute of Technology 66 <tr> <td colspan=2 align=center> <input type="submit" value="submit"> </td> </tr> </center> </table> </form> .

*.*.*.</body> Login.servlet.sql.java: import javax.io. public class Ini extends GenericServlet { Prasad V.html <html> <head> <title>Registration page</title> </head> <body bgcolor=pink> <center> <table> <form METHOD="POST" ACTION="authent"> <tr> <td> Username </td> <td><input type="text" name="usr"></td> </tr> <tr> <td> Password </td> <td> <input type="password" name="pwd"> </td> </tr> <tr> <td align=center colspan="2"><input type="submit" value="submit"></td> </tr> </table> </center> </form> </body> </html> Ini. import java. Potluri Siddhartha Institute of Technology 67 . import java.

setString(3.getParameter("pwd"). st.setString(5. st.getConnection("jdbc:oracle:thin:@195.executeUpdate(). try { Class.setString(6.getParameter("email").100.?. pwd1=req.driver.email1). PreparedStatement st=con.close().15 8:1521:cclab".setString(1. public void service(ServletRequest req.email1.getWriter(). con. st. email1=req."scott". Connection con=DriverManager."hyd"). PrintWriter out=res.ServletResponse res) throws ServletException. st. .prepareStatement("insert into personal values(?.pwd1).?.setContentType("text/html")."25").pwd1.?.getParameter("user").jdbc. res.forName("oracle. st.private String user1."tiger").user1)."21234").IOException { user1=req.?. st.101.setString(2.OracleDriver").?)"). st.setString(4.

Potluri Siddhartha Institute of Technology 71 .xml: <web-app> <servlet> <servlet-name>init1</servlet-name> <servlet-class>Ini</servlet-class> </servlet> <servlet-mapping> <servlet-name>init1</servlet-name> <url-pattern>/regis</url-pattern> </servlet-mapping> </web-app> OUTPUT: Prasad V.println("not found "+s). Potluri Siddhartha Institute of Technology 68 { out. } catch(ClassNotFoundException c) Prasad V. Potluri Siddhartha Institute of Technology 69 Prasad V. Potluri Siddhartha Institute of Technology 70 Prasad V.} catch(SQLException s) { out.println("not found "+c). } }} web.

JSP Expressions . Potluri Siddhartha Institute of Technology 72 Prasad V. Each of these is described in more detail below. Potluri Siddhartha Institute of Technology 73 RESULT: Thus a table is created and the details are entered into the table using jdbc from the registration form successfully. Declarations of the form <%! code %> that are inserted into the body of the servlet class. Scriptlets of the form <% code %> that are inserted into the servlet's service method. and 3. outside of any existing methods. There are three forms: 1. Expressions of the form <%= expression %> that are evaluated and inserted into the output. Potluri Siddhartha Institute of Technology 74 Week-10 Date: 29-09-08 ----------------------------------------------------------------------------------------------------------AIM: Write a JSP which does the following job Insert the details of the 3 or 4 users who register with the web site (week9) by using registration form.Prasad V. DESCRIPTION: JSP Scripting Elements JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page. 2. Prasad V. Authenticate the user when he submits the login form using the user name and password from the database (similar to week8 instead of cookies).

for example. · session. For example.util. but for the purpose of expressions. the HttpServletResponse. This evaluation is performed at run-time (when the page is requested). the following shows the date/time that the page was requested: Current time: <%= new java. . Potluri Siddhartha Institute of Technology 75 To simplify these expressions. if you want output to appear in the resultant page.Date() %> Prasad V. converted to a string. the HttpSession associated with the request (if any).A JSP expression is used to insert Java values directly into the output. These implicit objects are discussed in more detail later. Scriptlets have the following form: <% Java Code %> Scriptlets have access to the same automatically defined variables as expressions. and inserted in the page. It has the following form: <%= Java Expression %> The Java expression is evaluated. JSP Scriptlets If you want to do something more complex than insert a simple expression. the HttpServletRequest. the PrintWriter (a buffered version of type JspWriter) used to send output to the client. JSP scriptlets let you insert arbitrary code into the servlet method that will be built to generate the page. and · out. there are a number of predefined variables that you can use. So. and thus has full access to information about the request. · response. you would use the out variable. the most important ones are: · request.

Potluri Siddhartha Institute of Technology 76 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.getQueryString(). and blocks left open can affect the static HTML outside of the scriptlets. here is a JSP fragment that Prasad V. 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). and any static HTML (template text) before or after a scriptlet gets converted to print statements. For example.<% String queryData = request.println("Attached GET data: " + queryData). It has the following form: <%! Java Code %> Since declarations do not generate any output. This means that scriptlets need not contain complete Java statements.html: <!--Home. they are normally used in conjunction with JSP expressions or scriptlets. %> PROGRAM: Login. %> Note that code inside a scriptlet gets inserted exactly as written.</h1></center> <table border="1" width="100%" height="100%"> .html--> <html> <body> <center><h1>XYZ Company Ltd. out.

<tr> <td valign="top" align="center"><br/> <form action="auth.</td> </tr> .</td> </tr> <tr> <td>User Name</td> <td><input type="text" name="user"/></td> </tr> <tr> <td>Password</td> <td><input type="password" name="pwd"/></td> </tr> <tr> <td>&nbsp. Potluri Siddhartha Institute of Technology 77 <td>&nbsp.jsp"><table> <tr> <td colspan="2" align="center"><b>Login Page</b></td> </tr> <tr> <td colspan="2" align="center"><b>&nbsp.</td> Prasad V.

pwd.getParameter("pwd")."%> <html> <head> <title> This is simple data base example in JSP</title> </title> </head> <body bgcolor="yellow"> <%!String uname. try .*.<tr> <td colspan="2" align="center"><input type="submit" value="LogIN"/></td> </tr> </table> </form> </td> </tr> </table> </body> </html> Auth.getParameter("user").jsp: <%@page import="java. pwd=request.%> <% uname=request.sql.

Prasad V.executeQuery("select name."scott".getConnection("jdbc:oracle:thin:@195.jdbc.driver.forName("oracle. } catch(Exception e){out.15 8:1521:CCLAB".} %> </body> </html> OUTPUT: Prasad V. Statement st=con. Potluri Siddhartha Institute of Technology 79 . if(rs.println(""+e).100.println("UnAuthorized person").OracleDriver").close(). ResultSet rs=st.println("Authorized person")."tiger"). Potluri Siddhartha Institute of Technology 78 Connection con=DriverManager. } else { out.{ Class.createStatement().next()) { out.password from personal where name='"+uname+"' and password='"+pwd+"'").101. } con.

java: import javax.Prasad V. Potluri Siddhartha Institute of Technology 80 RESULT: The user is authenticated when he submits the login form using the user name and password from the database. import javax.*.io.*.IOException . Quantity. import java. Amount)) of each category. Potluri Siddhartha Institute of Technology 81 import java.HttpServletResponse res) throws ServletException. 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.*.servlet.*. public class Retrieve extends HttpServlet { public void service(HttpServletRequest req. Prasad V.http. Week-11: Date: 06-10-08 ----------------------------------------------------------------------------------------------------------AIM: Extract data from the tables and display them in the catalogue page using JDBC. import java.util. PROGRAM: Retrieve. Price.*.sql.servlet. DESCRIPTION: Create tables in the database which contain the details of items (books in our case like Book name.

100. PrintWriter out=res. } catch(SQLException sq) Prasad V.executeQuery("select * from cart").forName("oracle.getString(2)+"</td> ").15 8:1521:cclab".getInt(3)+"</td> ").println("</table></center>")."scott". Statement s=con. while(r.println("<tr> <td> "+r.println("<td> "+r.next()) { out. Potluri Siddhartha Institute of Technology 82 . out. con. out.101.println("<td> "+r.getConnection("jdbc:oracle:thin:@195.getWriter(). out.getString(4)+"</td> </tr>").println("<thead> <th> Book name </th> <th> Price </th> <th> Quantity </th> <th> Amount </th> </thead>"). ResultSet r=s. try{ Class.close().setContentType("text/html"). out.println("<td> "+r. out.jdbc. } out."tiger"). Connection con=DriverManager.createStatement().{ res.getString(1)+"</td> ").println("<center> <table border=1>").driver.OracleDriver").

xml: <web-app> <servlet> <servlet-name>set</servlet-name> <servlet-class>Cartenter</servlet-class> </servlet> <servlet> <servlet-name>display</servlet-name> <servlet-class>Retrieve</servlet-class> </servlet> <servlet-mapping> <servlet-name>set</servlet-name> <url-pattern>/enterdata</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>display</servlet-name> . } catch(ClassNotFoundException cl) { out. } } } web.println("class not found"+cl).{ out.println("sql exception"+sq).

Some are: · getAttribute(String name) · getAttributeNames · isNew() · getCreationTime · getId · invalidate() .<url-pattern>/display1</url-pattern> </servlet-mapping> </web-app> Prasad V. Session is required to maintain the state. Potluri Siddhartha Institute of Technology 84 OUTPUT: RESULT: The data is extracted from the tables and displayed in the catalogue page using JDBC Prasad V. Potluri Siddhartha Institute of Technology 85 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. Potluri Siddhartha Institute of Technology 83 CREATE THE TABLE AND INSERT VALUES INTO THE TABLE: Prasad V. Methods of session Object: There are numerous methods available for session Object.

setContentType("text/html"). .util. public class Cart extends HttpServlet { Prasad V.http. PrintWriter pw=res. import java. } public void service(HttpServletRequest req. Potluri Siddhartha Institute of Technology 86 public void init(ServletConfig config) throws ServletException { super.getWriter(). Program : Cart .ServletException { res.java import java.servlet.io.*.HttpServletResponse res) throws IOException. import javax.*.*.*.· getLastAccessedTime · getMaxInactiveInterval · removeAttribute(String name) · setAttribute(String.init(config). object) The <jsp:include> element allows you to include either static and dynamic files in a JSP file. import javax.servlet.

cart=new ArrayList(). if(cart==null) { pw.length.next()+"</b>").println("<br><b>"+it. } String itemselected[]. ArrayList cart=(ArrayList)hs.getAttribute("cart").getParameterValues("book").setAttribute("cart".add(item). cart. Potluri Siddhartha Institute of Technology 87 while(it. }} pw.i++) { item=itemselected[i].iterator().java .HttpSession hs=req.getSession(). hs.cart). String item. itemselected=req. Prasad V.hasNext()) { pw. if(itemselected!=null) { for(int i=0.println("Items in the cart<br>"). Iterator it=cart. } }} Catalogue.println("No items in your cart").i<itemselected.

*. HttpSession hs=req.ServletException { res. import javax. Potluri Siddhartha Institute of Technology 88 } pw.*. public class Catalogue extends HttpServlet { int itemcount=0. if(cart!=null) { itemcount=cart.servlet.init(config). Prasad V. pw. ArrayList cart=(ArrayList)hs. import java.size().setContentType("text/html"). } public void service(HttpServletRequest req. public void init(ServletConfig config) throws ServletException { super.HttpServletResponse res) throws IOException. import javax. PrintWriter pw=res.getWriter().getSession().*.http.getAttribute("cart").import java.println("You have"+itemcount+"items in cart").io.servlet.println("<body><center><fieldset><legend>Catalogu e</legend><form action='cart' method='get'><input .*.util.

println("<input type='checkbox' name='book' value='web programming'>Web programming</input><br>").println("<input type='checkbox' name='book' value='Software Engineering'>Software Engineering</input><br>").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>"). .println("<input type='checkbox' name='book' value='Internet & World wide web'>Internet & World wide web</input><br>").type='checkbox' value='Java2' name='book'>java2</input><br>").println("<input type='checkbox' name='book' value='software project management'>software project management</input><br>").println("<input type='checkbox' name='book' value='Java2 Complete Reference'>Java2 Complete Reference</input><br>"). pw. pw. pw. pw. pw. 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> . pw. Potluri Siddhartha Institute of Technology 89 pw.pw.println("</fieldset></center>").println("<input type='checkbox' name='book' value='Computer networks'>Computer networks</input><br>"). Prasad V.

Potluri Siddhartha Institute of Technology 91 Result : Thus the session management is successfully created using jsp Week 13: Aim : Write a program to implement MVC architecture. The MVC pattern . 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. Potluri Siddhartha Institute of Technology 90 <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> Prasad V.<servlet-name>cat</servlet-name> <servlet-class>Catalogue</servlet-class> </servlet> <servlet-mapping> Prasad V.

whenever a controller changes a view. The buttons can be hooked up to trampolines that receive action events. How It Works The MVC abstraction can be graphically represented as follows. Events typically cause a controller to change a model. Similarly. or both. Even new types of views and controllers that never existed before can interface with a model without forcing a change in the model design. and route them to an action listener that . Potluri Siddhartha Institute of Technology 93 The spinner’s data is held in a model that is shared with the text field. Prasad V. for example. but it easy is to synthesize a spinner using existing element types. 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. all dependent views are automatically updated. and controllers for handling events that affect the model or view(s). that spawns an action event every time it is clicked. Potluri Siddhartha Institute of Technology 92 hinges on a clean separation of objects into one of three categories — models for maintaining data. Each button in the spinner is an event source. or view.Prasad V. the view gets data from the underlying model to refresh itself. Because of this separation. We currently do not have an element type that can directly represent a spinner component. views for displaying all or a portion of the data. multiple views and controllers can interface with the same model. Whenever a controller changes a model’s data or properties. by revealing areas that were previously hidden. The text field provides a view of the spinner’s current value.

Potluri Siddhartha Institute of Technology 94 Eshop. Depending on the source of the event. Recall that a trampoline is a predefined action listener that simply delegates action handling to another listener. the ultimate action listener either increments or decrements the value held in the model — The action listener is an example of a controller.eventually handles that event. instead of modifying the spinner’s model directly. Program : Prasad V. they delegate the task to a separate controller (action listener). are also controllers — However. Multiple Controllers The MVC pattern allows any number of controllers to modify the same model. a third event source in this example — Whenever the text field has focus. in fact. While we have so far focused only on the two arrow buttons as likely source of events. 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.Times" size="+3"> BOOK STORE . The trampolines that initially receive the action events fired by the arrow buttons. there is.jsp: <%@ page session="true" %> <html> <head> <title>BOOK STORE</title> </head> <body bgcolor="#33CCFF"> <font face="Times New Roman.

jsp: .95</option> </select> <b>Quantity: </b><input type="text" name="qty" SIZE="3" value=1> <input type="hidden" name="action" value="ADD"> <input type="submit" name="Submit" value="Add to Cart"> </form> </center> <p> <jsp:include page="Cart.95</option> <option> 10590 | Winston | XML BIBLE |Wiley | 2 | 14.jsp" flush="true" /> </body> Prasad V.95</option> <option> 10589 | Deitel | Internet |McGraw Hill | 4 | 44. Potluri Siddhartha Institute of Technology 95 </html> Cart.</font> <hr><p> <center> <form name="shoppingForm" action="ShoppingServlet" method="POST"> <b>BOOK:</b> <select name=BOOK> <option> 10588 | Hans Bergsten | Java Server Pages | O'Reilly | 2 | 34.

getisbn() %></b></td> <td><b><%= anOrder.elementAt(index). if (buylist != null && (buylist. %> <tr> <td><b><%= anOrder.util. index < buylist.index++) { BOOK anOrder = (BOOK) buylist.shoppingcart").<%@ page session="true" import="java.getValue("shopping.size().size() > 0)) { %> <center> <table border="0" cellpadding="0" width="100%" bgcolor="#FFFFFF"> <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. shopping.getAuthor() %></b></td> .*.BOOK" %> <% Vector buylist = (Vector) session.

Potluri Siddhartha Institute of Technology 96 <td><b><%= anOrder.getEdition() %></b></td> Prasad V.getPrice() %></b></td> <td><b><%= anOrder.getPublisher() %></b></td> <td><b><%= anOrder.getTitle() %></b></td> <td><b><%= anOrder.getQuantity() %></b></td> <td> <form name="deleteForm" action="ShoppingServlet" method="POST"> <input type="submit" value="Delete"> <input type="hidden" name= "delindex" value='<%= index %>'> <input type="hidden" name="action" value="DELETE"> </form> </td> </tr> <% } %> </table> <p> <form name="checkoutForm" action="ShoppingServlet" method="POST"> <input type="hidden" name="action" value="CHECKOUT"> <input type="submit" name="Checkout" value="Checkout"> </form> .<td><b><%= anOrder.

*. Potluri Siddhartha Institute of Technology 97 BOOK STORE CHECK OUT </font> <hr><p> <center> <table border="0" cellpadding="0" width="100%" bgcolor="#FFFFFF"> <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> .util.BOOK" %> <html> <head> <title>BOOK STORE</title> </head> <body bgcolor="#33CCFF"> <font face="Times New Roman.jsp: <%@ page session="true" import="java.Times" size=+3> Prasad V.</center> <% } %> Checkout. shopping.

getAuthor() %></b></td> <td><b><%= anOrder.getEdition() %></b></td> <td><b><%= anOrder. String amount = (String) request.getAttribute("amount").getPrice() %></b></td> <td><b><%= anOrder.getisbn() %></b></td> <td><b><%= anOrder.<td></td> </tr> <% Vector buylist = (Vector) session. %> <tr> <td><b><%= anOrder.invalidate().getPublisher() %></b></td> <td><b><%= anOrder.elementAt(i).i++) { BOOK anOrder = (BOOK) buylist.getValue("shopping. %> <tr> <td> </td> <td> </td> .getQuantity() %></b></td> </tr> Prasad V.size(). for (int i=0.shoppingcart").getTitle() %></b></td> <td><b><%= anOrder. i < buylist. Potluri Siddhartha Institute of Technology 98 <% } session.

html: <html> <body> <h1> Sorry.xml: <web-app> <servlet> .<td><b>TOTAL</b></td> <td><b>$<%= amount %></b></td> <td> </td> </tr> </table> <p> <a href="Eshop. there was an unrecoverable error! <br> Please try <a href="/examples/jsp/shopping/EShop. </h1> </body> </html> OUTPUT: Prasad V.jsp">again</a>.jsp">Shop some more!</a> </center> </body> </html> Error. Potluri Siddhartha Institute of Technology 99 Web.

*.*. import javax. public class ShoppingServlet extends HttpServlet { public void init(ServletConfig conf) throws ServletException { super.init(conf).*.*.html").util. import javax. import java. } public void doPost (HttpServletRequest req.java: import java.servlet.getSession(false).http.servlet. HttpServletResponse res) throws ServletException.sendRedirect("/error. if (session == null) { res. } . IOException { HttpSession session = req. Prasad V.io.<servlet-name>ShoppingServlet</servlet-name> <servlet-class>ShoppingServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ShoppingServlet</servlet-name> <url-pattern>/ShoppingServlet</url-pattern> </servlet-mapping> </web-app> ShoppingServlet.BOOK. Potluri Siddhartha Institute of Technology 100 import shopping.

Vector buylist=(Vector)session. .getParameter("action").equals("ADD")) { boolean match=false.getValue("shopping. } //end of if name matches } // end of for if (!match) buylist. BOOK aCD = getBOOK(req). buylist.equals(aCD.getTitle())) { cd.getParameter("delindex"). if (cd.getTitle(). buylist.size(). if (!action.getQuantity()+aCD.intValue(). } else { // not first buy for (int i=0. Prasad V. } else if (action. String action = req.addElement(aCD). int d = (new Integer(del)).removeElementAt(d).equals("CHECKOUT")) { if (action.setElementAt(cd. i< buylist.addElement(aCD). i++) { BOOK cd = (BOOK) buylist.getQuantity()).setQuantity(cd.elementAt(i). //first order buylist.i). if (buylist==null) { buylist = new Vector().shoppingcart").equals("DELETE")) { String del = req. Potluri Siddhartha Institute of Technology 101 match = true.

} } session. RequestDispatcher rd = sc. int n = amount. String url="/Checkout.forward(req. ServletContext sc = getServletContext(). rd.amount).indexOf('.forward(req. rd. total += (price * qty). res).jsp". // ServletContext sc = getServletContext().getPrice().005.size(). for (int i=0. req.substring(0. } else if (action.toString().setAttribute("amount".getQuantity().i++) { BOOK anOrder = (BOOK) buylist. buylist).putValue("shopping. RequestDispatcher rd = req. float price= anOrder.shoppingcart". String url="/Eshop. String amount = new Float(total). amount = amount.res). .equals("CHECKOUT")) { float total =0. } total += 0. int qty = anOrder.jsp". i< buylist.').getRequestDispatcher(url).getRequestDispatcher(url).n+3).elementAt(i).

String Edition = t.setPrice((new Float(price)).nextToken(). price = price.getParameter("qty"). book.nextToken(). return book. BOOK book = new BOOK().nextToken().replace('$'.setisbn(isbn).nextToken().} Prasad V.getParameter("BOOK"). String isbn= t.trim().intValue()). book.' '). book.setEdition(Edition). Potluri Siddhartha Institute of Technology 102 } private BOOK getBOOK(HttpServletRequest req) { String myBOOK = req.setPublisher(publisher).nextToken().floatValue()).nextToken().setTitle(title).setQuantity((new Integer(qty)). book. String author= t. String price = t.setAuthor(author). String qty = req."|"). book. String publisher = t. book. StringTokenizer t = new StringTokenizer(myBOOK. book. } } . String title = t.

java: package shopping. Prasad V. int quantity. price=0. author="". . publisher="". String title. float price. Edition="". quantity=0. Potluri Siddhartha Institute of Technology 103 String Edition. String author.book. String publisher. } public String getPublisher() { return publisher. public BOOK() { isbn="". public class BOOK { String isbn. } public void setPublisher(String title1) { publisher=title1. title="".

} public String getTitle() { return title. . } public String getisbn() { return isbn. } public String getAuthor() { return author. } public String getEdition() { return Edition.} public void setEdition(String group1) { Edition=group1. } public void setAuthor(String group) { Prasad V. Potluri Siddhartha Institute of Technology 104 author=group. } public void setTitle(String cty) { title=cty. } public void setisbn(String title) { isbn=title.

} public void setQuantity(int q) { quantity=q. } } OUTPUT: Prasad V.} public void setPrice(float p) { price=p. } public int getQuantity() { return quantity.jsp <%@ taglib uri="hello" prefix="examples"%> <html> . Experiment :14 Aim : Write a program to implement custom tag libraries in JSP Description : Program : First. Potluri Siddhartha Institute of Technology 106 RESULT: Thus the cart page is dynamited with HTTP sessions and useBean concept. Potluri Siddhartha Institute of Technology 105 Prasad V. } public float getPrice() { return price.

Potluri Siddhartha Institute of Technology 107 <title>First Custom tags</title> </head> <body> <i><examples:hello/> </i> </body> </html> Web.tld <taglib> <tlib-version>1.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.<head> Prasad V.2</jsp-version> <tag> <name>hello</name> <tag-class>tagext.HelloTag</tag-class> <body-content>JSP</body-content> . Hello.0</tlib-version> <jsp-version>1.

import javax. pageContext. import java.jsp.write("HellOWorld").jsp.java package tagext.getOut().getName()+"and it's"+date).*. import javax.util. } .getOut().servlet.servlet.write("My name is :"+getClass(). } public int doEndTag() { Date date=new Date().</tag> </taglib> Prasad V.tagext.TagSupport. Potluri Siddhartha Institute of Technology 108 HelloTag.*. public class HelloTag extends TagSupport { public int doStartTag() { return EVAL_BODY_INCLUDE. }catch(Exception e){} return EVAL_PAGE. try { pageContext.

Potluri Siddhartha Institute of Technology 110 Apache Struts 2 was originally known as WebWork 2. The framework is designed to streamline the full development cycle. extensible framework for creating enterprise-ready Java web applications. Description: Apache Struts 2 is an elegant. After working independently for several years. Potluri Siddhartha Institute of Technology 111 Step 3: Step 4: Prasad V. Potluri Siddhartha Institute of Technology 113 . Potluri Siddhartha Institute of Technology 112 step 5: Prasad V. This new version of Struts is simpler to use and closer to how Struts was always meant to be. from building. Potluri Siddhartha Institute of Technology 109 Result : Thus the implementation of custom tag libraries in JSP is done.} Output Prasad V. Implementation: Step 1: Step 2: Prasad V. to maintaining applications over time. the WebWork and Struts communities joined forces to create Struts2. Experiment No : 14 Aim : Display “Hello World” using Struts Framework in NetBeans. Prasad V. to deploying.

Potluri Siddhartha Institute of Technology 114 step 8: step 9: Prasad V. Also make sure that you use the same name when you open the file in your browser. some of the examples in our advanced classes require the latest versions of the browsers. Q: What browser should I use? A: You can do all the training with all of the well-known browsers. Firefox. like Internet Explorer. Potluri Siddhartha Institute of Technology 115 Question & Answers Q: After I have edited an HTML file. I cannot view the result in my browser. Q: Does my computer have to run Windows? What about a Mac? . the browser doesn't know that. Why? A: Make sure that you have saved the file with a proper name and extension like "c:\mypage. Use the browser's refresh/reload button to force the browser to reload the page. However.step 6: step 7: Prasad V. When you have modified a page. but the changes don't show in the browser.htm". Q: I have edited an HTML file. Netscape. or Opera. Why? A: A browser caches pages so it doesn't have to read the same page twice.

Instead. video. Some markup languages (eg those used in wordprocessors) only describe appearances Prasad V. XML is actually a metalanguage—a language for describing other languages—which lets you design your own markup languages for limitless different types of documents. etc. etc). and adaptable way. and is not normally re-usable for anything else. the international standard metalanguage for text document markup (ISO 8879). 3. received. ‘this is bold’). It is extensible because it is not a fixed format like HTML (which is a single. SeeWhere's the spec? . ‘this is a heading’.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’. It improves the functionality of the Web by letting you identify your information in a more accurate. ‘this is a list’. print. but this method can only be used for display. What is XML? (ans) XML is the Extensible Markup Language. 2. XML can do this because it's written in SGML.A: You can do all your training on a non-Windows computer like a Mac. predefined markup language). Potluri Siddhartha Institute of Technology 116 (‘this is italics’. flexible. audio. 1. ‘this is the caption of this figure’. What is XML for (aka ‘Where should I use XML’)? (ans) Its goal is to enable generic SGML to be served. Braille. XML is sometimes referred to as ‘self-describing data’ because the names of the markup elements should represent the type of content they hold. XML has been designed for ease of implementation and for interoperability with both SGML and HTML. and processed on the Web in the way that is now possible with HTML. Programs can use this with a stylesheet to create output for screen.

Despite early attempts. it can be used to store textual information across any platform. This is its most common Web application. Publishing The original goal of XML as defined in the quotation at the start of this section. Because it is backed by an international standard. browsers never allowed other SGML. Information storage because XML is portable and non-proprietary. which held development back for over a decade by making it impossible to program for it reliably. Common uses for XML include: Information identification because you can define your own markup. XML fixes that by making it compulsory to stick to the rules. 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. structure) means it is possible to get all the benefits of robust document management and control (with XML) and . storage. Combining the three previous topics (identity. and by making the rules much simpler than SGML. with a transformation system to serve it as HTML until such time as browsers are able to handle XML consistently. it will remain accessible and processable as a data format. making it ideal for an information-management back-end to serving the Web. you can define meaningful names for all your information items. Information structure XML can therefore be used to store and identify any kind of (hierarchical) information structure. or complex document sets or data sources. and they allowed it (even encouraged it) to be corrupted or broken. only HTML (although there were unknownplugins). especially for long. deep.

htm SGML is very large. 4. There is an SGML FAQ from David Megginson at http://math. It has been in heavy industrial and commercial use for nearly two decades. AJaX sites. blog newsfeeds. Messaging and data transfer XML is also very heavily used for enclosing or encapsulating information in order to Prasad V. machine-processable data can be exchanged between consenting systems.edu:8800/hm/sgml/cts-faq. Potluri Siddhartha Institute of Technology 117 pass it between different computing systems which would otherwise be unable to communicate. where before it was only comprehensible by humans (HTML).publish to the Web (as HTML) as well as to paper (as PDF) and to other formats (eg Braille. it provides a common envelope for inter-process communication (messaging). and the web browser for display and interaction. and thousands of other data-exchange services use XML for data management and transmission. Web services Building on all of these. the international standard for defining descriptions of the structure of different types of electronic document. 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 . Weather services. Audio. By providing a lingua franca for data identity and structure. powerful.albany. What is SGML? (ans)SGML is the Standard Generalized Markup Language (ISO 8879:1986). and complex. etc) from a single source document by using the appropriate stylesheets. e-commerce sites. as well as its use in browsers. and there is a significant body of expertise and software to go with it.

SGML. and from patients' medical and clinical records to musical notation. SGML is very large and complex. and easier for programmers to write programs to handle them. and HTML all the same thing? (ans) Not quite. with section headings. lists. originating with Tim Berners-Lee at CERN in 1989–90. It defines a very simple class of report-style documents. XML is an abbreviated version of SGML. and XML files may still be processed in the same way as any other SGML file (see the question on XML software). from transcriptions of ancient Irish manuscripts to the technical documentation for stealth bombers. XHTML. There is a HTML and XHTML FAQ maintained by Steven Pemberton at http://www. to make it easier to use over the Web.Aren't XML. plus some hypertext and multimedia. SGML is the mother tongue. tables. and probably overkill for most common office desktop applications. paragraphs. What is HTML? (ANS)HTML is the HyperText Markup Language (RFC 1866).4. and has been used for describing thousands of different document types in many fields of human activity. however.w3. easier Prasad V. . which started as a small application of question A. Potluri Siddhartha Institute of Technology 118 for you to define your own document types. and more suited to delivery and interoperability over the Web.too complex to program for in a Web environment. easier to understand. with a few informational elements. The current recommendation is to use the XML version. and illustrations. But it is still SGML. SGML for the Web.org/MarkUp/2004/xhtml-faq 6. but very few presentational elements [10]. See the question on extending HTML. 5. It omits all the complex and less-used options of SGML in return for the benefits of being easier to write applications for.

HTML is just one of many SGML or XML applications—the one most frequently used on the Web. 7. Technical readers will find it more useful to think of XML as being SGML−− rather than HTML++. XML allows the flexible development of user-defined document types.Who is responsible for XML? (ans) XML is a project of the World Wide Web Consortium (W3C). 8. and the development of the specification is supervised by an XML Working Group.4. inflexible document type (HTML) which was being much abused for tasks it was never designed for. whose syntax allows many powerful but hard-to-program options. and it removes the more complex options of SGML. non-proprietary. the complexity of full question A. SGML.0 specification was accepted by the W3C as a Recommendation on Feb 10. A Special Interest Group of co-opted contributors and experts from various fields contributed comments and reviews by email. The v1. making it easier to program for. 1998. XML is a public format: it is not a proprietary development of any company. 9.Why not just carry on extending HTML? (ans) HTML was already overburdened with dozens of interesting but incompatible . although the membership of the WG and the SIG represented companies as well as research and academic institutions. persistent. It provides a robust. and verifiable file format for the storage and transmission of text and data both on and off the Web.Why is XML such an important development? (Ans) It removes two constraints which were holding back Web developments: dependence on a single.

· XML can be used to describe and identify information accurately and unambiguously.13.Why should I use XML? (aka ‘What is XML for?) (ans) Here are a few reasons for using XML (in no particular order). knitting. genealogy. mathematics. rabbit-keeping. at least manipulate as if they could understand it). many new applications require a more robust and flexible infrastructure. Prasad V. engineering. finance. because it provides only one way of describing your information. controlling. ‘How do I control formatting and appearance?’. linguistics. petroleum geology. and you may have additional reasons not mentioned here (if so. or allowing/disallowing particular types of document structure. chemistry. · XML allows documents which are all the same type to be created and handled consistently and without structural errors. and while it will continue to play an important role for the content it currently represents. only the structure of them.24. Potluri Siddhartha Institute of Technology 119 HTML is now well beyond the limit of its usefulness as a way of describing information. cooking. in a way that computers can be programmed to ‘understand’ your information (well. Not all of these will apply to your own requirements. or the actual text or data content of your documents. hill-walking. stellar cartography. [Note that this has absolutely nothing whatever to do with formatting. electronics.] . XML allows groups of people or organizations to question C. create their own customized markup applications for exchanging information in their domain (music. question C. history. surfing. If you want styling or formatting. etc). see question C.inventions from different manufacturers. 10. appearance. because it provides a standardised way of describing.19. please let the editor of the FAQ know!).

· XML provides a common syntax for messaging systems for the exchange of information between applications. order. The two are combined at output time to apply the required formatting to the text or data identified by its structure (location. which made inter-system messaging unnecessarily messy. rank. so it can't be hijacked or pirated.· XML provides a robust and durable format for information storage and transmission. 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. · XML lets you separate form (appearance) from content. Previously. so XML documents can be pieced together from disparate sources. They can be converted into any other format with no loss of information. for lots of good reasons. Not just free of charge (free as in beer) but free of legal encumbrances (free as in speech). It doesn't belong to anyone. durable (persistent) because it uses plain-text file formats which will outlast proprietary binary ones. or taken apart and re-used in different ways. If everyone uses the same syntax it makes writing these systems much faster and more reliable. Your XML file contains your document information (text. and can thus be tested and verified. Prasad V. · XML is free. · XML information can be manipulated programmatically (under machine control). Potluri Siddhartha Institute of Technology 120 . but you don't pay for XML itself). complex. or whatever). and expensive. data) and identifies its structure: your formatting and other processing needs are identified separately in a stylesheet or processing system. position. Robust because it is based on a proven standard. each messaging system had its own format and all were different.

· 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 FAQ FPRIVATE 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 1–line 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') Prasad V. Potluri Siddhartha Institute of Technology 121 " 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. Servlet-based Prasad V. Potluri Siddhartha Institute of Technology 122 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.

Applets are normally based on Abstract Windowing Toolkit components to maintain backward-compatibility with the widest range of browsers' Java implementations. the Java API documentation for the two types will show you they have little in common. it is best to use a single servlet to handle each form submission. Give each servlet responsibility to validate a single form input. Servlet concepts Q: What's the difference between applets and servlets? A: There are many fundamental differences between Applet and Servlet classes. in a restrictive security environment called a "sandbox". 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.Q: How can I assemble data from multiple input forms? A: First. typically embedded in an HTML page. The application classes are downloaded to the client and run in a Java Virtual Machine provided by the browser. Q: How can I write a servlet using Javascript? A: Java servlets is a server side technology that delivers dynamic content to Web . Applets are essentially graphical user interface (GUI) applications that run on the client side in a network environment. Servlets can be used to control all aspects of the request and response exchange between a Web browser and the server. and pass the error cases on to JSP documents that explain the problem and allow users to amend the input. Servlets are used to dynamically generate HTTP responses and return HTML content to Web browsers on the server side. A single servlet for all input would be too complicated. called a servlet container.

though this is only advisable in rare cases. 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 . It is also possible to dynamically generate Prasad V. Potluri Siddhartha Institute of Technology 123 Javascript using a servlet and use it as the source for a script tag. It is possible to include Javascript in the output of servlets and Java Server Pages. but the code is only interpreted and executed after it has been downloaded by the Web browser. If you need to configure the supporting classes. but these classes must be added to the classes or lib directory of your application. This means that it is not possible to write servlet code in Javascript. Can I include normal Java classes in servlets? A: Any Java class can be used in a Web application. The Java API classes can be used directly by adding import statements to your servlet class. However. this can be done with standard servlet configuration features using the ServletConfig and ServletContext objects available to the init(ServletConfig) method. just like standard Web pages. Other supporting classes can also be imported. A servlet is not invoked directly through a main method. the class is loaded and run by a servlet container. 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. Javascript is also delivered by a Web server. the environment or context in which servlets are executed is different. provided you make the classes available to the servlet container at runtime.browsers and other clients.

If you need to check indirectly. 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. : Are servlets multi-threaded? A: Yes. 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. fast way to create web pages that display dynamically-generated content. Potluri Siddhartha Institute of Technology 124 you can use static variables to store and present information that is common to all threads. What is JavaServer Pages technology? JavaServer Pages (JSP) technology provides a simplified. developed through an industry-wide initiative led by Sun . Each thread of your servlet runs as if a single user were accessing it alone. The JSP specification. the servlet container includes it in the hyperlink URLs it generates for servlets and JSP. The servlet container allocates a thread for each new request for a single servlet without any special programming. you can override the init(ServletConfig) method and add log(String) statements to it. like a hit counter for instance. so one way to check is to make a request to the servlet and check the response. This method is called after the servlet container has instantiated the servlet before it is brought into service.container. but Prasad V. servlets are normally multi-threaded. Rather than exchange a session ID in a cookie.

and describes the format and syntax of the page. so theoretically you could write servlets to support your web-based applications.Microsystems.com/products/servlet. JSP pages separate the page logic from its design and display. Why do I need JSP technology if I already have servlets? JSP pages are compiled into servlets. It passes any formatting (HTML or XML) tags directly back to the response page. In many applications. JSP pages are compiled into servlets and may call JavaBeans components (beans) or Enterprise JavaBeans components (enterprise beans) to perform processing on the server. JSP technology is a key component in a highly scalable architecture for web-based applications. JSP technology is part of the Java technology family. The JSP specification represents a broad spectrum of industry input. defines the interaction between the server and the JSP 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. JSP technology was designed to simplify the process of creating pages by separating web presentation from web content. However. Detailed information can be found at http://java. the response sent to the client is a combination of template data and dynamically-generated . JSP pages are not restricted to any specific platform or web server.sun. as opposed to the browser (applets). What is a servlet? A servlet is a program written in the Java programming language that runs on the server. As such. In this way.

it is much easier to work with JSP pages than to do everything with servlets. instead of relying heavily on scripting within the page itself. Using JSP and Enterprise JavaBeans technologies together is a great way to implement distributed enterprise applications with web-based front ends. Where can I get the most current version of the JSP specification? The JavaServer Pages 2.Prasad V.dev. In this situation.com/products/jsp/industry.1. It includes an implementation of JSP technology version 2. industry-standard method supporting numerous servers. You can download GlassFish builds from https://glassfish. How does the JSP specification relate to the Java Enterprise Edition 5 Platform? The JSP 2. JSP technology speeds development with reusable components and tags. All . open-source Java EE 5 implementation.java. Which web servers support JSP technology? There are a number of JSP technology implementations for different web servers.1 specification is an important part of the Java EE 5 Platform.html.sun. The latest information on officially-announced support can be found at http://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. browsers and tools. Potluri Siddhartha Institute of Technology 125 data. Is Sun providing a reference implementation for the JSP specification? The GlassFish project is Sun's free.1 specification is available for download from here.

This site includes numerous resources. Where do I get more information on JSP technology? The first place to check for information on JSP technology is http://java. Potluri Siddhartha Institute of Technology 126 Prasad V. as well as pointers to mailing lists and discussion groups for JSP technology-related topics.com/products/jsp/.sun.JSP implementations support a Java programming language-based scripting language. Prasad V. which provides inherent scalability and support for complex operations. Potluri Siddhartha Institute of Technology 127 .