ex. no: 1 image mapping aim: algorithm: start the program

65
Ex. No: 1 IMAGE MAPPING AIM: To write a map and fix the hotspots to show the information of it in a web page. ALGORITHM: 1. Start the program. 2. Get the india map image and link it to the package. <img src="flag.jpg"> <img align="right" src = "India Map.gif" usemap="#india"> 3. Fix the hotspots in that image. 4. Map the reference of the hotspots in the image. <area shape="circle" coords="274,745,20" href="tn.html"> 5. Mention the derived link. 6. Click the link to get the desired image. 7. Stop the program. PROGRAM: Program Home.html <html> <head> <title>Home - States of India!!</title> </head> <body> <img align="right" src = "India Map.gif" usemap="#india"> <map name="india"> <area shape="circle" coords="274,745,20" href="tn.html"> <area shape="rect" coords="287,532,328,653" href="ap.html"> <area shape="circle" coords="325,718,3" href="py.html"> <area shape="rect" coords="278,696,313,725" href="tn.html"> </map> <h1><u>Republic of India</u></h1> <img src="flag.jpg"> <p>India is the Seventh Largest country in the world by geographical area, the second most populous country with over 1.2 billion people, and the most populous democracy in the world. India is a federal constitutional Republic with a parliamentry democracy consisting of 28 states and 7 Union Terrirories.</p> <h2>Features</h2> <ul> <li><b>Population</b> - 1,028,610,328 (2001 census). <li><b>Capital </b> - New Delhi <li><b>Largest City </b> - Mumbai <li><b>Currency </b> - Indian Rupee. <li><b>Time Format</b> - IST (UTC + 5:30) <li><b>National Sport </b> - Hockey <li><b>Current PM </b> - Manmohan Singh <li><b>Current President </b> - Prathiba Patil </ul> <h2><b>To view the details of states please click on the specified area in the map!!</b></h2> </body> </html> tn.html WWW.Vidyarthiplus.Com

Upload: others

Post on 18-Dec-2021

2 views

Category:

Documents


0 download

TRANSCRIPT

Ex. No: 1 IMAGE MAPPING

AIM: To write a map and fix the hotspots to show the information of it in a web page.

ALGORITHM: 1. Start the program.

2. Get the india map image and link it to the package. <img src="flag.jpg"> <img align="right" src = "India Map.gif" usemap="#india">

3. Fix the hotspots in that image.

4. Map the reference of the hotspots in the image. <area shape="circle" coords="274,745,20" href="tn.html">

5. Mention the derived link.

6. Click the link to get the desired image.

7. Stop the program.

PROGRAM: Program Home.html <html> <head> <title>Home - States of India!!</title> </head> <body> <img align="right" src = "India Map.gif" usemap="#india"> <map name="india"> <area shape="circle" coords="274,745,20" href="tn.html"> <area shape="rect" coords="287,532,328,653" href="ap.html"> <area shape="circle" coords="325,718,3" href="py.html"> <area shape="rect" coords="278,696,313,725" href="tn.html"> </map> <h1><u>Republic of India</u></h1> <img src="flag.jpg"> <p>India is the Seventh Largest country in the world by geographical area, the second most populous

country with over 1.2 billion people, and the most populous democracy in the world. India is a federal

constitutional Republic with a parliamentry democracy consisting of 28 states and 7 Union

Terrirories.</p> <h2>Features</h2> <ul> <li><b>Population</b> - 1,028,610,328 (2001 census). <li><b>Capital </b> - New Delhi <li><b>Largest City </b> - Mumbai <li><b>Currency </b> - Indian Rupee. <li><b>Time Format</b> - IST (UTC + 5:30) <li><b>National Sport </b> - Hockey <li><b>Current PM </b> - Manmohan Singh <li><b>Current President </b> - Prathiba Patil </ul> <h2><b>To view the details of states please click on the specified area in the map!!</b></h2> </body> </html> tn.html

WWW.Vidyarthiplus.Com

<html> <head> <title>Tamil Nadu - India</title> </head> <body>(Data as on 16.12.2010) <h1>Tamil Nadu</h1> <h3>is one of the 28 states of India. Its capital and largest city is Chennai. Tamil Nadu lies in the

southernmost part of the Indian Peninsula and is bordered by the States of Puducherry, Kerala,

Karnataka and Andhra Pradesh. It is bound by the Eastern Ghats in the north, the Nilgiri, the

Anamalai Hills, and Palakkad on the west, by the Bay of Bengal in the east, the Gulf of Mannar, the

Palk Strait in the south east, and by the Indian Ocean in the south.</h3> <h3> <ol> <li><i>Districts </i> - 32 <li><i>Capital City </i> - Chennai <li><i>Largest City </i> - Chennai <li><i>Governor </i> - Shri Konijeti Rosaiah. <li><i>Chief Minister</i> - Mrs. J. Jayalalitha <li><i>Popultation </i> - 66,396,000 <li><i>Dance </i> - Bharthanatyam <li><i>Festivals</i> - Pongal, Alanganallur Jallikattu etc., <li><i>Cuisine </i> - Dosai, Adai, Idly, Vadai, Pongal, Appam(Aappam), Paniyaram, Puttu(Pittu),

Uppumavu(Uppuma), Santhakai(Noodles), Idiyappam and Uthappam. <li><i>Tourist spots </i> <ul> <li>Mamallapuram (Shore Temple) <li>Brihadeeshwara Temple <li>Ooty <li>Kodaikanal. <li>Kanyakumari. (Thiruvalluvar statue etc.,) <li>Marina Beach(chennai) <li>Madurai Meenakshi Amman Temple. <li>Thanjavur. <li>Velankanni. <li>Rameswaram. </ul> </ol> </body> </html> Ap.html <html> <head> <title>Andhra Pradesh - India</title> </head> <body>(Data as on 16.12.2010) <h1>Andhra Pradesh</h1> <h3>A.P., is a state situated on the southeastern coast of India. It is India's fourth largest state by area

and fifth largest by population.</h3> <h3> <ul> <li><i>Districts </i> - 23 <li><i>Capital City </i> - Hyderabad <li><i>Largest City </i> - Hyderabad <li><i>Governor </i> - E. S. L. Narasimhan

WWW.Vidyarthiplus.Com

<li><i>Chief Minister</i> - Nallari Kiran Kumar Reddy <li><i>Popultation </i> - 76,210,007 <li><i>Tourist spots </i> - Tirumala Tirupati, Charminar, Golconda Fort, Chandragiri Fort,

Chowmahalla Palace, Falaknuma Palace etc., </ul> </body> </html> Py.html <html> <head> <title>Puducherry - India</title> </head> <body> (Data as on 16.12.2010) <h1>Puducherry</h1> <h3> <ol> <li><i>Districts </i> - 4 <li><i>Capital City </i> - Pondicherry <li><i>Largest City </i> - Pondicherry <li><i>Governor </i> - Iqbal Singh <li><i>Chief Minister</i> - Shri N. Rangasamy <li><i>Popultation </i> - 973,829 <li><i>Tourist spots </i> - Aurobindo Ashram, Auroville etc., </ol> </body> </html>

WWW.Vidyarthiplus.Com

RESULT:

WWW.Vidyarthiplus.Com

Thus the HTML program for image hotspots was executed.

Ex. No: 2 STYLE SHEET

AIM: To write a webpage that displays college information using various style sheet.

ALGORITHM: 1. Start the program.

2. Create a web page with framesets consisting two frames.

3. In the first frame include the links.

4. In the second frameset display the webpage of the link.

5. Create a external style sheets.

6. Create a inline and internal style and make a link to the external style sheet.

7. Stop the program.

PROGRAM:

FRAME.html: <!DOCTYPE html PUBLIC "-//w3c/DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> <html xmlns="http://www.w3.org/1991/xhtml"> <head> <title>APEC</title> </head> <frameset cols="20%,90%"> <frameset rows="4*,4*"> <frame src="adhi.html" id="upperLeftFrame"name="upperleftframe"></frame> <frame src="recent.html" id="lowerLeftFrame"name="lowerleftframe"></frame> </frameset> <frame src="website.html" id="rightFrame"name="rightleftframe"></frame> </frameset> </html>

WEBSITE.html: <html> <head> <title>hello</title> <link rel="stylesheet" type="text/css" href="D:\SRI\3ex\ss.css"/> </head> <body background="D:\SRI\3ex\2.jpg"> <h1 style="color:red" ><center> ADHIPARASAKTHI ENGINEERING

COLLEGE</center></pre></h1> <h2 style="color:yellow"><center> MELMARUVATHUR-603319 </center></h2> <p> <h5 style="color:yellow"><center>APPROVED BY AICTE Affliated to ANNA UNIVERSITY CHENNAI Accrediated by National Board of Accrediation(AICTE)</center> </h5><br><br><br><br><br><br><br><br> </p><h2 ><center> <a href="course.html"> COURSES</a><br> <a href="facil.html">FACILITIES</a><br>

WWW.Vidyarthiplus.Com

<a href="staff.html">STAFF DETAILS</a><br> <a href="timetable.html">TIMETABLE</a><br> <a href="percent.html">PERCENTAGE</a><br> </h2></center> </body> </html>

COURSE.html: <html> <head> <title>hello</title> </head> <body background="D:\SRI\3ex\28.jpg"> <h3 style="color:purple" > UG Courses offered , <ul> <li>B.E.,Computer Science and Engineering</li> <li>B.E.,Electrical and Electronics Engineering</li> <li>B.E.,Electronics and Communication Engineering</li> <li>B.E.,Civil Engineering</li> <li>B.E.,Mechanical Engineering</li> <li>B.Tech.,InformationTecnology</li> <li>B.Tech.,Chemical Engineering</li> </ul> PG courses offered, <ol> <li>M.E.,ComputerScience and Engineering</li> <li>M.E.,Applied Electronics</li> <li>M.E.,VLSI Design</li> <li>M.E.,Thermal Engineering</li> </ol> </h3> <a href="website.html">HOME</a> </body> </html>

FACIL.html: <html> <head> <title>hello</title> </head> <body background="D:\SRI\3ex\29.jpg"> <h2> <marquee bgcolor="white" loop="100" scrollamount="2" width="100%"><h2

style="color:purple">Facilities</h2></marquee> <ul> <center> <li>Digital library</li> <li>APECComputer Centre</li> <li>Transport facilities</li> <li>Wi-fi connection</li> <li>Sports&Games</li> <li>NCC</li> <li>NSS</li> <li>YRC</li>

WWW.Vidyarthiplus.Com

</center></ul> </h2> <ahref="website.html"><center>HOME</center></a> </body> </html>

STAFF.html: <html> <head> <title>hello</title> </head> <body background="D:\SRI\3ex\37.1.jpg" > <table border="4" style="color:red" cellpadding="20" cellspacing="10"> <h2> <tr><thcolspan="3">M.D-Mr.G.B.SenthilKumar</th></tr> <th style="color:purple">POST</th> <th style="color:purple">NAME</th> <th style="color:purple">CONTACT</th> <tr> <td>principal</td> <td>Dr.S.Jeyasri</td> <td>23142345</td> </tr> <tr> <td>Vice-principal</td> <td>Prof.R.Senthil</td> <td>423153462</td> </tr> <tr> <td>HOD/CSE</td> <td>Msr.A.Bhuvaneswari</td> <td>4574764745</td> </tr> <tr> <td>HOD/ECE</td> <td>Mr.S.Nagarajan</td> <td>3563463</td> </tr> <tr> <td>HOD/EEE</td> <td>Mr.S.Baskaran</td> <td>476574</td> </tr> <tr> <td>HOD/IT</td> <td>Mrs.Valli</td> <td>65867968</td> </tr> </h2> </table> <a href="website.html">HOME</a> </body> </html>

WWW.Vidyarthiplus.Com

TIMETABLE.html: <html> <head> <title>CSE</title> </head> <body bgcolor="green"> <font face="times new roman" size="+3" color="red"><h1> <br>PRE-FINAL YEAR CSE </font> <table border="1" align ="center"> <tr> <td bgcolor="green">DAY/HOUR</td> <td>1</td> <td>2</td> <td bgcolor="green">BREAK</td> <td>3</td> <td>4</td> <td bgcolor="green">LUNCH</td> <td>5</td> <td>6</td> <td>7</td> </tr> <tr> <td bgcolor="green">MONDAY</td> <td>AI</td> <td>LAB</td> <td bgcolor="brown"></td> <td colspan="2"><-LAB-></td> <td bgcolor="brown"></td> <td>ACA</td> <td>OOAD</td> <td>WT</td> </tr> <tr> <td bgcolor="green">TUESDAY</td> <td>AI</td> <td>WT</td> <td bgcolor="brown"></td> <td>NM</td> <td>WT</td> <td bgcolor="brown"></td> <td>OOAD</td> <td colspan="2"><-LAB-></td> </tr> <tr> <td bgcolor="green">WEDNESDAY</td> <td>NM</td> <td>PCD</td> <td bgcolor="brown"></td> <td>AI</td> <td>OOAD</td> <td bgcolor="brown"></td>

WWW.Vidyarthiplus.Com

<td colspan="3"><-LAB-></td> </tr> <tr> <td bgcolor="green">THURSDAY</td> <td>ACA</td> <td>LAB</td> <td bgcolor="brown"></td> <td colspan="2"><-LAB-></td> <td bgcolor="brown"></td> <td>WT</td> <td>OOAD</td> <td>AI</td> </tr> <tr> <td bgcolor="green">FRIDAY</td> <td>AI</td> <td>ACA</td> <td bgcolor="brown"></td> <td>WT</td> <td>PCD</td> <td bgcolor="brown"></td> <td>PCD</td> <td>OOAD</td> <td>NM</td> </tr></table> </body> <a href="website.html">HOME</a> </html>

PERCENT.html: <html> <head><title> hello</title></head> <body background="D:\SRI\3ex\28.jpg"> <h3 style="color:purple" ><center>PERCENTAGE</center><table width="100%" cellspacing="2"

cellpadding="2" border="5"> <tr> <th>S.NAME</th> <th>PERCENTAGE</th> </tr> <tr> <td align="center">Suganya</td> <td align="center">99%</td> </tr> <tr> <td align="center">Gohila</td> <td align="center">99%</td> </tr> <tr> <td align="center">Dhivya</td> <td align="center">91%</td> </tr> <tr> <td align="center">Saranya</td> <td align="center">90%</td> </tr>

WWW.Vidyarthiplus.Com

<tr> <td align="center">Ashadevi</td> <td align="center">85%</td> </tr> <tr> <td align="center">Hartha</td> <td align="center">85%</td> </tr> <tr> <td align="center">SRI</td> <td align="center">85%</td> </tr> </body> <a href="website.html">HOME</a> </html>

RECENT.html: <html> <head> <title>hello</title> </head> <body background="D:\SRI\3ex\28.jpg"> <h2 style="color:purple">RECENT INFORMATION</h2> <ul> <center> <li>CAMPUS INTERVIEW IS GOING ON IT WILL ON-CAMPUS AND OFF-

CAMPUS(company name TCS,HCL,WIPRO) </li> <li>SYMPOSIUM CAN BE CONDUCTED ON FEB16th </li> <li>WORKSHOP CAN BE CONDUCTED ON FEB 8th</li> <li>CULTURAL PROGRAMMING CONDUCED ON MEDICAL COLLEGE AT FEB 10th TO

FEB 13th</li> <li>MINI PROJECT </li> </center></ul> </h2> </body> </html>

ADHI.html: <html> <head> <title>hello</title> </head> <body background="D:\SRI\3ex\29.jpg"> <h2 style="color:purple">ADHIPARASAKTHI EDUCATION TRUST</h2> <ul> <center> <li>ADHIPARASAKTHI SCHOOL</li> <li>ADHIPARASAKTHI POLYTECHNIC</li> <li>ADHIPARASAKTHI ENGINEERING COLLEGE</li> <li>ADHIPARASAKTHI DENTAL COLLEGE</li> <li>ADHIPARASAKTHI MEDICAL COLLEGE</li> <li>ADHIPARASAKTHI MATRICULATION SCHOOL</li> <li>ADHIPARASAKTHI ARTS AND SCIENCE COLLEGE</li>

WWW.Vidyarthiplus.Com

<li>ADHIPARASAKTHI NURSING</li> <li>ADHIPARASAKTHI AGRICULTURE</li> <li>ADHIPARASAKTHI PHARMACY</li> <li>ADHIPARASAKTHI PHYSIOTHERAPY</li> </center></ul> </h2> </body> </html> SS.css: h1 { font-family:Blackadder ITC; } h5 { font-family:Arial; }

OUTPUT:

WWW.Vidyarthiplus.Com

RESULT:

Thus the program to create webpage usingCSS was executed.

WWW.Vidyarthiplus.Com

Ex. No: 3 INFORMATION RETRIEVAL FROM XML DOCUMENT

AIM: To write a program, which takes user id as input and displays the user details by

taking the user information from the XML document.

ALGORITHM

User Information

<?xml version="1.0"?> <userdata> <user1> <jntuno>561</jntuno> <name> chandu</name> <phno>9989891510</phno> <address>srikakulam</address> </user1> <user2> <jntuno>540</jntuno> <name> karteek</name> <phno>9701443556</phno> <address>srikakulam1</address> </user2> <user3> <jntuno>525</jntuno> <name> giri</name> <phno>9897895301</phno> <address>rajam</address> </user3> <user4> <jntuno>526</jntuno> <name>gopi</name> <phno>9999789540</phno> <address>parlakimidi</address> </user4> <user5> <jntuno>513</jntuno> <name> manoj</name> <phno>9989233331</phno> <address>hyderabad</address> </user5> <user6> <jntuno>514</jntuno> <name> balaji</name> <phno>9999789560</phno> <address>vizag</address> </user6> <user7> <jntuno>567</jntuno>

WWW.Vidyarthiplus.Com

<name>kiran </name> <phno>9999178957</phno> <address>vijayanagaram</address> </user7> <user8> <jntuno>518</jntuno> <name> sekhar</name> <phno>789580</phno> <address>bobili</address> </user8> <user9> <jntuno>517</jntuno> <name>chaitu</name> <phno>789590</phno> <address>sallur</address> </user9> <user10> <jntuno>595</jntuno> <name> sravan</name> <phno>9000789500</phno> <address>sklm</address> </user10> </userdata> Information Retrival

<html>

<!--DOM with javascript> <head> <title>user profile example</title> </head> <body> <script type="text/JavaScript"> var xmldoc=new ActiveXObject("Microsoft.XMLDOM"); xmldoc.load("data.xml"); var ele=xmldoc.documentElement; var y=window.prompt("eneter user num",1); var node=ele.childNodes.item(y-1); for(var i=0;i<node.childNodes.length;i++) { var child=node.childNodes.item(i); var val=child.firstChild; document.write("<h2>"+child.nodeName+":"+val.nodeValue); } </script> </body> </html>

WWW.Vidyarthiplus.Com

Output screens for XML document

WWW.Vidyarthiplus.Com

Result

Thus the program to get user id as input and displays the user details by taking the user

information from the XML document was executed.

WWW.Vidyarthiplus.Com

Ex. No: 4 SOCKET PROGRAMMING USING HTTP, FTP, SMTP, POP3

AIM: Write programs in Java using sockets to implement the following: i. HTTP request ii. FTP iii. SMTP iv. POP3 Algorthm Step 1: Import all necessary packages Step 2: Create an URL to the server specifying the html page Step 3: Get the host and port details from the URL Step 4: Request the file from the server using GET method of HTTP Request Step 5: Receive the response from the server Step 6: Display the response on the console Program import java.io.*;

import java.net.*; public class HTTP { public static void main(String[] args) { try { OutputStream to_file = new FileOutputStream("f:\\temp.txt"); URL url = new URL("http://www.wickedlysmart.com/HeadFirst/HeadFirstJava/HeadFirstJavaIndex.html"); String protocol = url.getProtocol(); String host = url.getHost(); int port = url.getPort(); if(port == -1) port = 80; String filename =url.getFile(); System.out.println(filename); Socket socket = new Socket(host, port); InputStream from_server = socket.getInputStream(); PrintWriter to_server = new PrintWriter(socket.getOutputStream()); to_server.print("Get" + filename +"\n\n"); to_server.flush(); byte[] buffer = new byte[4096]; int byte_read; while((byte_read = from_server.read(buffer)) != -1) { to_file.write(buffer,0,byte_read); System.out.print((char)byte_read); } socket.close(); to_file.close(); }

WWW.Vidyarthiplus.Com

catch(Exception e) { e.printStackTrace(); } }} Output

FTP

Aim To write a java program to demonstrate a simple FTP operation Algorithm FTP Client: Step 1: Establish a connection with the server at a particular port Step 2: Specify the name of the file to be read Step 3: Receive the contents of the file from the server FTP Server: Step 1: Accept the connection with the client Step 2: Listen to the port for the name of the file to be sent Step 3: Send the file character by character Step 4: Terminate the connection

FTP Client: import java.io.*; import java.net.*; public class FTPClient { public static void main(String[] args)

WWW.Vidyarthiplus.Com

{ try { Socket client = new Socket("127.0.0.1",10000); PrintWriter writer = new PrintWriter(client.getOutputStream()); writer.println("f:/demo/HTTP.java"); writer.flush(); InputStreamReader stream = new InputStreamReader(client.getInputStream()); BufferedReader reade r = new BufferedReader(stream); String str = null; while((str = reader.readLine()) != null) { System.out.println(str); } reader.close(); } catch(Exception e) { System.out.println("Connection is terminated by the Server"); } } } FTP Server : impor t java.io.*; import java.net.*; public class FTPServer { public static void main(String[] arg) { try { ServerSocket server = new ServerSocket(10000); Socket client; client= server.accept(); InputStreamReader stream = new InputStreamReader(client.getInputStream()); BufferedReader reader = new BufferedReader(stream); String filename = reader.readLine(); PrintWriter w riter = new PrintWriter(client.getOutputStream()); FileInputStream fileStream = new FileInputStream(new File(filename)); int ch; while((ch = fileStream.read()) != -1) { writer.write(ch); writer.flush(); } writer.close(); } catch(Exception e)

WWW.Vidyarthiplus.Com

{ e.printStackTrace(); } } }

WWW.Vidyarthiplus.Com

SMTP

Aim To write a java socket program to implement a simple SMTP client Algorithm Step 1: Import all necessary packages Step 2: Establish a connection with the server Step 3: Read the acceptance from the server Step 4: Say HELO to the server Step 5: Read the greeting from the server Step 6: Send sender address to server Step 7: Read the verification of sender from server Step 8: Send recipient address to server Step 9: Read the verification of recipient from server Step 10: Send DATA command to the server Step 11: Read the start indication from server Step 12: Send the message to the server Step 13: Read the acceptance of message from server Step 14: Close the connection Program import java.io.*; import java.net.Socket; public class SMTPClient { public static void main(String[] args) throws Exception { Strin g results = send("localhost", 25,"[email protected]","localhost/localdomain","Test Email","<b>You got mail!</b>"); System.out.println(results); } public static String send(String host,int port,String from,S tring to,String subject, String message) throws Exception { StringBuffer buffer = new StringBuffer(); try { Socket smtpSocket = new Socket(host, port); DataOutputStream output = new DataOutputStream(smtpSocket.getOutputSt ream()); BufferedReader input =new BufferedReader(new InputStreamReader( new DataInputStream(smtpSocket.getInputStream()))); try { read(input, buffer); send(output, "HELO localhost.localdomain\r\n", buffer);read(input, buffer); send(output, "MAIL FROM: " + from + "\r\n", buffer); read(input, buffer); send(output, "RCPT to: " + to + "\r\n", buffer); read(input, buffer);

WWW.Vidyarthiplus.Com

send(output, "DATA\r\n", buffer); read(input, buffer); send(output, "Subject: " + subject + "\r\n", buffer); send(output, message, buffer); send(output, "\r\n.\r\n", buffer); read(input, buffer); smtpSocket.close(); } catch (IOException e) { System.out.println("Cannot send email as an error occurred."); } } catch (Exception e) { System.out.println("Host unknown"); } return buffer.toString(); } private static void send(DataOutputStream output,String data,StringBuffer buffer) throws IOException { output.writeBytes(data); buffer.append(data); } private static void read(BufferedReader br, StringBuffer buffer) throws IOException { int c; while ((c = br.read()) != -1) { buffer.append((char) c); if (c == '\n') { break; } } } } Output

WWW.Vidyarthiplus.Com

POP3 Aim To write a java socket program to implement a POP3 Client Algorithm Step 1: Step 2: Step 3: Step 4: Step 5: Program import java.io.*; import java.net.*; import java.util.*; public class Pop3ClientDemo { protected int port = 110; protected String hostname = "localhost"; protected String username = ""; protected String password = ""; protected Socket socket; protected BufferedReader br; protected PrintWriter pw; // Cons tructs a new instance of the POP3 client public Pop3ClientDemo() throws Exception { try { // Get user input getInput(); // Get mail messages

WWW.Vidyarthiplus.Com

displayEmails(); } catch(Exception e) { System.err.println ("Error occured - details follow"); e.print StackTrace(); System.out.println(e.getMessage()); } } // Returns TRUE if POP response indicates success, FALSE if failure protected boolean responseIsOk() throws Exception { String line = br.readLine(); System.out.println("< "+line); return line.to UpperCase().startsWith("+OK"); } // Reads a line from the POP server, and displays it to screen protected String readLine(boolean debug) throws Exception { String line = br.readLine(); // Append a < character to indicate this is a server protocol r esponse if (debug) System.out.println("< "+line); else System.out.println(line); return line; } // Writes a line to the POP server, and displays it to the screen protected void writeMsg(String msg) throws Exception { pw.println( msg); pw.flush(); System.out.println("> "+msg); } // Close all writers, streams and sockets protected void closeConnection() throws Exception { pw.flush(); pw.close(); br.close(); socket.close(); } // Send the QUIT command, and close connection protected void sendQuit() throws Exception

WWW.Vidyarthiplus.Com

{ System.out.println("Sending QUIT"); writeMsg("QUIT"); readLine(true); System.out.println("Closing Connection"); closeConnection(); } // Display emails in a message protected void displayEmails() thro ws Exception { BufferedReader userinput = new BufferedReader( new InputStreamReader (System.in) ); System.out.println("Displaying mailbox with protocol commands and responses below"); System.out.println("------------------------------------------- -------------------"); // Open a connection to POP3 server System.out.println("Opening Socket"); socket = new Socket(this.hostname, this.port); br = new BufferedReader(new InputStreamReader(socket.getInputStream())); pw = new PrintWriter(new OutputStr eamWriter(socket.getOutputStream())); // If response from server is not okay if(! responseIsOk()) { socket.close(); throw new Exception("Invalid POP3 Server"); } // Login by sending USER and PASS commands System.out.println("Sending username"); writeMsg("USER "+this.username); if(!responseIsOk()) { sendQuit(); throw new Exception("Invalid username"); } System.out.println("Sending password"); writeMsg("PASS "+this.password); if(!responseIsOk()) { sendQuit(); throw new Exception("Invalid password"); } // Get mail count from server .... System.out.println("Checking mail"); writeMsg("STAT"); // ... and parse for number of messages String line = readLine(true); StringTokenizer tokens = n ew StringTokenizer(line," "); tokens.nextToken();

WWW.Vidyarthiplus.Com

int messages = Integer.parseInt(tokens.nextToken()); int maxsize = Integer.parseInt(tokens.nextToken()); if (messages == 0) { System.out.println ("There are no messages."); sendQuit(); return; } System.out.println ("There are " + messages + " messages."); System.out.println("Press enter to continue."); userinput.readLine(); for(int i = 1; i <= messages ; i++) { System.out.println("Retrieving message number "+i); writeMsg("RET R "+i); System.out.println(" -------------------- "); line = readLine(false); while(line != null && !line.equals(".")) { line = readLine(false); } System.out.println("--------------------"); System.out.println("Press enter to continue. To s top, type Q then enter"); String response = userinput.readLine(); if (response.toUpperCase().startsWith("Q")) break; } sendQuit(); } public static void main(String[] args) throws Exception { Pop3ClientDemo client = new Pop 3ClientDemo(); } // Read user input protected void getInput() throws Exception { String data=null; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter POP3 server hostname:"); data = br.readLine( ); if(data == null || data.equals("")) hostname="localhost"; else hostname=data; System.out.print("Please enter mailbox username:"); data = br.readLine();

WWW.Vidyarthiplus.Com

if(!(data == null || data.equals(""))) username=data; System.out.prin t("Please enter mailbox password:"); data = br.readLine(); if(!(data == null || data.equals(""))) password=data; } }

WWW.Vidyarthiplus.Com

Ex. No: 5 CREATING SIMPLE CHAT APPLICATION

AIM: To create simple chat application with datagram sockets and datagram packets.

ALGORITHM: 1. Start the UDP chat program

2. Import the package java.net.*;

3. Declare the datagramsocket,datagrampacket,BufferedReader,InetAddress.

4. Start the main function

5. In the main function using while loop it perform the loop until str.equals is STOP

There important while loop function are

clientsocket = new DatagramSocket(cport);

dp = new DatagramPacket(buf, buf.length);

dis = new BufferedReader(new

InputStreamReader(System.in)); 6. Terminate the UDP client program

PROGRAM: source code java programming UDP Chat server

import java.io.*; import java.net.*;

class UDPServer {

public static DatagramSocket serversocket; public static DatagramPacket dp; public static BufferedReader dis;

public static InetAddress ia; public static byte buf[] = new byte[1024];

public static int cport = 789,sport=790; public static void main(String[] a) throws IOException

{ serversocket = new DatagramSocket(sport); dp = new DatagramPacket(buf,buf.length);

dis = new BufferedReader (new InputStreamReader(System.in));

ia = InetAddress.getLocalHost(); System.out.println("Server is Running..."); while(true)

{ serversocket.receive(dp);

String str = new String(dp.getData(), 0,

dp.getLength());

if(str.equals("STOP")) { System.out.println("Terminated..."); break; }

System.out.println("Client: " + str); String str1 = new String(dis.readLine()); buf = str1.getBytes(); serversocket.send(new

WWW.Vidyarthiplus.Com

DatagramPacket(buf,str1.length(), ia, cport));

} } }

Source code java programming UDP Chat Client import java.io.*; import java.net.*; class UDPClient { public static DatagramSocket clientsocket;

public static DatagramPacket dp; public static BufferedReader dis;

public static InetAddress ia;

public static byte buf[] = new byte[1024]; public static int cport = 789, sport = 790; public static void main(String[] a) throws IOException {

clientsocket = new DatagramSocket(cport); dp = new DatagramPacket(buf, buf.length);

dis = new BufferedReader(new InputStreamReader(System.in)); ia = InetAddress.getLocalHost();

System.out.println("Client is Running... Type 'STOP' to Quit");

while(true)

{

String str = new String(dis.readLine()); buf = str.getBytes();

if(str.equals("STOP")) {

System.out.println("Terminated..."); clientsocket.send(new DatagramPacket(buf,str.length(), ia, sport)); break;

} clientsocket.send(new DatagramPacket(buf, str.length(), ia, sport));

clientsocket.receive(dp); String str2 = new String(dp.getData(), 0, dp.getLength()); System.out.println("Server: " + str2);

} } }

WWW.Vidyarthiplus.Com

Result:

Thus the to create simple chat application with datagram sockets and datagram packets.

WWW.Vidyarthiplus.Com

Ex. No: 6a INVOKING SERVLET FROM HTML FORMS

AIM: To write a java program for invoking servlet from HTML form.

ALGORITHM: 1. Start the program.

2. Create the form as ResponseDemoServlet with textfield,submit

Button and reset button. 3. The class ResponseDemoServlet implements the interface servlet.

4. Create the out object for the PrintWriter class and call the method

Getwriter as response.getwriter.

5. Display the server port, server name, protocol, character encoding, content length.

6. Create the class as enumeration with parameters as object.

7. Stop the program.

PROGRAM: Client Page: <HTML> <HEAD> <TITLE>Sending a request</TITLE> </HEAD> <BODY> <FORM ACTION= ResponseDemoServlet METHOD="POST"> <BR><BR> Author: <INPUT TYPE="TEXT" NAME="Author"> <INPUT TYPE="SUBMIT" NAME="Submit"> <INPUT TYPE="RESET" VALUE="Reset"> </FORM> </BODY> </HTML>

Server Page: importjavax.servlet.*; importjava.io.PrintWriter; importjava.io.IOException; importjava.util.Enumeration; public class ResponseDemoServlet implements Servlet { public void init(ServletConfigconfig) throws ServletException { } public void destroy() { } public void service(ServletRequest request, ServletResponse response) throwsServletException, IOException { PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("ServletResponse"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<B>Demonstrating the ServletResponse object</B>"); out.println("<BR>"); out.println("<BR>Server Port: " + request.getServerPort());

WWW.Vidyarthiplus.Com

out.println("<BR>Server Name: " + request.getServerName()); out.println("<BR>Protocol: " + request.getProtocol()); out.println("<BR>Character Encoding: " + request.getCharacterEncoding()); out.println("<BR>Content Type: " + request.getContentType()); out.println("<BR>Content Length: " + request.getContentLength()); out.println("<BR>Remote Address: " + request.getRemoteAddr()); out.println("<BR>Remote Host: " + request.getRemoteHost()); out.println("<BR>Scheme: " + request.getScheme()); Enumeration parameters = request.getParameterNames(); while (parameters.hasMoreElements()) { String parameterName = (String) parameters.nextElement(); out.println("<br>Parameter Name: " + parameterName); out.println("<br>Parameter Value: " + request.getParameter(parameterName)); } Enumeration attributes = request.getAttributeNames(); while (attributes.hasMoreElements()) { String attribute = (String) attributes.nextElement(); out.println("<BR>Attribute name: " + attribute); out.println("<BR>Attribute value: " + request.getAttribute(attribute)); } out.println("</BODY>"); out.println("</HTML>"); } public String getServletInfo() { return null; } publicServletConfiggetServletConfig() { return null; } }

OUTPUT:

WWW.Vidyarthiplus.Com

RESULT: Thus the program for invoking servlet from HTML form was executed and the output

was verified.

WWW.Vidyarthiplus.Com

Ex. No 6b INVOKING SERVLET FROM SERVLET FORM

AIM: To write a program for invoking servlet from HTML form. ALGORITHM:

1. Start the program.

2. Create the class as Loginservlet.

3. Enter the username and password in the form.

4. If username and password are correct then the welcome servlet page is opened.

5. Else the message “Loginfailed” will be displayed.

6. RequestDispatcher is used to transfer messages efficiently.

7. Stop the program.

PROGRAM:

LOGIN Page:

importjavax.servlet.*; importjavax.servlet.http.*; import java.io.*; importjava.util.*; public class LoginServlet extends HttpServlet { private void sendLoginForm(HttpServletResponse response, booleanwithErrorMessage) throwsServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>Login</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); if (withErrorMessage) out.println("Login failed. Please try again.<BR>"); out.println("<BR>"); out.println("<BR>Please enter your user name and password."); out.println("<BR><FORM METHOD=POST>"); out.println("<BR>User Name: <INPUT TYPE=TEXT NAME=userName>"); out.println("<BR>Password: <INPUT TYPE=PASSWORD NAME=password>"); out.println("<BR><INPUT TYPE=SUBMIT VALUE=Submit>"); out.println("</FORM>"); out.println("</BODY>"); out.println("</HTML>"); } public void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException { sendLoginForm(response, false); } public void doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException { String userName = request.getParameter("userName"); String password = request.getParameter("password"); if (userName!=null && password!=null && userName.equals("jamesb") &&password.equals("007")) {

WWW.Vidyarthiplus.Com

RequestDispatcherrd = request.getRequestDispatcher("WelcomeServlet"); rd.forward(request, response); } else { sendLoginForm(response, true); } } }

Response Page for Login: importjavax.servlet.*; importjavax.servlet.http.*; import java.io.*; public class WelcomeServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>Welcome</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<P>Welcome to the Bulbul's and Boni's Web Site.</P>"); out.println("</BODY>"); out.println("</HTML>"); } }

OUTPUT:

RESULT: Thus the program for login page and its response was done successfully and the output was

verified.

WWW.Vidyarthiplus.Com

Ex. No: 7 ONLINE EXAMINATION

AIM: To write the JSP program for online examination.

ALGORITHM: 1. Start the program.

2. With the scriplet tag, include information like document

Created on and author. 3. Set the content type using page content type=”txt\html”.

4. Include the doctype with transitional flavour.

5. Get the input as regno , name and store in the table.

6. Create the forms as exam and index.

7. Click the submit button, after completing all the

questions. If the answers are correct it will display as correct else incorrect.

8. Stop the program.

PROGRAM: Newjsp.jsp: <%--

Document : exam Created on : Feb 23, 2011, 7:19:15 PM Author : A

--%>

<%@page contentType="text/html" 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>Examination Panel</title> </head>

<body bgcolor="cyan"> <%@ page language="java" %> <%@ page import ="java.sql.*" %>

<%

String reg= request.getParameter("txt_reg"); String name = request.getParameter("txt_name"); out.println("<h2>Welcome" + name + "...Your Register number is " + reg +

"!!</h2><br><br><br>"); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String sTable = "exam"; String sSql = "SELECT * FROM " + sTable + ""; String database = "jdbc:odbc:sDBQ";

Connection cn = null; Statement st = null;

WWW.Vidyarthiplus.Com

ResultSet rs = null;

try { cn = DriverManager.getConnection( database ,"sa",""); st = cn.createStatement(); rs = st.executeQuery( sSql );

ResultSetMetaData rsmd = rs.getMetaData(); String s1,s2,s3,s4; int i=1; while(rs.next()) {

out.println("<form name='exam' action='newjsp2.jsp' method='post'><b>"+i+" . " +

rs.getString(1) + "</b><br><br>"); s1 = rs.getString(2); s2 = rs.getString(3);

s3 = rs.getString(4); s4 = rs.getString(5); out.println("<input type=radio name=opt"+i+" value="+s1+" CHECKED>"+ s1 +"

<br><br>"); out.println("<input type=radio name=opt"+i+" value="+s2+">" + s2 +"<br><br>");

out.println("<input type=radio name=opt"+i+" value="+s3+">" + s3 +"<br><br>"); out.println("<input type=radio name=opt"+i+" value="+s4+">" + s4 +"<br><br>");

i++; } out.println("<input name ='submit' value='Submit' type='submit'/>");

/*int n = rsmd.getColumnCount(); out.println( "<table border=1 cellspacing=3><tr>" );

for( int i=1; i<=n; i++ ) // Achtung: erste Spalte mit 1 statt 0

out.println( "<th>" + rsmd.getColumnName( i ) + "</th>" );

while( rs.next() ) {out.println( "</tr><tr>" );

for( int i=1; i<=n; i++ ) // Achtung: erste Spalte mit 1 statt 0 o ut.println( "<td nowrap>" + rs.getString( i ) + "</td>" ); }

out.println( "</tr></table>" );*/ }finally {

try { if( null != rs ) rs.close(); } catch( Exception ex ) {} try { if( null != st ) st.close(); } catch( Exception ex ) {} try { if( null != cn ) cn.close(); } catch( Exception ex ) {}

} %> </body>

</html>

Newjsp1.jsp <%--

Document : index Created on : Feb 9, 2011, 6:50:54 PM Author : A --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

WWW.Vidyarthiplus.Com

"http://www.w3.org/TR/html4/loose.dtd">

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Welcome to Online Examination</title>

</head> <body bgcolor="cyan"> <form name="index" action="newjsp.jsp" method="post"> <center><h1><span><font color="red">Welcome to Online

Examination</font></span></h1>

<br> <h2><u><span><font color="blue">Instructions to the

Candidates</font></span></u></h2>

<br><h3><ol><li>Fill the correct Registration number.</li> <br><li>Enter your name.</li> <br><li>Read the questions carefully.</li> <br><li>No negative marking.</li></ol></h3>

<br> <b>Enter your Register number</b>

<input type="text" name="txt_reg"> <b>Enter your Name</b> <input type="text" name="txt_name"><br><br>

<input name ="submit" value="Submit" type="submit"/> </center>

</form>

</body>

</html>

Newjsp2.jsp <%--

Document : report Created on : Feb 23, 2011, 9:09:37 PM

Author : A --%> <%@page import="com.sun.java.swing.plaf.windows.resources.windows_es"%>

<%@page contentType="text/html" 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>Exam Report</title> </head> <body bgcolor="cyan">

<center><h1>Your Report Card</h1></center> <%@ page language="java" %> <%@ page import ="java.sql.*" %> <%

WWW.Vidyarthiplus.Com

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String sTable = "exam"; String sSql = "SELECT * FROM " + sTable + ""; String database = "jdbc:odbc:sDBQ"; Connection cn = null;

Statement st = null; ResultSet rs = null; try { cn = DriverManager.getConnection( database ,"sa",""); st = cn.createStatement();

rs = st.executeQuery( sSql ); ResultSetMetaData rsmd = rs.getMetaData(); String s1,s2,s3,s4; int i=1;

int correct=0,incorrect=0,total=0; out.println("<h2><br><br><center><table border=1 cellpadding=2

cellspacing=2><tr><th>Question</th><th>Your Answer</th><th>Correct

Answer</th><th>Status</th></tr>"); while(rs.next())

{ total++;

s1 = rs.getString(1); s2 = request.getParameter("opt"+i); s3 = rs.getString(6);

if(s2.equals(s3)) { s4="Correct";

correct++;

}

else { s4="Incorrect";

incorrect++; } out.println("<tr><td>"+s1+"</td><td>"+s2+"</td><td>"+s3+"</td><td>"+s4+"</td></tr>");

i++; }

out.println("</table><br><br><table><b><tr><td>Correct

Answers</td><td>"+correct+"</td></tr>"); out.println("<tr><td>Incorrect Answers</td><td>"+incorrect+"</td></tr>");

out.println("<tr><td>Total

Questions</td><td>"+total+"</td></tr></table></b></center></h2>");

} finally {

try { if( null != rs ) rs.close(); } catch( Exception ex ) {} try { if( null != st ) st.close(); } catch( Exception ex ) {} try { if( null != cn ) cn.close(); } catch( Exception ex ) {} } %>

</body> </html>

WWW.Vidyarthiplus.Com

WWW.Vidyarthiplus.Com

RESULT: Thus the JSP program for online examination was executed by connecting the

SQLSERVER and result was verified.

WWW.Vidyarthiplus.Com

WWW.Vidyarthiplus.Com

Ex. No 8 Lock Servlet

Aim To write a program to lock servlet itself to a particular server IP address and port number.

import java.io.*; import java.net.*; import java.util.*; import javax.servlet.*; public class KeyedServerLock extends GenericServlet { // This servlet has no class or instance variables // associated with the locking, so as to simplify // synchronization issues. public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); // The piracy check shouldn't be done in init // because name/port are part of request. String key = getInitParameter("key"); String host = req.getServerName(); int port = req.getServerPort(); // Check if the init parameter "key" unlocks this server. if (! keyFitsServer(key, host, port)) { // Explain, condemn, threaten, etc. out.println("Pirated!"); } else { // Give 'em the goods out.println("Valid"); // etc... } } // This method contains the algorithm used to match a key with // a server host and port. This example implementation is extremely // weak and should not be used by commercial sites. // private boolean keyFitsServer(String key, String host, int port) { if (key == null) return false; long numericKey = 0; try { numericKey = Long.parseLong(key); } catch (NumberFormatException e) {

WWW.Vidyarthiplus.Com

return false; } // The key must be a 64-bit number equal to the logical not (~) // of the 32-bit IP address concatenated with the 32-bit port number. byte hostIP[]; try { hostIP = InetAddress.getByName(host).getAddress(); } catch (UnknownHostException e) { return false; } // Get the 32-bit IP address long servercode = 0; for (int i = 0; i < 4; i++) { servercode <<= 8; servercode |= hostIP[i]; } // Concatentate the 32-bit port number servercode <<= 32; servercode |= port; // Logical not long accesscode = ~numericKey; // The moment of truth: Does the key match? return (servercode == accesscode); } }

Output: Pirated

RESULT: Thus the program to lock servlet itself to a particular server IP address and port

number was executed

WWW.Vidyarthiplus.Com

Ex. No 9 Session Tracking

Aim To write a java program for Session tracking using hidden form fields and Session tracking for a hit count

Session tracking using hidden form fields

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ShoppingCartViewerHidden extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>"); out.println("<BODY>"); // Cart items are passed in as the item parameter. String[] items = req.getParameterValues("item"); // Print the current cart items. out.println("You currently have the following items in your cart:<BR>"); if (items == null) { out.println("<B>None</B>"); } else { out.println("<UL>"); for (int i = 0; i < items.length; i++) { out.println("<LI>" + items[i]); } out.println("</UL>"); } // Ask if the user wants to add more items or check out. // Include the current items as hidden fields so they'll be passed on. out.println("<FORM METHOD=GET>"); // submit to self if (items != null) { for (int i = 0; i < items.length; i++) { out.println("<INPUT TYPE=HIDDEN NAME=item VALUE=\"" + items[i] + "\">"); } } out.println("Would you like to<BR>"); out.println("<INPUT TYPE=SUBMIT VALUE=\" Add More Items \">"); out.println("<INPUT TYPE=SUBMIT VALUE=\" Check Out \">"); out.println("</FORM>"); out.println("</BODY></HTML>"); } }

WWW.Vidyarthiplus.Com

WWW.Vidyarthiplus.Com

You currently have the following items in your cart:

● Java Servlet Programming ● Java in a Nutshell ● Webmaster in a Nutshell

Would you like to

Session tracking for a hit count

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SessionTracker extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); // Get the current session object, create one if necessary HttpSession session = req.getSession(true); // Increment the hit count for this page. The value is saved // in this client's session under the name "tracker.count". Integer count = (Integer)session.getValue("tracker.count"); if (count == null) count = new Integer(1); else count = new Integer(count.intValue() + 1); session.putValue("tracker.count", count); out.println("<HTML><HEAD><TITLE>SessionTracker</TITLE></HEAD>"); out.println("<BODY><H1>Session Tracking Demo</H1>"); // Display the hit count for this page out.println("You've visited this page " + count + ((count.intValue() == 1) ? " time." : " times.")); out.println("<P>"); out.println("<H2>Here is your session data:</H2>"); String[] names = session.getValueNames(); for (int i = 0; i < names.length; i++) { out.println(names[i] + ": " + session.getValue(names[i]) + "<BR>"); } out.println("</BODY></HTML>"); } }

WWW.Vidyarthiplus.Com

Output

Session Tracking Demo You've visited this page 4 times.

Here is your session data:

tracker.count: 4

WWW.Vidyarthiplus.Com

Ex. No 10 Converting Static Pages into Dynamic Pages using Servlet

Aim

To Convert the static webpages of assignments 2 into dynamic webpages using servlets and cookies.

Algorithm

Step 1: First install the tomcat into the system.

Step 2: Then make a subdirectly(eg., tr) in the \tomcat\webapps.

Step 3: Under tr create WEB-INF directory and also place the html files in this tr directory only.

Step 4: Next under WEB-INF create two subclasses lib,classes and web.xml

Step 5: Next place all the class files under the classes and jar files(servlet-api.jar,classes12.jar

etc...) under lib subdirectories.

Step 6: After this start tomcat by giving the following command at the instll_dir>tomcat>bin

Catalina.bat run

Step 7: At the I.E(web browser) give the url as http;//localhost:8080//tr/htmlfile or servlet url

pattern Portno 8080 is assigned for the tomcat.

Web.xml <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>Servlet 2.4 Examples</display-name> <description> Servlet 2.4 Examples. </description> <servlet> <servlet-name>reg</servlet-name> <servlet-class>reg</servlet-class> </servlet> <servlet> <servlet-name>login</servlet-name> <servlet-class>login</servlet-class> </servlet> <servlet> <servlet-name>profile</servlet-name> <servlet-class>profile</servlet-class> </servlet> <servlet> <servlet-name>catalog</servlet-name> <servlet-class>catalog</servlet-class> <servlet-mapping> <servlet-name>order</servlet-name>

WWW.Vidyarthiplus.Com

<url-p</servlet> <servlet> <servlet-name>order</servlet-name> <servlet-class>order</servlet-class> </servlet> attern>order</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>catalog</servlet-name>

<url-pattern>catalog</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>profile</servlet-name> <url-pattern>profile</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>login</servlet-name> <url-pattern>login</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>reg</servlet-name> <url-pattern>reg</url-pattern> </servlet-mapping>

</web-app>

Main.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <body bgcolor="pink"> <br /><br /><br /><br /><br /> <h1 align="center"><U>ONLINE BOOK STORAGE</U></h1><br /><br /><br /> <h2 align="center"><pre> <b>Welcome to online book storage. Press LOGIN if you are having id otherwise press REGISTRATION </b></pre></h2> <br /><br /><pre> <div align="center"><a href="/tr/login.html">LOGIN</a> <a href="/tr/reg.html"> REGISTRATION</a></div></pre> </body>

</html>

WWW.Vidyarthiplus.Com

Login.html <html> <body bgcolor="pink"><br /><br /><br /> <form name="myform" method="post" action="/tr/login"> <div align="center"><pre> LOGIN ID :<input type="text" name="id" /><br /> PASSWORD :<input type="password" name="pwd" /></pre><br /><br /> </div> <br /><br /> <div align="center"> <input type="submit" value="ok" onclick="validate()" /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" /> </div> </form> </body>

</html>

Reg.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <body bgcolor="pink"><br /><br /> <form name="myform" method="post" action="/tr/reg"> <div align="center"><pre> NAME :<input type="text" name="name" /><br /> ADDRESS :<input type="text" name="addr" /><br /> CONTACT NUMBER :<input type="text" name="phno" /><br /> LOGINID :<input type="text" name="id" /><br /> PASSWORD :<input type="password" name="pwd" /></pre><br /><br /> </div> <br /><br /> <div align="center"> <input type="submit" value="ok" onclick="validate()" /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" /> </div> </form> </body>

</html>

Profile.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <body bgcolor="pink"><br /><br /><br /> <form name="myform" method="post" action="/tr/profile"> <div align="center"><pre> LOGIN ID :<input type="text" name="id" /><br /> </pre><br /><br /> </div> <br /><br /> <div align="center"> <input type="submit" value="ok" onclick="validate()" /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" />

</div></form></body></html>

WWW.Vidyarthiplus.Com

WWW.Vidyarthiplus.Com

Catalog.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <body bgcolor="pink"><br /><br /><br /> <form method="post" action="/tr/catalog"> <div align="center"><pre> BOOK TITLE :<input type="text" name="title" /><br /> </pre><br /><br /> </div> <br /><br /> <div align="center"> <input type="submit" value="ok" name="button1"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="reset" value="clear" name="button2"/> </div> </form>

</body></html>

Order.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <body bgcolor="pink"><br /><br /> <form method="post" action="/tr/reg"> <div align="center"><pre> NAME :<input type="text" name="name" /><br /> PASSWORD :<input type="password" name="pwd" /> TITLE :<input type="text" name="title" /><br /> NO. OF BOOKS :<input type="text" name="no" /><br /> DATE :<input type="text" name="date" /><br /> CREDIT CARD NUMBER:<input type="password" name="cno" /><br /></pre><br /><br /> </div> <br /><br /> <div align="center"> <input type="submit" value="ok" name="button1"/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" name="button2"/> </div> </form> </body>

</html>

WWW.Vidyarthiplus.Com

Login.java import java.sql.*; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class login extends HttpServlet { public void service(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException { PrintWriter pw=resp.getWriter(); pw.println("<html><body bgcolor=\"pink\"); String id=req.getParamenter("id"); String pwd=req.getParameter("pwd"); try { Driver d=new oracle.jdbc.driver.OracleDriver(); DriverManager.registerDriver(d); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger") ; Statement stmt=con.createStatement(); String sqlstmt="select id,password from login"; ResultSet rs=stmt.executeQuery(sqlstmt); int flag=0; while(rs.next()) { if(id.equal(rs.getString(1))&&pwd.equals(rs.getString(2))) { flag=1; } } if(flag==0) { pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>"); pw.println("<a href=\"/tr/login.html\">press LOGIN to RETRY</a>"); } else { pw.println("VALID LOGIN ID<br><br>"); pw.println("<h3><ul>"); pw.println("<li><ahref=\"profile.html\"><fontcolor=\"black\">USER PROFILE</font> </a></li><br><br>"); pw.println("<li><ahref=\"catalog.html\"><fontcolor=\"black\">BOOKS CATALOG</font></a></li><br><br>"); pw.println("<li><ahref=\"order.html\"><fontcolor=\"black\">ORDER CONFIRMATION</font> </a></li><br><br>"); } pw.println("</body></html>"); } catch(Exception e) { resp.sendError(500,e.toString()); }

}

WWW.Vidyarthiplus.Com

Reg.html import java.sql.*; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class login extends HttpServlet { public void service(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException { PrintWriter pw=resp.getWriter(); pw.println("<html><body bgcolor=\"pink\"); String name=req.getParamenter("name"); String addr=req.getParameter("addr"); String phno=req.getParameter("phno"); String id=req.getParamenter("id"); String pwd=req.getParameter("pwd"); int no=Integer.parseInt(phno); try { Driver d=new oracle.jdbc.driver.OracleDriver(); DriverManager.registerDriver(d); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger") ; Statement stmt=con.createStatement(); String sqlstmt="select id,password from login"; ResultSet rs=stmt.executeQuery(sqlstmt); int flag=0; while(rs.next()) { if(id.equal(rs.getString(1))&&pwd.equals(rs.getString(2))) { flag=1; } } if(flag==1) { pw.println("SORRY INVALID ID ALREADY EXITS TRY AGAIN WITH NEW ID<br><br>"); pw.println("<a href=\"/tr/reg.html\">press REGISTER to RETRY</a>"); } else { Statement stmt1=con.createStatement(); stmt1.executeUpdate("insertintologin values("+names","+addr+","+no+","+id+","+pwd+")"); pw.println("YOUR DETAILS ARE ENTERED<br><br>"); pw.println("<a href=\"/tr/login.html\">press LOGIN to login</a>"); } pw.println("</body></html>"); } catch(Exception e) { resp.sendError(500,e.toString());

} }}

WWW.Vidyarthiplus.Com

WWW.Vidyarthiplus.Com

Catlog.java import java.sql.*; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class login extends HttpServlet { public void service(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException { PrintWriter pw=resp.getWriter(); pw.println("<html><body bgcolor=\"pink\"); String title=req.getParameter("title"); try { Driver d=new oracle.jdbc.driver.OracleDriver(); DriverManager.registerDriver(d); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger") ; Statement stmt=con.createStatement(); String sqlstmt="select id,password from login"; ResultSet rs=stmt.executeQuery(sqlstmt); int flag=0; while(rs.next()) { pw.println(",div align=\"center\">"); pw.println("TITLE :"+rs.getString(1)+"<br>"); pw.println("AUTHOR :"+rs.getString(2)+"<br>"); pw.println("VERSION :"+rs.getString(3)+"<br>"); pw.println("PUBLISHER :"+rs.getString(4)+"<br>"); pw.println("COST :"+rs.getString(5)+"<br>"); pw.println("</div"); flag=1; } if(flag==0) { pw.println("SORRY INVALID TITLE TRY AGAIN <br><br>"); pw.println("<a href=\"/tr/catalog.html\">press HERE to RETRY</a>"); } pw.println("</body></html>"); } catch(Exception e) { resp.sendError(500,e.toString()); } } }

WWW.Vidyarthiplus.Com

Profile.java import java.sql.*; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class login extends HttpServlet { public void service(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException { PrintWriter pw=resp.getWriter(); pw.println("<html><body bgcolor=\"pink\"); String id=req.getParamenter("id"); try { Driver d=new oracle.jdbc.driver.OracleDriver(); DriverManager.registerDriver(d); Connection con=DriverManager.getConnection("jdbc:oracle:thin: @localhost:1521:orcl","scott","tiger"); Statement stmt=con.createStatement(); String sqlstmt="select * from login where id="+id+""; ResultSet rs=stmt.executeQuery(sqlstmt); int flag=0; pw.println("<br><br><br>"); while(rs.next()) { pw.println("<div align=\"center\">"); pw.println("NAME :"+rs.getString(1)+"<br>"); pw.println("ADDRESS :"+rs.getString(2)+"<br>"); pw.println("PHONE NO :"+rs.getString(3)+"<br>"); pw.println("</div>"); flag=1; } if(flag==0) { pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>"); pw.println("<a href=\"/tr/profile.html\">press HERE to RETRY</a>"); } pw.println("</body></html>"); } catch(Exception e) { resp.sendError(500,e.toString()); } }

}

WWW.Vidyarthiplus.Com

Order.java import java.sql.*; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class login extends HttpServlet { public void service(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException { PrintWriter pw=resp.getWriter(); pw.println("<html><body bgcolor=\"pink\"); String id=req.getParamenter("id"); String pwd=req.getParameter("pwd"); String title=req.getParameter("title"); String count1=req.getParameter("no"); String date=req.getParameter("date"); String cno=req.getParameter("cno"); int count=Integer.parseInt(count1); try { Driver d=new oracle.jdbc.driver.OracleDriver(); DriverManager.registerDriver(d); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger") ; Statement stmt=con.createStatement(); String sqlstmt="select id,password from login"; ResultSet rs=stmt.executeQuery(sqlstmt); int flag=0,amount,x; while(rs.next()) { if(id.equals(rs.getString(1))&&pwd.equals(rs.getString(2))) { flag=1; } } if(flag==0) { pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>"); pw.println("<a href=\\"/tr/order.html\\">press HERE to RETRY</a>"); } else { Statement stmt2=con.createStatement(); String s="select cost from book where title="+title+""; ResultSet rs1=stmt2.executeQuery(s); int flag1=0; while(rs1.next()) { flag1=1;

x=Integer.parseInt(rs1.getString(1)); amount=count*x;

WWW.Vidyarthiplus.Com

pw.println("AMOUNT :"+amount+"<br><br><br><br>"); Statement stmt1=con.createStatement(); stmt1.executeUpdate("insertintodetails values('"+id+",'"+title+"'+amount+'","'+cno+'")"'); pw.println("YOUR ORDER has taken<br>"); } if(flag1==0) { pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>"); pw.println("<a href=\\"/tr/order.html\\">press HERE to RETRY</a>"); } } pw.println("</body></html>"); con.close(); } catch(Exception e) { resp.sendError(500,e.toString()); }

} Output

WWW.Vidyarthiplus.Com

WWW.Vidyarthiplus.Com

WWW.Vidyarthiplus.Com

Ex. No 12 AJAX.

AIM: To write a java script program for a AJAX.

ALGORITHM: 1. Start the program.

2. A scripting language that is commonly hosted in a browser to add Interactivity to HTML PAGES. 3. Defines the structure of a webpage as a set of programmable objects that can be accessed through javascript. 4. Allows a client-side script to perform and httprequest.

5. AJAX applications use xmlhttprequest object to perform asynchronous requests to the server as opposed to performing a full page refresh.

6. Display the result.

7. Stop the program.

PROGRAM: <html> <head> <script type="text/javascript"> functionloadXMLDoc() { if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 &&xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","new.txt",true); xmlhttp.send(); } </script> <title>ajax program</title> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="loadXMLDoc()">Change Content</button> </body> </html>

New.txt:

WELCOME!!!

WWW.Vidyarthiplus.Com

OUTPUT:

RESULT:

Thus the program for AJAX was executed and the output was verified.

WWW.Vidyarthiplus.Com

WWW.Vidyarthiplus.Com