Anda di halaman 1dari 84

VIDYAA VIKAS COLLEGE OF ENGINEERING & TECHNOLOGY

THIRUCHENGODE – 637214

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

RECORD NOTE BOOK

NAME :…………………………………………….............

REG NO :…...………………………………………………...

SUBJECT CODE :….……………………………………….

SUBJECT TITLE :…………………………………………..


VIDYAA VIKAS COLLEGE OF ENGINEERING &TECHNOLOGY

THIRUCHENGODE – 637214

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Certified that this is the bonafide record of work done by


Mr./Ms…..……………………………………………………….with register
Number………………………………..of III Year / V Semester during the
Academic year 2017-2018 for INTERNET PROGRAMMING LABORATORY-
CS6501.

Staff-in-charge Head of the Department

Submitted for the university practical examination held on……………….

Internal Examiner External Examiner


INDEX

EX.NO DATE NAME OF THE EXPERIMENT PAGE NO MARKS SIGNATURE


CREATING A WEBPAGE USING IMAGE
1
MAP
CREATION OF WEBPAGE USING
2.1 EXTERNAL CASCADING STYLE SHEET
CREATION OF WEBPAGE USING
2.2
EMBEDDED CASCADING STYLE SHEET
CREATION OF WEBPAGE USING
2.3
INLINE CASCADING STYLE SHEET
USER INFORMATION AND
3 INFORMATION RETRIEVAL FROM
XML
IMPLEMENTING HTTP REQUEST
4.1
USING SOCKETS
4.2 IMPLEMENTING FTP USING SOCKETS
IMPLEMENTING SMTP USING
4.3
SOCKETS
IMPLEMENTING POP3 USING
4.4
SOCKETS
CREATING SIMPLE CHAT
APPLICATION WITH DATAGRAM
5
SOCKETS AND DATAGRAM PACKETS
INVOKING SERVLET FROM HTML
6.1
FORMS
6.2 INVOKING SERVLET FROM APPLET
THREE TIER ARCHITECTURE USING
7
SERVLETS
LOCK SERVLET ITSELF TO A
8 PARTICULAR SERVER IP ADDRESS
AND PORT NUMBER
SESSION TRACKING USING HIDDEN
9.1
FORM FIELDS
9.2 SESSION TRACKING FOR A HIT COUNT

9.3 SHOPPING CART

TOTAL

AVERAGE
EX.NO: 1 WEBPAGE CONCEPTS DATE:
CREATING A WEBPAGE USING IMAGE MAP

AIM :

ALGORITHM:
PROGRAM
HOME.HTML
<html>
<head>
<title>Home - States of India!!!</title>
</head>
<body bgcolor="gold">
<h1><u><center>Republic of India</center></u></h1>
<p>
India is the Seventh Lagest country in the world by geographical area, the second most
populous country with over 1.2 billion people, and the populus democracy in the world. India is a
federal constitutional republic with a parliamentry democracy consisting of 28 states and 7 union
Terriories.
</p>
<center>
<img align="center" size="100" src="z:\ india.jpg" usemap="#india"/>
<map name="india"
<area shape="circle" coords="104,266,20" href="ANDHRAPRADESH.html">
<area shape="circle" coords="87,321,10" href="KERALA.html">
<area shape="circle" coords="76,270,20" href=" KARNATAKA.html">
<area shape="circle" coords="103,306,20" href="TAMILNADU.html">
</map>
</center>
<h2> Features</h2>
<ul>
<li><b>Population</b> - 1,028,783,343(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>Nation Sport</b> - Hockey
<li><b>Current PM</b> - Manmohan Singh
<li><b>Current President</b> - Pranab mukargi
</li>
</ul>
<h2>
<b>To view details of states please click on the specified area in the map !!!</b>
</h2>
</body>
</html>
ANDHRAPRADESH.HTML
<html>
<head><title>Andhra Pradesh - India</title></head>
<body bgcolor="tan">
<h1><center>Andhra Pradesh</center></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>Districts<i> - 23</i>
<li>Capital City<i> - Hyderabad</i>
<li>Largest City<i> - Hyderabad</i>
<li>Governor<i> - E. S. L. Narasimhan</i>
<li>Chief Minister<i> - N. Kiran Kumar Reddy</i>
<li>Population<i> - 78,323,330</i>
<li>Tourist spots<i> - Tirumala Tirupati, Charminar, Golconda Fort, Chandragiri, Chowmahalla
Place, Falaknuma Palace etc.,</i>
</ul>
<a href="Home.html">back</a>
</body>
</html>
KARNATAKA.HTML
<html>
<head><title>Karnataka - India</title></head>
<body bgcolor="wheat">
<h1><center>Karnataka</center></h1>
<h3>
<ul>
<li>Districts<i> - 30</i>
<li>Capital City<i> - Bangalore</i>
<li>Largest City<i> - Bangalore</i>
<li>Governor<i>- Hansraj Bhardwaj</i>
<li>Chief Minister<i> - D. V. Sadananda Gowda</i>
<li>Population<i> - 61,130,704</i>
<li>Tourist spots<i> - Gol Gumbaz, Mysore Palace, Keshava Temple etc.,</i>
</ul>
</h3>
<a href="Home.html">back</a>
</body>
</html>
KERALA.HTML
<html>
<head><title>Kerala - India</title></head>
<body bgcolor="indianred">
<h1><center>Kerala</center></h1>
<h3>
<ul>
<li>Districts<i> - 14</i>
<li>Capital City<i> - Thiruvanandapuram</i>
<li>Largest City<i> - Thiruvanandapuram</i>
<li>Governor<i> - Hansraj Bhardwaj</i>
<li>Chief Minister<i> -Oommen Chandy </i>
<li>Population<i> - 33,387,677</i>
<li>Tourist spots<i> - Edakkal Caves, Palayur, Kovalam Beach,Munnar, Kochi, Alapuzha etc.,</i>
</ul>
</h3>
<a href="Home.html">Back</a>
</body>
</html>
TAMILNADU.HTML
<html>
<head><title>Tanil Nadu - India</title></head>
<body bgcolor="palegreen">
<h1><center>Tamil Nadu</center></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, Andhra Pradesh.
</h3>
<h3>
<ul>
<li>Districts<i> - 32</i>
<li>Capital City<i> - Chennai</i>
<li>Largest City<i> - Chennai</i>
<li>Governor<i> - Konijeti Rosaiah</i>
<li>Chief Minister<i> - Jayalalithaa</i>
<li>Population<i> - 72,138,958</i>
<li>Tourist spots<i> - Mamallapuran, Ooty, Kodaikanal, Marina, Madurai Meenakshi Amman
Temple, Thanjavur etc.,</i>
</ul>
<a href="Home.html">back</a>
</body>
</html>

OUTPUT:

HOME.HTML
RESULT:
Thus the image is embedded in an webpage and the related information was shown
when the hot spots are clicked using html and output is verified.
EX.NO:2.1 CREATION OF WEBPAGE USING EXTERNAL DATE:

CASCADING STYLE SHEET

AIM:

ALGORITHM:-
PROGRAM:

External.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="ex.css"/>
</head>
<body> <center>
<h1> External style sheet</h1></center>
<h2><center>ACET</center></h2>
<p>
<h3>Our Institution consists of various departments:<br>
1.CSE<br>
2.ECE<br>
3. MECH<br>
4. EEE<br>
5. MECHT<br>
6. CIVIL<br>
7. IT<br> </h3>
</p>
</body>
</html>

EX.CSS
h1
{
font-family:arial;
color:red;
}
h2
{
font-family:verdana;
color:green;
}
OUTPUT:

Open the External.html in a browser window and the web page displays as:

RESULT:

Thus the external style sheet was created using html and output is verified.
EX.NO:2.2 CREATION OF WEBPAGE USING EMBEDDED DATE:

CASCADING STYLE SHEET

AIM:

ALGORITHM:
PROGRAM:

Embed.html
<html>
<head>
<title> Embedded style sheet </title>
<style type="text/css">
h1
{
font-family:arial;
color:green;
}
h2
{
font-family:arial;
color:red;
left:20px;
}
h3
{
font-family:arial;
color:blue;
}
p
{
font-size:14pt;
font-family:verdana;
}
</style>
</head>
<body>
<h1> <center>EMBEDDED STYLE SHEET </h1>
<h2> Computer science and Engineering</h2>
<h3>
<p>
It is the best department. It has several lab facilities.
</p>
</h3>
</body>
</html>
OUTPUT:

Open Embed.html in a browser window and the web page appears as:

RESULT:

Thus the embedded style sheet was successfully created using cascading style sheet and
output is verified.
EX.NO:2.3 CREATION OF WEBPAGE USING INLINE DATE:

CASCADING STYLE SHEET

AIM:

ALGORITHM:
PROGRAM:

INLINE.HTML
<html>
<head>
<title>inline sheet</title>
</head>
<body>
<p style="font-family:Showcard Gothic">Welcome user..</p>
<p style="font-size:40pt;font-family:Microsoft sans serif">Gmail</p>
<p style="font-size:30pt;color:red;font-family:arial">The worlds largest spam free Email
provider</p>
<p style="font-size:30pt;color:blue;font-family:Kristen ITC">Old user login here...</p>
<h4 style="font-family:Lucida Handwriting">User Name:<input type="text" value=">@gmail.com.
<br><br> Password:<input type="password"value=""<br><br></h4>
<input type="submit" value="login">
<input type="reset"value="cancel"><br><br>
<p style="font-size:15pt;font-family=Lucida Handwriting">if u have your username or password
<a href="pass.html">click</a>here<br>
<p style="font-size:15pt;font-family=fixedsys">if you are a new user
<a href="logon.html">logon</a>here</p>
</body>
</html>

LOGON.HTML
<html>
<head>
<title>hai</title>
</head>
<body>
<h4 style="font-family:Lucida Handwriting">User Name:<input type="text" value="
">@gmail.com.<br><br>
password:<input type="password" value=""><br><br>
new password:<input type="new password" value=""><br>
<br>
confirm password:<input type="confirm password"value=""><br><br>
<input type="submit" value="ok">
<input type="submit" value="cancel">
</body>
</html>

PASS.HTML
<html>
<head> <title>hai</title>
</head> <body>
<h1>welcome to gmail</h1>
</body>
</html>
OUTPUT:
INLINE.HTML

RESULT:

Thus the web page is created using inline cascading style sheet was successfully executed and
output is verified.
EX.NO:3 USER INFORMATION AND INFORMATION DATE:

RETRIEVAL FROM XML

AIM:

ALGORITHM:
PROGRAM:
User Information
Info.xml
<?xml version="1.0" encoding="UTF-8"?>
<cse>
<id>2</id>
<name>Mani</name>
<department>cse</department>
<designation>AP</designation>

<id>1</id>
<name>Raj</name>
<department>cse</department>
<designation>AP</designation>
<id>3</id>
<name>jaya</name>
<department>cse</department>
<designation>AP</designation>
<id>4</id>
<name>madhan</name>
<department>cse</department>
<designation>AP</designation>
<id>5</id>
<name>jaga</name>
<department>cse</department>
<designation>AP</designation>
<id>6</id>
<name>kareem</name>
<department>cse</department>
<designation>AP</designation>
<id>7</id>
<name>amala</name>
<department>cse</department>
<designation>AP</designation>
<id>8</id>
<name>geetha</name>
<department>cse</department>
<designation>AP</designation>
<id>9</id>
<name>dipthi</name>
<department>cse</department>
<designation>AP</designation>
<id>10</id>
<name>bala</name>
<department>cse</department>
<designation>AP</designation>
</cse>
Information Retrieval

Elements.html

<HTML>
<HEAD>
<TITLE>Searching for Elements </TITLE>
<SCRIPT LANGUAGE="JavaScript">
function readXMLData()
{
var xmlDocumentObject, idnode, namenode, designationnode, departmentnode;
xmlDocumentObject=new XMLHttpRequest();
xmlDocumentObject.open("GET","info.xml",false);
xmlDocumentObject.send();
xmlDocumentObject=xmlDocumentObject.responseXML;
idnode = xmlDocumentObject.getElementsByTagName("id");
departmentnode = xmlDocumentObject.getElementsByTagName("department");
designationnode = xmlDocumentObject.getElementsByTagName("designation");
namenode = xmlDocumentObject.getElementsByTagName("name");
for (i = 0; i < idnode.length; i++)
{
output=idnode[i].firstChild.nodeValue;
if (output == document.getElementById("myText").value) {
displayDIV.innerHTML = idnode[i].firstChild.nodeValue + " " + namenode[i].firstChild.nodeValue
+ " " + departmentnode[i].firstChild.nodeValue + " " + designationnode[i].firstChild.nodeValue
}
}
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Searching for Elements</H1>
<input type="text" id="myText" value="">
<input type="BUTTON" VALUE="Get the last senator's name" ONCLICK="readXMLData()">
<P>
<DIV ID="displayDIV"> </DIV>
</BODY>
</HTML>
OUTPUT:
Output screens for XML document
Elements.html

RESULT:

Thus the program which takes user Id as an input and returns the user details by taking the
user information from the XML document is done successfully and output was verified.
EX.NO:4.1 SOCKETS AND SERVLETS DATE:

IMPLEMENTING HTTP REQUEST USING SOCKETS

AIM:

ALGORITHM:
PROGRAM:

import java.io.*;
import java.net.*;
public class HTTP
{
public static void main(String[] args)
{
try
{
OutputStream to_file = new FileOutputStream("z:\\temp.txt");
URL url = new
URL("http://www.computerhope.com/starthtm.htm");
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();
}
catch(Exception e)
{
e.printStackTrace();
}
}}
OUTPUT:

java HTTP

Temp.txt

RESULT:
Thus the java socket program for implementing HTTP request is done successfully and
output was verified.
EX.NO:4.2 IMPLEMENTING FTP USING SOCKETS DATE:

AIM:

ALGORITHM:
PROGRAM:

FTP Client:
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);
}
}
}}
FTP Server:

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("sample.txt");
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)
{
}
}
}
}
OUTPUT:

Server:

C:\Program Files\Java\jdk1.7.0\bin>java -cp . FTPServer


FTP Server Started on Port Number 5217
Waiting for Connection ...
FTP Client Connected ...
Waiting for Connection ...
Waiting for Command ...
SEND Command Receiced ...
Waiting for Command ...
SEND Command Receiced ...
Waiting for Command ...
GET Command Received ...
Waiting for Command ...
GET Command Received ...
Waiting for Command ...

Client:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\GRTCSELAB1-01>cd\

C:\>cdpr
'cdpr' is not recognized as an internal or external command,
operable program or batch file.

C:\>cd "Program Files"

C:\Program Files>cd Java

C:\Program Files\Java>cd jdk1.7.0

C:\Program Files\Java\jdk1.7.0>cd bin

C:\Program Files\Java\jdk1.7.0\bin>javac FTPClient.class


javac: invalid flag: FTPClient.class
Usage: javac <options> <source files>
use -help for a list of possible options

C:\Program Files\Java\jdk1.7.0\bin>java -cp . FTPClient


[ MENU ]
1. Send File
2. Receive File
3. Exit

Enter Choice :1
Enter File Name :abc.txt
File not Exists...
[ MENU ]
1. Send File
2. Receive File
3. Exit

Enter Choice :1
Enter File Name :abc.txt
Sending File ...
File Send Successfully
[ MENU ]
1. Send File
2. Receive File
3. Exit

Enter Choice :2
Enter File Name :sample
File not found on Server ...
[ MENU ]
1. Send File
2. Receive File
3. Exit

Enter Choice :2
Enter File Name :sample.txt
Receiving File ...
File Already Exists. Want to OverWrite (Y/N) ?
y
File Receive Successfully
[ MENU ]
1. Send File
2. Receive File
3. Exit

Enter Choice :

RESULT:
Thus the java socket program to demonstrate simple FTP operation is done successfully and
output was verified.
EX.NO:4.3 IMPLEMENTING SMTP USING SOCKETS DATE:

AIM:

ALGORITHM:
PROGRAM:

import java.net.*;
import java.io.*;
public class smtpclient
{
public static void main(String[] argc)
{
Socket s1;
PrintStream p1;
DataInputStream d1;
String recvreply;
try
{
s1=new Socket("202.54.16.99",25);
d1=new DataInputStream(new BufferedInputStream(s1.getInputStream(),2500));
p1=new PrintStream(new BufferedOutputStream(s1.getOutputStream(),2500),true);
recvreply=d1.readLine();
System.out.println("Server Response : " + recvreply);
p1.println("HELO 202.54.16.99");
recvreply=d1.readLine();
System.out.println("Server Response : " + recvreply);
p1.println("MAIL FROM: <csd@rocketmail.com>");
recvreply=d1.readLine();
System.out.println("Server Response : " + recvreply);
p1.println("RCPT TO: <cdsd@rocketmail.com>");
recvreply=d1.readLine();
System.out.println("Server Response : " + recvreply);
p1.println("DATA");
recvreply=d1.readLine();
System.out.println("Server Response : " + recvreply);
p1.println("From : The God of Love<das@rocketmail.com>");
p1.println("Reply-To : asds@rocketmail.com");
p1.println("To : sdv@hotmail.com>");
p1.println("Subject : Gameplan for Disaster");
p1.println("Date : 5th Dec");
p1.println("Content-Type: text/html; charset=us-ascii");
p1.println("Content-Transfer-Encoding: 7-bit");
p1.println("<b>Hello sd,</b>");
p1.println("Howdy!!!.......So how are things with u");
p1.println("Just wanted to give u this link....check it out");
p1.println("\r\n");
p1.println("\r\n");
p1.println("<a href=http://www.yahoo.com>Search Engine</a>");
p1.println("\r\n");
p1.println("Bye for Now");
p1.println("<b>The God of Love</b>");
p1.println(".");
recvreply=d1.readLine();
System.out.println("Server Response : " + recvreply);
p1.println("QUIT");
recvreply=d1.readLine();
System.out.println("Server Response : " + recvreply);
s1.close();
System.out.println("Closed Connection with Server");
}
catch(IOException e)
{
System.out.println("Error in Connecting to Port");
}
}
}

OUTPUT:

C:\Program Files\Java\jdk1.7.0\bin>java -cp . SMTPClient1


220 GRTCSELAB3-26 Microsoft ESMTP MAIL Service, Version: 6.0.2600.5949 ready at
Mon, 29 Jun 2015 12:14:42 +0530
HELO localhost.localdomain
250 GRTCSELAB3-26 Hello [127.0.0.1]
MAIL FROM: sender@somewhere.com
250 2.1.0 sender@somewhere.com....Sender OK
RCPT to: localhost/localdomain
250 2.1.5 localhost/localdomain@GRTCSELAB3-26
DATA
354 Start mail input; end with <CRLF>.<CRLF>
Subject: Test Email
<b>hi how are you</b>
.
250 2.6.0 <GRTCSELAB3-26FRaqbC00000002@GRTCSELAB3-26> Queued mail for delivery

RESULT:

Thus the program to send mail using SMTP is executed successfully.


EX.NO:4.4 IMPLEMENTING POP3 USING SOCKETS DATE:

AIM:

ALGORITHM:

PROGRAM:

package mail;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

public class ReceiveMail {

public static void check(String host, String storeType, String user,


String password)
{
try {

//create properties field


Properties properties = new Properties();

properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);

//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");

store.connect(host, user, password);

//create the folder object and open it


Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);

// retrieve the messages from the folder in an array and print it


Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);

for (int i = 0, n = messages.length; i < n; i++) {


Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());

//close the store and folder objects


emailFolder.close(false);
store.close();

} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {

String host = "pop.gmail.com";// change accordingly


String mailStoreType = "pop3";
String username = "bbaallaajjiigrt@gmail.com";// change accordingly
String password = "*********";// change accordingly

check(host, mailStoreType, username, password);

OUTPUT:

Email Number 1
Subject: The best of Gmail, wherever you are
From: Gmail Team <mail-noreply@google.com>
Text: javax.mail.internet.MimeMultipart@535b58
---------------------------------
Email Number 2
Subject: Three tips to get the most out of Gmail
From: Gmail Team <mail-noreply@google.com>
Text: javax.mail.internet.MimeMultipart@922804
---------------------------------
Email Number 3
Subject: Stay more organized with Gmail's inbox
From: Gmail Team <mail-noreply@google.com>
Text: javax.mail.internet.MimeMultipart@cf40f5
---------------------------------
Email Number 4
Subject: attendance name list II, III, IV CSE
From: Balaji Sampath Kumar <bbaallaajjiigrt@gmail.com>
Text: javax.mail.internet.MimeMultipart@b1c260
---------------------------------
Email Number 5
Subject: CS2311 OOPS - III EEE
From: Balaji Sampath Kumar <bbaallaajjiigrt@gmail.com>
Text: javax.mail.internet.MimeMultipart@503429
---------------------------------
Email Number 6
Subject: CS2411 OS - IV EEE
From: Balaji Sampath Kumar <bbaallaajjiigrt@gmail.com>
Text: javax.mail.internet.MimeMultipart@1908ca1
---------------------------------
Email Number 7
Subject: oops lab manual exp1,2
From: Balaji Sampath Kumar <bbaallaajjiigrt@gmail.com>
Text: javax.mail.internet.MimeMultipart@100ab23
---------------------------------
Email Number 8
Subject: oops lab exp1,2 all
From: Balaji Sampath Kumar <bbaallaajjiigrt@gmail.com>
Text: javax.mail.internet.MimeMultipart@e3b895
---------------------------------
Email Number 9
Subject: turboc compiler
From: Balaji Sampath Kumar <bbaallaajjiigrt@gmail.com>
Text: javax.mail.internet.MimeMultipart@6b7920
---------------------------------
Email Number 10
Subject: pl/sql ebook
From: Balaji Sampath Kumar <bbaallaajjiigrt@gmail.com>
Text: javax.mail.internet.MimeMultipart@1dd46f7

RESULT:

Thus the program for java socket program to implement a POP3 Client
is executed successfully.
EX.NO:5 CREATING SIMPLE CHAT APPLICATION DATE:
WITH DATAGRAM SOCKETS AND
DATAGRAM PACKETS

AIM:

ALGORITHM:
PROGRAM:

UDPClient.java
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);
}
}
}

UDPServer.java
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
DatagramPacket(buf,str1.length(), ia, cport));
}
}
}

OUTPUT:

UDPClient.java
UDPServer.java

RESULT:
Thus the java socket program to create a simple chat application with datagram sockets and
packets is done successfully and output was verified
EX.NO:6.1 INVOKING SERVLET FROM HTML FORMS DATE:

AIM:

ALGORITHM:
PROGRAM:

Myservletdemo.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class myservletdemo extends GenericServlet
{
public void service(ServletRequest req,ServletResponse res)
throws ServletException,IOException
{
PrintWriter out=res.getWriter();
Enumeration en=req.getParameterNames();
while(en.hasMoreElements())
{
String name_received=(String)en.nextElement();
out.print(name_received+"=");
String value_received=req.getParameter(name_received);
out.println(value_received);
out.println(" ");
}
out.close();
}
}
Myservletdemo.html
<html>
<head>
<title>Student Information Form</title>
</head>
<body>
<form name="form1" action="http://localhost:8080/servlet/myservletdemo">
<h1>STUDENT INFORMATION FORM</H1>
<h3>Enter student information in following fields-</h3>
<table>
<tr>
<td>Roll Number</td>
<td><input type="text" name="Roll Number" size="25" value=" "></td>
</tr> <tr>
<td>Student Name</td>
<td><input type="text" name="Student Name" size="25" value=" "></td>
</tr>
<tr>
<td>Student Address</td>
<td><input type="text" name="Student Address" size="50" value=" "></td>
</tr>
<tr>
<td>Phone</td>
<td><input type="text" name="Phone" size="10" value=" "></td>
</tr>
<tr>
<td>Total Marks</td>
<td><input type="text" name="Total Marks" size="25" value=" "></td>
</tr>
</table>
<input type="submit" value="submit">
</form>
</center>
</body>
</html>
WEB.XML
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
metadata-complete="true">
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<servlet>
<servlet-name>myservletdemo</servlet-name>
<servlet-class>myservletdemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservletdemo</servlet-name>
<url-pattern>/myservletdemo</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT:
RESULT:

Thus the program for invoking servlet using html was created successfully and output is
verified.
EX.NO:6.2 INVOKING SERVLET FROM APPLET DATE:

AIM:

ALGORITHM:
PROGRAM:

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("<html><body bgcolor=blue><h2>Server Response</h2>");
pw.println("<h3>Current Date and Time From Server:</h3>");
pw.println("<b>"+d+"</b></body></html>");
}
}
web.xml:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0" metadata-complete="true">
<display-name>Welcome to Tomcat</display-name>
<description> Welcome to Tomcat
</description>
<servlet>
<servlet-name>MyServer</servlet-name>
<servlet-class>MyServer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServer</servlet-name>
<url-pattern>/MyServer</url-pattern>
</servlet-mapping>
</web-app>
AppletClient.java:
import java.applet.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class AppletClient extends Applet implements ActionListener
{
public void init()
{
Label la=new Label("INVOKING SERVLET FROM APPLET");
la.setFont(new Font("Courier",Font.BOLD,15));
la.setForeground(Color.blue);
add(la);
Button b1=new Button("Click Here To Display Date Information From Server");
b1.setBackground(Color.black);
b1.setForeground(Color.white);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
System.out.println("EXE");
try
{
String url = "http://localhost:8080/MyServer/MyServer";
getAppletContext().showDocument(new URL(url),"_blank");
repaint();
}
catch(Exception e)
{
System.out.println(e);
}
}}
AppletClient.HTML:
<html>
<head>
<title>Invoking Servlets From Applet</title>
</head>
<body bgcolor="violet">
<applet code="AppletClient.class" width="400" height="200">
</applet>
</body>
</html>
OUTPUT:
Applet Client.html

RESULT:
Thus the program to invoke the servlet program from the applet was executed and verified
successfully.
EX.NO:7 THREE TIER ARCHITECTURE USING SERVLETS DATE:

AIM:

ALGORITHM:
PROGRAM:

online.html
<html>
<head>
<title> Database test</title>
</head>
<body>
<center>
<form action="http://localhost:8080/exam/exam" method=POST>
<div align="left"><br>
<b>seat number:</b> <input type="text" name="Seat_no">
<div align="right"><br>
<b>Name:</b> <input type="text" name="Name" size="50"><br>
</div>
<br>
<br>
<b>1.Is JAVA a platform independency</b><br/>
<input type="radio" name="group1" value="True">True
<input type="radio" name="group1" value="False">False<br>
<b>2.ASP .NET is a client side programming</b><br/>
<input type="radio" name="group2" value="True">True
<input type="radio" name="group2" value="False">False<br>
<b>3.MATHEMATICS is the backbone of engineering</b><br/>
<input type="radio" name="group3" value="True">True
<input type="radio" name="group3" value="False">False<br>
<b>4.You are working in IBM machines</b><br/>
<input type="radio" name="group4" value="True">True
<input type="radio" name="group4" value="False">False<br>
<b>5.C++ is a fully OOP's language</b><br/>
<input type="radio" name="group5" value="True">True
<input type="radio" name="group5" value="False">False<br>
<br><br><br>
<center>
<input type="submit" value="submit"><br><br>
</center>
</form>
</body>
</html>

Exam.java:

import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class exam extends HttpServlet
{
String message,Seat_no,Name,ans1,ans2,ans3,ans4,ans5;
int Total=0;
Connection connect;
Statement stmt =null;
ResultSet rs=null;
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
try
{
String url="jdbc:odbc:StudentDB2";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connect=DriverManager.getConnection(url," "," ");
message="Connection Successful";
}
catch(ClassNotFoundException cnfex)
{
cnfex.printStackTrace();
}
catch(SQLException sqlex)
{
sqlex.printStackTrace();
}
catch(Exception excp)
{
excp.printStackTrace();
}
Seat_no=request.getParameter("Seat_no");
Name=request.getParameter("Name");
ans1=request.getParameter("group1");
ans2=request.getParameter("group2");
ans3=request.getParameter("group3");
ans4=request.getParameter("group4");
ans5=request.getParameter("group5");
if(ans1.equals("True"))
Total+=2;
if(ans2.equals("False"))
Total+=2;
if(ans3.equals("True"))
Total+=2;
if(ans4.equals("True"))
Total+=2;
if(ans5.equals("False"))
Total+=2;
try
{
Statement stmt=connect.createStatement();
String query="INSERT into StudentTable VALUES ("+Seat_no+",'"+Name+"',"+Total+")";
//*****"+"Seat_no,Name,Marks"+")"+" VALUES("
int result=stmt.executeUpdate(query);
stmt.close();
}
catch(SQLException ex)
{
}
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<body bgcolor=yellow>");
out.println("<h1>"+message+"</h1>\n");
out.println("<h3>DataBase Updated");
out.println("<br><br>");
out.println("<b>"+"The Student Database is as follows");
out.println("<table border=5>");
try
{
Statement stmt=connect.createStatement();
String query="SELECT * FROM StudentTable";
rs=stmt.executeQuery(query);
out.println("<th>"+"Seat_no"+"</th>");
out.println("<th>"+"Name"+"</th>");
out.println("<th>"+"Marks"+"</th>");
while(rs.next())
{
out.println("<tr>");
out.println("<td>"+rs.getInt(1)+"</td>");
out.println("<td>"+rs.getString(2)+"</td>");
out.println("<td>"+rs.getInt(3)+"</td>");
out.println("</tr>");
}
out.println("</table>");
}
catch(SQLException ex)
{}
finally
{
try
{
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(connect!=null)
connect.close();
}
catch(SQLException e)
{}
}
out.println("<center>");
out.println("<h1>Thanks!</h1>\n");
out.println("</center>");
out.println("</body></html>");
}}

Web.xml:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0" metadata-complete="true">
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<servlet>
<servlet-name>exam</servlet-name>
<servlet-class>exam</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>exam</servlet-name>
<url-pattern>/exam</url-pattern>
</servlet-mapping>
</web-app>

Execution steps:
1. Create the database StudentDB2.mdb in which Studenttable is created. Note that we have to
create an empty database by specifying simply the field names such as Seat_no, Name and
Marks.
2. Create the DSN for Student database:
Open the Control panel and double click on the Administrative Tools icon. Then double click
on the Datasources(ODBC) icon. The window appears as:
Database(Database1.mdb) –DSN CONNECTION(studentDB2)

3. Click on User DSN tab and select Microsoft Access Driver (*.mdb) and then click on the
finish button. Then type the Data Source Name as StudentDB2 and click on select button to
select the database file for corresponding DSN. Click on OK button. Now connection to the
database is done using JDBC-ODBC driver.
4. Create a html program as online.html in which True/False questions are displayed.
5. Then Create a java program as Exam.java which is a servlet code for computing the total
score of each student and it displays the database contents.
6. Compile the java program by using javac exam.java. then class file will be created and place
the corresponding class file to the location c:\ "Program Files\apache-tomcat-
7.0.29\webapps\exam\WEB-INF\class.
7. Then edit the web.xml file in WEB-INF for servlet name and servlet class as exam
8. Now open online.html file in a browser window the web page opens and if we click on
submit button the student information should get updated in the database by invoking a
servlet.

OUTPUT:
RESULT:
Thus the java servlet program to conduct online examination and to display student mark list
available in a database was executed successfully and output is verified.
EX.NO:8 LOCK SERVLET ITSELF TO A PARTICULAR DATE:
SERVER IP ADDRESS AND PORT NUMBER

AIM:

ALGORITHM:
PROGRAM:
import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
public class KeyedServerLock extends GenericServlet {
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/plain");
PrintWriter out = res.getWriter();

String key = getInitParameter("key");


String host = req.getServerName();
int port = req.getServerPort();
if (! keyFitsServer(key, host, port))
{ out.println("Pirated!");
out.println(key);
out.println(host);
}
else {
out.println("Valid");
}
}
private boolean keyFitsServer(String key, String host, int port) {
byte hostIP[];
try {
hostIP = InetAddress.getByName(host).getAddress();
}
catch (UnknownHostException e) {
return false;
}
long servercode = 0;
for (int i = 0; i < 4; i++) {
servercode <<= 8;
servercode |= hostIP[i];
}
servercode <<= 32;
servercode |= port;
System.out.println(servercode);
long numericKey = 0;
try {
numericKey = Long.parseLong(key);
}
catch (NumberFormatException e) {
return false;
}
long accesscode = ~numericKey;
return (servercode == accesscode);
}
}
Web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
metadata-complete="true">
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<servlet>
<servlet-name>KeyedServerLock</servlet-name>
<servlet-class>KeyedServerLock</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>KeyedServerLock</servlet-name>
<url-pattern>/KeyedServerLock</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:

RESULT:
Thus the java servlet program to lock servlet itself to a particular server IP address and port
number which requires an init parameter key that is appropriate for its servlet IP address and port
before it unlocks itself and handles a request was executed successfully and output is verified.

EX.NO:9.1 SESSION TRACKING USING HIDDEN DATE:


FORM FIELDS

AIM:

ALGORITHM:
PROGRAM:

FirstServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet1 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:8080/secserv/SecondServlet1' method ='get'>");
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);
} }
}
Web.xml:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
metadata-complete="true">
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<servlet>
<servlet-name>FirstServlet1</servlet-name>
<servlet-class>FirstServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet1</servlet-name>
<url-pattern>/FirstServlet1</url-pattern>
</servlet-mapping>
</web-app>
SecondServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet1 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/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
metadata-complete="true">
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<servlet>
<servlet-name>SecondServlet1</servlet-name>
<servlet-class>SecondServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SecondServlet1</servlet-name>
<url-pattern>/SecondServlet1</url-pattern>
</servlet-mapping>
</web-app>

Hidden Field.html
<html>
<head><title>Hidden Field</title></head>
<body>
<form action="http://localhost:8080/firstserv/FirstServlet1" method="get">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</body>
</html>
OUTPUT:

Hidden Field.html

First Servlet
Second servlet

RESULT:
Thus the java servlet program for session tracking using hidden form fields was executed
successfully and output is verified.
EX.NO:9.2 SESSION TRACKING FOR A HIT COUNT DATE:

AIM:

ALGORITHM:

PROGRAM:

PageHitCounter.java
import java.io.*;
import java.sql.Date;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PageHitCounter extends HttpServlet{
private int hitCount;
public void init()
{
// Reset hit counter.
hitCount = 0;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
// This method executes whenever the servlet is hit
// increment hitCount
hitCount++;
PrintWriter out = response.getWriter();
String title = "Total Number of Hits";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">" + hitCount + "</h2>\n" +
"</body></html>");
}
public void destroy()
{
// This is optional step but if you like you
// can write hitCount value in your database.
}}

Web.xml:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
metadata-complete="true">
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<servlet>
<servlet-name>PageHitCounter</servlet-name>
<servlet-class>PageHitCounter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PageHitCounter</servlet-name>
<url-pattern>/PageHitCounter</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:

RESULT:
Thus the java servlet program for tracking the session for each page hit count was executed
successfully and output is verified.
EX.NO:9.3 SHOPPING CART DATE:

AIM:

PROCEDURE:

Steps

1. Double click the exe file and follow the steps by clicking next.
 The easiest way is to simply download and run the 32-bit/64-bit Windows Service Installer of
the latest version on Apache Tomcat. In my case the latest version of Apache Tomcat is 7 and
the download link is :
 http://mirrors.hostingromania.ro/apache.org/tomcat/tomcat-7/v7.0.26/bin/apache-tomcat-
7.0.26.exe
 Run this file if you agree with the license terms and switch to the Full type of install so all the
optional components are checked in the following screen:
Figure 1-Apache Tomcat Installation - choose full install

 If you now click on Next you get the following screen:

Figure 2-Apache Tomcat installation : provide username and password


 The only think you have to do here is to fill a “User Name”, provide a “Password” for it and
eventually tick on the checkbox for “Create shortcuts for all users”. Leave everything as is.
Normally you don’t need to change anything. Click on Next.

2. Tomcat uses an environment variable named JAVA_HOME to indicate the location of the JAVA
directory.
3. Additionally it uses another environment variable named CATALINA_HOME to indicate the
location of Tomcat’s Jakarta level directory.
4. In Windows XP (or equivalent) go to:
Control PanelSystemAdvancedEnvironment Variables
Click on the New button to add the following as seen with the screen grab attached:

Just these two need to be added to what ever you have already.
CATALINA_HOME c:\tomcat6\apache-tomcat-6.0.20
JAVA_HOME c:\program files\java\jdk1.6
5. Save the modifications and re-boot your computer to apply the new environment variable settings.
6. This can be tested from the command prompt (StartRun and type cmd<Enter>) by typing ECHO
followed by a space and then the variable enclosed inside a pair of % characters
(e.g. ECHO % JAVA_HOME%).
7. Starting and Stopping the server:
This is done via two batch files – startup and shutdown
They can be found in the Tomcat bin folder. It is recommended you create a shortcut for
each and place on your desktop.
Start the server by running the startup batch file – you should get a display like this:
8. Next test that the server can run a JSP page.
 In the webapps\ROOT\ folder you will find an index.jsp file.
 The ROOT folder is where the JSP pages need to live.
 Open your web browser and in offline mode type the following in the url text box:
 http://localhost:8080/index.jsp
If the following page appears then you have successfully installed Tomcat:

9. If the page does not appear then there is a problem and you should check all the steps you have
made.
10.Finally, shut down the server when not in use by simply running the shut down batch file.

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>
<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>
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>
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>
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());
}
}
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());
} }}
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());
}
}
}
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());
}
}
}
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;
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());
}
}

RESULT:
Thus the shopping cart application was executed successfully and output is verified.

Anda mungkin juga menyukai