Beruflich Dokumente
Kultur Dokumente
AIM:
Create a web page with the following using HTML
a. To embed a map in a web page
b. To fix the hot spots in that map
c. Show all the related information when the hot spots are clicked.
PROCEDURE:
Step 1:Create a html with map tag.
Step 2:Set the source attribute of the img tag to the location of the image and also set the usemap
attribute.
Step 3:Specify an area with name, shape and href set of the appropriate value.
Step 4:Repeat the step (iii) as many hotspots you want to put in the map.
Step 5:Create html file for each and every hotspots. The user will select the particular location it
shows information about it.
CODING:
hotspot.html
<html>
<head>
<title>hotspots</title>
</head>
<body bgcolor="gray">
<map name="india">
<area href="chennai.html" shape="circle" coords="217,400,10" title="click here"
target="nw">
<area href="bangaluru.html" shape="circle" coords="165,400,10" title="click here">
<area href="hyderabad.html" shape="circle" coords="190,330,10" title="click here">
<area href="mumbai.html" shape="circle" coords="90,300,10" title="click here">
<area href="delhi.html" shape="circle" coords="175,140,10" title="click here">
<area href="kolkata.html" shape="circle" coords="355,238,10" title="click here">
</map>
<h2>
<font color="red">
<i>INTERNATIONAL AIRPORTS IN INDIA</i>
</font>
</h2>
<img src="india.jpg" width="500" height="500" border="5" usemap="#india">
</body>
</html>
chennai.html
<html>
<head></head>
<body bgcolor="#C0C0C0">
<h1>
<center>
<font color="green"> CHENNAI INTERNATIONAL AIRPORT<br>CHENNAI </font>
<center>
</h1>
<hr size="5" color="yellow"></hr>
<img src="CIA.jpg" align="right" width="400" height="300">
<table border="5" cellpadding="5">
<tr><td>Name<td>Chennai International Airport
<tr><td>Location<td>Chennai,TamilNadu,India
<tr><td>Airport Type<td>Public
<tr><td>Owner<td>Airports Authority of India
<tr><td>Serves<td>Chennai Metropolitan Area
<tr><td>Opened<td> 1910
<tr><td>Website<td> Chennai Airport<br> (http://www.aai.aero/chennai/index.jsp)
<tr><td>Hub for<td>Air Costa,Air India,Blue Dart Aviation,Jet Airways,SpiceJet
<tr><td>Focus city for<td>GoAir,IndiGo
</table>
</body>
</html>
bangaluru.html
<html>
<head></head>
<body bgcolor="#CD853F">
<h1>
<center>
<font color="#D2B48C">KEMPEGOWDA INTERNATIONAL AIRPORT<br>
BENGALURU </font>
<center>
</h1>
<hr size="5" color="yellow"></hr>
<img src="KIA.jpg" align="right" width="400" height="300">
<table border="5" cellpadding="5">
<tr><td>Name<td>Kempegowda International Airport
<tr><td>Location<td>Devanahalli, Karnataka, India
<tr><td>Airport Type<td>Public
<tr><td>Owner<td>Bangalore International Airport Limited
<tr><td>Serves<td>Bengaluru
<tr><td>Opened<td>2008
<tr><td>Website<td>www.bengaluruairport.com
<tr><td>Hub for<td>AirAsia India,Air Pegasus,Jet Airways,Deccan Charters
<tr><td>Focus city for<td>Air India,GoAir,IndiGo,SpiceJet
</table>
</body>
</html>
hyderabad.html
<html>
<head></head>
<body bgcolor="#F08080">
<h1>
<center>
<font color="yellow">RAJIV GANDHI INTERNATIONAL AIRPORT<br>
HYDERABAD</font>
<center>
</h1>
<hr size="5" color="green"></hr>
<img src="RGIA.jpg" align="right" width="400" height="300">
<table border="5" cellpadding="5">
<tr><td>Name<td>Rajiv Gandhi International Airport
<tr><td>Location<td>Shamshabad, Hyderabad,Telangana, India
<tr><td>Airport Type<td>Public
<tr><td>Owner<td>Airports Authority of India
<tr><td>Serves<td>Hyderabad
<tr><td>Opened<td>2008
<tr><td>Website<td>www.hyderabad.aero
<tr><td>Hub for<td>Blue Dart Aviation,Lufthansa Cargo,Spicejet,TruJet
<tr><td>Focus city for<td>Air India,Jet Airways,indigo
</table>
</body>
</html>
mumbai.html
<html>
<head></head>
<body bgcolor="#FFB6C1">
<h1>
<center>
<font color="#9ACD32">CHHATRAPATHI SHIVAJI INTERNATIONAL AIRPORT<br>
MUMBAI</font>
<center>
</h1>
<hr size="5" color="yellow"></hr>
<img src="CSIA.jpg" align="right" width="400" height="300">
<table border="5" cellpadding="5">
<tr><td>Name<td>Chhatrapati Shivaji International Airport
<tr><td>Location<td>Mumbai, Maharashtra,India
<tr><td>Airport Type<td>Public
<tr><td>Owner<td>Airports Authority of India
<tr><td>Serves<td>Mumbai Metropolitan Region
<tr><td>Opened<td>1942
<tr><td>Website<td>www.csia.in
<tr><td>Hub for<td>Air India,GoAir,Jet Airways,JetKonnect
</table>
</body>
</html>
delhi.html
<html>
<head></head>
<body bgcolor="#FFF5EE">
<h1>
<center>
<font color="#4169E1">INDIRA GANDHI INTERNATIONAL AIRPORT<br>
DELHI</font>
<center>
</h1>
<hr size="5" color="yellow"></hr>
<img src="IGIA.jpg" align="right" width="400" height="300">
<table border="5" cellpadding="5">
<tr><td>Name<td>Indira Gandhi International Airport
<tr><td>Location<td>South West Delhi, Delhi,India
<tr><td>Airport Type<td>Public
<tr><td>Owner<td>Airports Authority of India
<tr><td>Serves<td>Delhi/NCR
<tr><td>Website<td>www.newdelhiairport.in
<tr><td>Hub for<td>Air India,AirAsia India,GoAir,IndiGo,Jet Airways,SpiceJet,Vistara
</table>
</body>
</html>
kolkata.html
<html>
<head></head>
<body bgcolor="#FFFFE0">
<h2>
<center>
<font color="#FF1493">NETAJI SUBHAS CHANDRA BOSE INTERNATIONAL
AIRPORT<br>KOLKATA</font>
<center>
</h2>
<hr size="5" color="yellow"></hr>
<img src="NSCBIA.jpg" align="right" width="400" height="300">
<table border="5" cellpadding="5">
<tr><td>Name<td>Netaji Subhas Chandra Bose International Airport
<tr><td>Location<td>Kolkata, North 24 parganas, India
<tr><td>Airport Type<td>Public
<tr><td>Owner<td>Airports Authority of India
<tr><td>Serves<td>Kolkata
<tr><td>Website<td>www.kolkatainternationalairport.com
<tr><td>Hub for<td>Air India,Air India Regional,Blue Dart Aviation,IndiGo,Jet
Airways,Spirit Air (India)
<tr><td>Focus City for<td>SpiceJet
</table>
</body>
</html>
OUTPUT:
RESULT:
Thus creating a webpage with image maps and hotspots was developed successfully.
Ex.No:2 CREATING A WEBPAGE WITH CASCADING STYLE SHEET
AIM:
Create a web page for our college with the following.
a. Cascading style sheets.
b. Embedded style sheets.
c. Inline style sheets.
PROCEDURE:
Step 1:Create a html file with portioning the web page into frames.
Step 2:In each frame, to call various html files.
Step 3:Create a html file for college banner with external style sheet.
Step 4: Create a html file to implement the college information with various CSS.
Step 5:Repeat the step (iv)for all the frames.
Step 6:Creating an external CSS file for applying styles which are to be used in that web page.
CODING:
frame1.html
<html>
<head>
<title>jcet</title>
</head>
<frameset cols="150,*,150" frameborder=0 >
<frame src="empty.html">
<frameset rows="135,*">
<frame src="frame2.html">
<frameset cols="230,*">
<frame src="frame3.html">
<frame src="frame4.html" scrolling="auto">
</frameset>
</frameset>
<frame src="empty.html">
</frameset>
</html>
frame2.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div id="id">
<img src="D:\html\logo1.jpg" align="left">
<img src="D:\html\logo2.jpg" align="right" height="99px" width="98px">
<center class="s1">JAYARAM<br>COLLEGE OF ENGINEERING AND TECHNOLOGY
</center>
<center class="s2">KARATTAMPATTI,PAGALAVADI-621014<br>LEARN TO
LEAD</center>
</div>
<marquee>
<font color="blue">Welcome to JCET!!!</font>
</marquee>
</body>
</html>
frame3.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<center class="s4">DEPARTMENTS</center>
<center class="s3">CSE</center>
<center class="s3">ECE</center>
<center class="s3">EEE</center>
<center class="s3">IT</center>
<center class="s3">MECH</center>
<center class="s3">CIVIL</center>
<center class="s3">S&H</center>
<center class="s3">MCA</center>
</body>
</html>
frame4.html
<html>
<head>
<style>
p:first-letter
{
font-size:20pt;
font-style:italic;
}
h2
{
color:purple;
}
</style>
</head>
<body>
<img src="JCET.jpg" width="700px" align="center" border="5" style="border-
color:brown;"> <br><br>
<h2>JCET</h2>
<ul>
<li>JCET providing quality education since 1994.</li>
<li>It is approved by AICTE,New Delhi.</li>
<li>Affiliated to Anna University,Chennai.</li>
<li>It has Microsoft Innovation Center(MIC).</li>
<li>It has well efficient placement cell.</li>
<li>Microsoft,Google and many companies are connected to our campus. </li>
<li>NCC,NSS and many social services are available.</li>
</ul><br>
<h2>Courses Offered</h2>
<table >
<tr><th>Departments<th>UG Courses(B.E.)<th>PG Courses(M.E.)<th>Research Center
<tr><td>CSE <td>Computer Science and Engineering
<td>Computer Science and Engineering<br>Software Engineering
<td>Yes
<tr><td>ECE <td>Electronics and Communication Engineering
<td>Communication System<br>Applied Electronics
<td>Yes
<tr><td>EEE <td>Electrical and Electronics Engineering
<td>Power Systems
<td>No
<tr><td>MECH<td>Mechanical Engineering
<td>Manufacturing Engineering
<td>Yes
<tr><td>EIE <td>Electronics and Instrumentation Engineering
<td> -
<td>No
<tr><td>CIVIL<td>Civil Engineering
<td> -
<td>No
<tr><td>IT <td>B.Tech(Information Technology)
<td> -
<td>No
<tr><td>MCA<td> -
<td>Master of Computer Application
<td>No
</table>
<h2>Our Vision</h2>
<p> Today's JCET students tomorrow's
Successful Professionals.</p>
<br />
<h2>Our Mission</h2>
<p> To prepare the students using science
and technology in the development of our nation with social, ethical and moral values.
</p><br/>
<h2>Quality Policy</h2>
<p> JCET aims to achieve and maintain
supremacy and reputation as a leading institution in the country imparting value
added quality professional education to students by providing them the required acumen to
become valuable professionals in the future .</p><br>
<h2>Our Motto</h2>
<p> Learn to Lead</p>
</body>
</html>
style.css
#id
{
height:100px;
width:1045px;
background:radial-gradient(#FAFAD2,#ADFF2F);
}
.s1
{
color:#9400d3;
font-size:25px;
text-shadow:2px 0px 5px red;
}
.s2
{
color:#9400d3;
font-size:20px;
text-shadow:2px 0px 5px red;
}
.s3
{
height:30px;
width:200px;
background:linear-gradient(white,orange);
border-style:solid;
border-color:gray;
}
.s4
{
height:20px;
width:200px;
background:linear-gradient(white,purple);
border-style:solid;
border-color:gray;
}
OUTPUT:
RESULT:
Thus the web page for our college with various CSS was developed successfully.
Ex.No:3 STORING AND RETRIEVING STUDENT INFORMATION FROM
XML FILE
AIM:
Create and save an XML document at the server, which contains 10 student information and
display them using JavaScript by user id.
PROCEDURE:
Step 1: Create an UserInfo.xml file containing the 10 user information
Step 2: Create InputFrom.html file and write JavaScript for accessing user information.
Step 3: Load InputFrom.html file on internet explorer or Mozilla Firefox
Step 4: Enter the user id on the text box.
Step 5: Click on submit button, Now invoke the display() function created in JavaScript.
Step 6: Display the user information on the browser.
Step 7: View the output.
Step 8: Stop the procedure.
CODING:
//UserInfo.xml
<?xml version="1.0" encoding="UTF-8"?>
<Student>
<Person-Details>
<id>101</id>
<name>Anand</name>
<city>pune</city>
<std>second</std>
<marks>70 percent</marks>
</Person-Details>
<Person-Details>
<id>102</id>
<name>RAVICHANDRAN</name>
<city>Salem</city>
<std>First</std>
<marks>80 percent</marks>
</Person-Details>
<Person-Details>
<id>103</id>
<name>Anand Kumar</name>
<city>Chennai</city>
<std>First</std>
<marks>85 percent</marks>
</Person-Details>
<Person-Details>
<id>104</id>
<name>Senthinathan M</name>
<city>OOTY</city>
<std>First</std>
<marks>85 percent</marks>
</Person-Details>
<Person-Details>
<id>105</id>
<name>K.Manikandan</name>
<city>Trichy</city>
<std>First</std>
<marks>90 percent</marks>
</Person-Details>
<Person-Details>
<id>106</id>
<name>Muthukumar</name>
<city>Chennai</city>
<std>First</std>
<marks>65 percent</marks>
</Person-Details>
<Person-Details>
<id>107</id>
<name>Kalaiselvan</name>
<city>Trichy</city>
<std>First</std>
<marks>68 percent</marks>
</Person-Details>
<Person-Details>
<id>108</id>
<name>Muthuselvan</name>
<city>Trichy</city>
<std>First</std>
<marks>88 percent</marks>
</Person-Details>
<Person-Details>
<id>109</id>
<name>Kalaivanan </name>
<city>Trichy</city>
<std>First</std>
<marks>78 percent</marks>
</Person-Details>
<Person-Details>
<id>110</id>
<name>Ramar</name>
<city>Trichy</city>
<std>First</std>
<marks>87 percent</marks>
</Person-Details>
</Student>
//InputFrom.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
function Display()
{
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.open("GET","UserInfo.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("Person-Details");
var key_id=document.getElementById("key").value;
for(i=0;i<x.length;i++)
{
if(key_id.match(x[i].getElementsByTagName("id")[0].childNodes[0].nodeValue))
j=i;
}
document.write("<h3>User details are...</h3>");
document.write("<table
border='3'><tr><th>ID</th><th>NAME</th><th>CITY</th><th>STANDARD</th><th>Marks</th
></tr>");
document.write("<tr><td>");
document.write(x[j].getElementsByTagName("id")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[j].getElementsByTagName("name")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[j].getElementsByTagName("city")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[j].getElementsByTagName("std")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[j].getElementsByTagName("marks")[0].childNodes[0].nodeValue);
document.write("</td><tr>");
document.write("<tr><tdtable>");
}
</script>
<form name='myform'>
Enter ID:<input type='text' id='key'/><br/>
<input type='button' value='submit' onclick='Display()'/>
</form>
</body>
</html>
OUTPUT:
RESULT:
Thus the given student information successfully created and saved XML Document and
Output was verified.
EX.NO: 4a TO IMPLEMENT HTTP REQUEST PROGRAM USING JAVA
AIM:
To implement HTTP request socket programming using java
PROCEDURE:
Step 1: Start the program
Step 2: create main class HTTP_Request
Step 3: In the main class create String object Request="WWW.google.com";
Step 4: create object for socket( ) class using Sclient_Socket=new Socket (Request, 80);
Step 5: create sub class Get_Web_Page( ) and get the input and output streams
Step 5.1: create object output for DataOutputStream( ) class
Step 5.2: Create object input for DataInputStream( ) class
Step 6: Write the HTTP request to the server
Step 7: Display the contents of web page as output.
Step 8: closing the streams and socket using Output.close(), input.close(),
client_Socket.close()
Step 9: compile and run the program.
CODING:
//HTTP_Request.java
import java.io.*;
import java.net.*;
public class HTTP_Request
{
public static void main(String arg[])
{
try
{
String Request="WWW.google.com";
Socket client_Socket=new Socket(Request,80);
System.out.println("The client is\n"+client_Socket);
Get_Web_Page(client_Socket);
}
catch(UnknownHostException e)
{
System.err.println("UnknownHostException:"+e.getMessage());
}
catch(IOException e)
{
System.err.println("IOException:"+e.getMessage());
}
}
public static void Get_Web_Page(Socket client_Socket)
{
try
{
DataOutputStream output=new
DataOutputStream(client_Socket.getOutputStream());
DataInputStream input=new
DataInputStream(client_Socket.getInputStream());
output.writeBytes("GET/HTTP/1.0\r\n\r\n");
String input_txt;
while((input_txt=input.readLine())!=null)
{
System.out.println(input_txt);
if(input_txt.indexOf("</HTML>")!=-1)
break;
}
output.close();
input.close();
client_Socket.close();
}
catch(Exception e)
{
System.err.println("Exception:"+e.getMessage());
}
}
}
OUTPUT:
RESULT:
Thus the java program to implement HTTP request socket was executed successfully.
Ex.No:4b FTP SOCKET PROGRAMMING
AIM:
To implement FTP socket programming using java
PROCEDURE :
Step 1: install FtpServer.java on one machine.
Step 2:.install FtpClient.java another machine.
Step 3.execute FtpServer.java.
Step 4.execute FtpClient.java.
Step 5: use GUI objects provided on the FtpClient.java to upload or download the particular
file.
CODING:
//FTPServer.java
import java.net.*;
import java.io.*;
import java.util.*;
public class FTPServer
{
public static void main(String args[]) throws Exception
{
ServerSocket soc=new ServerSocket(5217);
System.out.println("FTP Server Started on Port Number 5217");
while(true)
{
System.out.println("Waiting for Connection ...");
transferfile t=new transferfile(soc.accept());
}
}
}
class transferfile extends Thread
{
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;
transferfile(Socket soc)
{
try
{
ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
System.out.println("FTP Client Connected ...");
start();
}
catch(Exception ex)
{}
}
void SendFile() throws Exception
{
String filename=din.readUTF();
File f=new File(filename);
if(!f.exists())
{
dout.writeUTF("File Not Found");
return;
}
else
{
dout.writeUTF("READY");
FileInputStream fin=new FileInputStream(f);
int ch;
do
{
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
}
while(ch!=-1);
fin.close();
dout.writeUTF("File Receive Successfully");
}
}
void ReceiveFile() throws Exception
{
String filename=din.readUTF();
if(filename.compareTo("File not found")==0)
{
return;
}
File f=new File(filename);
String option;
if(f.exists())
{
dout.writeUTF("File Already Exists");
option=din.readUTF();
}
else
{
dout.writeUTF("SendFile");
option="Y";
}
if(option.compareTo("Y")==0)
{
FileOutputStream fout=new FileOutputStream(f);
int ch;
String temp;
do
{
temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
{
fout.write(ch);
}
}while(ch!=-1);
fout.close();
dout.writeUTF("File Send Successfully");
}
else
{
return;
}
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for Command ...");
String Command=din.readUTF();
if(Command.compareTo("GET")==0)
{
System.out.println("\tGET Command Received ...");
SendFile();
continue;
}
else if(Command.compareTo("SEND")==0)
{
System.out.println("\tSEND Command Receiced ...");
ReceiveFile();
continue;
}
else if(Command.compareTo("DISCONNECT")==0)
{
System.out.println("\tDisconnect Command Received ...");
System.exit(1);
}
}
catch(Exception ex)
{}
}
}
}
//FTPClient.java
import java.net.*;
import java.io.*;
import java.util.*;
class FTPClient
{
public static void main(String args[]) throws Exception
{
Socket soc=new Socket("127.0.0.1",5217);
transferfileClient t=new transferfileClient(soc);
t.displayMenu();
}
}
class transferfileClient
{
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;
BufferedReader br;
transferfileClient(Socket soc)
{
try
{
ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
br=new BufferedReader(new InputStreamReader(System.in));
}
catch(Exception ex)
{}
}
void SendFile() throws Exception
{
String filename;
System.out.print("Enter File Name :");
filename=br.readLine();
File f=new File(filename);
if(!f.exists())
{
System.out.println("File not Exists...");
dout.writeUTF("File not found");
return;
}
dout.writeUTF(filename);
String msgFromServer=din.readUTF();
if(msgFromServer.compareTo("File Already Exists")==0)
{
String Option;
System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
Option=br.readLine();
if(Option=="Y")
{
dout.writeUTF("Y");
}
else
{
dout.writeUTF("N");
return;
}
}
System.out.println("Sending File ...");
FileInputStream fin=new FileInputStream(f);
int ch;
do
{
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
}
while(ch!=-1);
fin.close();
System.out.println(din.readUTF());
}
void ReceiveFile() throws Exception
{
String fileName;
System.out.print("Enter File Name :");
fileName=br.readLine();
dout.writeUTF(fileName);
String msgFromServer=din.readUTF();
if(msgFromServer.compareTo("File Not Found")==0)
{
System.out.println("File not found on Server ...");
return;
}
else if(msgFromServer.compareTo("READY")==0)
{
System.out.println("Receiving File ...");
File f=new File(fileName);
if(f.exists())
{
String Option;
System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
Option=br.readLine();
if(Option=="N")
{
dout.flush();
return;
}
}
FileOutputStream fout=new FileOutputStream(f);
int ch;
String temp;
do
{
temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
{
fout.write(ch);
}
}
while(ch!=-1);
fout.close();
System.out.println(din.readUTF());
}
}
public void displayMenu() throws Exception
{
while(true)
{
System.out.println("[ MENU ]");
System.out.println("1. Send File");
System.out.println("2. Receive File");
System.out.println("3. Exit");
System.out.print("\nEnter Choice :");
int choice;
choice=Integer.parseInt(br.readLine());
if(choice==1)
{
dout.writeUTF("SEND");
SendFile();
}
else if(choice==2)
{
dout.writeUTF("GET");
ReceiveFile();
}
else
{
dout.writeUTF("DISCONNECT");
System.exit(1);
}
}
}
}
OUTPUT:
RESULT:
Thus the java program to implement the FTP socket programming was executed
successfully.
Ex.No:4c IMPLEMTATION OF SIMPLE MAIL TRANSFER PROTOCOL(SMTP)
AIM:
To implement simple mail transfer protocol using JavaAPI.
PROCEDURE:
Step 1:To configure the smtp mail server with username and password.
Step 2:To create a client socket which is connected to the SMTP server.
Step 3:To Create a buffered reader for line-oriented reading from the standard input device.
Step 4:Create a print writer for line-oriented writing to the socket.
Step 5:Display SMTP greeting from SMTP server program.
Step 6:Read and write a command string from or to the standard input device and SMTP server
respectively.
Step 7:Send the mail.
Step 8:Verify the output.
CODING:
//SMTPDemo.java
import java.io.*;
import java.net.*;
class SMTPDemo
{
public static void main (String [] args)
{
String SMTPServer = "smtp.mail.yahoo.com";
int SMTPPort = 25;
Socket client = null;
try
{
client = new Socket (SMTPServer, SMTPPort);
BufferedReader stdin;
stdin = new BufferedReader (new InputStreamReader (System.in));
InputStream is = client.getInputStream ();
BufferedReader sockin;
sockin = new BufferedReader (new InputStreamReader (is));
OutputStream os = client.getOutputStream ();
PrintWriter sockout;
sockout = new PrintWriter (os, true);
System.out.println ("S:" + sockin.readLine ());
while (true)
{
System.out.print ("C:");
String cmd = stdin.readLine ();
sockout.println (cmd);
String reply = sockin.readLine ();
System.out.println ("S:" + reply);
if (cmd.toLowerCase ().startsWith ("data") && reply.substring
(0, 3).equals ("354"))
{
do
{
cmd = stdin.readLine ();
if (cmd != null && cmd.length () > 1 &&
cmd.charAt (0) == '.')
cmd = ".";
sockout.println (cmd);
if (cmd.equals ("."))
break;
}
while (true);
reply = sockin.readLine ();
System.out.println ("S:" + reply);
continue;
}
if (cmd.toLowerCase ().startsWith ("quit"))
break;
}
}
catch (IOException e)
{
System.out.println (e.toString ());
}
finally
{
try
{
if (client != null)
client.close ();
}
catch (IOException e)
{}
}
}
}
OUTPUT:
>javac SMTPDemo.java
>java SMTPDemo
s:220 smtp.mail.yahoo.com ESMTP ready
c:helo smtp.mail.yahoo.com
s:250 smtp.mail.yahoo.com
c:mail from:<somewhere@yahoo.com>
s:250 2.1.0 <somewhere@yahoo.com>... Sender OK
c:rcpt to: <somewhere@yahoo.com>
s:250 2.1.5 <somewhere@yahoo.com>... Recipient OK
c:data
s:354 Enter mail,end with “.” on line by itself
Subject:Test Email
This is my smtp mail message
s:250 2.0.0 g22McAxW027265 accepted for delivery
c:quit
s:221 2.0.0 Bye
RESULT:
Thus the simple mail transfer protocol using JavaAPI was executed successfully.
Ex.No:5 CHAT APPLICATION
AIM:
To write a java program for creating simple chat application with datagram sockets
and datagram packets.
PROCEDURE:
Server:
Step 1: Create a datagram socket and creating the linked list of port numbers in order to
handle any number of clients.
Step 2: When a new request from client, then register the client.
Step 3: Connect all the clients.
Step 4: Receive the message from the client.
Step 5: Send the message to all the clients.
Step 6: When a client wanted to exit, close the particular client thread.
Step 7: Send the client exit message to remaining clients.
Client:
Step 1: Connecting to the server.
Step 2: Get the name of the client name.
Step 3: Start a new thread for receiving messages from the server.
Step 4: Send the messages to the server.
Step 5: Receive the other client messages from the server.
Step 6: When wanted to exit, send the message /exit to the server.
PROGRAM:
//Server.java
import java.io.*;
import java.util.*;
import java.net.*;
public class Server
{
static DatagramSocket server_Socket=null;
static LinkedList portNoList=null;
static HashMap portNos=null;
static public void Send_Message(String msg,int port_Number)throws IOException
{
byte sendbuffer[]=msg.getBytes();
server_Socket.send(new
DatagramPacket(sendbuffer,sendbuffer.length,InetAddress.getLocalHost(),port_Number));
}
static public void sendToAll(String msg,int Special_Port_Number)throws IOException
{
byte sendbuffer[]=msg.getBytes();
Iterator itr=portNoList.iterator();
while(itr.hasNext())
{
String strPortNo=(String)itr.next();
int portNo=Integer.parseInt(strPortNo);
if(Special_Port_Number!=portNo)
server_Socket.send(new
DatagramPacket(sendbuffer,sendbuffer.length,InetAddress.getLocalHost(),portNo));
}
}
public static void main(String[] args)
{
try
{
server_Socket=new DatagramSocket(1024);
portNoList=new LinkedList();
portNos=new HashMap();
System.out.println("The Chat Server Started....");
while(true)
{
byte buffer[]=new byte[1024];
DatagramPacket pkt=new DatagramPacket(buffer,buffer.length);
server_Socket.receive(pkt);
String clientMsg=new String(pkt.getData(),0,pkt.getLength());
if(clientMsg.indexOf("$##$")!=-1)
{
StringTokenizer st=new StringTokenizer(clientMsg,"$##$");
String clientName=st.nextToken();
String strPortNo=st.nextToken();
int clientPortNumber=Integer.parseInt(strPortNo);
portNoList.add(strPortNo);
portNos.put(clientName,strPortNo);
Send_Message("------------Welcome "+clientName+ "!!!--------",clientPortNumber);
sendToAll(clientName + " has joined the chat room!!!",clientPortNumber);
}
else if(clientMsg.indexOf("!$")!=-1)
{
StringTokenizer st=new StringTokenizer(clientMsg,"$!");
String clientName=st.nextToken();
String msg="<"+clientName +">" +st.nextToken();
String portNo=(String)portNos.get(clientName);
if(msg.indexOf("/exit")!=-1)
{
Send_Message("/exit",Integer.parseInt(portNo));
portNoList.remove(portNo);
portNos.remove(clientName);
msg="---------------"+clientName +"has left the chat room!!!"+"-----------------";
}
sendToAll(msg,Integer.parseInt(portNo));
}
}
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
//Client.java
import java.io.*;
import java.net.*;
public class Client implements Runnable
{
public static void main(String[] args)
{
try
{
client_Port=(int)(50000*Math.random());
while(true)
{
try
{
client_Socket=new DatagramSocket(client_Port);
}
catch(BindException e)
{
client_Port=(int)(50000*Math.random());
while(client_Port<1023||client_Port>65536)
{
client_Port=(int)(50000*Math.random());
}
continue;
}
break;
}
System.out.print("\nSession for client has started. You can terminate it by typing/exit");
System.out.print("\nEnter your name:");
BufferedReader buff=new BufferedReader(new InputStreamReader(System.in));
String client_name=buff.readLine();
String Start_Msg=client_name +"$##$" +client_Port;
byte sendBuffer[]=Start_Msg.getBytes();
client_Socket.connect(InetAddress.getLocalHost(),1024);
client_Socket.send(new DatagramPacket(sendBuffer,sendBuffer.length));
Thread th=new Thread(new Client());
th.start();
while(true)
{
String msg=buff.readLine();
msg="!$" + client_name +"!$" +msg;
sendBuffer=msg.getBytes();
client_Socket.send(new DatagramPacket(sendBuffer,sendBuffer.length));
if(msg.indexOf("/exit")!=-1)
break;
}
th.join();
buff.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
client_Socket.close();
}
}
static DatagramSocket client_Socket=null;
static int client_Port;
public void run()
{
byte ReceiveBuffer[]=new byte[1024];
while(true)
{
DatagramPacket pkt=new DatagramPacket(ReceiveBuffer,ReceiveBuffer.length);
try
{
client_Socket.receive(pkt);
}
catch(IOException e)
{
e.printStackTrace();
}
String msg=new String(pkt.getData(),0,pkt.getLength());
if(msg.indexOf("/exit")!=-1)
break;
System.out.println(msg +"\n");
}
}
}
OUTPUT:
RESULT:
Thus the java program for creating simple chat application with datagram sockets and
datagram packets was executed successfully.
Ex.No:6a INVOKING SERVLETS FROM HTML FORM
AIM:
CODING:
//Server.html
<html>
<head>
<title>INVOKING SERVLET FROM HTML</title>
</head>
<body>
<center> <b>ABC Company Pvt.Ltd </b>
<form name = "PostParam" method = "Post" action="http://localhost/new/servlet/serv">
<table border=2 color="Green" align="center">
<tr>
<td><b>Employee: </b> </td>
<td><input type = "textbox" name="ename" size="25" value=""></td>
</tr>
<tr>
<td><b>Phone: </b> </td>
<td><input type = "textbox" name="phoneno" size="25" value=""></td>
</tr>
<tr>
<td><b>Salary: </b></td>
<td><input type="textbox" name="salary" size="25" value=""></td>
</tr>
<tr>
<td><b>Id:</b></td>
<td><input type="textbox" name="id" size="25" value=""></td>
</tr>
</table><br>
<input type = "submit" value="Submit">
</form>
</center>
</body>
</html>
//serv.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class serv extends GenericServlet
{
public void service(ServletRequest request,ServletResponse response)throws
ServletException,IOException
{
PrintWriter out=response.getWriter();
String name=request.getParameter("ename");
String phno=request.getParameter("phoneno");
String sal=request.getParameter("salary");
String id=request.getParameter("id");
out.println("ABC Company details");
out.println("EmployeeName:"+name);
out.println("Phone No: "+phno);
out.println("id: "+id);
out.println("Salary: "+sal);
}
}
//web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
<servlet>
<servlet-name>serv</servlet-name>
<servlet-class>serv</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>serv</servlet-name>
<url-pattern>/servlet/serv</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
RESULT:
AIM:
To write a java applet program that invokes servlet.
PROCEDURE:
Step 1: Write a java applet program (AppletClient.java) with the following:
o Define the class AppletClient which extends the property of the class Applet
and implements the interface ActionListener.
o Define the objects for Button and add the button in the init() method of Applet
class.
o Make the button to listen the action by using the method addActionListener().
o Set the URL of the servlet program by using the object of the class URL.
o Define the object for AppletContext and display the response from the server
using the method showDocument().
Step 2: Create an HTML file (AppletClient.html) that contains the applet tag and pass the
class name to that applet code.
Step 3: Write a simple servlet program (MyServer.java) that contains any response message.
Step 4: Run the HTML file (AppletClient.html) that contains the corresponding applet code.
Step 5: Click the button on the applet window in order to invoke the servlet program.
CODING:
//AppletClient.html
<html>
<head>
<title>Invoking Servlets From Applet</title>
</head>
<body>
<applet code="AppletClient.class" width="300" height="100">
</applet>
</body>
</html>
//AppletClient.java
import java.io.*;
import java.net.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class AppletClient extends Applet implements ActionListener
{
public void init()
{
Button b1=new Button("Click Here to Access Date Information from Server");
b1.setBackground(Color.black);
b1.setForeground(Color.red);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
try
{
AppletContext ac=getAppletContext();
URL u=new URL("http://localhost/new/servlet/MyServer");
ac.showDocument(u);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
//MyServer.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class MyServer extends GenericServlet
{
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException
{
PrintWriter pw=res.getWriter();
Date d=new Date();
pw.println("<h3>Current Date and Time From Server:</h3>");
pw.println("<b>"+d+"</b>");
}
}
//web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
<servlet>
<servlet-name>MyServer</servlet-name>
<servlet-class>MyServer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServer</servlet-name>
<url-pattern>/servlet/MyServer</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
RESULT:
Thus the java applet program that invokes servlets was executed
successfully.
Ex.No :7 ONLINE EXAMINATION
AIM:
To develop a java program to create three – tier application using Servlet and
Database.
(i) For conducting on-line examination
(ii) For displaying student mark list. Assume that student information is available
in a database which has been stored in a database server.
PROCEDURE:
Step 1: Start All Programs – Microsoft office 2007 – Microsoft MS Access 2007
Step 8: Select ODBC Tools, Create user DSN Name (ExamStudent), Description: Exam,
Configure StudentDB.mdb file
Step 11: Type the given servlet source code saves into StudentServlet.java
Step 12:Start Tomcat server.
//web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
<servlet>
<servlet-name>StudentServlet</servlet-name>
<servlet-class>StudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/servlet/StudentServlet</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
RESULT:
Thus the java program to creating three-tier application using servlets and database
for conducting on-line examination was developed successfully.
Ex.No:8 LOCK SERVLET ITSELF TO A PARTICULAR SERVER IP ADDRESS AND
PORT NUMBER
AIM:
To develop a program to lock servlet itself to a particular server IP address and port number.
It requires an init parameter key that is appropriate for its servlet IP address and port before it unlocks
itself and handles a request
PROCEDURE:
Step 1: Create an HTML form which contains user Interface to allow the user to enter the key.
Step 2: Create a servlet program in which the host IP and port number is obtained. It is then converted
to numberic form. This numeric value can be set as a key value at which the server IP and port
number is locked. On providing this key the authorized access message will be displayed.
Step 3: Now compile the KeyIPLock.java source code to generate the class file using following
command.
Step 4: Now copy the generated class file (In May case it is KeyIPLock.class) to the classes folded
present inside the C:\jakarta-tomcat-5.0.27\webapps\sample\WEB-INF\classes folder.
Step 5: Now move back to WEB-INF floder in which the web.xml is present. Edit this file by
providing the servlet name and init parameter.
Step 6: Open the web browser and invoke the HTML document created in Step1. Type the key and
click submit button.
CODING:
//Keylock.html
<html>
<head>
<title>Input form</title>
</head>
<body>
<center>
<form name="form1" method=get action="http://localhost/new/servlet/KeyIPLock">
<table>
<tr>
<td><b>Enter Key</b></td>
<td><input type="text" name="user_key" size="25" value=""></td>
</tr>
</table>
<input type="submit" value="submit">
</form>
</center>
</body>
</html>
//KeyIPLock.java
import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
public class KeyIPLock extends GenericServlet
{
public void service(ServletRequest req, ServletResponse res)throws ServletException,
IOException
{
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
String userKey = req.getParameter("user_key");
String key=getInitParameter("key");
String host = req.getServerName();
String HostIP="";
long result=0;
int port=req.getServerPort();
if(key==null)
{
out.println("Invalid Access");
}
try
{
InetAddress IP=InetAddress.getLocalHost();
HostIP=IP.getHostAddress();
String[]ipAddressInArray=HostIP.split("\\.");
for(int i=3;i>=0;i--)
{
long ip=Long.parseLong(ipAddressInArray[3-i]);
result |= ip<<(i*8);
result=result+port;
}
}
catch(UnknownHostException e)
{
out.println(e);
}
long K=Long.parseLong(userKey);
out.println("Key Submitted by user="+K);
out.println("Key present as init parameter="+result);
if(K==result)
{
out.println("Authentic access:Request is handled!!!");
}
else
{
out.println("Error!!! Unauthorized access");
}
}
}
//web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
<servlet>
<init-param>
<param-name>key</param-name>
<param-value>3232235849</param-value>
</init-param>
<servlet-name>KeyIPLock</servlet-name>
<servlet-class>KeyIPLock</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>KeyIPLock</servlet-name>
<url-pattern>/servlet/KeyIPLock</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
RESULT:
Thus a program to lock servlet itself was developed successfully.
Ex.No:9a SESSION TRACKING USING HIDDEN FORM FIELDS
AIM:
To develop servlet program for session tracking using hidden form fields.
PROCEDURE:
Step 6: create SecondServlet.java program and Getting the value from the hidden field
Step 7: configure web-inf file
Step 8: open on internet explorer type the following http://localhost/sample/index.html
Step 9: type the name on text box and press go button
Step 10: stop the procedure
CODING:
//index.html
<html>
<head></head>
<form action="http://localhost/new/servlet/FirstServlet">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</html>
//FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.print("<form action= 'http://localhost/new/servlet/SecondServlet' >");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
//SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
//web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class> FirstServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> FirstServlet </servlet-name>
<url-pattern>/servlet/ FirstServlet </url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SecondServlet</servlet-name>
<servlet-class> SecondServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> SecondServlet </servlet-name>
<url-pattern>/servlet/ SecondServlet </url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
RESULT:
Thus the servlet program for session tracking using hidden fields was developed
successfully.
Ex.No:9b SESSION TRACKING FOR A HIT COUNT
AIM:
To develop a java servlet program session tracking for a hit count.
PROCEDURE:
CODING:
//HitCount.html
<html>
<body>
<h3>Hit Count Example with HttpSession</h3>
<form method="get" action="http://localhost/new/servlet/HitCount">
Click for Hit Count <input type="submit" value="GET HITS">
</form>
</body>
</html>
//HitCount.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class HitCount extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html") ;
PrintWriter out = res.getWriter( );
HttpSession session = req.getSession();
Integer hitNumber = (Integer) session.getAttribute("rama");
if(hitNumber == null)
{
hitNumber = new Integer(1);
}
else
{
hitNumber = new Integer(hitNumber.intValue()+1) ;
}
session.setAttribute("rama", hitNumber);
out.println("Your Session ID: " + session.getId());
out.println("<br>Session Creation Time: " + new
Date(session.getCreationTime()));
out.println("<br>Time of Last Access: " + new
Date(session.getLastAccessedTime()));
out.println("<br>Latest Hit Count: " + hitNumber);
}
}
//web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
<servlet>
<servlet-name>HitCount</servlet-name>
<servlet-class>HitCount</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HitCount</servlet-name>
<url-pattern>/servlet/HitCount</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
RESULT:
Thus the java servlet program for session tracking using hitcount was developed successfully.
Ex.No:10 STATIC WEB PAGES INTO DYNAMIC WEB PAGES USING SERVLETS AND
COOKIES
AIM :
Install TOMCATE Web server. Convert the static web pages 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 will have separate shopping cart.
PROCEDURE :
Step 1: We will create a HTML form for entering the user name, password, and cardID
details.
Step 2: Invoke the servlet program in which the validity of the user name, password and card
id is checked.
Step 3: Fo valid user then the welcome message will be displayed otherwise the “Invalid
user” message will be displayed.
Step 4: Create valid servlet code and set the cookies for current user name .
Step 5:compile the above servlet LoginServlet.java and copy the its class file in tomcats
folder at C:\jakarta-tomcat-5.0.27\webapps\sample\WEB-INF\classes
Step 6:Edit the web.xml in WEB-INF folder. We must store the user information such as user
name, password and Card ID in the web.xml using init-param.
Step 7: on successful login, the information from the cookie is checked and shopping cart
page for corresponding user can be displayed.
Step 8:Compile the above servlet LoginSuccess.java and copy its class fil in tomcat’s folder
at C:\jakarta-tomcat-5.0.27\webapps\sample\WEB-INF\classes
Step 9: Start tomcat web server. Open the web browser and display the login form created in
step1.
CODING:
//LoginForm.html
<html>
<head></head>
<body>
<div align="center">
<br><br>
<form name="PostParam" method="Post" action="http://localhost/new/servlet/LoginServlet">
Enter Username:
<input type="text" value="" name="User">
<br><br>
Enter Password:
<input type="password" value="" name="Password">
<br><br>
Enter Card ID:
<input type="text" value="" name="CardID">
<br><br>
<input type="submit" value="Login">
</form>
</div>
</body>
</html>
//LoginServlet.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String usr=req.getParameter("User");
String pwd=req .getParameter("Password");
String card=req.getParameter("CardID");
boolean flag=true;
String userID=getInitParameter("usernames");
String password=getInitParameter("passwords");
String cardids=getInitParameter("cardIDs");
if(userID.equals(usr))
{
Cookie MyCookie=new Cookie("CurrentUser",usr);
MyCookie.setMaxAge(60*60);
res.addCookie(MyCookie);
res.sendRedirect("http://localhost/new/servlet/LoginSuccess");
}
if(flag==true)
{
out.println("<h4>Invalid user, Please try again by cliking following
link</h4>");
out.println("<a href='http://localhost/new/LoginForm.html'>"
+"LoginForm.html");
}
}
}
//LoginSuccess.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginSuccess extends HttpServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse res)throws
ServletException,IOException
{
Cookie[] my_cookies=req.getCookies();
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<b>");
String userName=null;
if(my_cookies!=null)
{
for(Cookie cookie:my_cookies)
{
if(cookie.getName().equals("CurrentUser"))
userName=cookie.getValue();
}
}
out.print("<h3>Login success!!!Welcome</h3>");
out.print("<h2>This is a shopping cart for "+userName+"</h2>");
out.close();
}
}
//web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
<servlet>
<init-param>
<param-name>usernames</param-name>
<param-value>mani</param-value>
</init-param>
<init-param>
<param-name>passwords</param-name>
<param-value>River3</param-value>
</init-param>
<init-param>
<param-name>cardIDss</param-name>
<param-value>111</param-value>
</init-param>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>LoginSuccess</servlet-name>
<servlet-class>LoginSuccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/servlet/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginSuccess</servlet-name>
<url-pattern>/servlet/LoginSuccess</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
RESULT:
Thus the java program for the static web pages are converted into dynamic web pages was
developed successfully.
Ex.No:11 JSP STRUCTS FRAMEWORK
AIM:
We are creating the struts 2 example without IDE.
ALGORITHM:
Step 1:Create the directory structure
Step 2:Create input page (index.jsp)
Step 3:Provide the entry of Controller in (web.xml) file
Step 4:Create the action class (Product.java)
Step 5:Map the request with the action in (struts.xml) file and define the view components
CODING:
index.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
<s:form action="product">
<s:textfield name="id" label="Product Id"></s:textfield>
<s:textfield name="name" label="Product Name"></s:textfield>
<s:textfield name="price" label="Product Price"></s:textfield>
<s:submit value="save"></s:submit>
</s:form>
web.xml
?xml version="1.0" encoding="UTF-8"?>
<web-app>
<filter>
<filter-name>struts2</filter-name>
<filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Product.java
package com.javatpoint;
public class Product
{
private int id;
private String name;
private float price;
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public float getPrice()
{
return price;
}
public void setPrice(float price)
{
this.price = price;
}
public String execute()
{
return "success";
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="product" class="com.javatpoint.Product">
<result name="success">welcome.jsp</result>
</action>
</package>
</struts>
welcome.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
Product Id:<s:property value="id"/><br/>
Product Name:<s:property value="name"/><br/>
Product Price:<s:property value="price"/><br/>
OUTPUT:
RESULT:
Thus the JSP struct framework using java without IDE was implemented successfully.
Ex.No:12 AJAX BASED APPLICATION
AIM:
To develop and explore the following application in AJAX:
(i) Searching in real time with live searches
(ii) Getting instant login feedback
(iii) Getting the answer with auto complete
(iv) Dragging and dropping with Ajax
Step 4: Store the all the file in wamp server c:/wamp/www location.
Step 6: Open on internet explorer type following command on the address bar.
http://localhost/livesearch.html.
CODING:
//livesearch.html
<html>
<head>
<script>
function showResult(str)
{
if (str.length==0)
{
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<h1>JAYARAM COLLEGE OF ENGG AND TECH</h1>
<h2>AJAX BASED LIVE SEARCH EXERCISE</h2><hr>
<form>
<input type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>
</body>
</html>
//livesearch.php
<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("links.xml");
$x=$xmlDoc->getElementsByTagName('link');
$q=$_GET["q"];
if (strlen($q)>0)
{
$hint="";
for($i=0; $i<($x->length); $i++)
{
$y=$x->item($i)->getElementsByTagName('title');
$z=$x->item($i)->getElementsByTagName('url');
if ($y->item(0)->nodeType==1)
{
if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))
{
if ($hint=="")
{
$hint="<a href='" .
$z->item(0)->childNodes->item(0)->nodeValue
. "' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue
. "</a>";
}
else
{
$hint=$hint . "<br />
<a href='" . $z->item(0)->childNodes->item(0)-
>nodeValue . "' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue
. "</a>";
}
}
}
}
}
if ($hint=="")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
echo $response;
?>
//links.xml
<?xml version="1.0" encoding="UTF-8"?>
<pages>
<link>
<title>HTML a tag</title>
<url>http://www.w3schools.com/tags/tag_a.asp</url>
</link>
<link>
<title>HTML br tag</title>
<url>http://www.w3schools.com/tags/tag_br.asp</url>
</link>
<link>
<title>CSS background Property</title>
<url>http://www.w3schools.com/cssref/css3_pr_background.asp</url>
</link>
<link>
<title>CSS border Property</title>
<url>http://www.google.com</url>
</link>
<link>
<title>JavaScript Date Object</title>
<url>http://www.w3schools.com/jsref/jsref_obj_date.asp</url>
</link>
<link>
<title>JavaScript Array Object</title>
<url>http://www.w3schools.com/jsref/jsref_obj_array.asp</url>
</link>
</pages>
OUTPUT:
(ii)Getting instant login feedback:-
PROCEDURE:
Step 4: store the all the file in wamp server c:/wamp/www location.
Step 7: Type the required user name and password on the text box.
CODING:
//index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Modal Ajax Login Form</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript" src="javascript/jquery.simplemodal.js"></script>
<script type="text/javascript" src="javascript/init.js"></script>
<link type='text/css' href='style/stylesheet.css' rel='stylesheet' media='screen' />
<link type='text/css' href='style/basic.css' rel='stylesheet' media='screen' />
</head>
<body align="center">
<h1>COLLEGE MANAGEMENT SYSTEM</h1>
<h2>Click the login (existing user) link to launch the modal box</h2>
<br/>
<span style="font-size: 15px;">
<a id="login_link" href="#">LOGIN</a> |MEMBERS AREA</a>
</span>
<div id="login_form" style='display:none'>
<div id="status" align="left">
<center>
<h1><img src="images/key.png" align="absmiddle"> LOGIN</h1>
<div id="login_response"><!-- spanner --></div>
</center>
<form id="login" action="javascript:alert('success!');">
<input type="hidden" name="action" value="user_login">
<input type="hidden" name="module" value="login">
<label>E-Mail</label>
<input type="text" name="email"><br />
<label>Password</label>
<input type="password" name="password"><br />
<label> </label>
<input value="Login" name="Login" id="submit" class="big" type="submit" />
<div id="ajax_loading">
<img align="absmiddle" src="images/spinner.gif">
Processing...
</div>
</form>
</div>
</div>
</body>
</html>
//do-login.php
<?php
$config = array();
$config['email'] = 'demo@demo.com';
$config['password'] = 'demo123';
error_reporting(E_ALL ^ E_NOTICE);
session_id();
session_start();
header('Cache-control: private');
if($_POST['action'] == 'user_login')
{
$post_email = $_POST['email'];
$post_password = $_POST['password'];
if($post_email == $config['email'] && $post_password == $config['password'])
{
$_SESSION['username'] = $post_email;
if($_POST['remember_me'])
{
setcookie ("remember_me", true, (time() + TIME_DIFF) +
(3600 * 24 * 30));
setcookie ("info", $user_id.','.md5($password), (time() +
TIME_DIFF) + (3600 * 24 * 30));
}
echo 'OK';
}
else
{
$auth_error = '<div id="notification_error">The login info is not
correct.</div>';
echo $auth_error;
}
}
?>
//private.php
<?php
include 'config.php';
if(!isSet($_SESSION['username']))
{
header("Location: login.php");
exit;
}
?>
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>private page</title>
<meta name="author" content="bit repository">
<meta name="keywords" content="private">
<meta name="description" content="private page">
</head>
<body>
<center>welcome,
<?php echo $_session['username']; ?> | <a href="logout.php">logout</a><br /><br />
<h1>welcome to JAYARAM COLLEGE OF ENGG AND TECH</h1>
<h2>Karattampatti, Trichy.<h2>
</center>
</body>
</html>
//config.php
<?php
error_reporting(E_ALL ^ E_NOTICE);
session_start();
header('Cache-control: private');
header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
$config_username = 'demo';
$config_password = 'demo123';
$cookie_name = 'siteAuth';
$cookie_time = (3600 * 24 * 30);
if(!$_SESSION['username'])
{
include_once 'autologin.php';
}
?>
//autologin.php
<?php
if(isSet($cookie_name))
{
if(isSet($_COOKIE[$cookie_name]))
{
parse_str($_COOKIE[$cookie_name]);
if(($usr == $config_username) && ($hash == md5($config_password)))
{
$_SESSION['username'] = $config_username;
}
}
}
?>
//logout.php
<?php
include 'config.php';
if(isSet($_SESSION['username']))
{
unset($_SESSION['username']);
if(isSet($_COOKIE[$cookie_name]))
{
setcookie ($cookie_name, '', time() - $cookie_time);
}
header("Location: index.html");
exit;
}
?>
OUTPUT:
iii) Getting the answer with auto complete:-
ALGORITHM:
Step 1: Index.html:-This is the index file, which there are input box and the result to be
shown as image bellow.
Step 2: script.js:- This file holds the AJAX code used to send and receive ajax requests
to/from the server.
Step 5: Matched result is sent back to the JavaScript code, Ajax, and display that bellow text
box.
CODING:
//index.html
<html>
<head>
<title> Ajax Php Auto Suggest </title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script language="Javascript" src="js/jquery.js"></script>
<script language="Javascript" src="js/script.js"></script>
</head>
<body>
<center>
<div class="main">
<div class="">
<a href="http://www.scriptime.blogspot.in">scriptime</a>
</div>
<div id="holder">
Enter Keyword : <input type="text" id="keyword" tabindex="0">
<img src="images/loading.gif" id="loading">
</div>
<div id="ajax_response"></div>
</div>
</center>
</body>
</html>
//name_fetch.php
<?php
include("config.php");
$keyword = $_POST['data'];
$sql = "select name from ".$db_table." where ".$db_column." like '".$keyword."%'
limit 0,20";
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result))
{
echo '<ul class="list">';
while($row = mysql_fetch_array($result))
{
$str = strtolower($row['name']);
$start = strpos($str,$keyword);
$end = similar_text($str,$keyword);
$last = substr($str,$end,strlen($str));
$first = substr($str,$start,$end);
$final = '<span class="bold">'.$first.'</span>'.$last;
echo '<li><a href=\'javascript:void(0);\'>'.$final.'</a></li>';
}
echo "</ul>";
}
else
echo 0;
?>
//config.php
<?php
$host = "localhost";
$db_name = "midhun";
$db_user = "root";
$db_pass = "";
$db_table= "tb_username";
$db_column = "name";
$conn = mysql_connect($host,$db_user,$db_pass) or die(mysql_error());
mysql_select_db($db_name,$conn)or die(mysql_error());
?>
OUTPUT:
iv) Dragging and dropping with AJAX
PROCEDURE:
//foldertreeUpdateItem.php
<?
echo "OK";
exit;
if(isset($_GET['renameId']) && isset($_GET['newName']))
{
$res = mysql_query("select * from category where ID='".$_GET['renameId']."'");
if($inf = mysql_fetch_array($res))
{
mysql_query("update category set
categoryName='".$_GET['newName']."' where ID='".$inf["ID"]."'") or
die("NOT OK");
echo "OK";
}
echo "NOT OK";
exit;
}
if(isset($_GET['deleteIds']))
{
mysql_query("delete from category where ID IN(".$_GET['deleteIds']."')") or
die("NOT OK");
echo "OK";
}
echo "NOT OK";
?>
//saveNodes.php
<?
if(!isset($_GET['saveString']))die("no input");
echo "Message from saveNodes.php\n";
$items = explode(",",$_GET['saveString']);
for($no=0;$no<count($items);$no++)
{
$tokens = explode("-",$items[$no]);
echo "ID: ".$tokens[0]. " is sub of ".$tokens[1]."\n";
}?>
OUTPUT:
Before dragging:
After dragging:
RESULT:
Thus the given applications was developed in AJAX using WAMP Server
successfully.
Ex.No:13 WEB SERVICES
AIM:
To implement a program to run the web service.
ALGORITHM:
Step 3:In the server side web application, save the new web services program in java
extension.
Step 4:In the web service side name the pack as pack1.
Step 5:Clean and build the server side and then text the web service.
Step 6:Create the client side as web application client and save the program in jsp and html
extention.
Step 7:Clean and build the server side and then tick the web service client.
CODING:
//Webservice.java
package pack1;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import java.sql.*;
@WebService()
public class NewWebService
{
@WebMethod (operationName="get")
public String[] get(@WebParam(name="from")String from,@WebParam
(name="to")String to)
{
String hello[]=new String[6];
int i=0;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mysql" ,"root","root");
Statement s = con.createStatement();
s.executeUpdate("use testing");
s.execute("select * from details ");
ResultSet rs = s.getResultSet();
if (rs != null)
{
while ( rs.next() )
{
hello[i]= rs.getString("name");
i++;
hello[i]= rs.getString("date");
i++;
}
}
}
catch (Exception e)
{
System.out.println("Error: " + e);
}
return hello;
}
}
//Action.jsp
<%@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>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<% String from1=request.getParameter("From1");
String to1=request.getParameter("To1"); %>
<%-- start web service invocation --%><hr/>
<%
try
{
pack1.NewWebService service = new pack1.NewWebService();
java.lang.String from = from1;
java.lang.String to = to1;
String n[]=service.get(from, to);
java.util.ArrayList<java.lang.String> result =new
java.util.ArrayList<java.lang.String>();
for(int i=0;i<n.length;i++)
{
result.add(n[i]);}
out.println("Result = "+result);
}
catch (Exception ex)
{}
%>
<%-- end web service invocation --%><hr/>
</body>
</html>
//Index.jsp
<%@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>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form name="air" action="action.jsp" method="post">
From<input type="text" name="From1" id="From1"><br/>
To<input type="text" name="To1" id="To1"><br/>
<input type="submit" value="GetDtails">
</form>
</body>
</html>
OUTPUT:
RESULT:
Thus the webservices was implemented using netbeans IDE and java successfully.
CONTENT BEYOND SYLLABUS
EX. NO: 14 TIMING EVENT
AIM:
To create a time event using java script
PROCEDURE:
Step 1: Start the Program
Step 2: Create a time event using javascript
Step 3: Create a function with timer
Step 4: Get the Date function using Date( )
Step 5: Get the hour, minutes and second by using getHours( ), getMinutes( ) and
getSeconds( ) respectively.
Step 6: Check the hour, minute snd seconds
Step 7: Display the result.
CODING:
<!DOCTYPE html>
<html>
<head>
<script>
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout(function(){startTime()},500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
OUTPUT:
16:15:13
RESULT:
Thus the timing event using java script is created.
EX. NO: 15 GRADE SYSTEM
AIM:
To create student mark details using java script.
PROCEDURE:
Step 1: Start the Program
Step 2: Create a calculate function using script
Step 3: Check the grade with following if condition
(i). if the mark less than 35, print the grade as “D”
(ii). if the average >= 75, print the grade as “A+”
(iii). if the average >=60 and <75, print the grade as “A”
(iv). if the average >=50 and <65, print the grade as “B”
(v). if the average >=35 and <50, print the grade as “C”
(vi). if the average <35, print the grade as “Fail”
Step 4: Print result, grade, total and average
Step 5: Stop
CODING:
<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
<script type = "text/javascript">
function calc()
{
var m1,m2,m3,avg = 0,total = 0, result = "",grade = "";
m1 = parseInt(document.form1.wp.value);
m2 = parseInt(document.form1.sp.value);
m3 = parseInt(document.form1.cg.value);
total = m1+m2+m3;
avg = total/3;
if( m1 < 35 || m2 < 35 || m3 < 35)
{
result = "fail";
grade = "D";
}
else if(avg >= 75)
{
result = "Distinction";
grade = "A+";
}
else if(avg >= 60 && avg < 75)
{
result = "First class";
grade = "A";
}
else if(avg >= 50 && avg < 60)
{
result = "Second class";
grade = "B";
}
else if(avg >=35 && avg < 50)
{
result = "Pass class";
grade = "C";
}
else if (avg < 35)
{
result = "Fail";
Grade = "D";
}
document.form1.result.value = result;
document.form1.grade.value = grade;
document.form1.total.value = total;
document.form1.average.value = avg;
}
</script>
</head>
<body>
<form name = "form1">
<table border = "1">
<tr><td> Student Name</td>
<td><input type = "text" /></td></tr>
<tr><td colspan = "2" align = "center">Subject Marks</td></tr>
<tr>td>Web Programming</td>
<td><input type = "text" name = "wp" /></td></tr>
<tr><td>Computer Graphics</td>
<td><input type = "text" name = "cg" /></td></tr>
<tr><td>System Programming</td>
<td><input type = "text" name = "sp" /></td></tr>
<tr><td colspan = "2" align = "center">
<input type = "button" onclick = "calc()" value = "calculte" /></td></tr>
<tr><td>Total</td>
<td><input type = "text" name = "total"/></td></tr>
<tr><td>Average</td>
<td><input type = "text" name = "average" /></td></tr>
<tr><td>Result</td>
<td><input type = "text" name = "result" /></td></tr>
<tr><td>Grade</td>
<td><input type = "text" name = "grade"/></td></tr>
</table>
</form>
</body>
</html>
OUTPUT:
RESULT:
Thus the student mark details using java script is successfully created.