You are on page 1of 86

Department of Computer Science and Engineering / Dr.N.G.

P IT

Dr. N.G.P. INSTITUTE OF TECHNOLOGY

Coimbatore-641048

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL

Internet Programming Laboratory (R2013)

Prepared by Approved by
Mr.V.Suresh ,AP/CSE HoD/CSE
Department of Computer Science and Engineering / Dr.N.G.P IT

CREATING A WEBPAGE USING IMAGE MAP

AIM:
To create a web page with image and hot spots using HTML
i) To embed an image map in a web page
ii) To fix the hot spots
iii) Show all the related information when the hot spots are clicked.

ALGORITHM:
Step 1 : Open a notepad.
Step 2 : Write the code for imagemap.html.
Step 3 : Enter a program that includes tags for <MAP> and other tags.
Step 4 : Insert Hyperlink using <A href>.
Step 5 : Save the file with .html extension.
Step 6 : Run the program in a web browser
Step 7 : Display Results.

HTML CODE:
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="IndiaMap.gif" usemap="#india"/>
<map name="india">
<area shape="circle" coords="160,340,20" href="ANDHRAPRADESH.html">
<area shape="circle" coords="120,440,10" href="KERALA.html">
<area shape="circle" coords="140,420,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
Department of Computer Science and Engineering / Dr.N.G.P IT

<li><b>Time Format</b> - IST (UTC + 5:30)


<li><b>National Sport</b> - Hockey
<li><b>Current PM</b> - Narendra Modi
<li><b>Current President</b> - Pranab Mukerji
</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>

KERALA.HTML
<html>
<head><title>Kerala - India</title></head>
<body bgcolor="indianred">
<h1><center>Kerala</center></h1>
<h3>
<ul>
<li>Districts<i> - 14</i>
Department of Computer Science and Engineering / Dr.N.G.P IT

<li>Capital City<i> - Thiruvanandapuram</i>


<li>Largest City<i> - Thiruvanandapuram</i>
<li>Governor<i> - Justice.P.Sadasivam</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>About Tamil Nadu</TITLE>
</HEAD>
<BODY>
<CENTER><H1>Tamil Nadu</H1></CENTER>
<HR>
<UL>
<LI>Area : 1,30,058 Sq. Kms.</LI>
<LI>Capital : Chennai</LI>
<LI>Language : Tamil</LI>
<LI>Population : 6,21,10,839</LI>
</UL><hr>
<a href="Home.html">back</a>
</BODY></HTML>
Department of Computer Science and Engineering / Dr.N.G.P IT

OUTPUT:
Department of Computer Science and Engineering / Dr.N.G.P IT

RESULT:
Thus the program to create a webpage using with Image-map was executed and the
Output was verified successfully.
Department of Computer Science and Engineering / Dr.N.G.P IT

CREATION OF HTML PAGE USING CASCADING STYLE SHEET

AIM:
To create a web page that displays college information using various style sheets.

ALGORITHM:
Internal CSS:
STEP 1: Create a HTML program with <style> tag.
STEP 2: Inside the <style> tag, specify the format required for that web page.
STEP 3: Run the program with a web browser.

External CSS:
STEP 4: Open a notepad, type the needed CSS in it and save it with .css extension.
STEP5: Refer this .css file in the HTML using the tag <link>.
STEP 6: Run the program with a web browser.

SOURCE CODE:
xyz.css

h3{font-family:arial;font-size:20;color:cyan}
table{border-color:green}
td{font-size:20pt;color:magenta}

College.html

<html>
<head><h1><center>ALL STYLE
SHEETS</center></h1>
<title>USE of INTERNAL and EXTERNAL STYLESHEETS
</title>
<link rel="stylesheet" href="xyz.css" type="text/css">
<style type="text/css">
.vid{font-family:verdana;fontstyle:
italic;color:red;text-align:center}
.ani{font-family:tahoma;font-style:italic;fontsize:
20;text-align:center;}
font{font-family:georgia;color:blue;font-size:20}
ul{list-style-type:circle}
</style>
</head>
<body>
<ol style="list-style-type:lower-alpha">
<b> KNOWLEDGE INSTITUTE OF TECHNOLOGY </b><br><br><br>
</ol>
Department of Computer Science and Engineering / Dr.N.G.P IT

<p style="font-size:20pt;color:purple"> Dr.NGP INSTITUTE OF TECHNOLOGY </p>


<p class="ani">Dr.NGP INSTITUTE OF TECHNOLOGY.<br>It is approved by AICTE(All
India Council for Technical Education).It is
affliated to Anna University.<br></p>
<h2 class="vid"> Dr.NGP INSTITUTE OF TECHNOLOGY </h2>
<br>
<font>It is an ISO certified Institution</font><br>
<br>
<font>

<h2>List of Courses offered</h2>


<ul>
<li>Computer Science and Engineering</li>
<li>Electronics and Communication Engineering</li>
<li>Mechanical Engineering</li>
<li>Electrical and Electronics Engineering</li>
<li>ME_CSE</li>
<li>ME_CAD</li>
<li>ME_Structural</li>
<li>ME_ECE</li>
</ul>
</font>
<h3>Results of cse students</h3>
<table width="100%" cellspacing="2"
cellpadding="2" border="5">
<tr>
<th>S.NAME</th>
<th>MARKS</th>
<th>RESULT</th>
</tr>
<tr>
<td align="center">Ram</td>
<td align="center">100</td>
<td align="center">pass</td>
</tr>
<tr>
<td align="center">Bala</td>
<td align="center">99</td>
<td align="center">pass</td>
</tr>
<tr>
<td align="center">Ramu</td>
<td align="center">98</td>
<td align="center">pass</td>
</tr>
Department of Computer Science and Engineering / Dr.N.G.P IT

</table>
</body>
</html>
<body>
<ol style="list-style-type:lower-alpha">
<li> Dr.NGP INSTITUTE OF TECHNOLOGY </li>

</ol>
<p style="font-size:20pt;color:purple"> Dr.NGP INSTITUTE OF TECHNOLOGY </p>
<p class="ani">Dr.NGP INSTITUTE OF TECHNOLOGY <br>It is approved by AICTE(All
India
Council for Technical Education). It is affliated to Anna University.<br></p>
<h2 class="vid">OEC</h2>
<br>
<font>It is an ISO certified Institution</font><br>
<br>
<font>
<h2>List of Courses offered</h2>
<ul>
<li>Computer Science and Engineering</li>
<li>Electronics and Communication Engineering</li>
<li>Mechanical Engineering</li>
<li>Electrical and Electronics Engineering</li>
<li>ME_CSE</li>
<li>ME_CAD</li>
<li>ME_Structural</li>
<li>ME_ECE</li>
</ul>
</font>
<h3>Results of cse students</h3>
<table width="100%" cellspacing="2" cellpadding="2" border="5">
<tr>
<th>S.NAME</th>
<th>MARKS</th>
<th>RESULT</th>
</tr>
<tr>
<td align="center">Dinesh</td>
<td align="center">100</td>
<td align="center">pass</td>
</tr>
<tr>
<td align="center">Bala</td>
<td align="center">99</td>
<td align="center">pass</td>
</tr>
Department of Computer Science and Engineering / Dr.N.G.P IT

<tr>
<td align="center">Gopi</td>

<td align="center">98</td>
<td align="center">pass</td>
</tr>
</table>
</body>
</html>

OUTPUT
SCREEN SHOT:
Department of Computer Science and Engineering / Dr.N.G.P IT

RESULT:
Thus the program to create a HTML page using types of Cascading Style Sheet was
executed and the output was verified successfully.

CREATE AND SAVE AN XML DOCUMENT AT THE SERVER

AIM:

TO create and save an XML document at the server

ALGORITHM:

STEP 1: Start the program


STEP 2: Create a Form using form elements,
STEP 3: Write a script program for validate the form using javascript,
STEP 4: Save the file with extension html.
STEP 5: Execute the page by opening html file from any browser.
STEP 6: Stop the program.

PROGRAM:
INFO.XML

/* XML Document which stores info */


<?xml version="1.0" ?>
<document>
<users>
<user>
<userid>abc</userid>
<password>abc</password>
<first_name>raj</first_name>
<last_name>kumar</last_name>
<dob>10/1/1982</dob>
</user>
<user>
<userid>ravi</userid>
<password>ravi</password>
<first_name>ravi</first_name>
<last_name>kumar</last_name>
<dob>11/11/1982</dob>
</user>
<user>
<userid>sri</userid>
<password>sri</password>
<first_name>sri</first_name>
<last_name>ram</last_name>
Department of Computer Science and Engineering / Dr.N.G.P IT

<dob>12/12/1983</dob>
</user>
<user>
<userid>lax</userid>
<password>lax</password>

<first_name>laxman</first_name>
<last_name>kumar</last_name>

<dob>1/1/1980</dob>
</user>
<user>
<userid>chandu</userid>
<password>chandu</password>
<first_name>chandana</first_name>
<last_name>priya</last_name>
<dob>9/11/1998</dob>
</user>
<user>
<userid>vysu</userid>
<password>vysu</password>
<first_name>vyshnavi</first_name>
<last_name>matha</last_name>
<dob>17/6/1982</dob>
</user>
<user>
<userid>prem</userid>
<password>prem</password>
<first_name>prem</first_name>
<last_name>kumar</last_name>
<dob>11/11/1988</dob>
</user>
<user>
<userid>geeta</userid>
<password>geeta</password>
<first_name>geeta</first_name>
<last_name>anjali</last_name>
<dob>13/1/1972</dob>
</user>
<user>
<userid>preeti</userid>
<password>preeti</password>
<first_name>prethi</first_name>
<last_name>priya</last_name>
<dob>7/11/1968</dob>
</user>
Department of Computer Science and Engineering / Dr.N.G.P IT

<user>
<userid>praveen</userid>
<password>praveen</password>
<first_name>kumar</first_name>
<last_name>kumar</last_name>

<dob>11/11/1999</dob>
</user>
</users>
</document>

RESULT.HTML
/*html program which uses xml document
For searching */
<html>
<head>
<title>authorization page</title>
<script language="JavaScript" Run At=server>
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.load("info.xml");
function search()
{
var id=document.myform.id.value;
var pword=document.myform.pword.value;
var qry=xmlDoc.selectNodes("document/users/user[userid='"+id+"']");
if(qry.length!=0)
{
if(pword!=qry.item(0).childNodes.item(1).text)
//document.body.innerHTML="Password incorrect";
document.write("success");
}
else
document.body.innerHTML="No matching data found. userid incorrect";
}
</script>
</head>
<body>
<pre>
<center>
<form name="myform" method=post action="result.html">
User id:<input type=text name=id><br>
password :<input type=password name=pword><br>
<input type=submit value=Go onClick="search()">
</form>
</center>
Department of Computer Science and Engineering / Dr.N.G.P IT

</pre>
</body>
</html>

OUTPUT
Department of Computer Science and Engineering / Dr.N.G.P IT

RESULT:
Thus the program to Create and save an XML document at the server, takes user Id as an
input and returns the User details by taking the user information from the XML document was
executed and the output was verified successfully.

JAVA SOCKET PROGRAM TO DEMONSTRATE HTTP REQUEST

AIM:

Write programs in Java using sockets to implementHTTP request

ALGORITHM:
STEP 1: Import all the necessary packages
STEP 2: Create an URL to the server specifying the html page
STEP 3: Get the host and port details from the URL
STEP 4: Request the file from the server using GET method of HTTP Request
STEP 5: Receive the response from the server
STEP 6: Display the response on the console

PROGRAM:
import java.io.*;
import java.net.*;
public class HTTP
{
public static void main(String[] args)
{
try
{
OutputStream to_file = new FileOutputStream("f:\\temp.txt");
URL url = new
URL("http://www.wickedlysmart.com/HeadFirst/HeadFirstJava/HeadFirstJavaIndex.html");

String protocol = url.getProtocol();


String host = url.getHost();
int port = url.getPort();
if(port == -1) port = 80;
String filename =url.getFile();
System.out.println(filename);
Socket socket = new Socket(host, port);
InputStream from_server = socket.getInputStream();
PrintWriter to_server = new PrintWriter(socket.getOutputStream());
Department of Computer Science and Engineering / Dr.N.G.P IT

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:
Screen Shot: 1
Department of Computer Science and Engineering / Dr.N.G.P IT

RESULT:
Thus the program to create in Java using sockets to implement HTTP request was
verified successfully.

JAVA SOCKET PROGRAM TO DEMONSTRATE FTP


AIM:
To write a java program to demonstrate a simple FTP operation

ALGORITHM:
FTP Client:
Step 1: Establish a connection with the server at a particular port
Step 2: Specify the name of the file to be read
Step 3: Receive the contents of the file from the server
FTP Server:
Step 1: Accept the connection with the client
Step 2: Listen to the port for the name of the file to be sent
Step 3: Send the file character by character
Step 4: Terminate the connection

PROGRAM:
FTP Client:
import java.io.*;
import java.net.*;
public class FTPClient
{
public static void main(String[] args)
{
try
{
Socket client = new Socket("127.0.0.1",10000);
PrintWriter writer = new PrintWriter(client.getOutputStream());
writer.println("f:/demo/HTTP.java");
InputStreamReader stream = new InputStreamReader(client.getInputStream());
BufferedReader reader = new BufferedReader(stream);
String str = null;
while((str = reader.readLine()) != null)
{
System.out.println(str);
}
reader.close();
Department of Computer Science and Engineering / Dr.N.G.P IT

}
catch(Exception e)
{
System.out.println("Connection is terminated by the Server"); } } }
FTP Server:
import java.io.*;
import java.net.*;
public class FTPServer
{
public static void main(String[] arg)
{
try
{
ServerSocket server = new ServerSocket(10000);
Socket client;
client= server.accept();
InputStreamReader stream = new InputStreamReader(client.getInputStream());
BufferedReader reader = new BufferedReader(stream);
String filename = reader.readLine();
PrintWriter writer = new PrintWriter(client.getOutputStream());

FileInputStream fileStream = new FileInputStream(new File(filename));


int ch;
while((ch = fileStream.read()) != -1)
{
writer.write(ch);
writer.flush();
}
writer.close();
}
catch(Exception e)
{
e.printStackTrace();
}}}

OUTPUT:
Department of Computer Science and Engineering / Dr.N.G.P IT

RESULT:
Thus the program to create in Java using sockets to implement FTP was verified
successfully.

JAVA SOCKET PROGRAM TO DEMONSTRATE SMTP

AIM:
To write a java socket program to implement a simple SMTP client

ALGORITHM:
Step 1: Import all necessary packages
Step 2: Establish a connection with the server
Step 3: Read the acceptance from the server
Step 4: Say HELO to the server
Step 5: Read the greeting from the server
Step 6: Send sender address to server
Step 7: Read the verification of sender from server
Step 8: Send recipient address to server
Step 9: Read the verification of recipient from server
Step 10: Send DATA command to the server
Step 11: Read the start indication from server
Step 12: Send the message to the server
Step 13: Read the acceptance of message from server
Step 14: Close the connection

PROGRAM:
import java.io.*;
import java.net.Socket;
Department of Computer Science and Engineering / Dr.N.G.P IT

public class SMTPClient {


public static void main(String[] args) throws Exception {
String results = send("localhost",
25,
"sender@somewhere.com",
"localhost/localdomain",
"Test Email",
"<b>You got mail!</b>");
System.out.println(results);
}
public static String send(String host,int port,String from,String to,String subject,
String message) throws Exception
{
StringBuffer buffer = new StringBuffer();
try {
Socket smtpSocket = new Socket(host, port);
DataOutputStream output = new
DataOutputStream(smtpSocket.getOutputStream());
BufferedReader input =new BufferedReader(new InputStreamReader(
new DataInputStream(smtpSocket.getInputStream())));
try {
read(input, buffer);

send(output, "HELO localhost.localdomain\r\n", buffer);


read(input, buffer);
send(output, "MAIL FROM: " + from + "\r\n", buffer);
read(input, buffer);
send(output, "RCPT to: " + to + "\r\n", buffer);
read(input, buffer);
send(output, "DATA\r\n", buffer);
read(input, buffer);
send(output, "Subject: " + subject + "\r\n", buffer);
send(output, message, buffer);
send(output, "\r\n.\r\n", buffer);
read(input, buffer);
smtpSocket.close();
}
catch (IOException e) {
System.out.println("Cannot send email as an error occurred.");
}}
catch (Exception e) {
System.out.println("Host unknown");
}
return buffer.toString();
}
private static void send(DataOutputStream output,String data,StringBuffer buffer)
Department of Computer Science and Engineering / Dr.N.G.P IT

throws IOException
{
output.writeBytes(data);
buffer.append(data);
}
private static void read(BufferedReader br, StringBuffer buffer) throws IOException
{
int c;
while ((c = br.read()) != -1)
{
buffer.append((char) c);
if (c == '\n')
{
break;
}
}}}

OUTPUT:
Department of Computer Science and Engineering / Dr.N.G.P IT

RESULT:
Thus the program to create in Java using sockets to SMTP was verified successfully.

JAVA SOCKET PROGRAM TO DEMONSTRATE POP3

AIM:
To write a java socket program to implement a POP3 Client

ALGORITHM:
Step 1: Get the host name, mailbox user name and password
Step 2: Establish the connection with the server
Step 3: Get the number of messages
Step 4: Retrieve a message whose number is specified by the user
Step 5: Repeat steps 3 and 4 until the user enters Q to quit

PRPGRAM:
import java.io.*;
import java.net.*;
import java.util.*;
public class Pop3ClientDemo
{
protected int port = 110;
protected String hostname = "localhost";
protected String username = "";
Department of Computer Science and Engineering / Dr.N.G.P IT

protected String password=” ";

protected Socket socket;


protected BufferedReader br;
protected PrintWriter pw;
// Constructs a new instance of the POP3 client
public Pop3ClientDemo() throws Exception
{
try
{
// Get user input
getInput();
// Get mail messages
displayEmails();
}
catch(Exception e)
{
System.err.println ("Error occured - details follow");
e.printStackTrace();
System.out.println(e.getMessage());
}
}

// Returns TRUE if POP response indicates success, FALSE if failure


protected boolean responseIsOk() throws Exception
{
String line = br.readLine();
System.out.println("< "+line);
return line.toUpperCase().startsWith("+OK");
}
// Reads a line from the POP server, and displays it to screen
protected String readLine(boolean debug) throws Exception
{
String line = br.readLine();
// Append a < character to indicate this is a server protocol response
if (debug)
System.out.println("< "+line);
else
System.out.println(line);
return line;
}
// Writes a line to the POP server, and displays it to the screen
protected void writeMsg(String msg) throws Exception
{
Department of Computer Science and Engineering / Dr.N.G.P IT

pw.println(msg);
pw.flush();
System.out.println("> "+msg);
}
// Close all writers, streams and sockets
protected void closeConnection() throws Exception
{
pw.flush();
pw.close();
br.close();
socket.close();
}
// Send the QUIT command, and close connection
protected void sendQuit() throws Exception
{
System.out.println("Sending QUIT");
writeMsg("QUIT");
readLine(true);
System.out.println("Closing Connection");
closeConnection();
}

// Display emails in a message


protected void displayEmails() throws Exception
{
BufferedReader userinput = new BufferedReader( new InputStreamReader
(System.in) );
System.out.println("Displaying mailbox with protocol commands and responses below");
System.out.println("--------------------------------------------------------------");
// Open a connection to POP3 server
System.out.println("Opening Socket");
socket = new Socket(this.hostname, this.port);
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
// If response from server is not okay
if(! responseIsOk())
{
socket.close();
throw new Exception("Invalid POP3 Server");
}
// Login by sending USER and PASS commands
System.out.println("Sending username");
writeMsg("USER "+this.username);
Department of Computer Science and Engineering / Dr.N.G.P IT

if(!responseIsOk())
{
sendQuit();
throw new Exception("Invalid username");
}
System.out.println("Sending password");
writeMsg("PASS "+this.password);
if(!responseIsOk())
{
sendQuit();
throw new Exception("Invalid password");
}
// Get mail count from server ....
System.out.println("Checking mail");
writeMsg("STAT");
// ... and parse for number of messages
String line = readLine(true);
StringTokenizer tokens = new StringTokenizer(line," ");
tokens.nextToken();
int messages = Integer.parseInt(tokens.nextToken());
int maxsize = Integer.parseInt(tokens.nextToken());
if (messages == 0)
{
System.out.println ("There are no messages.");

sendQuit();
return;
}
System.out.println ("There are " + messages + " messages.");
System.out.println("Press enter to continue.");
userinput.readLine();
for(int i = 1; i <= messages ; i++){
System.out.println("Retrieving message number "+i);
writeMsg("RETR "+i);
System.out.println("--------------------");
line = readLine(false);
while(line != null && !line.equals("."))
{
line = readLine(false);
}
System.out.println("--------------------");
System.out.println("Press enter to continue. To stop, type Q then enter");

String response = userinput.readLine();


if (response.toUpperCase().startsWith("Q"))
break;
Department of Computer Science and Engineering / Dr.N.G.P IT

}
sendQuit();
}
public static void main(String[] args) throws Exception
{
Pop3ClientDemo client = new Pop3ClientDemo();
}
// Read user input
protected void getInput() throws Exception
{
String data=null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter POP3 server hostname:");
data = br.readLine();
if(data == null || data.equals("")) hostname="localhost";
else
hostname=data;
System.out.print("Please enter mailbox username:");
data = br.readLine();
if(!(data == null || data.equals("")))
username=data;
System.out.print("Please enter mailbox password:");
data = br.readLine();

if(!(data == null || data.equals("")))


password=data;

}
}
Department of Computer Science and Engineering / Dr.N.G.P IT

RESULT:
Thus the program to create in Java using sockets to implement POP3 was verified successfully.

SIMPLE CHAT APPLICATION WITH DATAGRAM SOCKETS AND DATAGRAM


PACKETS

AIM:
To write a java program to create a simple chat application with datagram sockets and packets.

ALGORITHM:
Server Side
Step 1: Import net and io packages and class
Step 2: Create a datagram socket and datagram packet
Step 3: While client send datagram packet to server listen to client port
Step 4: Get the datagram packet into a string
Step 5: Display the string
Client Side
Step 1: Import net and io packages
Step 2: Create a datagram socket and datagram packet
Step 3: Get input from the user and convert the string into a datagram packet
Step 4: send the datagram packet to the server through serve port

PROGRAM:
Department of Computer Science and Engineering / Dr.N.G.P IT

Server Side:
import java.io.*;
import java.net.*;
class Server
{
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 waiting for data from client");
while(true)
{
serversocket.receive(dp);
String s=new String(dp.getData(),0,dp.getLength());
System.out.println(s);
}
}}

Client Side:
import java.io.*;
import java.net.*;
class Client
{
public static DatagramSocket clientsocket;
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);
dis=new BufferedReader(new InputStreamReader(System.in));
ia=InetAddress.getLocalHost();
System.out.println("Client is sending data to Server ");
while(true)
{
String str=dis.readLine();
Department of Computer Science and Engineering / Dr.N.G.P IT

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

OUTPUT:
Department of Computer Science and Engineering / Dr.N.G.P IT

RESULT:

Thus the program was written, verified and executed successfully.


Department of Computer Science and Engineering / Dr.N.G.P IT

INVOKING SERVLETS FROM HTML

AIM:
To write a program to invoke Servlet from HTML form.

ALGORITHM:
STEP 1: Create a HTML page including some form elements.
STEP 2: Inside the <form> tag, for the action attribute specify the full path name of the File.
STEP 3: Create a .java file that imports javax.http.servlet.*;
STEP 4: Set classpath where servlet-api.jar file resides.
STEP 5: Compile the servlet program using javac programname.java
STEP 6: Place the class file …\Tomcat 5.5\webapps\Examples\WEB-INF\classes\folder.
STEP 7: Define the doPost function to process the data obtained from the HTML file.
STEP 8: Modify the web.xml file using your servletClassName.
STEP 9: Invoke the class file using http://localhost:8080/servetClassName from your browser

PROGRAM:
Postparam.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class postparam extends GenericServlet
{
public void service(ServletRequest request,ServletResponse response)throws
ServletException,IOException
{
PrintWriter pw=response.getWriter();
Enumeration e=request.getParameterNames();
while(e.hasMoreElements())
{
String pname=(String)e.nextElement();

pw.print(pname+"=");
String pvalue=request.getParameter(pname);
pw.println(pvalue);
}
pw.close();}}

Postparam.html
<html>
<body>
<center>
<form name="Postparam" method=POST action="http://localhost:8080/examples/postparam">
<table>
<tr>
Department of Computer Science and Engineering / Dr.N.G.P IT

<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>
</table>
<input type="submit" value="Submit">
</body>
</html>

XML Code:
//Include the code in Web.xml document//
<servlet>
<servlet-name>Postparam</servlet-name>
<servlet-class>Postparam</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Postparam</servlet-name><url-pattern>/Postparam</url-pattern></servlet-
mapping>
Department of Computer Science and Engineering / Dr.N.G.P IT

OUTPUT:
Department of Computer Science and Engineering / Dr.N.G.P IT

RESULT:
Thus the program to invoke Servlet from HTML form was executed and the output was verified
successfully.
Department of Computer Science and Engineering / Dr.N.G.P IT

INVOKING SERVLET FROM APPLET

AIM:
To write a program to invoke Servlet from Applet form

ALGORITHM:
1. Create the java program with the following
a) Define the class Myapplet which extends the property of the class Applet
and implements the interface ActionListener.
b) Define the objects for Button and add the button in the init() method of
Applet class
c) Make the button to listen the action by using the method addActionListener().
d) Set the URL of the servlet program by using the object of the class URL.
e) Define the object for AppletContext in order to display the output of the servlet
on new browser window.
2. Create HTML file that contains the applet tag and pass the class name to that applet code.
3. Create the simple servlet program that contains any response message
4. Run the HTML file that contains the corresponding applet code.
5. Click the button on the applet window in order to invoke the servlet program.

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>
<servlet>
<servlet-name>Applet</servlet-name>
<servlet-class>MyServer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Applet</servlet-name>
<url-pattern>/MyServer</url-pattern>
</servlet-mapping>
</web-app>
Department of Computer Science and Engineering / Dr.N.G.P IT

AppletClient.java:
import java.applet.*;
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)
{
try
{
AppletContext ac=getAppletContext();
URL url = new URL("http://localhost:8080/servlets3/MyServer");
ac.showDocument(url);
}
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>
Department of Computer Science and Engineering / Dr.N.G.P IT

OUTPUT:

RESULT:
Department of Computer Science and Engineering / Dr.N.G.P IT

Thus invoking servelet from applet was written,executed and verified successfully.

ONLINE EXAM USING SERVLET WITH THREE-TIER APPLICATION

AIM:
To write java servlet programs to conduct online examination and to display student mark list
available in a database.

ALGORITHM:
Client:
Step1: In index.html on the client side declare the contents that you like to transfer to the server
using html form and input type tags.
Step2: create a submit button and close all the included tags
Servlet:
Step 1: Import all necessary packages
Step 2: Define a class that extends servlet
Step 3: In the doPost() method, do the following:
i) Set the content type of the response to "text/html"
ii) Create a writer to the response
iii) Get a paratmeter from the request
iv) If its value is equal to right answer then add 5 to mark variable
v) Similarly repeat step
vi) for all parameters
vii) Display the result in an html format using the writer

Student marklist database:


Step 1: Import necessary to java packages and javax packages and classes
Step 2: Create a class that extends HttpServlet and implements ServletException and
IOException
Step 3: In the doGet() method, do the following:
i) Create a PrintWriter object
ii) Open a connection with the data source name
iii) Write a sql query and execute to get the resultset
iv) Display the resultset information in html form

PROGRAM:
SERVLET CODE:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class StudentServlet3 extends HttpServlet
{
String message,Seat_no,Name,ans1,ans2,ans3,ans4,ans5;
int Total=0; Connection
connect; Statement stmt=null;
ResultSet rs=null;
Department of Computer Science and Engineering / Dr.N.G.P IT

public void doPost(HttpServletRequest request,HttpServletResponse response)


throws ServletException,IOException
{
try
{
String url="jdbc:odbc:NEO"; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connect=DriverManager.getConnection(url," "," "); message="Thank you for
participating in online Exam";
}
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("False")) Total+=2;
if(ans5.equals("False")) Total+=2;
try
{
Statement stmt=connect.createStatement();
String query="INSERT INTO student("+"Seat_no,Name,Total"+")
VALUES('"+Seat_no+"','"+Name+"','"+Total+"')";
int result=stmt.executeUpdate(query);
stmt.close();
}
catch(SQLException ex)
{
}
response.setContentType("text/html"); PrintWriter
Department of Computer Science and Engineering / Dr.N.G.P IT

out=response.getWriter(); out.println("<html>");
out.println("<head>"); out.println("</head>");

out.println("<body bgcolor=cyan>");
out.println("<center>");
out.println("<h1>"+message+"</h1>\n"); out.println("<h3>Yours results stored in our

database</h3>"); out.print("<br><br>");
out.println("<b>"+"Participants and their Marks"+"</b>");
out.println("<table border=5>");
try
{
Statement stmt=connect.createStatement(); String
query="SELECT * FROM student";
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.print("<td>"+rs.getInt(1)+"</td>");
out.print("<td>"+rs.getString(2)+"</td>");
out.print("<td>"+rs.getString(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("</body></html>");
Total=0;
}}

HTML CODE:
Department of Computer Science and Engineering / Dr.N.G.P IT

<html>
<head><title>Database Test</title></head>
<body><center>

<h1>Online Examination</h1>
</center>
<form action="StudentServlet3.view" method="POST">
<div align="left"><br></div>
<b>Seat Number:</b><input type="text" name="Seat_no">
<div align="Right">
<b>Name:</b><input type="text" name="Name" size="50"><br>
</div><br><br>
<b>1. Every host implements transport layer.</b><br/>
<input type="radio" name="group1" value="True">True
<input type="radio" name="group1" value="False">False<br>
<b>2. It is a network layer's responsibility to forward packets reliably from source to
destination</b><br/>

<input type="radio" name="group2" value="True">True


<input type="radio" name="group2" value="False">False<br>
<b>3. Packet switching is more useful in bursty traffic</b><br/>
<input type="radio" name="group3" value="True">True
<input type="radio" name="group3" value="False">False<br>
<b>4. A phone network uses packet switching</b><br/>
<input type="radio" name="group4" value="True">True
<input type="radio" name="group4" value="False">False<br>
<b>5. HTML is a Protocol for describing web contents</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>
Department of Computer Science and Engineering / Dr.N.G.P IT

OUTPUT:

RESULT :

Thus online exam was conducted using three tier application was written and verified
successfully.
Department of Computer Science and Engineering / Dr.N.G.P IT

STUDENT MARKLIST USING SERVLET

AIM:
To create a three tier application for displaying the student marklist

ALGORITHM:
Client:
Step1: In index.html on the client side declare the contents that you like to transfer to the server
using html form and input type tags.
Step2: Create a submit button and close all the included tags.
Servlet:
Step 1: Import all necessary packages
Step 2: Define a class that extends servlet
Step 3: In the doPost() method, do the following:
i) Set the content type of the response to "text/html"
ii) connect with the database which has the student marklist
iii) query the data to the database
Step 4: Display the student marklist.

PROGRAM:
SERVLET CODE:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class serv extends HttpServlet
{
String message,Reg_no;
Connection connect;
Statement stmt=null; ResultSet
rs=null;
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
try
{
String url="jdbc:odbc:NEO";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connect=DriverManager.getConnection(url," "," "); message="Mark List";
}
catch(ClassNotFoundException cnfex){
cnfex.printStackTrace();
}
catch(SQLException sqlex)
{
Department of Computer Science and Engineering / Dr.N.G.P IT

sqlex.printStackTrace();
}
catch(Exception excp)
{
excp.printStackTrace();
}
Reg_no=request.getParameter("regno");
response.setContentType("text/html"); PrintWriter
out=response.getWriter(); out.println("<html>");
out.println("<head>"); out.println("</head>");
out.println("<body bgcolor=cyan>");
out.println("<center>");
out.println("<h1>"+message+"</h1>\n");
try
{
Statement stmt=connect.createStatement();

String query=new String("SELECT * FROM MarkList WHERE regno= "+Reg_no);


rs=stmt.executeQuery(query);
boolean b=rs.next();
out.println("Regsitration No:"+rs.getInt(1)); out.println("<br>"+"Name:"+rs.getString(2));
out.println("<table
border=5>"); out.println("<th>"+"cs01"+"</th>"); out.println("<th>"+"cs02 "+"</th>");
out.println("<th>"+"cs03"+"</th>"); out.println("<th>"+"status"+"</th>");
while(b)
{
out.println("<tr>"); out.print("<td>"+rs.getString(3)+"</td>");
out.print("<td>"+rs.getString(4)+"</td>");
out.print("<td>"+rs.getString(5)+"</td>");
out.print("<td>"+rs.getString(6)+"</td>"); out.println("</tr>");
b=rs.next();
}
out.println("</table>");
}
catch(SQLException ex){
out.println("error in connection");
}
finally
{
try
{ if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
Department of Computer Science and Engineering / Dr.N.G.P IT

if(connect!=null)
connect.close();

catch(SQLException e){ }
}
out.println("</center>");
out.println("</body></html>");
}
}

HTML CODE:
<html>
<head><title> mark sheet</title></head>
<body><center>
<h1>Student Mark Sheet</h1>

</center><form action="serv" method="POST"> registration number:<input type="text"


name="regno">
<input type="submit" value="Submit"><br><br>
</form></body></html>

OUTPUT:
Department of Computer Science and Engineering / Dr.N.G.P IT

RESULT:
Thus the program to create an online Examination using JSP with three tier architecture
Department of Computer Science and Engineering / Dr.N.G.P IT

INSTALL TOMCAT SERVER

AIM:
Install TOMCAT web server. Convert the static web pages of assignments 2 into dynamic web
pages using servlets and cookies. Hint: Users information (user id, password,) would be stored in
web.xml. Write a servlet program to check user login.

Tomcat Installation Procedure:


Step 1: Install JDK 1.7
Download the latest JDK here:
http://www.oracle.com/technetwork/java/javase/downloads/index.html
Start by creating a new directory /usr/java:

1. [root@srv6 ~]# mkdir /usr/java


Change to the /usr/java directory
1. [root@srv6 ~]# cd /usr/java
2. [root@srv6 java ]#
Download the appropriate JDK and save it to /usr/java directory we created above.
Unpack jdk-7u5-linux-x64.tar.gz in the /usr/java directory using tar -xzf:
1. [root@srv6 java]# tar -xzf jdk-7u5-linux-x64.tar.gz
This will create the directory /usr/java/jdk1.7.0_05. This will be our JAVA_HOME.
We can now set JAVA_HOME and put Java into the path of our users.
To set it for your current session, you can issue the following from the CLI:
1. [root@srv6 java]# JAVA_HOME=/usr/java/jdk1.7.0_05
2. [root@srv6 java]# export JAVA_HOME
3. [root@srv6 java]# PATH=$JAVA_HOME/bin:$PATH
4. [root@srv6 java]# export PATH
To set the JAVA_HOME permanently, however, we need to add below to the ~/.bash_profile of
the user (in this case, root).
We can also add it /etc/profile and then source it to give to all users.
1. JAVA_HOME=/usr/java/jdk1.7.0_05
2. export JAVA_HOME
3. PATH=$JAVA_HOME/bin:$PATH
4. export PATH
Once you have added the above to ~/.bash_profile, you should log out, then log back in and
check that the JAVA_HOME is set correctly.
1. [root@srv6 ~]# echo $JAVA_HOME
2. /usr/java/jdk1.7.0_05
Step 2: Download and Unpack Tomcat 7.0.29 (or latest)

We will install Tomcat 7 under /usr/share.


Switch to the /usr/share directory:
1. [root@srv6 ~]# cd /usr/share
2. [root@srv6 share ]#
Download apache-tomcat-7.0.29.tar.gz (or the latest version) here and save it to /usr/share
Once downloaded, you should verify the MD5 Checksum for your Tomcat download using the
md5sum command.
Department of Computer Science and Engineering / Dr.N.G.P IT

1. [root@srv6 share ]# md5sum apache-tomcat-7.0.29.tar.gz


2. 307076fa3827e19fa9b03f3ef7cf1f3f *apache-tomcat-7.0.29.tar.gz
Compare the output above to the MD5 Checksum provided next to the download link and you
used above and check that it matches.
unpack the file using tar -xzf:
1. [root@srv6 share ]# tar -xzf apache-tomcat-7.0.29.tar.gz
This will create the directory /usr/share/apache-tomcat-7.0.29
Step 3: Configure Tomcat to Run as a Service.
We will now see how to run Tomcat as a service and create a simple Start/Stop/Restart script, as
well as to start Tomcat at boot.
Change to the /etc/init.d directory and create a script called 'tomcat' as shown below.
1. [root@srv6 share]# cd /etc/init.d
2. [root@srv6 init.d]# vi tomcat
And here is the script we will use.
1. #!/bin/bash
2. # description: Tomcat Start Stop Restart
3. # processname: tomcat
4. # chkconfig: 234 20 80
5. JAVA_HOME=/usr/java/jdk1.7.0_05
6. export JAVA_HOME

7. PATH=$JAVA_HOME/bin:$PATH
8. export PATH
9. CATALINA_HOME=/usr/share/apache-tomcat-7.0.29
10. case $1 in
11. start)
13. sh $CATALINA_HOME/bin/startup.sh
;;
15. stop)
16. sh $CATALINA_HOME/bin/shutdown.sh
;;
18. restart)
19. sh $CATALINA_HOME/bin/shutdown.sh
20. sh $CATALINA_HOME/bin/startup.sh
21. ;;
22. esac
23. exit 0
The above script is simple and contains all of the basic elements you will need to get going.
As you can see, we are simply calling the startup.sh and shutdown.sh scripts located in the
Tomcat bin directory (/usr/share/apache-tomcat-7.0.29/bin).
You can adjust your script according to your needs and, in subsequent posts, we'll look at
additional examples.
CATALINA_HOME is the Tomcat home directory (/usr/share/apache-tomcat-7.0.29)
Now, set the permissions for your script to make it executable:
1. [root@srv6 init.d]# chmod 755 tomcat
Department of Computer Science and Engineering / Dr.N.G.P IT

We now use the chkconfig utility to have Tomcat start at boot time. In my script above, I am
using chkconfig: 234 20 80. 2345 are the run levels and 20 and 80 are the stop and start priorities
respectively. You can adjust as needed.

1. [root@srv6 init.d]# chkconfig --add tomcat


2. [root@srv6 init.d]# chkconfig --level 234 tomcat on
Verify it:
1. [root@srv6 init.d]# chkconfig --list tomcat
2. tomcat 0:off 1:off 2:on 3:on 4:on 5:off 6:off
Now, let's test our script.
Start Tomcat:
1. [root@srv6 ~]# service tomcat start
2. Using CATALINA_BASE: /usr/share/apache-tomcat-7.0.29
3. Using CATALINA_HOME: /usr/share/apache-tomcat-7.0.29
4. Using CATALINA_TMPDIR: /usr/share/apache-tomcat-7.0.29/temp
5. Using JRE_HOME: /usr/java/jdk1.7.0_05
6. Using CLASSPATH: /usr/share/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/share/apache-
tomcat-7.0.29/bin/tomcat-juli.jar
Stop Tomcat:
1. [root@srv6 ~]# service tomcat stop
2. Using CATALINA_BASE: /usr/share/apache-tomcat-7.0.29
3. Using CATALINA_HOME: /usr/share/apache-tomcat-7.0.29
4. Using CATALINA_TMPDIR: /usr/share/apache-tomcat-7.0.29/temp
5. Using JRE_HOME: /usr/java/jdk1.7.0_05
6. Using CLASSPATH: /usr/share/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/share/apache-
tomcat-7.0.29/bin/tomcat-juli.jar
Restarting Tomcat (Must be started first):
1. [root@srv6 ~]# service tomcat restart
2. Using CATALINA_BASE: /usr/share/apache-tomcat-7.0.29
3. Using CATALINA_HOME: /usr/share/apache-tomcat-7.0.29
4. Using CATALINA_TMPDIR: /usr/share/apache-tomcat-7.0.29/temp

5. Using JRE_HOME: /usr/java/jdk1.7.0_05

6. Using CLASSPATH: /usr/share/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/share/apache-


tomcat-7.0.29/bin/tomcat-juli.jar
7. Using CATALINA_BASE: /usr/share/apache-tomcat-7.0.29
8. Using CATALINA_HOME: /usr/share/apache-tomcat-7.0.29
9. Using CATALINA_TMPDIR: /usr/share/apache-tomcat-7.0.29/temp
10. Using JRE_HOME: /usr/java/jdk1.7.0_05
11. Using CLASSPATH: /usr/share/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/share/apache-
tomcat-7.0.29/bin/tomcat-juli.jar
We should review the Catalina.out log located at /usr/share/apache-tomcat-
7.0.29/logs/catalina.out and check for any errors.
1. [root@srv6 init.d]# more /usr/share/apache-tomcat-7.0.29/logs/catalina.out
We can now access the Tomcat Manager page at:
Department of Computer Science and Engineering / Dr.N.G.P IT

http://yourdomain.com:8080 or http://yourIPaddress:8080 and we should see the Tomcat home


page.

RESULT:
Thus the installation of Tomcat server is done successfully.
Department of Computer Science and Engineering / Dr.N.G.P IT

LOGIN APPLICATION WITH STRUTS FRAMEWORK IN JAVA

AIM:
To create a Login Application with Struts Framework in Java

ALGORITHM:
Step1: In index.html on the client side declare the contents that you like to transfer to the server
using html form and input type tags.
Step2: create a submit button and close all the included tags
Servlet:
Step 1: Import all necessary packages

Step 2: Define a class that extends servlet


Step 3: In the doPost() method, do the following:
i) Set the content type of the response to "text/html"
ii) Create a writer to the response
iii) Get a paratmeter from the request
iv) If its value is equal to right answer then add 5 to mark variable
v) Similarly repeat step
vi) for all parameters
vii) Display the result in an html format using the writer

Student Database System:


Step 1: Import necessary to java packages and javax packages and classes
Step 2: Create a class that extends HttpServlet and implements ServletException and
IOException
Step 3: In the doGet() method, do the following:
i) Create a PrintWriter object
ii) Open a connection with the data source name
iii) Write a sql query and execute to get the resultset
iv) Display the resultset information in html form

PROGRAM:
UserAction.java
packagecom.src.loginapp.action;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
Department of Computer Science and Engineering / Dr.N.G.P IT

import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping;


import com.src.loginapp.form.UserInformationForm;
public class UserAction extends Action{ publicActionForward
execute(ActionMappingmapping,ActionForm form,
HttpServletRequestrequest,HttpServletResponse response) throws Exception {
UserInformationFormuserInformationForm = (UserInformationForm) form;
List errorList = new ArrayList(); // check if username is empty if
(userInformationForm.getUsername() == null ||
"".equals(userInformationForm.getUsername().trim()))
{ // set error message errorList.add(new String("Please enter Username"));
request.getSession().setAttribute("errorList", errorList); //stay in login page
returnmapping.findForward("failure"); } // check if password is empty else if
(userInformationForm.getPassword() == null ||
"".equals(userInformationForm.getPassword().trim()))
{ // set error message errorList.add(new String("Please enter Password"));
request.getSession().setAttribute("errorList", errorList); // stay in login page
returnmapping.findForward("failure");
} // forward to welcome page returnmapping.findForward("success"); } }
UserInformationForm.java
packagecom.src.loginapp.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
public classUserInformationFormextendsActionForm
{ String username;
String password;
publicStringgetUsername()
{ return username; }
publicvoidsetUsername(String username)

{ this.username= username; }
publicStringgetPassword()
{ return password; }
publicvoidsetPassword(String password)
{ this.password= password; } }
login.jsp
<%@tagliburi="http://struts.apache.org/tags-html" prefix="html"%>
<%@tagliburi="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ tagliburi="http://struts.apache.org/tags-logic" prefix="logic" %>
<html>
<head>
</head>
<body>
<h1>Struts Login Application</h1>
Department of Computer Science and Engineering / Dr.N.G.P IT

<html:form action="/Login">

<div style="padding:16px">
<logic:present name="errorList">
<logic:iterate id="error" name="errorList">
<p style="color:red"><bean:write name="error"/></p>
</logic:iterate>
</logic:present>
</div>
<div style="padding:16px">
User Name :
<html:text property="username" size="20" maxlength="20"/>
<br></br>
Password :
<html:password property="password" size="20" maxlength="20"/>
</div>
<div style="padding:16px">
<div style="float:left;padding-right:8px;">
<html:submit></html:submit>
</div>
</div>
</html:form>
</body>
</html>

OUTPUT:
Department of Computer Science and Engineering / Dr.N.G.P IT
Department of Computer Science and Engineering / Dr.N.G.P IT

RESULT:
Thus the program was written verified and executed successfully.

HIBERNATE

AIM:
To write a Hibernate Simple Program Using Java Application with Eclipse

ALGORITHM:
Step – 1 Creating Java Project
Step – 2 SimpleProgram Hibernate Project structure
Step – 3 Adding Jar Files
Step – 4 Creating your SimpleProgram Hibernate program (Controller &Pojo)
Step – 5 Creating hibernate.cfg.xml
Step – 6 Creating Student.hbm.xml
Step – 7 OutPut for Running Console hiberanate application
Step – 8 OutPut for Running Oracle hibernate application

PROGRAM:
AddStudent.java:
Department of Computer Science and Engineering / Dr.N.G.P IT

package com.candidjava;
//package code;
import java.sql.*;
import java.io.*;
import org.hibernate.*;
import org.hibernate.cfg.*;

public class AddStudent {


private static SessionFactory sessionFactory;
public static void main(String args[]) throws Exception {
DataInputStream d = new DataInputStream(System.in);
System.out.println("ENTER YOUR NAME");
String name = d.readLine();
System.out.println("ENTER YOUR DEGREE");
String degree = d.readLine();
System.out.println("ENTER YOUR PHONE");
String phone = d.readLine();
System.out.println("Name: " + name);
System.out.println("Degree: " + degree);
System.out.println("Phone: " + phone);
if ((name.equals("") || degree.equals("") || phone.equals(""))) {
System.out.println("All informations are Required");
} else {
try {
// begin try
sessionFactory = new Configuration().configure(
"com\\xml\\hibernate.cfg.xml").buildSessionFactory();
}

catch (Exception e) {
System.out.println(e.getMessage());
System.err.println("Initial SessionFactory creation failed."+ e);
}
Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();
Student stu = new Student();
stu.setName(name);
stu.setDegree(degree);
stu.setPhone(phone);
s.save(stu);
tx.commit();
System.out.println("Added to Database");
if (s != null)
s.close();
}
}
Department of Computer Science and Engineering / Dr.N.G.P IT

Student.java:
package com.candidjava;
//package code;
import java.io.*;
public class Student implements Serializable {
private long id;
private String name;
private String degree;
private String phone;
public long getId() {
return id;
}
public String getName() {
return name;
}
public String getDegree() {
return degree;
}
public String getPhone() {
return phone;
}
public void setId(long string) {
id = string;
}

public void setName(String string) {


name = string;
}
public void setDegree(String string) {
degree = string;
}
public void setPhone(String string) {
phone = string;
}
public String toString() {
return name;
}
}

hibernate.cfg.xml:
<!DOCTYPE hibernate-configuration PUBLIC
Department of Computer Science and Engineering / Dr.N.G.P IT

"-//Hibernate/Hibernate Configuration DTD//EN"


"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="studentFactory">
<property name="connection.driver_class">
oracle.jdbc.OracleDriver
</property>
<property name="connection.url">
jdbc:oracle:thin:@localhost:1521:XE
</property>
<property name="connection.username">
system
</property>
<property name="connection.password">
system
</property>
<property name="connection.pool_size">5</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.OracleDialect
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="\com\\xml\\Student.hbm.xml" />
</session-factory>

Student.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="com.candidjava.Student" table="Studentdemo">

<id name="id" type="long" column="ID">


Department of Computer Science and Engineering / Dr.N.G.P IT

<generator class="increment" />

</id>

<property name="name" column="name" not-null="true" />

<property name="degree" column="degree" />

<property name="phone" column="phone" />

</class>

</hibernate-mapping>

OUTPUT;
Department of Computer Science and Engineering / Dr.N.G.P IT
Department of Computer Science and Engineering / Dr.N.G.P IT

RESULT:
Thus the program was written,verified and executed successfully.

SPRING

AIM:
To write a Simple Program Using Java Application with Eclipse

ALGORITHM:
 Create the java project

 add spring jar files

 create the class

 create the xml file to provide the values

 create the test class

PROGRAM:
Student.java
package com.javatpoint;
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void displayInfo(){
System.out.println("Hello: "+name);
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
Department of Computer Science and Engineering / Dr.N.G.P IT

<beans

xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
mlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="studentbean" class="com.javatpoint.Student">
<property name="name" value="Vimal Jaiswal"></property>
</bean>
</beans>

Test.java
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);
Student student=(Student)factory.getBean("studentbean");
student.displayInfo(); } }
OUTPUT:
Department of Computer Science and Engineering / Dr.N.G.P IT

RESULT:

Thus the program was written,verified and executed successfully.

TEXT ADVANCED JAVA SCRIPT PROGRAM TO GET

AIM:
To create a text box and submit button of event handling submit form () using AJAX.

ALGORITHM:
Step 1: Start
Step 2: Create a text box and submit button of event handling submit form ().
Step 3: Create new Active object of XMLHTTP under exception
Step 4: if ready state is four then get the message else error message.
Step 5: Stop

PROGRAM:
Department of Computer Science and Engineering / Dr.N.G.P IT

Ajax.html
<html>
<head>
<script>
function submitForm()
{ var xhr;
try { xhr = new ActiveXO
{ try { xhr = new ActiveXObject('Mic
}
catch (e2)
{
try { xhr = new XMLHttpRequest();
catch (e3) { xhr = false; }
}}
xhr.onreadystatechange = function()
{ if(xhr.readyState == 4)
{
if(xhr.status == 200)
document.ajax.dyn="
else
document.ajax.dyn="Er
}};
xhr.open(GET, "data.txt", true);
xhr.send(null);
}
</script>
</head>
<body>
<FORM method="POST"
<INPUT type="BUTTON"
type="text" name="dyn"
</FORM>
</body>
</html>

Data.txt
Ajax exchanges the data with the server, and update parts of a web page without reloading the
whole page.

OUTPUT:
Department of Computer Science and Engineering / Dr.N.G.P IT

RESULT:
Thus the AJAX program was successfully tested and executed.

WEB SERVICES AND DATABASE

AIM:
To consider a case where we have two web Services- an airline service and a travel agent and the
travel agent is searching for an airline. Implement this scenario using Web Services and Data
base.

ALGORITHM:
STEP 1: Start the program,
STEP 2: Write a program in jsp and save it as filename.jsp
Department of Computer Science and Engineering / Dr.N.G.P IT

STEP 3: Place the jsp file …\Tomcat 5.5\webapps\Examples\WEB-INF\jsp\ folder.


STEP 4: Create a data base to store the existing user details. If a new login has to be created, then
display the corresponding page.
STEP 5: Create a table in MS ACCESS or ORACLE that contains three fields .
STEP 6: Create a DSN to map the Microsoft Access Driver using ODBC in Administrative
Tools.
STEP 7: Import java.sql.* in the java program to execute the SQL queries.
STEP 8: Load the database driver by using Class.forName().
STEP 9: Create a Connection and Statement Object.
STEP 10: Establish a Database Connection with DSN using DriverManager.getConnection( ).
STEP 11: Execute the query using executeQuery() and that gets stored in a Resultset.
STEP 12: Until there are records in table specified get the fields in each record one by one and
display onto the screen.
STEP 13: Close the Statement and Connection Object.
STEP 14: DIsplay the results
STEP 15: Write a JSP program and save it with extension filename.jsp
STEP 16: Compile and Run the java program,
STEP 17: Enter the jsp file name into the command prompt window.
STEP 18: Stop the program.

PROGRAM:
Database used: MS Access
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>Travel Agency</title>
</head>
<body>
<center><h1>Travel Easy</h1>
<h3> - A Smarter way to travel</h3>
<br><br>
<b> Enter your Details</b>
<form name="index" action="AirlineList.jsp" method="post">
<br>
<table cellpadding="6" cellspacing="6">
<tr>
<td><b>From</b></td>
<td><input type="text" name="txt_from"</td>
</tr>
<tr>
Department of Computer Science and Engineering / Dr.N.G.P IT

<td><b>To</b></td>
<td><input type="text" name="txt_to"</td>
</tr>
<tr>
<td><b>Date of Journey</b></td>
<td><input type="text" name="txt_depart"</td>
</tr>
<tr>
<td><b>Number of Passengers</b></td>
<td><input type="text" name="txt_no"</td>
</tr>
<tr>
<td><b>Type of Flight</b></td>
<td><input type="Radio" name="group1" value="domestic">Domestic Flights</td
</tr>
<tr>
<td></td>
<td><input type="Radio" name="group1" value="international">International
Flights</td>
</tr>
<tr>
<td><b>Select desired Airlines</b></td>
<td>
<select name="airline">
<option>Kingfisher</option>
<option>SpiceJet</option>
</select>
</td>

</tr>
</table>
<br><br>
<input type="Submit" name="Submit" value="Find Flights">
</form>
</center>
</body>
</html>

Airlinelist.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">
Department of Computer Science and Engineering / Dr.N.G.P IT

<title>Domestic Flights</title>
</head>
<body>
<center><h1>Travel Easy</h1>
<h3> - A Smarter way to travel</h3>
</center>
<br><br>
<%@ page language="java" %>
<%@ page import ="java.sql.*" %>
<%@ page import =
"java.util.Date,java.text.SimpleDateFormat,java.text.ParseException"%>
<%
String type = request.getParameter("group1");
String from= request.getParameter("txt_from");
String to = request.getParameter("txt_to");
String depart= request.getParameter("txt_depart");
String ret = request.getParameter("txt_return");
String no = request.getParameter("txt_no");
String airline = request.getParameter("airline");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String sTable = type;
String sSql = "SELECT * FROM " sTable " WHERE From='" from "' and TO='" to "'
and DepartDate='" depart "' and SeatCapacity>=" no "";
String sDBQ = "d:/" airline ".mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" sDBQ
“;DriverID=22;READONLY=true";
Connection cn = null;

Statement st = null;
ResultSet rs = null;
try {
cn = DriverManager.getConnection( database ,"","");
st = cn.createStatement();
rs = st.executeQuery( sSql );
ResultSetMetaData rsmd = rs.getMetaData();
String s1,s2,s3,s4,s5,s6,s7,s8;
int i=1;
String flight_no[] = new String[100];

//out.println("<form name='AirlLine' action='' method='post'><b>" i " . " rs.getString(1)


"</b><br><br>");
out.println("<h3><b>" airline " Flights</b></h3><br>");
out.println("<table cellspacing=20 cellpaddinng=15>");
out.println("<tr><th>Flight No</th><th>From</th><th>To</th><th>Departure
Date</th><th>Arrival Date</th><th>Start Time</th>");
Department of Computer Science and Engineering / Dr.N.G.P IT

out.println("<th>Reach Time</th><th>Seats Remaining</th></tr>");


while(rs.next())
{
s1 = rs.getString(1);
flight_no[i] = s1;
s2 = rs.getString(2);
s3 = rs.getString(3);
s4 = rs.getString(4);
s5 = rs.getString(5);
s6 = rs.getString(6);
s7 = rs.getString(7);
s8 = rs.getString(8);
out.println("<tr><td>" s1 "</td>");
out.println("<td>" s2 "</td>");
out.println("<td>" s3 "</td>");
out.println("<td>" s4 "</td>");
out.println("<td>" s5 "</td>");
out.println("<td>" s6 "</td>");
out.println("<td>" s7 "</td>");
out.println("<td>" s8 "</td></tr>");
i;
out.println("</table>");
if(i==1)
{
out.println("<br><center><b>Sorry!! No flights scheudle
available</b></center><br>");
}

else
{
out.println("<form name='AirlineList' action='" airline ".jsp' method='post'>");
out.println("<br><table><tr><td>Select Flight</td><td>");
out.println("<select name='flight_no'>");
for(int temp=1;temp<i;temp )
{
out.println("<option>" flight_no[temp] "</option>");
}
out.println("</select></td></tr><tr></tr>");
out.println("<tr><td><input type='hidden' name='no' value='" no "'</td>");
out.println("<td><input type='hidden' name='air_type' value='" type "'</td></tr>");
for(int j=1;j<=Integer.parseInt(no);j )
{
out.println("<tr><th>Passenger " j " details</th></tr>");
out.println("<tr></tr>");
out.println("<tr><td>Name</td><td><input type='text' name='pas" j "_name'</td></tr>");
out.println("<tr><td>Age</td><td><input type='text' name='pas" j
Department of Computer Science and Engineering / Dr.N.G.P IT

"_age'</td></tr>");
out.println("<tr><td>Sex</td><td><input type='text' name='pas" j
"_sex'</td></tr>");
out.println("<tr></tr>");
}
out.println("</table><br><br><input type='Submit' name='Submit' value='Book
Now'/></form>");
}
//out.println("<input name ='submit' value='Submit' type='submit'/>");
}
finally {
try { if( null != rs ) rs.close(); } catch( Exception ex ) {}
try { if( null != st ) st.close(); } catch( Exception ex ) {}
try { if( null != cn ) cn.close(); } catch( Exception ex ) {}
}
%>
</body>
</html>
Kingfisher.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>Kingfisher Airlines</title>
</head>
<body>
<%@ page language="java" %>
<%@ page import ="java.sql.*" %>
<%
String s = request.getParameter("no");
out.println("<h1><center>Indian Airlines</h1><br><h3>- Have a nice
trip!!!</h3></center><br>");
out.println("<br><br>Your Booking Details");
out.println("<br><br><table cellspacing=10 cellpaddin=10>");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String sTable = request.getParameter("air_type");
String sSql = "SELECT * FROM " sTable " WHERE FlightNo='"
request.getParameter("flight_no") "'";
String sDBQ = "d:/airindia.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" sDBQ
";DriverID=22;READONLY=true";
Connection cn = null;
Statement st = null;
Department of Computer Science and Engineering / Dr.N.G.P IT

ResultSet rs = null;
String name,age,sex,flightno,from,to,departure,arrival,starttime,reachtime,seat;
out.println("<tr><th>Name</th><th>Age</th><th>Sex</th><th>Flight
No</th><th>From</th><th>To</th><th>Departure Date</th><th>Arrival Date</th><th>Start
Time</th><th>Reach Time</th><th>Seat No</th></tr>");
try
{
cn = DriverManager.getConnection( database ,"","");
st = cn.createStatement();
rs = st.executeQuery( sSql );
ResultSetMetaData rsmd = rs.getMetaData();
int seat1=1;
while(rs.next())
{
flightno = rs.getString(1);
from = rs.getString(2);
to = rs.getString(3);
departure = rs.getString(4);
arrival = rs.getString(5);
starttime = rs.getString(6);

reachtime = rs.getString(7);
seat = rs.getString(8);
seat1 = Integer.parseInt(seat);
for(int i=1;i<=Integer.parseInt(s);i )
{
name= request.getParameter("pas" i "_name");
age = request.getParameter("pas" i "_age");
sex = request.getParameter("pas" i "_sex");
flightno = request.getParameter("flight_no");
out.println("<tr><td>" name "</td><td>" age "</td><td>" sex "</td>");
out.println("<td>" flightno "</td><td>" from "</td><td>" to "</td><td>" departure
"</td>");
out.println("<td>" arrival "</td><td>" starttime "</td><td>" reachtime "</td><td>"
seat1 "</td>");
seat1--;
}
}
Connection cn1 = null;
Statement st1 = null;
ResultSet rs1 = null;

try
{
sSql = "update " sTable" set SeatCapacity=" seat1 " WHERE FlightNo='"
Department of Computer Science and Engineering / Dr.N.G.P IT

request.getParameter("flight_no") "'";
rs1 = st.executeQuery( sSql );
}
catch(Exception e)
{
}
}
finally {
try { if( null != rs ) rs.close(); } catch( Exception ex ) {}
try { if( null != st ) st.close(); } catch( Exception ex ) {}
try { if( null != cn ) cn.close(); } catch( Exception ex ) {}
}
%>
</body>
</html>
SpiceJet.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>SpiceJet Airlines</title>
</head>
<body>
<%@ page language="java" %>
<%@ page import ="java.sql.*" %>
<%
String s = request.getParameter("no");
out.println("<h1><center>SpiceJet Airlines</h1><br><h3>- Have a nice
trip!!!</h3></center><br>");
out.println("<br><br>Your Booking Details");
out.println("<br><br><table cellspacing=10 cellpaddin=10>");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String sTable = request.getParameter("air_type");
String sSql = "SELECT * FROM " sTable " WHERE FlightNo='"
request.getParameter("flight_no") "'";
String sDBQ = "d:/SpiceJet.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" sDBQ
";DriverID=22;READONLY=true";
Connection cn = null;
Statement st = null;
ResultSet rs = null;
String name,age,sex,flightno,from,to,departure,arrival,starttime,reachtime,seat;
out.println("<tr><th>Name</th><th>Age</th><th>Sex</th><th>Flight
Department of Computer Science and Engineering / Dr.N.G.P IT

No</th><th>From</th><th>To</th><th>Departure Date</th><th>Arrival Date</th><th>Start


Time</th><th>Reach Time</th><th>Seat No</th></tr>");
try
{
cn = DriverManager.getConnection( database ,"","");
st = cn.createStatement();
rs = st.executeQuery( sSql );
ResultSetMetaData rsmd = rs.getMetaData();
int seat1=1;
while(rs.next())
{
flightno = rs.getString(1);
from = rs.getString(2);
to = rs.getString(3);

departure = rs.getString(4);
arrival = rs.getString(5);
starttime = rs.getString(6);
reachtime = rs.getString(7);
seat = rs.getString(8);
seat1 = Integer.parseInt(seat);
for(int i=1;i<=Integer.parseInt(s);i )
{
name= request.getParameter("pas" i "_name");
age = request.getParameter("pas" i "_age");
sex = request.getParameter("pas" i "_sex");
flightno = request.getParameter("flight_no");
out.println("<tr><td>" name "</td><td>" age "</td><td>" sex "</td>");
out.println("<td>" flightno "</td><td>" from "</td><td>" to "</td><td>" departure
"</td>");
out.println("<td>" arrival "</td><td>" starttime "</td><td>" reachtime "</td><td>"
seat1 "</td>");
seat1--;
}
}
Connection cn1 = null;
Statement st1 = null;
ResultSet rs1 = null;
try
{
sSql = "update " sTable " set SeatCapacity=" seat1 " WHERE FlightNo='"
request.getParameter("flight_no") "'";
rs1 = st.executeQuery( sql );
}

catch(Exception e)
Department of Computer Science and Engineering / Dr.N.G.P IT

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

OUTPUT:

Database

(Similarly add for SpiceJet.mdb)


Department of Computer Science and Engineering / Dr.N.G.P IT

index.jsp

Airline.jsp:
Department of Computer Science and Engineering / Dr.N.G.P IT

Kingfisher.jsp

RESULT:
Thus the program to create a web services and Database interaction was executed and the Output
was verified successfully.
Department of Computer Science and Engineering / Dr.N.G.P IT

SESSION TRACKING HIDDEN FIELDS

AIM:

To write a program to demonstrate the session tracking hidden fields.

ALGORITHM:

Step 1: Start the program.

Step 2: Create a HTML file with form which has text fields and text buttons.

Step 3: Create a Servlet to read the text from the form, store it in a session and display it in a
hidden field.

Step 4: Create a Servlet to read the text from the hidden field , store it in a session and display it
in a webpage.

Step 5: Stop.

PROGRAM:

Index.html

<form action="go" method="get">


Name:<input type="text" name="uname"/><br/>
<input type="submit" value="go"/>
</form>

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{
Department of Computer Science and Engineering / Dr.N.G.P IT

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("uname");
out.print("Welcome "+n);

//creating form that have invisible textfield


out.print("<form action='welcome'>");
out.print("<input type='hidden' name='name' 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();

//Getting the value from the hidden field


String n=request.getParameter("name");
out.print("Hello "+n);

out.close();
Department of Computer Science and Engineering / Dr.N.G.P IT

}catch(Exception e){System.out.println(e);}
}

Output:
Department of Computer Science and Engineering / Dr.N.G.P IT
Department of Computer Science and Engineering / Dr.N.G.P IT

RESULT:
Thus the program was written, executed and the output is verified successfully.
Department of Computer Science and Engineering / Dr.N.G.P IT

SESSION TRACKING HIT COUNT

AIM:
To write a program to demonstrate the session tracking hit count.

ALGORITHM:
Step 1: Start the program.
Step 2: Use a variable to store the count value
Step 3: If no user visits the web page, the count value will be zero.
Step 4: Else it increments the count value as count=count+1.
Step 5: Return the value
Step 6: Stop.

PROGRAM:

Index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Session by Hit Count!</h1>
<form action="SessionTracker.jsp">
<input type="submit" value="Hit Count!!">
</form>
</body>
</html>

SessionTracker.jsp

<%@page import="java.util.Enumeration"%>
<%@page import="java.io.*"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
Department of Computer Science and Engineering / Dr.N.G.P IT

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%

// PrintWriter out = res.getWriter();

// Get the current session object, create one if necessary


// HttpSession session = req.getSession();

// Increment the hit count for this page. The value is saved
// in this client's session under the name "tracker.count".
Integer count = (Integer)session.getAttribute("tracker.count");
if (count == null)
count = 1;
else
count = count + 1;
session.setAttribute("tracker.count", count);

out.println("<HTML><HEAD><TITLE>SessionTracker</TITLE></HEAD>");
out.println("<BODY><H1>Session Tracking Demo</H1>");

// Display the hit count for this page


out.println("You've visited this page " + count + " times.");

out.println("<P>");

out.println("<H2>Here is your session data:</H2>");


Enumeration enums = session.getAttributeNames();
while (enums.hasMoreElements()) {
String name = (String) enums.nextElement();
out.println(name + ": " + session.getAttribute(name) + "<BR>");
}
out.println("</BODY></HTML>");

%>

</body>
Department of Computer Science and Engineering / Dr.N.G.P IT

</html>

OUTPUT:
Department of Computer Science and Engineering / Dr.N.G.P IT

RESULT:

Thus the program was written, executed and the output is verified successfully.
Department of Computer Science and Engineering / Dr.N.G.P IT