You are on page 1of 113

WEB TECHNOLOGIES LAB MANUAL IV-B.Tech.

I-Semester (CSE) (2011-2012)

PREPARED BY Mr. M.Parameshwar M.Tech.


Asst. Professor

DEPARTMENT OF COMPUTER SCIENCE &ENGINEERING

Sri Venkateswara Engg College

Syllabus
1. Develop static pages (using Only HTML) of an online Book store. The pages should resemble: www.amazon.com The website should consist the following pages. * Home page *Registration and user Login * User Profile Page * Books catalog * Shopping Cart * Payment By credit card * Order Conformation 2. Validate the Registration, user login, user profile and payment by credit card pages using JavaScript. 3. Create and save an XML document at the server, which contains 10 users information. Write a program, which takes User Id as an input and returns the user details by taking the user information from the XML document. 4. Bean Assignments a. Create a JavaBean which gives the exchange value of INR(Indian Rupees) into equivalent American/Canadian/Australian Dollar value. b. Create a simple Bean with a label - which is the count of number of clicks. Than create a BeanInfo class such that only the 'count' property is visible in the Property Window. c. Create two Beans-a)KeyPad .b)DisplayPad .After that integrate the two Beans to make it work as a Calculator. d. Create two Beans Traffic Light(Implemented as a Label with only three background coloursRed,Green,Yellow) and Automobile(Implemented as a TextBox which states its state/movement). The state of the Automobile should depend on the following Light Transition Table. Light Transition Automobile State Red -> Yellow Ready Yellow -> Green Move Green -> Red Stopped

5. Install TOMCAT web server. Convert the static web pages of assignments 2 into dynamic web pages using servlets and cookies. Hint: Users information (user id, password, credit card number) would be stored in web.xml. Each user should have a separate Shopping Cart. 6. Redo the previous task using JSP by converting the static web pages of assignments 2 into dynamic web pages. Create a database with user information and books information. The books catalogue should be dynamically loaded from the database. Follow the MVC architecture while doing the website. 7. Implement the 'Hello World!' program using JSP Struts Framework
2

Required Work There will be homework assignments of about 20 programmatic/project scripts/memos, most of which will involve programming. Assignments are due at the beginning of its theoretic class on the date specified. Late assignments will receive 75% of full credit if they are handed in within one week of the specified due date. After one week, no credit will be given or else losing of credits is made in practice. There is no specific attendance policy for the course, although it is expected that absences will leave the student unprepared for tests and assignments. Tests will not be rescheduled except in extreme circumstances. However, the lowest quiz grade will be dropped. Grades will be determined as follows:

15 Day to- Day evaluation Marks marks 10 Internal practical Examination marks 50 Final Exam (University / External End Exam) marks

At the minimum, traditional grading cutoffs will apply. That is, 90% is guaranteed an A, 87% is guaranteed a B+, etc. Depending on class performance, some shifting of grades (in an upward direction only) may occur as final letter grades are assigned.

LIST OF CONCEPTS UNDER TAKEN IN THE WEB TECHNOLOGIES LAB

Sl. No.
1

Name of the Program / Project concept

Record Code

Lab Page No. Code


WT-01 28-39

Develop static pages (using only HTML) of an online WT-01 Book store. The pages should resemble. Validate the Registration, user Login, User Profile WT-02 and payment by credit card pages using JavaScript Create and save an XML document at the server, which contains 10 users information. Write a program which takes User Id as an input and returns the user details by taking the user information from XML document. a) Create a JavaBean which gives the exchange value of INR(Indian Rupees) into equivalent American/Canadian/Australian Dollor value.
WT-03

WT-02

49-59

WT-03

60-67

WT-04a

WT-04a 73-86

WT-04b b)Create a simple Bean with a label- which is the count of number of clicks. Then create a Bean Info class such that only the count property is visible in the property window. WT-04c c) Create two Beans a) Key Pad b) Display Pad After that integrate the two Bean to make it work as a calculator.

WT-04b 77-78

WT-04c 79-83

d) Create two Beans Traffic Light (implemented as a WT-04d Label with only three background colours- Red, Green,Yellow) and Automobile(implemented as a textbox which states its state/movement). The state of the Automobile should depend on the following Light Transition table. Install TOMCAT web server. Covert the static web WT-05 pages of assignments 2 into dynamic web pages using servlets and cookies. Hint: Users Information (user Id, password, credit card number) would be stored. In web.xml. Each user should have a separate

WT-04d 84-86

WT-05 97-101

shopping cart.
6 WT-06 Redo previous task using JSP by converting the static webpages of assignments 2 into dynamic webpages. Create a database with user information and books information. The books catalogure be dynamically loaded from the database. Follow MVC architecture while doing the website. WT-07 WT-06 103-111

10 Implement the Hello World program using JSP

WT-07

112

Struts Framework

INTRODUCTION Course Objectives : The Web Technologies Lab for engineers is a 3 hour training lab course spread at about 42 hours. The Lab co-ordinates two sections of one is Introduction to HTML, Java Script,

Java Beans, Servlets, JSP and Struts and other is Programming of self- explanative simple practical concepts include training and its programming also an extension to the university prescribed work for the lab. In developing web applications concepts in Web Technologies by using servlets and jsp whenever and wherever it is mandatory in corporate training way. Course goals: The specific goals of this course are:

To understand and be able to articulate the issues involved in designing, implementing web Technologies supported programming languages like servlets, jsp, and JDBC.

To appreciate the strengths and tradeoffs between different C/S programming paradigms, such as static or dynamic ones.

To develop a working knowledge of Web application programming provided by J2EE and struts framework.

Basic tags used in html <html> <body> <h1>My first page</h1> <h2>B.purushottam</h2> <h3>4th CSE</h3> <h4>SVEC</h4> <h5>kandl</h5> <h5>hyd</h5> <p>myself doing phd <br> u r very much </p> <hr>web techonology </body> </html>

Entities <html> <head> <title>Firstpage</title> </head> <body> <font face="arial" color="ff0000" size="+7"> my first page</font> a&ltb b&gtc IBM<sup>TM</sup> &copy &reg 30&deg &frac12 </body> </html>

Creation of table: <html> <caption>example table</caption> <table border="2" cellspacing="4" cellpadding="3"> <tr> <th>1<sup>st</sub></th> <th>2<sup>nd</sup></th> <th>3<sup>rd</sup></th> </tr> <tr> <td align="top">5</td> <td align="center">6</td> <td align="bottom">7</td> </tr> <tr> <td align="center" colspan="2"><img src="C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\sunset.jpg" width="20" height="20"></td> <td>8</td> </tr> </table> </html>
8

Designing a Calculator using forms <html> <body> <center> <form name ="calc"> <table border=4> <tr> <td> <input type="text" name="input" size="16"> <br> </td> </tr> <tr> <td> <input type="button" name="one" value="1" OnClick="calc.input.value+='1'"> <input type="button" name="two" value="2" OnClick="calc.input.value+='2'"> <input type="button" name="three" value="3" OnClick="calc.input.value+='3'"> <input type="button" name="plus" value="+" OnClick="calc.input.value+='+'"><br> <input type="button" name="four" value="4" OnClick="calc.input.value+='4'"> <input type="button" name="five" value="5" OnClick="calc.input.value+='5'"> <input type="button" name="six" value="6" OnClick="calc.input.value+='6'"> <input type="button" name="minus" value="-" OnClick="calc.input.value+='-'"><br> <input type="button" name="seven" value="7" OnClick="calc.input.value+='7'"> <input type="button" name="eight" value="8" OnClick="calc.input.value+='8'"> <input type="button" name="nine" value="9" OnClick="calc.input.value+='9'"> <input type="button" name="times" value="*" OnClick="calc.input.value+='*'"><br> <input type="button" name="clear" value="c" OnClick="calc.input.value=''"> <input type="button" name="zero" value="0" OnClick="calc.input.value+='0'"> <input type="button" name="dolt" value="= " OnClick="calc.input.value=eval(calc.input.value)">
9

<input type="button" name="div" value="/" OnClick="calc.input.value+='/'"> <br> </td> </tr> </table> </form> </center> </body> </html>

Display time & Date <html> <head> <title> The Date Object</title> </head> <body> <pre> <script language="javascript"> mydate=new Date() document.write("Today's Date\t:\t");
10

document.write(mydate.getDate()+"/"+mydate.getMonth()+"/"+mydate.getYear()); document.write("<br>"); document.write("systemtime\t:\t"); document.write(mydate.getHours()+":"+mydate.getMinutes()+":"+mydate.getSeconds()); </script> </pre> </body> </html>

Displaying an image <HTML> <head> <title>using SetTimeoutMethod</title> <script language="javascript"> window.defaultStatus="workingwithtimeout"; function disp() { document.write("<br><br><br>"); document.write("<center>"); document.write('<img src="C:my documents\Sunset.jpg" width="100"height="100">'); document.write("</center>"); }
11

function startbk() { setTimeout('disp()',3000); } </script> </head> <body> <center> <p>AN IMAGE WILL BE DISPLAYED IN 3 SECONDS AFTER YOU CLICK THIS BUTTON</P> <br><br> <input type="button"name="but1"value="startcountdown"onClick='startbk()'> </center> </body> </html>

1)

12

DESIGN A WEB PAGE FOR A.P. TOURISM ". Program:ap tourism.html:<Html> <frameset rows="20%,80%"> <frame name="AP" src="ap.html"/> <frameset cols="30%,70%"> <frame name="left" src="menu.html"/> <frame name="right" src="main.html"/> </frameset> </html>

Ap.html:<Html> <body> <center> <h1><strong>A.P.TOURISM</strong> </center> </body> </html>

Hyderabad.html:<html> <body bgcolor="yellow"> <center> <h3>WELCOME TO HYDEARABAD</h3>


13

<p>Capital City of A.P</p> </center> </body> </html>

Main.html:<html> <frameset cols="50%,50%" rows="50%,50%"> <frame name="hyd" src="wel.html"/> <frame name="viz" src="wel.html"/> <frame name="vjy" src="wel.html"/> <frame name="tpt" src="wel.html"/> </frameset> </html>

Menu.html:<html> <body> <h1><ul type="square"> <li><a href="hyderabad.html" target="hyd">Hyderabad</li> <li><a href="vizag.html" target="viz">Vizag</li> <li><a href="vijayawada.html" target="vjy">Vijayawada</li> <li><a href="tirupathi.html" target="tpt">Tirupathi</li> </ul> </h1> </body> </html>
14

Tirupathi.html:<html> <body bgcolor="VIOLET"> <center> <h3>WELCOME TO TIRUPATHI</h3> <p>venkateswara temple</p> </center> </body> </html>

Vijayawada.html:<html> <body bgcolor="pink"> <center> <h3>WELCOME TO VIJAYAWADA</h3> <p>educational city</p> </center> </body> </html>

Vizag.html:<html> <body bgcolor="green"> <center> <h3>WELCOME TO VIZAG</h3>


15

<p>steel plant</p> </center> </body> </html>

Wel.html:<html> <head><center><h1>WELCOME</h1> </center> </head> </html>

OUTPUT:-

CONCLUSION:The above program written by me is an errorless one.

16

Design a web page for BSNL using frame sets. Program:MAIN.HTML:<html> <frameset rows="20%, 80 %"> <frame name="title" src="title.html"> <frameset cols="20%, 80 %"> <frameset rows="50%,*"> <frame name="menu" src="menu.html"/> <frame name="display"/> </frameset> <frame name="application"/ > </frameset> </frameset> </html> MENU.HTML:<html> <body> <ul><br> <li><a href="isd.html" target="display"> ISD <li><a href="std.html" target="display"> STD </li> </li> </li>

<li><a href="local.html" target="display"> LOCAL

<li><a href="application.html" target="application"> APPLICATION FORM </li> </UL> </body></html>

17

TITLE.HTML:<html> <body bgcolor="red" text="orange"> <center> <H1> Bharath Sanchar Nigam Limited </H1> </center> </body> </html> APPLICATION.HTML:<html> <head> <title>application form</title> </head> <body> <form name="application"method="post" align="centre"> <br><br> <table cellpadding="10" cellspacing="10" align="centre"bgcolor="purple"> <tr><td>Name</td> <td><input type="text" size="10" maxlength="20"></td></tr> <tr><td><p>Address</td><td><textarea rows="4" cols="32"></textarea></td></tr> <tr><td><p>Gender</td> <td><input type="radio"name="gender">male<input> <input type="radio"name="gender">female<input></td></tr>
18

<p><tr><td>Connection</td></tr><tr><td><input type="checkbox" value="STD">STD</td> <tr><td><input type="checkbox" value="ISD">ISD</td> <tr><td><input type="checkbox" value="LOCAL">LOCAL</p></td><tr> <tr><td><p><input type="submit" value="SUBMIT"></p></td> <td><p><input type="reset"></p></td></tr> </form> </body> </html>

ISD.HTML:<Html> <body> <h1> ISD CALL @ Rs.6.00/UNIT </body> </html>

STD.HTML:<html> <body> <h1> </body> </html> STDCALL @ Rs.2.50/UNIT

19

LOCAL.HTML:<html> <body> <h1> LOCAL CALL @ Rs.1.00/unit </h1> </body> </html>

OUTPUT:

CONCLUSION:The above program written by me is an errorless one.

20

DESIGN A COMPLEX TABLE FOR ENTERING THE STUDENT MARKS YEAR WISE. Program:<html> <head> <title>Complex table</title> </head> <body> <table border ="2" align="center"> <caption>TABLE THAT SHOWS MARKSLIST</caption> <colspan="4" align="center"> <thead> <tr bgcolor="skyblue"> <th rowspan="3"> <h6>Name</h6> </th> <th rowspan="3"> <h6>Rollno</h6> </th> <th colspan="8" valign="top"> <h6>Markslist</h6> </th> <th rowspan="3" valign="center">

DETAILS

21

<h6>Total</h6> </th> </tr> <tr bgcolor=" pink" valign="bottom"> <th rowspan="2" valign="top"> 1 year</th> <th colspan="2">2 year</th> <th colspan="5">3 year</th> </tr> <tr bgcolor="yellow" valign="bottom"> <th>1 sem </th> <th>2 sem</th> <th>3 sem</th> <th colspan="4"> 2 sem</th> </tr> </thead> <tbody> <tr> <td>SHANKAR</td> <td>1209</td> <td>747</td> <td>650</td> <td>625</td> <td>655</td>

22

<td colspan="4">--</td> <td>1224</td> </tr> <tr> <td>SRAVAN</td> <td>579</td> <td>750</td> <td>650</td> <td>650</td> <td>635</td> <td colspan="4">--</td> <td>1224</td> </tr> <tr> <td>DURGAPRASAD</td> <td>1221</td> <td>700</td> <td>600</td> <td>675</td> <td>640</td> <td colspan="4">--</td> <td>1224</td> </tr> </tbody>

23

</table> </body> </html> OUTPUT:-

CONCLUSION:The program written by me is an error free program.

24

DESIGN A FEED BACK FORM USING FORMS". Program:<HTML> <head> <title> using html forms </title> </head> <body bgcolor="BLUE"> <h2> FEEDBACK FORM</h2> <p>please fill out this form to help us in building our website</p> <form method="post"action="/egi_bin/formmail> <p><strong>name:</strong> <input name="name"Type="test"size="25"></p> <p><strong>comments:</strong> <text area name="comments"rows="4"cols=36"> </text area></p> <p><strong>e-mail address:</strong> <input name="e-mail"type="password"size="25"></p> <P> <strong> Things you like: </strong></P> site design <input name="things" Type="checkbox"value="links"> Ease of use: <input name="things"Type="checkbox"value="ease"> images: <input name="things"Type="checkbox"value="images"> Search engine <input name="how to get to site"Type="radio"value="search Engine"> links form another site <input name="how to get to site"Type="radio"value="links">dietel.com website <input name="how to get to site"Type ="radio"value="dietel.com">
25

</p> <p><strong>rate our site(1-10):</strong> <select name="rating"> 0<opinion selected> <option>Amazing:-( <option>10 <option>9 <option>8 <option>7 <option>6 <option>5 <option>4 <option>3 <option>2 <option>1 <option>The pity:-( </select></p> <input Type="submit" value="submit your entries"> <input Type="reset"value="clear your entries"> </form> </body> </HTML>

26

OUTPUT:-

COCNLUSION:The program written by me is an errorless one.

27

1.

Develop static pages (using only HTML) of an online Book store. The pages should resemble. www.amazon.com The website should consist the following pages Home page User Profile Page Shopping Cart Order Confirmation Registration and User Login Books catalog Payment by Credit card

Homepage.html : <html> <head> <title>online book shop</title> </head> <frameset rows="30%,70%"> <frame name="frame1" src="homepagetext.html"> <frameset cols="30%,70%"> <frame name="frame2" src="homepagemenu.html"> <frame name="homepage" src=""> </frameset> </frameset> </html> Homepagetext.html <html> <head> <title>text of the homepage</title> </head> <body bgcolor="yellow"> <marquee><h1>WELCOME TO ONLINE BOOK STORE</h1></marquee> <img src="C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Sunset.jpg" width="50" height="60" align="right" alt="sacet"> <p>please <br> buy atleast one book<br> </p> </boby> </html>
28

Homepagemenu.html <html> <head> <title>menu of the homepage</title> </head> <body> <center><h2><u>MENU</u></h2></center> <ol> <a href="reg.html" target="homepage"> <li>REGISTRATION </a> <a href="login.html" target="homepage"> <li>LOGIN </a> <a href="profile.html" target="homepage"> <li>USER PROFILE </a> <a href="bookscatalog.html" target="homepage"> <li>BOOKS CATALOG </a> <a href="shoppingcart.html" target="homepage"> <li>SHOPPING CART </a> <a href="credit.html" target="homepage"> <li>CREDIT CARD </a> <a href="order.html" target="homepage"> <li>ORDER CONFORMATION </a> </ol> </body> </html> Reg.html <html> <head> <title>registration</title> </head> <body bgcolor="pink"> <frame name="regform" method="post" action=""> <center> <caption>REGRISTRATION</caption> <table> <tr> <td>first name</td>
29

<td><input type="text" name="name" value="" size="10"></td> </tr> <tr> <td>second name</td> <td><input type="text" name="name" value="" size="10"></td> </tr> <tr> <td>enter ur username</td> <td><input type="username" name="name" value="" size="10"></td> </tr> <tr> <td>enter ur password</td> <td><input type="password" name="name" value="" size="10"></td> </tr> <tr> <td>date of birth</td> <td><input type="number" name="" value="" size="3">DD</td> <td><input type="number" name="" value="" size="3">MM</td> <td><input type="number" name="" value="" size="3">YY</td> </tr> <tr> <td>nationality</td> <td><input type="text" name="name" value="" size="6"></td> </tr> <tr> <td>gender</td> <td><input type="radio">MALE</td> <td><input type="radio">FEMALE</td> </tr> <tr> <td>address</td> <td><textarea rows="4" cols="10"></textarea> </td> </tr> <td colspan=2><input type="button" value="submit" onclick="function()"> <input type="button" value="cancel" onclick="function()"></td> </tr> </table> </center> </body> </html>

30

Loging.html <html> <head> <title>login form</title> </head> <body bgcolor="green"> <frame name="login" method="post" action=""> <center> <caption>USER LOGIN</caption> <table> <tr> <td>enter userID</td> <td><input type="text" name="name" value="" size="10"></td> </tr> <tr> <td>enter password</td> <td><input type="password" name="name" value="" size="6"></td> </tr> <tr> <td colspan=1><input type="button" value="sign in" onclick="function()"> <input type="button" value="cancel" onclick="function()"></td> </tr> </table> </center> </body> </html> Userprofile.html <html> <head> <title>user profile</title> </head> <body bgcolor="orange"> <frame name="profile" method="post" action=""> <center> <table border="2" bgcolor="white" cellpadding="5"> <caption>USER PROFILE</caption> <tr> <td>name</td> <td>DOB</td> <td>address</td> <td>cellno</td> <td>e-mail</td> <td>gender</td> <td>nationality</td>
31

</tr> <tr> <td>Koyi</td> <td>15-jan-1978</td> <td>S R nagar</td> <td>9985130820</td> <td>thir@yahoo.com</td> <td>m</td> <td>indian</td> </tr> <tr> <td>naresh</td> <td>15-feb-1979</td> <td>A G colony</td> <td>998130821</td> <td>nag1@yahoo.com</td> <td>m</td> <td>indian</td> </tr> </table> </center> </body> </html> Bookscatalog.html: <html> <head> <title>books catalog</title> </head> <body bgcolor="sky blue"> <frame name="bookscatalog" method="post" action=""> <center> <table border="2" bocolor="blue" cellpadding="5"> <caption>BOOKS CATALOG</caption> <tr> <td>sno</td> <td>name of the book</td> <td>author</td> <td>publication</td> <td>edition</td> <td>availability</td> <td>price</td> <td>if u want add</td> </tr> <tr> <td>1</td>
32

<td>WT</td> <td>bates</td> <td>pearson</td> <td>2nd edition</td> <td>yes</td> <td>500</td> <td><input type="button" value="add" onclick="function()"></td> </tr> <tr> <td>2</td> <td>OS</td> <td>stallings</td> <td>pearson</td> <td>edition</td> <td>5th edition</td> <td>400</td> <td><input type="button" value="add" onclick="function()"></td> </tr> </table> </center> </body> </html> Shoppingcart.html <html> <head> <title>shopping cart</title> </head> <body bgcolor="violet"> <center> <caption>SHOPPING CART</caption> <p >selected books are hue check once again</p> <table border="1" cellpadding="15"> <tr> <td>sno</td> <td>name of book</td> <td>author</td> </tr> <tr> <td>1</td> <td>CN</td> <td>taninbalm</td> </tr> </table> <p><input type="submit" value="ok"></p> </center> </body> </html>
33

Creditcard.html: <html> <head> <title>credit card</title> </head> <body bgcolor="orange"> <frame name="credit card" method="post" action=""> <center> <caption>PAYMENT BY CREDIT CARD</caption> <table border="1" cellpadding="15"> <tr> <td>username</td> <td><input type="text" name="name" value="" size="10"></td> </tr> <tr> <td>pin no</td> <td><input type="number" name="" value="" size="10"></td> </tr> <tr> <td><input type="button" value="submit" onclick="function()"></td> <td><input type="button" value="cancel" onclick="function()"></td> </tr> </table> </center> </body> </html> Orderconfirmation.html: <html> <head> <title>order conforamtion</title> </head> <body bgcolor="blue"> <frame name="order conformation" method="post" action=""> <center> <caption>ORDER CONFORMATION</caption> <p>we will send books with in a week<br> <input type="submit" value="ok"></p> </center> </body> </html>

34

OUTPUT:loginform

Order.html output:

Registration.html

35

Userprofile.html output

Shoppingcart.html output:
36

Homepagetext.html output:

Homepage menu.html output:

Creditcard.html
37

bookscatalog.html

Homepage.html
38

STYLE SHEETS
39

<html> <head> <style type="text/css"> body { background-color:#d0e4fe; } h1 { color:orange; text-align:center; } p { font-family:"Times New Roman"; font-size:20px; } </style> </head> <body> <h1>CSS example!</h1> <p>This is a paragraph.</p> </body> </html>

40

Stylesheet.html

<html> <head> <style type="text/css"> body { background-image:url('img_tree.pngtop'); background-repeat:no-repeat; background-position:top right; margin-right:200px; } </style> </head>

41

Stylesheet.css

<body> <h1>Hello World!</h1> <p>W3Schools background no-repeat, set position example.</p> <p>Now the background image is only show once, and positioned away from the text.</p> <p> In this example we have also added a margin on the right side, so the background image will never disturb the text.</p> </body> </html>

42

EXAMPLES RELATED TO JAVASCRIPT


Program using javascript <html> <body> <script type="text/javascript"> document.write("Hello World!"); </script> </body> </html> Explanation: To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script> tag we use the type attribute to define the scripting language. So, the <script type="text/javascript"> and </script> tells where the JavaScript starts and ends. The document.write command is a standard JavaScript command for writing output to a page. By entering the document.write command between the <script> and </script> tags, the browser will recognize it as a JavaScript command and execute the code line. In this case the browser will write Hello World! to the page. COMMENT IN JAVASCRIPT <html> <body> <scripttype="text/javascript"> <!--document.write("HelloWorld!"); //--> </script> </body> </html> Explanation: Just add an HTML comment tag <!-- before the first JavaScript statement, and a --> (end of comment) after the last JavaScript statement. The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents JavaScript from executing the --> tag.
43

Where to Put the JavaScript: JavaScript in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event. SCRIPT IN <HEAD> <html> <head> <script type="text/javascript"> functionmessage() { alert("This alert box was called with the onload event"); } </script> </head> <body onload="message()"> </body> </html> Explanation: Scripts to be executed when they are called, or when an event is triggered, go in the head section. If you place a script in the head section, you will ensure that the script is loaded before anyone uses it.

Script in <body>
Scripts to be executed when the page loads go in the body section. If you place a script in the body section, it generates the content of a page <html> <head> </head> <body> <script type="text/javascript"> document.write("This message is written by JavaScript"); </script> </body> </html>

44

JavaScript is Case Sensitive


Unlike HTML, JavaScript is case sensitive - therefore watch your capitalization closely when you write JavaScript statements, create or call variables, objects and functions

JavaScript Statements
A JavaScript statement is a command to a browser. The purpose of the command is to tell the browser what to do. This JavaScript statement tells the browser to write "Hello Dolly" to the web page document.write("Hello Dolly"); It is normal to add a semicolon at the end of each executable statement. Most people think this is a good programming practice, and most often you will see this in JavaScript examples on the web. Note: Using semicolons makes it possible to write multiple statements on one line

JavaScript Code
JavaScript code (or just JavaScript) is a sequence of JavaScript statements. Each statement is executed by the browser in the sequence they are written. This example will write a heading and two paragraphs to a web page Ex:-<script type="text/javascript"> document.write("<h1>a heading</h1>"); document.write("<p>This is a paragraph.</p>"); document.write("<p>This is another paragraph.</p>"); </script>

JavaScript Blocks
JavaScript statements can be grouped together in blocks. Blocks start with a left curly bracket {, and ends with a right curly bracket }. The purpose of a block is to make the sequence of statements execute together. This example will write a heading and two paragraphs to a web page

45

Ex: <script type="text/javascript"> { document.write("<h1>a heading</h1>"); document.write("<p>This is a paragraph.</p>"); document.write("<p>This is another paragraph.</p>"); } </script>

JavaScript Comments
Comments can be added to explain the JavaScript, or to make the code more readable. Single line comments start with //. Multi line comments start with /* and end with */.

Ex: <script type="text/javascript"> //Write heading document.write("<h1>This is aheading</h1>"); //Write two paragraphs document.write("<p>This is a paragraph.</p>"); document.write("<p>This is another paragraph.</p>"); </script>

46

JavaScript Variables
As with algebra, JavaScript variables are used to hold values or expressions. A variable can have a short name, like x, or a more descriptive name, like carname. Rules for JavaScript variable names:

Variable names are case sensitive (y and Y are two different variables) Variable names must begin with a letter or the underscore character

Note: Because JavaScript is case-sensitive, variable names are case-sensitive. Ex: <html> <body> <script type="text/javascript"> var firstname; firstname="Hege"; document.write(firstname); document.write("<br />"); firstname="Tove"; document.write(firstname); </script> </body> </html>

O/P: hege Tove

47

Declaring (Creating) JavaScript Variables


Creating variables in JavaScript is most often referred to as "declaring" variables. You can declare JavaScript variables with the var statement: Ex: var x; var name; var x=5; var carname=Volvo; After the execution of the statements above, the variable x will hold the value 5, and carname will hold the value Volvo. Note: When you assign a text value to a variable, use quotes around the value.

48

2.

Validate the Registration, user Login, User Profile and payment by credit card pages using JavaScript Credit card validation: <html> <head> <script type="text/javascript"> function fna() { var fn,ln,pn; fn=f3.name.value; ln=f3.cno.value; pn=f3.pno.value; var u=ln.length; if(fn=="") { window.alert("enter customer name"); } else if(ln=="") { window.alert("enter cardno"); } else if(u!=16) { window.alert("Invalid cardno"); } else if(pn=="") { window.alert("Enter pin no:"); } else { window.alert("Credit card accepted..."); } } </script> </head> <body bgcolor="opera"> <form name="f3" method="post" action=" "> <center> <caption>PAYMENTBYCREDIT CARD</caption> <table><tr> <td>Customer name</td> <td><input type="text" name="name" value="" size="20"></td> </tr>
49

<tr> <td>card no</td> <td><input type="text" name="cno" value="" size="20"></td> </tr> <tr> <td>pin no</td> <td><input type="password" name="pno" value="" size="20"></td> </tr> </table></center> <center><input type="button" value="submit" onclick="fna()"></center> </form> </body> </html> Output:

50

Login page validation: <html> <head> <script type="text/javascript"> function fname() { var fn,ln; fn=f2.fna.value; ln=f2.pwd.value; if(fn=="") { window.alert("enter ur Id"); } else if(ln=="") { window.alert("enter ur password"); } else { window.alert("Login Success"); } } </script> </head> <body bgcolor="pink"> <form name="f2" method="post" action=" ">
51

<center> <table> <caption>LOGIN</caption> <tr> <td>enter user id</td> <td><input type="text" name="fna" value=""size="10"></td> </tr> <tr> <td>enter password</td> <td><input type="password"name="pwd" value=""size="6"></td> </tr> <tr> <td><input type="BUTTON" value="SIGN IN "onclick="fname()"></td> <td><input type="BUTTON" value="CANCEL"></td> </tr> </table> </center> </form> </body> </html>

52

Outputs:

53

Profile validation <html> <head> <script type="text/javascript"> function fname() { var fn,cn,db,nt,ad; fn=f1.fna.value; db=f1.dob.value; ad=f1.address.value; cn=f1.cno.value; nt=f1.nat.value; if(fn=="") { window.alert("entername"); } else if(db=="") { window.alert("enter date of birth"); } else if(ad=="") { window.alert("enter address"); } else if(cn=="") { window.alert("enter cellno:"); } else if(nt=="") { window.alert("enter nationality"); } else { window.alert("Profile Submited.."); } } </script> </head> <body bgcolor="orange"> <form name="f1" method="post" action=""> <center> <table border="2" bgcolor="white" cellpadding="5"> <caption>USER PROFILE</caption> <tr> <td>name</td>
54

<td><input type="text" name="fna" value="" size="10"></td> </tr> <tr> <td>Date of Birth</td> <td><input type="number" name="dob" value="" size="10"></td> </tr> <tr> <td>ADDRESS</td> <td><textarea rows="10" cols="10" name="address"></textarea></td> <tr> <td>CELLNUMBER</td> <td><input type="number" name="cno" value="" size="10"></td> </tr> <tr> <td>NATIONALITY</td> <td><input type="text" name="nat" value="" size="10"></td> </tr> <tr><td colspan=2 align=center><input type="button" value=SUBMIT onclick="fname()"> </center> </body> </html> Outputs:

Registration form validations:


55

<html> <head> <script type="text/javascript"> function checkform() { var fn,ln,ep,cp,db1,db2,db3,nt,ad,gen1,gen2; ln=f1.sna.value; ep=f1.pwd1.value; cp=f1.pwd2.value; fn=f1.fna.value; db1=f1.dd.value; db2=f1.mm.value; db3=f1.yy.value; nt=f1.nat.value; ad=f1.address.value; gen1=f1.gender[0].checked; gen2=f1.gender[1].checked; if(fn=="") { window.alert("enter first name"); } else if(ln=="") { window.alert("enter second name"); } else if(ep=="") { window.alert("enter ur pwd"); } else if(cp=="") { window.alert("confirm ur pwd"); } else if(ep!=cp) { window.alert("passwords are not match"); } else if(db1==""||db2==""||db3=="") { window.alert("date of birth"); } else if(nt=="") {
56

window.alert("enter nationality"); } else if(gen1==false||gen2==false) { window.alert("enter gender"); } else if(ad=="") { window.alert("enter address"); } else { window.alert("Registration conformed..."); } } </script> </head> <body bgcolor="pink"> <form name="f1" method="post" action=" "> <center> <caption>REGISTRATION</caption> <table> <tr> <td>first name</td> <td><input type="text" name="fna" value="" size="10"></td> </tr> <tr> <td>second name</td> <td><input type="text" name="sna" value="" size="10"></td> </tr> <tr> <td>enter pwd</td> <td><input type="password"name="pwd1" value="" size="6"></td> </tr> <tr> <td>conform ur pwd</td> <td><input type="password"name="pwd2" value="" size="6"></td> </tr> <tr> <td>Date of birth</td> <td><input type="text" name="dd" value="" size="2">DD</td> <td><input type="text" name="mm" value="" size="2">MM</td> <td><input type="text" name="yy" value="" size="4">YY</td> </tr> <tr> <td>nationality</td> <td><input type="text"name="nat" value="" size="10"></td> </tr>
57

<tr> <td>gender</td> <td><input type="radio" name=gender>Male <input type="radio" name=gender>Female</td> </tr> <tr> <td>Address</td> <td><textarea rows="3" cols="3" name=address></textarea></td> </tr> <tr> <td><input type="BUTTON" value="SUBMIT" onclick="checkform()"></td> <td><input type="RESET" value="CANCEL"></td> </tr> </table> </center> </form> </body> </html> Outputs:

58

59

3.

Create and save an XML document at the server, which contains 10 users information. Write a program which takes User Id as an input and returns the user details by taking the user information from XML document. Info.xml <?xml version="1.0"?> <info> <user> <name>suresh reddy</name> <id>1201</id> <dob>12/01/1989</dob> <place>S r nagar</place> <rank>07</rank> </user> <user> <name>chand</name> <id>1202</id> <dob>13/08/1989</dob> <place>Ongole</place> <rank>02</rank> </user> <user> <name>naresh</name> <id>1203</id> <dob>1/02/1988</dob> <place>bapatla</place> <rank>05</rank> </user>

60

<user> <name>Kalyan</name> <id>1204</id> <dob>18/09/1989</dob> <place>guntur</place> <rank>04</rank> </user> <user> <name>Koyi</name> <id>1205</id> <dob>13/07/1988</dob> <place>A g colony</place> <rank>06</rank> </user> <user> <name>alludu</name> <id>1206</id> <dob>3/05/1989</dob> <place>nellore</place> <rank>09</rank> </user> <user> <name>surendra</name> <id>1207</id> <dob>31/05/1987</dob> <place>martur</place>
61

<rank>10</rank> </user> <user> <name>suneel</name> <id>1208</id> <dob>05/06/1985</dob> <place>vizag</place> <rank>01</rank> </user> <user> <name>rajesh</name> <id>1209</id> <dob>07/04/1988</dob> <place>machilipatnam</place> <rank>08</rank> </user> <user> <name>pavan</name> <id>1210</id> <dob>20/03/1988</dob> <place>tenali</place> <rank>03</rank> </user> </info>

62

microsoft.js function loadXMLDOC(dname) { var xmldoc; if(window.ActiveXObject) { xmldoc=new ActiveXObject("microsoft.XMLDOM"); } else if(document.implementation && document.implementation.createDocument) { xmldoc=document.implementation.createDocument(" "," ","null"); } else { alert("the browser cannot handle this msg"); } xmldoc.async=false; xmldoc.load(dname); return(xmldoc); } function getid() { var doc=loadXMLDOC("info.xml"); var id=info.id.value; var a=doc.getElementsByTagName('name'); var b=doc.getElementsByTagName('id'); var c=doc.getElementsByTagName('dob');
63

var d=doc.getElementsByTagName('place'); var e=doc.getElementsByTagName('rank'); var count=0; for(var i=0;i<b.length;i++) { if(b[i].childNodes[0].nodeValue==id) { count=1; document.open(); document.write("<body bgcolor=yellow text=violet>"); document.write("<center><table border=1 cellpadding=5 cellspacing=5>"); document.write("<tr><th>name</th><th>id</th><th>dob</th><th>place</th><th>ran k</th></tr>"); document.write("<td>"+a[i].childNodes[0].nodeValue+"</td>"); document.write("<td>"+b[i].childNodes[0].nodeValue+"</td>"); document.write("<td>"+c[i].childNodes[0].nodeValue+"</td>"); document.write("<td>"+d[i].childNodes[0].nodeValue+"</td>"); document.write("<td>"+e[i].childNodes[0].nodeValue+"</td>"); document.close(); } } if(count==0) { } alert("the record is not found"); }

64

myxml.js function loadXMLDOC(dname) { var xmldoc; if(window.ActiveXObject) { xmldoc=new ActiveXObject("microsoft.XMLDOM"); }

else if(document.implementation && document.implementation.createDocument) { xmldoc=document.implementation.createDocument(" "," ","null"); } else { alert("the browser cannot handle this msg"); } xmldoc.async=false; xmldoc.load(dname); return(xmldoc); } function getid() { var doc=loadXMLDOC("info.xml"); var id=info.id.value; var a=doc.getElementsByTagName('name');
65

var b=doc.getElementsByTagName('id'); var c=doc.getElementsByTagName('dob'); var d=doc.getElementsByTagName('place'); var e=doc.getElementsByTagName('rank'); var count=0; for(var i=0;i<b.length;i++) { if(b[i].childNodes[0].nodeValue==id) { count=1; document.open(); document.write("<body bgcolor=yellow text=violet>"); document.write("<center><table border=1 cellpadding=5 cellspacing=5>"); document.write("<tr><th>name</th><th>id</th><th>dob</th><th>place</th><th>ran k</th></tr>"); document.write("<td>"+a[i].childNodes[0].nodeValue+"</td>"); document.write("<td>"+b[i].childNodes[0].nodeValue+"</td>"); document.write("<td>"+c[i].childNodes[0].nodeValue+"</td>"); document.write("<td>"+d[i].childNodes[0].nodeValue+"</td>"); document.write("<td>"+e[i].childNodes[0].nodeValue+"</td>"); document.close(); } } if(count==0) { }
66

alert("the record is not found");

studentdetails.html <html> <head> <script type="text/javascript" src="myxml.js"> </script> </head> <body bgcolor="pink"> <h1 align="center"><u>Welcome INFO Site</h1> <fieldset> <legend>STUDENT DETAILS</legend> <form name="info"> <table border="1" align="center" bgcolor="yellow"> <tr> <th>enter your ID</th> <td><input type="text" name="id" value=""></td> </tr> <tr> <td colspan="2" align="center"> <input type="button" value="get result" onclick="getid()"> <input type="reset" value="cancel"> </td> </tr> </table> </form> </fieldset> </html> Output:

67

Java Beans
//GuiAppl.java //main program import javax.swing.*; import java.awt.*; import java.awt.event.*; public class GuiAppl extends JFrame implements ActionListener { JTextField tfProdId, tfProdName, tfPrice; JButton jbStore; public GuiAppl() { tfProdId=new JTextField("enter prodid"); tfProdName=new JTextField("enter prodname"); tfPrice=new JTextField("enter price"); jbStore=new JButton("Display"); Container cp=getContentPane(); cp.setLayout(new FlowLayout()); cp.add(tfProdId); cp.add(tfProdName); cp.add(tfPrice); cp.add(jbStore); pack(); jbStore.addActionListener(this); }

68

public static void main(String a[])throws Exception { GuiAppl guiAppl=new GuiAppl(); guiAppl.setVisible(true); } public void actionPerformed(ActionEvent ae) { try { String vprodid, vprodname, vprice; vprodid=tfProdId.getText(); vprodname=tfProdName.getText(); vprice=tfPrice.getText(); ProdBean pb=new ProdBean(); pb.setProdId(vprodid); pb.setProdId(vprodname); pb.setPrice(vprice); } catch(Exception e) { System.out.println(e); } } }

69

ProdBean.java public class ProdBean { String propone, proptwo, propthree; public ProdBean() { } public void setProdId(String s1) { propone=s1; System.out.println("property one-->"+s1); } public String getProdId() { System.out.println("get property-->"+propone); return propone; } public void setProdName(String s2) { proptwo=s2; System.out.println("property two-->"+s2); } public String getProdName() { System.out.println("get property-->"+proptwo); return proptwo; } public void setPrice(String s3)
70

{ propthree=s3; System.out.println("property three-->"+s3); } public String getPrice() { System.out.println("get property-->"+propthree); return propthree; } } OUTPUT:

71

Procedure: 1. First compile the bean program 2. After that compile and run the main program Example: C:\abc\javac ProdBean.java (compiling bean prg) C:\abc\javac GuiAppl.java (compiling main prg) C:\abc\java GuiAppl (running main prg)

72

Bean Assignments
4a) Create a JavaBean which gives the exchange value of INR(Indian Rupees) into equivalent American/Canadian/Australian Dollor value.

CurrencyAppl.java //main program import javax.swing.*; import java.awt.*; import java.awt.event.*; public class CurrencyAppl extends JFrame implements ActionListener { JTextField tfameCurr, tfcanCurr, tfausCurr; //declare the text fields JButton jbStore;//declare button public CurrencyAppl()//constructor { tfameCurr=new JTextField("Enter Indian Currency(in Rs)"); //creation of text field tfcanCurr=new JTextField("Enter Indian Currency(in Rs)"); tfausCurr=new JTextField("Enter Indian Currency(in Rs)"); jbStore=new JButton("convert"); Container cp=getContentPane(); cp.setLayout(new FlowLayout()); cp.add(tfameCurr); cp.add(tfcanCurr); cp.add(tfausCurr);
73

cp.add(jbStore); pack(); jbStore.addActionListener(this); } public static void main(String a[])throws Exception { CurrencyAppl currencyAppl=new CurrencyAppl(); currencyAppl.setVisible(true); } public void actionPerformed(ActionEvent ae) { try { float vameCurr, vcanCurr, vausCurr; vameCurr=Float.parseFloat(tfameCurr.getText()); vcanC urr=Float.parseFloat(tfcanCurr.getText()); vausCurr=Float.parseFloat(tfausCurr.getText()); CurrencyBean cb=new CurrencyBean(); cb.setAmeCurr(vameCurr); cb.setCanCurr(vcanCurr); cb.setAusCurr(vausCurr); } catch(Exception e) { System.out.println(e); } } } CurrencyBean.java
74

public class CurrencyBean { float ameCurr,canCurr,ausCurr; public CurrencyBean() { } public void setAmeCurr(float ameCurr) { this.ameCurr=ameCurr; System.out.println("equivalent American Currency(in doller)--->"+(ameCurr/40)); }

public float getAmeCurr() { return ameCurr; } public void setCanCurr(float canCurr) { this.canCurr=canCurr; System.out.println("equivalent canadian Currency(in doller)--->"+(canCurr/35)); } public float getCanCurr() { return canCurr; } public void setAusCurr(float ausCurr)
75

{ this.ausCurr=ausCurr; System.out.println("equivalent Australian Currency(in doller)--->"+(ausCurr/30)); } public float getAusCurr() { return ausCurr; } }

Procedure: 1. First compile the bean program 2. After that compile and run the main program

Example: C:\abc\javac Currency.Bean.java (compiling bean prg) C:\abc\javac CurrencyAppl.java (compiling main prg) C:\abc\java CurrencyAppl (running main prg)

76

equivalent American Currency(in doller)--->0.125 equivalent canadian Currency(in doller)--->0.14285715 equivalent Australian Currency(in doller)--->0.16666667

Equivalent American Currency in dollar 0.35 Equivalent canadian Currency in dollar 0.4567 Equivalent Australian Currency in dollar 0.268

4b)

Create a simple Bean with a label- which is the count of number of clicks. Then create a Bean Info class such that only the count property is visible in the property window. import java.io.*; import java.util.*; import java.awt.*; import java.awt.event.*; public class Click extends Frame implements MouseListener { Label l; TextField t; private Integer count=0; public Click() { System.out.println("in con"); l=new Label("click on me"); t=new TextField("0",10); setLayout(new FlowLayout()); add(l); add(t);
77

l.addMouseListener(this); setSize(300,200); setVisible(true); } public void mouseClicked(MouseEvent me) { count=count+1; t.setText(count.toString()); } public void mousePressed(MouseEvent me){} public void mouseReleased(MouseEvent me){} public void mouseEntered(MouseEvent me){} public void mouseExited(MouseEvent me){} public static void main(String args[])throws Exception { Click c=new Click(); } } OUTPUT:

78

4c)

Create two Beans a) Key Pad b) Display Pad After that integrate the two Bean to make it work as a calculator

import java.awt.*; import java.awt.event.*; import java.io.Serializable;

public class Calc extends Frame implements ActionListener { private Integer res,res1; int op; TextField tf=new TextField("0",20); Button b1=new Button("1"); Button b2=new Button("2"); Button b3=new Button("3"); Button b4=new Button("4"); Button b5=new Button("5"); Button b6=new Button("6"); Button b7=new Button("7"); Button b8=new Button("8"); Button b9=new Button("9"); Button b0=new Button("0"); Button b11=new Button("+"); Button b12=new Button("-"); Button b13=new Button("x"); Button b14=new Button("/"); Button b15=new Button("=");
79

public Calc() { setLayout(new GridLayout(6,6)); setSize(200,200); setVisible(true); add(b0); add(b1); add(b2); add(b3); add(b4); add(b5); add(b6); add(b7); add(b8); add(b9); add(b11); add(b12); add(b13); add(b14); add(b15); add(tf); b0.addActionListener(this); b1.addActionListener(this); b2.addActionListener(this);
80

b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); b6.addActionListener(this); b7.addActionListener(this); b8.addActionListener(this); b9.addActionListener(this); b11.addActionListener(this); b12.addActionListener(this); b13.addActionListener(this); b14.addActionListener(this); b15.addActionListener(this); res=0; }

public void actionPerformed(ActionEvent ae) { String cmd=ae.getActionCommand(); if(cmd.equals("0")) { res=Integer.parseInt(res.toString()+"0"); tf.setText(res.toString()); } else if(cmd.equals("1")) { res=Integer.parseInt(res.toString()+"1"); tf.setText(res.toString()); } else if(cmd.equals("2")) { res=Integer.parseInt(res.toString()+"2"); tf.setText(res.toString()); } else if(cmd.equals("3")) { res=Integer.parseInt(res.toString()+"3"); tf.setText(res.toString()); } else if(cmd.equals("4")) { res=Integer.parseInt(res.toString()+"4"); tf.setText(res.toString()); }
81

else if(cmd.equals("5")) { res=Integer.parseInt(res.toString()+"5"); tf.setText(res.toString()); } else if(cmd.equals("6")) { res=Integer.parseInt(res.toString()+"6"); tf.setText(res.toString()); } else if(cmd.equals("7")) { res=Integer.parseInt(res.toString()+"7"); tf.setText(res.toString()); } else if(cmd.equals("8")) { res=Integer.parseInt(res.toString()+"8"); tf.setText(res.toString()); } else if(cmd.equals("9")) { res=Integer.parseInt(res.toString()+"9"); tf.setText(res.toString()); } else if(cmd.equals("+")) { res1=res; res=0; tf.setText("0"); op=0; } else if(cmd.equals("-")) { res1=res; res=0; tf.setText("0"); op=1;} else if(cmd.equals("x")) { res1=res; res=0; tf.setText("0"); op=2;} else if(cmd.equals("/")) { res1=res; res=0; tf.setText("0"); op=3;} else if(cmd.equals("=")) { res=Integer.parseInt(tf.getText()); if(op==0) res=res1+res; else if(op==1) res=res1-res; else if(op==2) res=res*res1; else if(op==3) { if(res!=0) res=res1/res;
82

else System.out.println("Div Zero"); } tf.setText(res.toString()); } } public void setRes(Integer r) { res=r; } public Integer getRes() { return res; } public static void main(String[] args) { Calc c=new Calc(); } }

83

4d)

Create two Beans Traffic Light (implemented as a Label with only three background colours- Red, Green,Yellow) and Automobile(implemented as a textbox which states its state/movement). The state of the Automobile should depend on the following Light Transition table. Light Transition Red Yellow Yellow Green GreenRed Program : Tsignal.java import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.Serializable; public class Tsignal extends Frame implements MouseListener { private Color col=Color.red; Choice sgen=new Choice(); Label l1=new Label("Ready"); public Tsignal() { setSize(200,200); setVisible(true); setLayout(new FlowLayout()); add(l1); this.addMouseListener(this); } Automobile State Ready Move Stop

public void mousePressed(MouseEvent me) {

84

Color c; if(col==Color.red) { c=Color.yellow; l1.setText("Ready"); } else if(col==Color.yellow) { c=Color.green; l1.setText("Move"); } else if(col==Color.green) { c=Color.red; l1.setText("Stopped"); } else { c=Color.red; l1.setText("Stopped"); } setCol(c); repaint(); } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } public void mouseReleased(MouseEvent me) { } public void mouseClicked(MouseEvent me) { }

85

public void setCol(Color c) { col=c; repaint(); } public Color getCol() { return col; } public void paint(Graphics g) { System.out.println(col.toString()); g.setColor(col); g.fillOval(50,50,100,100); } public static void main(String[] args) { Tsignal c=new Tsignal(); } } Output:

86

EXAMPLES ON SERVLET
A SERVLET PROGRAM TO PRINT " WELCOME TO SERVLET" Program:WEB.XML: <Web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>first</servlet-class> </servlet> <servlet-mapping> servlet-name>s1</servlet-name> <url-pattern>/first</url-pattern> </servlet-mapping> </web-app> FIRST.JAVA: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class first extends HttpServlet { public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html");
87

PrintWriter pw=res.getWriter(); pw.println("<h1>welcome to servlet</h1>"); pw.close(); } } OUTPUT:

CONCLUSION:The program written by me is an errorless one.

88

A SERVLET PROGRAM TO IMPLEMENT THE " DoGET " METHOD. Program:COLOR CHOOSEN.HTML: <html> <body> <form name="form 1" method="GET" action="./colors"> <b>COLOR</b> <select name="color" size="1"> <option value="red">Red</option> <option value="green">Green</option> <option value="blue">Blue</option> </select> <input type=submit value="send"/> </form> </body> </html> WEB.XML: <web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>colors</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/colors</url-pattern> </servlet-mapping> </web-app>

89

COLORS.JAVA: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class colors extends HttpServlet { { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException String color=req.getParameter("color"); PrintWriter pw=res.getWriter(); pw.println("<b>selected color is:</b>"); pw.println(color); pw.close(); } } OUTPUT:

Conclusion:-

The program written by me is an errorless one.

90

A SERVLET PROGRAM TO IMPLEMENT THE "DOPOST " METHOD. Program:COLOR CHOOSEN.HTML: <html> <body> <form name="form 1" method="POST" action="./colors"> <b>COLOR</b> <select name="color" size="1"> <option value="red">Red</option> <option value="green">Green</option> <option value="blue">Blue</option> </select> <input type=submit value="send"/> </form> </body> </html>

WEB.XML: <web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>colors</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/colors</url-pattern> </servlet-mapping> </web-app>

91

COLORS.JAVA: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class colors extends HttpServlet { public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { String color=req.getParameter("color"); PrintWriter pw=res.getWriter(); pw.println("<b>selected color is:</b>"); pw.println(color); pw.close(); } }

OUTPUT:

CONCLUSION:The program written by me is an errorless one.

92

A PROGRAM TO IMPLEMENT SERVLET COMMUNICATION". Program:PROFILE.HTML: <html> <head> <h1>user form</h1> </head> <body bgcolor="yellow"> <form action="./first" method="POST"> name:<input type="text" name="t1"><br><br> address:<input type="text" name="t2"><br><br> age:<input type="text" name="t3"><br><br> <input type="submit" value="send"/> <input type="reset" value="reset"/> </form> </body> </html>

WEB.XML: <web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>ser1</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/first</url-pattern> </servlet-mapping>

93

<servlet> <servlet-name>s2</servlet-name> <servlet-class>ser2</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>/second</url-pattern> </servlet-mapping> </web-app>

SER1.JAVA: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class ser1 extends HttpServlet { public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { String name=req.getParameter("t1"); String addr=req.getParameter("t2"); int age=Integer.parseInt(req.getParameter("t3")); Cookie c1=new Cookie ("c1",name); Cookie c2=new Cookie ("c2",addr); Cookie c3=new Cookie ("c3",age+" "); res.addCookie(c1); res.addCookie(c2); res.addCookie(c3); PrintWriter PW=res.getWriter();
94

PW.println("<a href=./second>click here</a>"); PW.close(); } }

SER2.JAVA: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class ser2 extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { PrintWriter Out=res.getWriter(); res.setContentType("text/html"); Cookie []cc=req.getCookies(); if(cc!=null) { for(int i=0;i<cc.length;i++) { String s1=cc[i].getName(); if(s1.equals("c1")) Out.println(cc[i].getValue()); else if(s1.equals("c2")) Out.println(cc[i].getValue()); else if(s1.equals("c3")) Out.println(cc[i].getValue()); }}}}
95

OUTPUT:

CONCLUSION:-

The program written by me is an errorless one.

96

5.

Install TOMCAT web server. Covert the static web pages of assignments 2 into dynamic web pages using servlets and cookies. Hint: Users Information (user Id, password, credit card number) would be stored. In web.xml. Each user should have a separate shopping cart. Aim: To validate the user login, user profile, and payment by credit card by using Html and java Servlets Description: 1. 2. 3. 4. 5. We start the designing of the program with an HTML and then proceed to design of a java servlets We start html tag first. In the head tag a funciton profile(f1,f2) is declared that describes the status of those users logged in successfully. In body tag, describe the background colors to be used by using bgcolor. Three forms are used in developing the web page. The first form will receive the username and password , on submit these data i.e username & password are send to servlet for processing the information. If these values are valid then the program displays logged in successful. This form is preceded by marquee that scroll to either to left or right as specified. Second form contains one text field , one password field and one text area . This form gives the details of the user. that will be displayed in text field. Third form contains the 2 text -field and one password field. This is useful to pay amount by credit card . To design a servlet import java packages, like servlet etc. Create a class UserInfo that extends properties of HttpServlet. The doPost method present in this class takes HttpServletRequest and HttpServletResponse as parameters. Set the MIME type to text/html . For any servlet the default MIME type is text/plain. An instance out for PrintWriter is created, which is initailized by using getWriter method. Strings user and password are created, which takes values sent by the user . Strinds ua,pa,ub,pb ........ contains the information of five users which is stored under the xml document. Values present in user password are verified with either ua,pa or ub,pb ........ if these are correct then display login successful message. else login invalid message.

6. 7. 8. 9.

10. 11. 12. 13. 14.

97

15. 16.

To successfully execute this application an xml file is also to be created that should contain user details . user details are mentioned with in init-param tags . Place the class file and xml file under the WEB-INF directory then deploy under Tomcat.

SOURCE CODE:
a. Register.html :

<html> <head> <script language="javascript"> <!-function profile(f1,f2) { document.f2.ta.value="USER NAME:"+document.f1.userid.value+"\n STATUS:logged in"; } //--> </script> </head> <body bgcolor="red"> <MARQUEE style="color:block;font-size:20; font-weight:bold" direction="left" bgcolor="white" scrollamount="20"> CHECK UR REGISTERED ACCOUNT HERE </marquee> <br><br> <form name="f1" method="post" action="http://localhoat:8080/WebApp/userinfo"> USER NAME:<input type="text" name="userid"><br><br> PASSWORD:<input type="password" name="password"><br><br> <input type="submit" name="login" value="login"><br><br> </form> <marquee style="color:white;font-size:20;font-weight:bold" direction="rirht" bgcolor="block" scrollamount="20"> CHECK UR USER PROFILE HERE</marquee> <br><br> <centere>USER PROFILE</CENTRE><BR><BR> <form name="f2"> USER NAME:<input type="text" name="userid1"><br><br> PASSWORD:<input type="password" name="password1"><br><br> <input type="button" value="check profile" onClick="profile(f1,f2)"> <textarea name="ta" cols=40 rows=15> </textarea> </form> </body> </html>
98

b. UserInfo.java:

import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class UserInfo extends HttpServlet{ public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException{ System.out.println("Inside depost method--->"); PrintWriter out=res.getWriter(); res.setContentType("text/html"); String user=req.getParameter("userid"); String psw=req.getParameter("password"); System.out.println("user name is-->"+user); String user1=req.getParameter("userid1"); String password1=req.getParameter("password1"); String user2=req.getParameter("userid2"); String password2=req.getParameter("password2"); String ua=getInitParameter("user1"); String pa=getInitParameter("pass1"); String ub=getInitParameter("user2"); String pb=getInitParameter("pass2"); String uc=getInitParameter("user3"); String pc=getInitParameter("pass3"); String ud=getInitParameter("user4"); String pd=getInitParameter("pass4"); String ue=getInitParameter("user5"); String pe=getInitParameter("pass5"); if((user.equals(ua)&&psw.equals(pa))||(user.equals(ub)&&psw.equals(pb))|| (user.equals(uc)&&psw.equals(pc))||(user.equals(ud)&&psw.equals(pd))|| (user.equals(ue)&&psw.equals(pe))) { out.println("<html><head>"); out.println("<script language=\"javascript\">"); out.println("alert(\"u have reegistered Successfully\")"); out.println("</script></head><body>"); } else { out.println("<html><head>"); out.println("<script language=\"javascript\">"); out.println("alert(\"not a valid user\")"); out.println("</script></head><body>"); out.println("<a href=\"./Register.html\">Back</body></html>"); } }}
99

c. Web.xml: <?xml version="1.0" encoding="ISO-8859-1"?> <web-app> <servlet> <servlet-name>request info</servlet-name> <servlet-class>UserInfo</servlet-class> </servlet> <init-param> <param-name>user1</param-name> <param-value>reddy1</param-value> </init-param> <init-param> <param-name>pass1</param-name> <param-value>dilip1</param-value> </init-param> <init-param> <param-name>user2</param-name> <param-value>reddy2</param-value> </init-param> <init-param> <param-name>pass2</param-name> <param-value>dilip2</param-value> </init-param> <init-param> <param-name>user3</param-name> <param-value>reddy3</param-value>
100

</init-param> <init-param> <param-name>pass3</param-name> <param-value>dilip3</param-value> </init-param> <init-param> <param-name>user4</param-name> <param-value>reddy4</param-value> </init-param> <init-param> <param-name>pass4</param-name> <param-value>dilip4</param-value> </init-param> <init-param> <param-name>user5</param-name> <param-value>reddy5</param-value> </init-param> <init-param> <param-name>pass5</param-name> <param-value>dilip5</param-value> </init-param> <servlet-mapping> <servlet-name>request info</servlet-name> <url-pattern>/requestinfo</url-pattern> </servlet-mapping> </web-app>
101

JavaServerPages (JSP)
Examples: Welcome.jsp <html> <body bgcolor=khaki> <table border=5 align="center"> <tr><th class="title"> <% out.println("wel come to jsp page"); %></tr> </table> </body> </html>

102

6.

Redo previous task using JSP by converting the static webpages of assignments 2 into dynamic webpages. Create a database with user information and books information. The books catalogure be dynamically loaded from the database. Follow MVC architecture while doing the website.

Home.jsp: <html> <center> <b><a href="main.jsp">REGISTRATION</a><br> <br><b><a href="login.jsp">Login</a> </center> </html>

103

Main.jsp: <html> <head><title></title></head> <script> <%@ page import="java.sql.*" %> <%@ page import="java.io.*" %> <%@ page import="java.lang.*" %> function check(f1) { var err=""; if(f1.uname.value=="") { alert("\nEnter User Name"); f1.uname.focus(); return false;} else if(f1.pwd.value=="") { alert("\nEnter Password"); f1.pwd.focus(); return false; } else if(!isNaN(f1.uname.value.charAt(0))) { alert("\nUserName should start with a letter"); f1.uname.focus(); return false; } } </script> <body> <table> <% Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String database = "jdbc:odbc:abc"; Connection con = DriverManager.getConnection(database,"",""); Statement smt=con.createStatement(); String uname=request.getParameter("uname"); System.out.println(uname); String pwd=request.getParameter("pwd"); System.out.println(pwd);

104

if(uname!=null) { try { smt.execute("insert into users values('"+uname+"','"+pwd+"')"); } catch(Exception e) { out.println("Error"); } response.sendRedirect("home.jsp"); } String query="select * from users"; smt.execute(query); ResultSet rs=smt.getResultSet(); con.close(); %> <form name=fr action="main.jsp" onsubmit="return check(document.fr)" method="post"> <center> User Name<input type=text name="uname"/> Password<input type=password name="pwd"/><br><br><br> <input type=submit value="Enter"></input> </center> </form> </body>

105

Catalog.jsp:

<html> <%@ page import="java.sql.*" %> <%@ page import="java.lang.*" %> <%@ page import="java.io.*" %> <body> <form name="myfrm" action="cart.jsp" method="get"> <center> <table align=center border=1> <input type=hidden name=uname value='<%out.print(request.getParameter("uname")); %>'></input> <tr><th></th><th>Title</th><th>Author</th></tr> <% Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String database = "jdbc:odbc:abc"; Connection con = DriverManager.getConnection(database,"",""); Statement smt=con.createStatement(); smt.execute("select * from catalog"); ResultSet rs=smt.getResultSet(); int i=1; while(rs.next()) { out.println("<tr><td><input type=checkbox name=b"+i+"></td><td>"); out.println(rs.getString("title")+"</td><td>"+rs.getString("author")+"</td></tr>"); i=i+1; } out.println("<input type=hidden name=rc value='"+i+"'></input>"); %>
106

<tr><td colspan=3 align=center><input type=submit value="Add to Cart"></input></td></tr> </table> </body> </html>

Create two table

1.users.mdb in that fields are username and password 2.catalog.mdb in the fields are title and author

Variable name: JAVA_HOME Variable value::C:\Program Files\Java\jdk1.5.0_05

Cart.jsp:

<html> <head> <%@ page import="java.sql.*" %> <%@ page import="java.io.*" %> <%@ page import="java.lang.*" %> <script> function submitted() { alert("Thank you for purchasing.."); document.location="catalog.jsp";

} </script> <body> <table align=center border=1> <tr><td colspan=4>User Name:


107

<% String uname=request.getParameter("uname"); out.println("<b>"+uname+"</b></tr><tr><th colspan=4>List of selected Books</th></tr>"); String filename = "c:\\users.mdb"; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="; database+= filename.trim() + ";DriverID=22;READONLY=false}"; Connection con = DriverManager.getConnection(database,"",""); Statement smt=con.createStatement(); smt.execute("select * from catalog"); ResultSet rs=smt.getResultSet(); int i=1; boolean f=false; while(rs.next()) { String val=request.getParameter("b"+i); if(val!=null) { String title=rs.getString("title"); String author=rs.getString("author"); out.println("<tr><td>"+title+"</td><td>"+author+"</td></tr>"); f=true; } i=i+1; } if(!f) out.println("<tr><td colspan=4>No books selected...</td></tr>"); %>

108

<tr><td colspan=4 align=center><input type=button value="Ok" onclick="submitted();"></input></td></tr> </body> </html> OUTPUT for JSP program(Data base programs):

Click on registration we will get

109

Enter username and password and click on enter.. automatically it navigates to HOME PAGE.. the vales of username and password stores in db it stores in DB. After that click on LOGIN page u get this window

Enter userid and password click on login ,it navigates to

110

Select the book titles (ie check the box corresponding title) and click on addcart.

Click on Ok we will get confirmation ie

111

7)

Implement the Hello World program using jsp struts Framework.

LINK PROGRAM -----------------------<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean" %> <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %> <%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic" %> <html:html locale="true"> <head> <title><bean:message key="welcome.title"/></title> <html:base/> </head> <body bgcolor="white"> <logic:notPresent name="org.apache.struts.action.MESSAGE" scope="application"> <font color="red"> ERROR: Application resources not loaded -- check servlet container logs for error messages. </font> </logic:notPresent> <h3><bean:message key="welcome.heading"/></h3> <p><bean:message key="welcome.message"/></p> </body> </html:html>

HELLO WORLD: --------------------<%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <link rel="stylesheet" href="struts.css" type="text/css"> <center><h1>HELLO WORLD</h1></center> <br/> <a href="./Welcome.do">Struts Welcome Page</a> </body> </html>
112

113

You might also like