0% found this document useful (0 votes)
1K views

Internet Programming Lab Manual

This document provides code samples for implementing various internet programming concepts using sockets and servlets in Java, including: 1. A HTTP request socket program that requests an HTML page from a server and displays the response. 2. An FTP socket program with client and server code that demonstrates a simple file transfer by establishing a connection, specifying a file name, and sending the file character by character. 3. A servlet program that retrieves user details from an XML document by taking a user ID as input. The document contains algorithms, code snippets with comments, and expected outputs for each concept to demonstrate how to implement basic internet programming tasks in Java.

Uploaded by

Ravi Ganesh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

Internet Programming Lab Manual

This document provides code samples for implementing various internet programming concepts using sockets and servlets in Java, including: 1. A HTTP request socket program that requests an HTML page from a server and displays the response. 2. An FTP socket program with client and server code that demonstrates a simple file transfer by establishing a connection, specifying a file name, and sending the file character by character. 3. A servlet program that retrieves user details from an XML document by taking a user ID as input. The document contains algorithms, code snippets with comments, and expected outputs for each concept to demonstrate how to implement basic internet programming tasks in Java.

Uploaded by

Ravi Ganesh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 91

SAMPLE LAB MANUAL

INTERNET PROGRAMMING LAB

Prepared By

Mr. R.Ganesh

Private Circulation

[email protected]
Ex No: 1 WEBPAGE CONCEPTS
Date:

a) Create a web page with the following using HTML


a. To embed a map in a web page
b. To fix the hot spots in that map
c. Show all the related information when the hot spots are clicked.

Aim:
To create webpage and embed map and fix the hot spots in that map and show related
information

Algorithm:
1.Start the program embed map in web page
2.Create ImageMap.html file
3.set the source attribute of the image tag to the location of the image & also set the use
map attributes
4..specify an area with name,shape & href set of the appropriate value
5.repeat step4 as many hotspots you want to put into the map.
6.create an html file for each & every hotspot the user will select the particular location
and it shows information about it.

Program:
<!- - Creating and Using Image Maps -->
<!-- ImageMap.html -->
<HTML>
<HEAD>
<TITLE>Image Map</TITLE>
</HEAD>
<BODY>
<MAP id = "picture">
<AREA href = "TamilNadu.html" shape = "circle"
coords = "170, 490, 30" alt = "Tamil Nadu" />
<AREA href = "Karnataka.html" shape = "rect"
coords = "115, 390, 150, 450" alt = "Karnataka" />
<AREA href = "AndhraPradesh.html" shape = "poly"
coords = "165, 355, 200, 355, 220, 380, 170, 425, 165,
355" alt = "Andhra Pradesh" />
<AREA href = "Kerala.html" shape = "poly"
coords = "115, 455, 160, 470, 140, 485, 150, 505, 150,
530, 135, 500, 115, 455" alt = "Kerala" />
</MAP>
<IMG src = "India.Jpg" alt = "India" usemap = "#picture" />
</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>
</BODY>
</HTML>

<!-- AndhraPradesh.html -->


<HTML>
<HEAD>
<TITLE>About Andhra Pradesh</TITLE>
</HEAD>
<BODY>
<CENTER><H1>Andhra Pradesh</H1></CENTER>
<HR>
<UL>
<LI>Area : 2,75,068 Sq. Kms</LI>
<LI>Capital : Hyderabad</LI>
<LI>Language : Telugu</LI>
<LI>Population : 7,57,27,541</LI>
</UL>
</BODY>
</HTML>

<!-- Kerala.html -->


<HTML>
<HEAD>
<TITLE>About Kerala</TITLE>
</HEAD>
<BODY>
<CENTER><H1>Kerala</H1></CENTER>
<HR>
<UL>
<LI>Area : 38,863 Sq. Kms.</LI>
<LI>Capital : Thiruvananthapuram</LI>
<LI>Language : Malayalam</LI>
<LI>Population : 3,18,38,619</LI>
</UL>
</BODY>
</HTML>

<!-- Karnataka.html -->


<HTML>
<HEAD>
<TITLE>About Karnataka</TITLE>
</HEAD>
<BODY>
<CENTER><H1>Karnataka</H1></CENTER>
<HR>
<UL>
<LI>Area : 1,91,791 Sq. Kms</LI>
<LI>Capital : Bangalore</LI>
<LI>Language : Kannada</LI>
<LI>Population : 5,27,33,958</LI>
</UL>
</BODY>
</HTML>

Output:-

Result:
Thus the webpage was created using HTML.
Ex No: 2
Date:
b) Create a web page with the following

a. Cascading style sheets.


b. Embedded style sheets.
c. Inline style sheets. Use our college information for the web pages.

Aim:
To Create a web page about college information using CSS.

Algorithm:
1.create html file with the style tag within the head section.
2.set the style properties such as font-family,font-size,color etc for the heading tag.
3.under the body section specify the headings & the datas required .
4.close all the tags.

Program:
<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;font-style:italic;color:red;text-align:center}
.ani{font-family:tahoma;font-style:italic;font-size: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>APOLLO GROUP OF INSTITUTIONS</b><br><br><br>
<li>AEC
<li>APOLLO Polytechnic college
<li>APOLLO arts and science
<li>APOllO VIDYASHRAM
</ol>
<p style="font-size:20pt;color:purple">MR.PRIYADHARSHAN</p>
<p class="ani">APOLLO Group of colleges is owned by Subramanian <br>It is approved by
AICTE(All India Council for Technical Education).
It is affliated to Anna University.<br></p>
<h2 class="vid"> AEC </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>Ece</li>
<li>mech</li>
<li>eee</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">Harshitha</td>
<td align="center">100</td>
<td align="center">pass</td>
</tr>
<tr>
<td align="center">Natasha</td>
<td align="center">99</td>
<td align="center">pass</td>
</tr>
<tr>
<td align="center">Hanshikah</td>
<td align="center">98</td>
<td align="center">pass</td>
</tr>
</table>
</body>
</html>

xyz.css:

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

Result:

Thus the webpage styles were added using CSS.


Ex No: 3
Date:

c) Create and save an XML document at the server, which contains 10 users Information. Write a
Program, which takes user Id as an input and returns the User details by taking the user
information from the XML document.

Aim:
To write a program which retrieve the user details from the XML document.

Algorithm:
1. The xml document reference to the xsl document
2. Create the user information in the users tag & insert the corresponding relevant information.
3. Close the opened tags

Program:

<!DOCTYPE html>

<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse:collapse;
}
th, td {
padding: 5px;
}
</style>
</head>
<body>
<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","cd_catalog.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.write("<table><tr><th>Artist</th><th>Title</th></tr>");
var x=xmlDoc.getElementsByTagName("CD");
for (i=0;i<x.length;i++)
{
document.write("<tr><td>");
document.write(x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
</script>
</body>
</html>

cd_catalog.xml

<CATALOG>

<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
</CATALOG>

Result:

Thus the user information was retrieved from the XML document.
Ex No: 4 SOCKETS & SERVLETS
Date:

a) Write programs in Java using sockets to implement the following:

i. HTTP request

Aim :
To write a java socket program to demonstrate HTTP Request

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

Program :

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

ii. 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");
writer.flush();
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();
}
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();
}}}

iii. SMTP

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

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

Program :

import java.io.*;
import java.net.Socket;
public class SMTPClient {
public static void main(String[] args) throws Exception {
String results = send("localhost", 25, "[email protected]", "localhost/localdomain",
"Test Email", "<b>You got mail!</b>");
System.out.println(results);
}
public static String send(String host,int port,String from,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)
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;
}
}
}
}

iv. POP3

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

Algorithm :

1.Get the host name, mailbox user name and password


2.Establish the connection with the server
3.Get the number of messages
4.Retrieve a message whose number is specified by the user
5.Repeat steps 3 and 4 until the user enters Q to quit

Program :
import java.io.*;
import java.net.*;
import java.util.*;
public class Pop3ClientDemo
{
protected int port = 110;
protected String hostname = "localhost";
protected String username = "";
protected String password = "";
protected Socket socket;
protected BufferedReader br;
protected PrintWriter pw;
// 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
{
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);
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;
}
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;
}
}

Result:
Thus the HTTP,FTP,SMTP,POP3 were implemented using java socket programming.
Ex No: 5
Date:

b) Write a program in Java for creating simple chat application with datagram sockets and
datagram packets.

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

Algorithm:
1.Start the UDP chat program
2.Import the package java.net.*;
3.Declare the datagramsocket,datagrampacket,BufferedReader,InetAddress.
4.Start the main function
5.In the main function using while loop it perform the loop until str.equals is STOP
6.There important while loop function are
clientsocket = new DatagramSocket(cport);
dp = new DatagramPacket(buf, buf.length);
dis = new BufferedReader(new
InputStreamReader(System.in));
ia = InetAddress.getLocalHost(); f it is stop then break the while loop
7.Terminate the UDP client program

Program:

UDP Chat server

import java.io.*;
import java.net.*;
class UDPServer
{
public static DatagramSocket serversocket;
public static DatagramPacket dp;
public static BufferedReader dis;
public static InetAddress ia;
public static byte buf[] = new byte[1024];
public static int cport = 789,sport=790;
public static void main(String[] a) throws IOException
{
serversocket = new DatagramSocket(sport);
dp = new DatagramPacket(buf,buf.length);
dis = new BufferedReader
(new InputStreamReader(System.in));
ia = InetAddress.getLocalHost();
System.out.println("Server is Running...");
while(true)
{
serversocket.receive(dp);
String str = new String(dp.getData(), 0,
dp.getLength());
if(str.equals("STOP"))
{
System.out.println("Terminated...");
break;
}
System.out.println("Client: " + str);
String str1 = new String(dis.readLine());
buf = str1.getBytes();
serversocket.send(new
DatagramPacket(buf,str1.length(), ia, cport));
}
}}

Output:- UDP Chat Server

C:\IPLAB>javac UDPServer.java
C:\IPLAB>java UDPServer
Server is Running...
Client: HelloWelcomeTerminated...

UDP Chat Client

import java.io.*;
import java.net.*;
class UDPClient
{
public static DatagramSocket clientsocket;
public static DatagramPacket dp;
public static BufferedReader dis;
public static InetAddress ia;
public static byte buf[] = new byte[1024];
public static int cport = 789, sport = 790;
public static void main(String[] a) throws IOException
{
clientsocket = new DatagramSocket(cport);
dp = new DatagramPacket(buf, buf.length) ;
dis = new BufferedReader(new
InputStreamReader(System.in));
ia = InetAddress.getLocalHost();
System.out.println("Client is Running... Type 'STOP'
to Quit");
while(true)
{
String str = new String(dis.readLine());
buf = str.getBytes();
if(str.equals("STOP"))
{
System.out.println("Terminated...");
clientsocket.send(new
DatagramPacket(buf,str.length(), ia,
sport));
break;
}
clientsocket.send(new DatagramPacket(buf,
str.length(), ia, sport));
clientsocket.receive(dp);
String str2 = new String(dp.getData(), 0,
dp.getLength());
System.out.println("Server: " + str2);
}}}

Output:- UDP Chat Client

C:\IPLAB>javac UDPClient.java
C:\IPLAB>java UDPClient
Client is Running... Type ‘STOP’ to Quit
HelloServer: WelcomeSTOP Terminated...

Result:

Thus simple chat application was created using datagram socket and datagram packet.
Ex No: 6
Date:

c) Write programs in Java using Servlets


Aim:
To invoke servlets from HTML forms

Procedure:
Step no Details of the step
Client:
1 In index.jsp on the client side declare the
contents that you like to transfer to the server
using html form and input type tags.
2 create a submit button and close all the
included tags.

Server:
1 In the servlet side using the parameter
request get the stings declared in the client
side (requst.getparameter)
2 Include necessary html coding that helps to
display the content

Program:
Servlet Code:

import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParam extends GenericServlet
{
public void service(ServletRequest request,ServletResponse response) throws ServletExcep-
tion,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();
}}

HTML CODE:
<HTML>
<head> <TITLE>INVOKING SERVLET FROM HTML</TITLE> </head>
<BODY> <CENTER>
<FORM name = "PostParam" method = "Post" action="http://localhost:8080/servlets-
examples/servlet/PostParam">
<TABLE> <tr> <td><B>Employee </B> </td>
<td><input type = "textbox" name="ename" size="25" value=""></td> </tr>
<tr> <td><B>Phone </B> </td> <td><input type = "textbox" name="phoneno" size="25"
value=""></td> </tr> </TABLE>
<INPUT type = "submit" value="Submit">
</FORM>
</CENTER>
</body>
</html>
ii. To invoke servlets from Applets

Aim:
To invoke servlets from Applet

Algorithm:
1.Start the Invoking Servlets from Applet
2.Create the Ats.html
3.Use the one input type for roll no
4.When submit button is click it perform the
action=http://localhost:8080/Student/Student
5.The save as the Ats.html
6.Then create java coding for AppletToServlet.java
7.In coding create three important objects Label sent and received and button click to
send to servlets.
8.Set the url as http://localhost:8080"+"/servlet/ServletToApple
9.Then create java coding for ServletToApplet.java and Intermediate.java (see the source
code)
10.Finally save and run the program
Note important files are Ats.html ,Applettoservlet.java ,servlets to applet.java and
Intermediate .java

Program:

Source code in Html invoking Servlets from Applets

<!—Ats.html -->
<HTML>
<BODY>
<CENTER>
<FORM name = "students" method = "post"
action="http://localhost:8080/Student/Student">
<TABLE>
<tr>
<td><B>Roll No. </B> </td>
<td><input type = "textbox" name="rollno" size="25"
value=""></td>
</tr>
</TABLE>
<INPUT type = "submit" value="Submit">
</FORM>
<CENTER>
</BODY>
</HTML>
Source code in java programming Invoking Servlets from Applets –

AppletToServlet.java

import java.io.*;
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.net.*;
/* <applet code="AppletToServlet" width="300"
height="300"></applet> */
public class AppletToServlet extends Applet implements
ActionListener {
TextField toSend;
TextField toGet;
Label l1;
Label l2;
Button send;
Intermediate s;
String value;
ObjectInputStream is;
ObjectOutputStream os;
public void init(){
toSend=new TextField(10);
add(toSend);
toGet=new TextField(10);
add(toGet);
l1=new Label("value sent");
l2=new Label("value received");
add(l1);
add(l2);
send=new Button("Click to send to servlet");
send.addActionListener(this);
add(send);
validate();
s=new Intermediate();
}
public void actionPerformed(ActionEvent e){
value=toSend.getText();
sendToServlet();
}
public void sendToServlet(){
try
{
URL url=new
URL("http://localhost:8080"+"/servlet/ServletToApple
t");
URLConnection con=url.openConnection();
s.setFname(value);
writeStuff(con,s);
s=new Intermediate();
Intermediate p=readStuff(con);
if(p!=null){
value=p.getFname();
toGet.setText("value:"+value);
validate();
}
}
catch(Exception e){
System.out.println(e);
}
}
public void writeStuff(URLConnection connection, Intermediate
value){
try{
connection.setUseCaches(false);
connection.setRequestProperty("CONTENT_TYPE",
"application/octet-stream");
connection.setDoInput(true);
connection.setDoOutput(true);
os=new
ObjectOutputStream(connection.getOutputStream());
os.writeObject(value);
os.flush();
os.close();
}
catch(Exception y){}
}
public Intermediate readStuff(URLConnec tion connection){
Intermediate s=null;
try{
is=new
ObjectInputStream(connection.getInputStream());
s=(Intermediate)is.readObject();
is.close();
}
catch(Exception e){}
return s;
}
}

Source code in java programing Invoking Servlets from Applets –


ServletToApplet.java

import java.util.*;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
public class ServletToApplet extends HttpServlet
{
String valueGotFromApplet;
public void init(ServletConfig config) throws
ServletException
{
System.out.println("Servlet entered");
super.init();
}
public void service(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
{
try
{
System.out.println("service entered");
ObjectInputStream ois=new
ObjectInputStream(request.getInputStream()
);
Intermediate ss=(Intermediate)ois.readObject();
valueGotFromApplet=ss.getFname();
System.out.println(valueGotFromApplet);
response.setContentType("application/octetstream");
ObjectOutputStream oos=new
ObjectOutputStream(response.getOutputStream());
oos.writeObject(ss);
oos.flush();
oos.close();
}
catch(Exception e){System.out.println(e);}
}
public String getServletInfo()
{
return "...";
}
}

Source code in java programing Invoking Servlets from Applets –


Intermediate.java

import java.io.*;
public class Intermediate implements Serializable{
String fname;
public String getFname(){
return fname;
}
public void setFname(String s){
fname=s;
}
}
D:\servlet\WEB-INF\classes>javac Intermediate.java
D:\servlet\WEB-INF\classes>javac AppletToServlet.java
D:\servlet\WEB-INF\classes>javac ServlettoApplet.java
D:\servlet\WEB-INF>type web.xml

<?xml version="1.0" encoding="ISO -8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Applicatio n
2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<!-- JSPC servlet mappings start -->
<servlet>
<servlet-name>ServletToApplet</servlet-name>
<servlet-class>ServletToApplet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletToApplet</servlet-name>
<url-pattern>/ServletToApplet</url-pattern>
</servlet-mapping>
<!-- JSPC servlet mappings end -->
</web-app>

D:\servlet>jar -cvf ServletToApplet.war .


added manifest
adding: ats.html(in = 97) (out= 76)(deflated 21%)
adding: WEB-INF/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/classes/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/classes/AppletToServlet.class(in = 3055) (out=1627)(def lated 46%)
adding: WEB-INF/classes/AppletToServlet.java(in = 1952) (out=776)(deflated 60%)
adding: WEB-INF/classes/Intermediate.class(in = 433) (out=273)(deflated 36%)
adding: WEB-INF/classes/Intermediate.java(in = 188) (out=126)(deflated 32%)
adding: WEB-INF/classes/ServletToApplet.class(in = 1660) (out=859)(deflated 48%)
adding: WEB-INF/classes/ServletToApplet.java(in = 975) (out=424)(deflated 56%)
adding: WEB-INF/web.xml(in = 698) (out= 315)(deflated 54%)
Step 1: Open Web Browser and type
Step 2: http://localhost:8080
Step 3: Select Tomcat Manager
Step 4: Deploy the war file and Run

OUTPUT of Servelet HTMl APPLET:

Result:
Thus the servlet was invoked using HTML forms and applet.
Ex No: 7
Date:

d) Write programs in Java to create three-tier applications using servlets for conducting on-line
examination for displaying student mark list. Assume that student information is available in a
database which has been stored in a database server.

Aim :
To implement the three-tier application using servlets to display Student mark list perform
by the jdbc:odbc connection.

Algorithm:
1.Start the three-tier application in servlets
2.Create the student.html
3.Use the Form post method
4.In the Form when click submit it is link to http://localhost:8080/Student/Student
5.Use the textbox get the student Roll no
6.Then create java coding Student.java for getting the data from the database
7.Use jdbc:odbc:Student connect to the database
8.And list out the data
9.Finally terminate the program for three -tier application inservlet
Note important files:
Student.html ,student.java,web.xml,student.war

Program:
Source code in html programming three tier application using servlets Displaying
Student Details

<!—Student.html -->
<HTML>
<BODY>
<CENTER>
<FORM name = "students" method = "post"
action="http://localhost:8080/Student/Student">
<TABLE>
<tr>
<td><B>Roll No. </B> </td>
<td><input type = "textbox" name="rollno" size="25"
value=""></td>
</tr>
</TABLE>
<INPUT type = "submit" value="Submit">
</FORM>
<CENTER>
</BODY>
</HTML>

Source code in java programming connection to the database using jdbc.odbc

import javax.servlet.http.*;
import java.io.*;
import javax.servlet.*;
import java.sql.*;
public class Student extends HttpServlet {
Connection dbConn ;
public void doPost(HttpServletRequest req,
HttpServletResponse res)
throws IOException, ServletException
{
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
dbConn =
DriverManager.getConnection("jdbc:odbc:Stud ent","","") ;
}
catch(ClassNotFoundException e)
{
System.out.println(e);
}
catch(Exception e)
{
System.out.println(e);
}
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String mrollno = req.getParameter("rollno") ;
try {
PreparedStatement ps =
dbConn.prepareStatement("select * from stud where
rollno = ?") ;
ps.setString(1, mrollno) ;
ResultSet rs = ps.executeQuery() ;
out.println("<html>");
out.println("<body>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("<body>");
out.println("<table border = 1>");
while(rs.next())
{
out.println("<tr><td>Roll No. : </td>");
out.println("<td>" + rs.getString(1) +
"</td></tr>");
out.println("<tr><td>Name : </td>");
out.println("<td>" + rs.getStri ng(2) +
"</td></tr>");
out.println("<tr><td>Branch : </td>");
out.println("<td>" + rs.getString(3) +
"</td></tr>");
out.println("<tr><td>10th Mark : </td>");
out.println("<td>" + rs.getString(4) +
"</td></tr>");
out.println("<tr><td>12th Mark : </td>");
out.println("<td>" + rs.getString(5) +
"</td></tr>");
}
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
catch (Exception e)
{
System.out.println(e);
}
}
}

Database Structure �� Student.mdb


Records
D:\Student\WEB-INF\classes>javac Student.java
D:\PostParam\WEB-INF>type 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>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<!-- JSPC servlet mappings start -->
<servlet>
<servlet-name>Student</servlet -name>
<servlet-class>Student</servlet -class>
</servlet>
<servlet-mapping>
<servlet-name>Student</servlet -name>
<url-pattern>/Student</url-pattern>
</servlet-mapping>
<!-- JSPC servlet mappings end -->
</web-app>

D:\PostParam>jar –cvf Student.war .


D:\Student>jar -cvf Student.war .
added manifest
adding: Student.html(in = 299) (out= 204)(deflated 31%)
adding: WEB-INF/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/classes/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/classes/Student.class(in = 2658) (out=
1358)(deflated 48%)
adding: WEB-INF/classes/Student.java(in = 1849) (out=
636)(deflated 65%)
adding: WEB-INF/classes/Student.mdb(in = 139264) (out=
7251)(deflated 94%)
adding: WEB-INF/web.xml(in = 666) (out= 312)(deflated 53%)
Step 1: Create ODBC connection for the database
Step 2: Open Web Browser and type
Step 3: http://localhost:8080
Step 4: Select Tomcat Manager
Step 5: Deploy the war file and Run
ii) Aim:

To implement the three-tier application using servlets to display Student mark list perform
by the jdbc:odbc connection.

Algorithm:

1. In the html program,define the html,head and title tag


2. Then the title is student information form and table simultaneously
3. Define the body tag inside create form and table simultaneously
4. The table consist of following information roll no, name,address, phone number and total marks.
5. In the service method,define request and response.
6. Create the object for printer writer and getwriter() value
7. The enumeration object get the servlet request parameter
8. Create object for string methods and it is displayed another object value received get parameter of
name received and displayed the value received

Program:

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;
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletExcep-
tion,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"+") VAL-
UES('"+Seat_no+"','"+Name+"','"+Total+"')";
int result=stmt.executeUpdate(query);
stmt.close();
}catch(SQLException ex){ } 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");
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:

<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 destina-tion</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>

Result:

Thus three-tier architecture was created using servlets.


Ex No: 8
Date:

e) Write a program to lock servlet itself to a particular server IP address and port number. It
requires an init parameter key that is appropriate for its servlet IP address and port before it
unlocks itself and handles a request

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

Algorithm:
1. This servlet has no class or instance variables.
2. The piracy check shouldn't be done in init.
3. Name/port are part of request.
4. Check if the init parameter "key" unlocks this server.
5. This method contains the algorithm used to match a key with a server host and port.

Program:

import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;

public class KeyedServerLock extends GenericServlet {

// This servlet has no class or instance variables


// associated with the locking, so as to simplify
// synchronization issues.

public void service(ServletRequest req, ServletResponse res)


throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();

// The piracy check shouldn't be done in init


// because name/port are part of request.
String key = getInitParameter("key");
String host = req.getServerName();
int port = req.getServerPort();

// Check if the init parameter "key" unlocks this server.


if (! keyFitsServer(key, host, port)) {
// Explain, condemn, threaten, etc.
out.println("Pirated!");
}
else {
// Give 'em the goods
out.println("Valid");
// etc...
}
}
// This method contains the algorithm used to match a key with
// a server host and port. This example implementation is extremely
// weak and should not be used by commercial sites.
//
private boolean keyFitsServer(String key, String host, int port) {

if (key == null) return false;

long numericKey = 0;
try {
numericKey = Long.parseLong(key);
}
catch (NumberFormatException e) {
return false;
}

// The key must be a 64-bit number equal to the logical not (~)
// of the 32-bit IP address concatenated with the 32-bit port number.

byte hostIP[];
try {
hostIP = InetAddress.getByName(host).getAddress();
}
catch (UnknownHostException e) {
return false;
}

// Get the 32-bit IP address


long servercode = 0;
for (int i = 0; i < 4; i++) {
servercode <<= 8;
servercode |= hostIP[i];
}

// Concatentate the 32-bit port number


servercode <<= 32;
servercode |= port;

// Logical not
long accesscode = ~numericKey;

// The moment of truth: Does the key match?


return (servercode == accesscode);
}
}

Result:

Thus the servlet was locked itself to a particular server ip address and port number..
Ex No: 9
Date:
f) Session tracking using hidden form fields and Session tracking for a hit count

Aim:
To write a java program for session tracking using hidden form fields and session tracking for a hit count.

Algorithm:
1. Get the current session object, create one if necessary.
2. Increment the hit count for this page. The value is saved in this client's session under the name
"tracker.count".
3. Display the hit count for this page.

Program:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ShoppingCartViewerHidden extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>");
out.println("<BODY>");

// Cart items are passed in as the item parameter.


String[] items = req.getParameterValues("item");

// Print the current cart items.


out.println("You currently have the following items in your cart:<BR>");
if (items == null) {
out.println("<B>None</B>");
}
else {
out.println("<UL>");
for (int i = 0; i < items.length; i++) {
out.println("<LI>" + items[i]);
}
out.println("</UL>");
}

// Ask if the user wants to add more items or check out.


// Include the current items as hidden fields so they'll be passed on.
out.println("<FORM METHOD=GET>"); // submit to self
if (items != null) {
for (int i = 0; i < items.length; i++) {
out.println("<INPUT TYPE=HIDDEN NAME=item VALUE=\"" +
items[i] + "\">"); }
}
out.println("Would you like to<BR>");
out.println("<INPUT TYPE=SUBMIT VALUE=\" Add More Items \">");
out.println("<INPUT TYPE=SUBMIT VALUE=\" Check Out \">");
out.println("</FORM>");
out.println("</BODY></HTML>");
}}

Program:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SessionTracker extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();

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


HttpSession session = req.getSession(true);

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

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

// Display the hit count for this page


out.println("You've visited this page " + count +
((count.intValue() == 1) ? " time." : " times."));

out.println("<P>");

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


String[] names = session.getValueNames();
for (int i = 0; i < names.length; i++) {
out.println(names[i] + ": " + session.getValue(names[i]) + "<BR>");
}
out.println("</BODY></HTML>");
}
}

Result:
Thus the java program for session tracking using hidden form fields and session tracking for a hit count
were implemented.
Ex No: 10
Date:

g) Install TOMCAT web server. Convert the static webpages of programs 1&2 into dynamic web
pages using servlets (or JSP) and cookies. Hint: Users information (user id, password, credit card
number) would be stored in web.xml. Each user should have a separate Shopping Cart.

Aim:
To install Tomcat web server and then write servlet program to convert static webpages into dynamic
webpages.

Procedure:
1) First install the tomcat in to the system.
2) Then make a subdirectory (e.g. tr) in the \tomcat\webapps
3) Under tr create WEB-INF directory and also place the html files in this tr directory only.
4) Next under WEB-INF create two subclasses lib,classes and web.xml
5) Next place all the class files under the classes and jar files(servlet-api.jar , classes12.jar etc..) under
lib subdirectories.
6) After this start tomcat by giving the following command at the instll_dir>tomcat>bin
Catalina.bat run
7) at the I.E(web browser) give the url as http://localhost:8080//tr/htmlfile or servlet url pattern
portno 8080 is assigned for the tomcat

Program:

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>

<servlet>

<servlet-name>order</servlet-name>

<servlet-class>order</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>order</servlet-name>

<url-pattern>/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:

<html>

<body bgcolor="pink">

<br><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;<input


type="reset" value="clear" >

</form>

</body>

</html>

reg.html:

<html>

<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;<input


type="reset" value="clear">

</form>

</body>

</html>

profile.html:

<html>

<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;<input


type="reset" value="clear" >

</form>

</body></html>

catalog.html:

<html>

<body bgcolor="pink"><br><br><br>

<form action="/tr/catalog" method="post">

<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;<input


type="reset" value="clear" name="button2">

</form>

</body>

</html>

order.html:

<html>

<body bgcolor="pink"><br><br><br>

<form action="/tr/order" method="post">

<div align="center"><pre>

LOGIN ID : <input type="text" name="id"><br>

PASSWORD : <input type="password" name="pwd"><br>

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;<input


type="reset" value="clear" name="button2">

</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.getParameter("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.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/login.html\">press LOGIN to RETRY</a>");

else

pw.println(" VALID LOGIN ID<br><br>");

pw.println("<h3><ul>");

pw.println("<li><a href=\"profile.html\"><font color=\"black\">USER


PROFILE</font></a></li><br><br>");

pw.println("<li><a href=\"catalog.html\"><font color=\"black\">BOOKS


CATALOG</font></a></li><br><br>");

pw.println("<li><a href=\"order.html\" ><font color=\"black\">ORDER


CONFIRMATION</font></a></li><br><br>");

pw.println("</ul>");

pw.println("</body></html>");

catch(Exception e)

resp.sendError(500,e.toString());
}

reg.java:

import java.sql.*;

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class reg 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.getParameter("name");

String addr=req.getParameter("addr");

String phno=req.getParameter("phno");

String id=req.getParameter("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 from login";

ResultSet rs=stmt.executeQuery(sqlstmt);

int flag=0;

while(rs.next())

if(id.equals(rs.getString(1)))

flag=1;

if(flag==1)

pw.println("SORRY LOGIN ID ALREADY EXISTS 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("insert into login


values('"+name+"','"+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());

catalog.java:

import java.sql.*;

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class catalog 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 * from book where title='"+title+"'";

ResultSet rs=stmt.executeQuery(sqlstmt);

int flag=0;

pw.println("<br><br><br>");

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 profile 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.getParameter("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 order 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.getParameter("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 <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("insert into odetails


values('"+id+"','"+title+"',"+amount+",'"+date+"','"+cno+"')");

pw.println(" YOUR ORDER has taken<br>");

if(flag1==0)
{

pw.println("SORRY INVALID BOOK TRY AGAIN <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());

OUTPUTS:
Result:
Thus the static webpages were converted into dynamic webpages.
Ex No: 11 ADVANCE CONCEPTS
Date:

a) Implement a simple program using following frameworks


a. JSP Struts Framework b. Hibernate c. Spring

Aim:

To Implement the “Hello World!” program using JSP Struts Framework.

Procedure:

Step 1:

In tomcat install directory

Open tomcat/webapps

Create a subdirectory (ts)

Copy the struts-blank.war file

At that directory path in cmd give the command as

Jar xvf struts-blank.war

Step 2:

create a directory (work in e:\) and copy struts.jar,servlet-api.jar into work d directory. Then set

the classpath as

set classpath=struts.jar;servlet-api.jar;

then copy the ActionOne.class file to webapps/ts/WEB-INF/classes

Program:

ActionOne.java:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import org.apache.struts.action.*;

public class ActionOne extends Action


{

public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest


request,HttpServletResponse response)throws Exception

System.out.println("----Action executed------");

PrintWriter pw=response.getWriter();

pw.println("HELLO WORLD");

return null;

step 3:

struts-config.xml file

<?xml version="1.0" encoding="UTF-8"?>

< struts-config>

<action-mappings>

<action path="/xxx" type="ActionOne"/>

</action-mappings>

</struts-config>

Step 4:

web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app>

<servlet>

<servlet-name>action</servlet-name>

<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

<init-param>
<param-name>config</param-name>

<param-value>/WEB-INF/struts-config.xml</param-value>

</init-param>

<init-param>

<param-name>debug</param-name>

<param-value>2</param-value>

</init-param>

<init-param>

<param-name>detail</param-name>

<param-value>2</param-value>

</init-param>

<load-on-startup>2</load-on-startup>

</servlet>

<!-- Standard Action Servlet Mapping -->

<servlet-mapping>

<servlet-name>action</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

<!-- The Usual Welcome File List -->

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

<!-- Struts Tag Library Descriptors -->

<taglib>

<taglib-uri>/tags/struts-bean</taglib-uri>

<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>

</taglib>
<taglib>

<taglib-uri>/tags/struts-html</taglib-uri>

<taglib-location>/WEB-INF/struts-html.tld</taglib-location>

</taglib>

<taglib>

<taglib-uri>/tags/struts-logic</taglib-uri>

<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>

</taglib>

<taglib>

<taglib-uri>/tags/struts-nested</taglib-uri>

<taglib-location>/WEB-INF/struts-nested.tld</taglib-location>

</taglib>

<taglib>

<taglib-uri>/tags/struts-tiles</taglib-uri>

<taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>

</taglib>

</web-app>

step 5:

then in I.E give the url as

http://localhost:8080/ts/xxx.do

Outputs:
springconfig.xml
?
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE beans PUBLIC
3 "-//SPRING//DTD BEAN//EN"
4 "http://www.springframework.org./dtd/spring-beans.dtd">
5 <beans>
6 <bean id="mybean" class="Inject">
7
8 <property name="name">
9 <value>mathan</value>
10 </property>
11 <property name="age">
12 <value>25</value>
13 </property>
14 <property name="company">
15 <value>C I T</value>
16 </property>
17 <property name="email">
18 <value>[email protected]</value>
19 </property>
20 <property name="address">
21 <value>1103760000</value>
22 </property>
23 </bean>
24
25 </beans>

Main.java
?
1 import org.springframework.beans.factory.xml.XmlBeanFactory;
2 import org.springframework.core.io.ClassPathResource;
3
4 public class Main {
5
6 public static void main(String[] args) {
7 XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
8 "springconfig.xml"));
9 Inject demo = (Inject) beanFactory.getBean("mybean");
10
11 System.out.println(demo);
12 }
13 }

Inject.java

?
1 class Inject {
2
3 private String name;
4 private int age;
5 private String company;
6 private String email;
7 private String address;
8
9 public void setAddress(String address) {
10 this.address = address;
11 }
12
13 public void setCompany(String company) {
14 this.company = company;
15 }
16
17 public void setEmail(String email) {
18 this.email = email;
19 }
20
21 public void setAge(int age) {
22 this.age = age;
23 }
24
25 public void setName(String name) {
26 this.name = name;
27 }
28
29 public String toString() {
30 return "Name :" + name + "\n" + "Age:" + age + "\n" + "Company: "
31 + company + "\n" + "E-Mail: " + email + "\n" + "Address: "
32 + address;
33 }
34 }

Output:

Algorithm
Step by Step tutorial on running your SimpleProgram Hibernate application with Eclipse IDE
Step – 1 Creating Dynamic web 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
• This application we will used to insert the data’s in database like sql,oracle,DB2 and etc.
• Here We will see how to save the data’s in oracle database .
Step – 1 Creating Dynamic web Project:
Start Eclipse and goto File -> New -> Project -> Dynamic Web Project

Step – 2 SimpleProgram Hibernate Project structure:


Project Structure:

Step – 3 Adding Jar Files:


JAR Files:

Step – 4 Creating your SimpleProgram Hibernate program(Controller & Pojo):


AddStudent.java:

?
1 package com.candidjava;
2
3 public class AddStudent {
4 public static void main(String[] args) {
5 try {
6 AddStudentControl ctrl = new AddStudentControl();
7 ctrl.addNewStudent(args);
8 } catch (Exception e) {
9 System.out.println(e.getMessage());
10 }
11 }
12 }
AddStudentControl.java:
Here we will use sessionFactory for create connetion Oracle database.

sessionFactory = new
Configuration().configure(“com\\xml\\hibernate.cfg.xml”).buildSessionFactory();
• Then we will create objects for pojo classes and then save the database using session.

Student stu=new Student();


s.save(stu);
• Then we will use Transaction statement for begin and commit the database.

Transaction tx= s.beginTransaction();


tx.commit();

package com.candidjava;

import java.sql.*;
import java.io.*;
import org.hibernate.*;
import org.hibernate.cfg.*;

public class AddStudentControl {

private static SessionFactory sessionFactory;

private Session getSession() {


Session s = null;
try {
sessionFactory = new Configuration().configure(
"com\\xmlFiles\\hibernate.cfg.xml").buildSessionFactory();
s = sessionFactory.openSession();
} catch (HibernateException e) {
System.out.println(e.getMessage());
}
return s;
}
public void addNewStudent(String[] args) throws Exception {
try {
Session s = getSession();
Transaction tx = s.beginTransaction();
Student stu = new Student();
DataInputStream ds = new DataInputStream(System.in);
System.out.println("*********************\n");
System.out.println("Enter the Student Id");
String stuid = ds.readLine();
System.out.println("Enter the Student RegNo");
String sturegno = ds.readLine();
System.out.println("Enter the Student name");
String stuname = ds.readLine();
System.out.println("Enter the Student mark1");
String stumark1 = ds.readLine();
System.out.println("Enter the Student mark2");
String stumark2 = ds.readLine();
System.out.println("Enter the Degree");
String degree = ds.readLine();
System.out.println("Enter the mobile No");
String mobileno = ds.readLine();
System.out.println("Enter the Student mail Id");
String mailid = ds.readLine();

stu.setStuid(stuid);

stu.setSturegno(sturegno);
stu.setStuname(stuname);
stu.setStumark1(stumark1);
stu.setStumark2(stumark2);
stu.setStuid(stuid);
stu.setDegree(degree);
stu.setMobileno(mobileno);
stu.setMailid(mailid);
s.save(stu);
tx.commit();
System.out.println("\n\n Details Added \n");
} catch (HibernateException e) {
System.out.println("error1" + e.getMessage());
System.out.println("error1");
}

}}// end of class


Student.java:
• It is a Pojo class. This class Must be a Serializable. Then here we will use get and set method.
private long id;
public long getId() {return id;}
public void setId(long String) {id = String;}
package com.candidjava;

import java.io.*;
public class Student implements Serializable {
private long id;
private String stuid;
private String sturegno;
private String stuname;
private String stumark1;
private String stumark2;
private String degree;
private String mobileno;
private String mailid;

public long getId() {


return id;
}

public String getStuid() {


return stuid;
}

public String getSturegno() {


return sturegno;
}

public String getStuname() {


return stuname;
}

public String getStumark1() {


return stumark1;
}

public String getStumark2() {


return stumark2;
}

public String getDegree() {


return degree;
}

public String getMobileno() {


return mobileno;
}

public String getMailid() {


return mailid;
}

public void setId(long string) {


id = string;
}

public void setStuid(String string) {


stuid = string;
}

public void setSturegno(String string) {


sturegno = string;
}

public void setStuname(String string) {


stuname = string;
}

public void setStumark1(String string) {


stumark1 = string;
}

public void setStumark2(String string) {


stumark2 = string;
}

public void setDegree(String string) {


degree = string;
}

public void setMobileno(String string) {


mobileno = string;
}

public void setMailid(String string) {


mailid = string;
}

Step – 5 Creating hibernate.cfg.xml:


hibernate.cfg.xml:

<property name=”connection.driver_class”> oracle.jdbc.OracleDriver</property>


Here we will use this property for load the driver in oracle database
<property name=”connection.url”> jdbc:oracle:thin:@localhost:1521:XE</property>
Then this property will use for open connetion inoracle database.

<property name=”connection.username”> system</property>


This property will use for username in oracle database.

<property name=”connection.password”> system</property>


This property will use for password in oracle database

<property name=”dialect”> org.hibernate.dialect.OracleDialect </property>


Here we will use oracle Dialect for generating query.

?
<!DOCTYPE hibernate-configuration PUBLIC
"-//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">false</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="\com\\xmlFiles\\Student.hbm.xml" />
</session-factory>
</hibernate-configuration>

Step – 6 Creating Student.hbm.xml:


Student.hbm.xml:

<class name=”com.candidjava.Student” table=”student” >


This tag will use for mapping Pojo class name and table name.

<id name=”id” type=”long” column =”ID”><generator class=”increment”/></id>


This tag will use for generating primary key id and also increment the id value.

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


This property will use for mapping the pojo class veriable name(name=”name” ) and table attribute
name(column=”name”).

</class>”/>
End of the class.

?
<?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="Student2">
<id name="id" type="long" column="Id">
<generator class="increment" />
</id>
<property name="stuid" column="StuId" not-null="true" />
<property name="sturegno" column="StuRegNO" />
<property name="stuname" column="StuName" />
<property name="stumark1" column="StuMark1" />
<property name="stumark2" column="StuMark2" />
<property name="degree" column="Degree" />

<property name="mobileno" column="MobileNo" />


<property name="mailid" column="MailId" />
</class>
</hibernate-mapping>
web.xml:
?
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>HibernateSaveQuery</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list></web-app>
OUTPUT:
Step – 7 OutPut for Running Console hiberanate application:
Step 8 OutPut for Running Oracle hibernate application:
Result:
Thus the simple program using Struts, Hibernate and Spring frameworks were implemented.
Ex No: 12
Date:

b) Explore the following application in AJAX: Searching in real time with live searches, Getting the
answer with auto complete, Chatting with friends ,Dragging and dropping with Ajax, Getting
instant login feedback, Ajax-enabled popup menus, Modifying Web pages on the fly.

Aim:

To write a program using AJAX for displaying cricket players profile.

Algorithm:

1. Create an XHTML document (AjaxDemo.html) with the following.

o Insert some images of cricket players.

o Call the function getContent() with respect to the onmouseover event. The function
accepts an argument that is the URL of another page contains the information about the
player.

o Call the function clearContent() with respect to the onmouseout event.

2. Within this XHTML document, insert AJAX based JavaScript code with the following.

o Create the object for ActiveXObject (for older versions of browsers such as IE5 and IE6).

o Create the object for XMLHttpRequest (for modern browsers such as IE7+, Firefox,
Chrome, Safari, and Opera).

o AJAX send the request with the use of send() and open() methods.

o Receive the response with the use of responseText Property.

o AJAX Call the function diplayProfile() with respect to the event onreadystatechange.

Program:
AjaxDemo.html

<html>
<head>
<title>Ajax Demo...</title>
<style type="text/css">
.box{border:1px solid blue;padding:10px}
</style>
<script type="text/javascript">
var req;
function getContent(url)
{
if(window.ActiveXObject)
{
req=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
req=new XMLHttpRequest();
}
req.onreadystatechange=diplayProfile;
req.open('POST',url,true);
req.send(null);
}
function diplayProfile()
{
if(req.readyState==4)
{
document.getElementById('contentArea').innerHTML=req.responseText;
}
}
function clearContent()
{
document.getElementById('contentArea').innerHTML='';
}
</script>
</head>
<body bgcolor="cyan">
<h1>Mouse over the image for More Information</h1>
<img src="sachin.jpg" height="95" width="80" onmouseover='getContent("sachin.html")'
onmouseout='clearContent()'/>
<img src="dravid.jpg" height="95" width="80" onmouseover='getContent("dravid.html")'
onmouseout='clearContent()'/>
<img src="dhoni.jpg" height="95" width="80" onmouseover='getContent("dhoni.html")'
onmouseout='clearContent()'/>
<img src="kohli.jpg" height="95" width="80" onmouseover='getContent("kohli.html")'
onmouseout='clearContent()'/>
<img src="raina.jpg" height="95" width="80" onmouseover='getContent("raina.html")'
onmouseout='clearContent()'/>
<img src="yuvi.jpg" height="95" width="80" onmouseover='getContent("yuvi.html")'
onmouseout='clearContent()'/>
<img src="veeru.jpg" height="95" width="80" onmouseover='getContent("veeru.html")'
onmouseout='clearContent()'/>
<div class="box" id="contentArea"/>
</body>
</html>

sachin.html

<html>
<body>
<b>Full name:</b> Sachin Ramesh Tendulkar<br/><br/>
<b>Born:</b> April 24, 1973, Bombay (now Mumbai), Maharashtra<br/><br/>
<b>Major teams:</b> India, Asia XI, Mumbai, Mumbai Indians, Yorkshire<br/><br/>
<b>Nickname:</b> Tendlya, Little Master<br/><br/>
<b>Playing role:</b> Top-order batsman<br/><br/>
<b>Batting style:</b> Right-hand bat<br/><br/>
<b>Bowling style:</b> Right-arm offbreak, Legbreak googly
</body></html>

dravid.html

<html>
<body>
<b>Full name:</b> Rahul Sharad Dravid<br/><br/>
<b>Born:</b> January 11, 1973, Indore, Madhya Pradesh <br/><br/>
<b>Major teams:</b> India, Scotland, Asia XI, ICC World XI, Karnataka, Kent,
Marylebone Cricket Club, Rajasthan Royals, Royal Challengers Bangalore<br/><br/>
<b>Nickname:</b> The Wall<br/><br/>
<b>Playing role:</b> Top-order batsman<br/><br/>
<b>Batting style:</b> Right-hand bat<br/><br/>
<b>Bowling style:</b> Right-arm offbreak
</body>
</html>

dhoni.html

<html>
<body bgcolor="cyan">
<b>Full name:</b> Mahendra Singh Dhoni<br/><br/>
<b>Born:</b>July 7, 1981, Ranchi, Bihar (now Jharkhand)<br/><br/>
<b>Major teams:</b>India, Asia XI, Bihar, Chennai Super Kings, Jharkhand<br/><br/>
<b>Playing role:</b>Wicketkeeper batsman<br/><br/>
<b>Batting style:</b>Right-hand bat<br/><br/>
<b>Bowling style:</b>Right-arm medium
</body>
</html>

kohli.html

<html>
<body>
<b>Full name:</b> Virat Kohli<br/><br/>
<b>Born:</b>November 5, 1988, Delhi<br/><br/>
<b>Major teams:</b>India, Delhi, India Red, India Under-19s, Royal Challengers Bangalore<br/><br/>
<b>Playing role:</b>Middle-order batsman<br/><br/>
<b>Batting style:</b>Right-hand bat<br/><br/>
<b>Bowling style:</b>Right-arm medium
</body>
</html>
raina.html

<html>
<body>
<b>Full name:</b> Suresh Kumar Raina<br/><br/>
<b>Born:</b>November 27, 1986, Muradnagar, Ghaziabad, Uttar Pradesh<br/><br/>
<b>Major teams:</b>India, Chennai Super Kings, India Blue, India Under-19s, Indian Board President's
XI, Rajasthan Cricket Association President's XI, Uttar Pradesh, Uttar Pradesh Under-16s<br/><br/>
<b>Playing role:</b>Middle-order batsman<br/><br/>
<b>Batting style:</b>Left-hand bat<br/><br/>
<b>Bowling style:</b> Right-arm offbreak
</body>
</html>

yuvi.html

<html>
<body>
<b>Full name:</b>Yuvraj Singh<br/><br/>
<b>Born:</b>December 12, 1981, Chandigarh<br/><br/>
<b>Major teams:</b>India, Asia XI, Kings XI Punjab, Pune Warriors, Punjab, Yorkshire<br/><br/>
<b>Playing role:</b>Middle-order batsman<br/><br/>
<b>Batting style:</b>Left-hand bat<br/><br/>
<b>Bowling style:</b>Slow left-arm orthodox
</body>
</html>

veeru.html

<html>
<body>
<b>Full name:</b>Virender Sehwag<br/><br/>
<b>Born:</b>October 20, 1978, Delhi<br/><br/>
<b>Major teams:</b>India, Asia XI, Delhi, Delhi Daredevils, ICC World XI, India Blue, Leicestershire,
Rajasthan Cricket Association President's XI<br/><br/>
<b>Playing role:</b>Top-order batsman<br/><br/>
<b>Batting style:</b>Right-hand bat<br/><br/>
<b>Bowling style:</b>Right-arm offbreak
</body>
</html>

Procedure:
Step no. Details of the step
1 Start the Program
2 Enter the chemistry element in
index.html
3 Read the element data by
request.getParameter() on chems.jsp.
4 Check given element in element list.
5 Display the definition of given
element.
6 Stop the Program

Program:
Chems.html

<html> <head>
<script type="text/javascript">
function loadXMLDoc()
{ var xmlhttp;
var data = (t1.value);
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} xmlhttp.onreadystatechange=function()
{ if (xmlhttp.readyState==4 && xmlhttp.status==200)
{ document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}}
xmlhttp.open("GET","chems.jsp?t1="+data,true); xmlhttp.send();
}
</script>
</head>
<body> <table> <tr><td witdh=150> Enter the Chem Name : </td>
<td> <Input type=text name=t1 ></td> </tr>
<tr><td witdh=150> Chem Name : </td>
<td> <div id="myDiv"></div></td> </tr>
<tr><td> <button type="button" onClick="loadXMLDoc()">Change Content</button></td> </tr>
</table> </body> </html>

chems.jsp

<% String d=request.getParameter("t1");


String[]name;
int i=0,n=0;
name=new String[10];
name[0]="atomic number";
name[1]="catalyst";
name[2]="acid";
name[3]="base";
name[4]="bond energy";
name[5]="chain reactons";
name[6]="covalent bonds";
name[7]="element";
name[8]="enzyme";
name[9]="kinetics";
String[] defn;
defn=new String[10];
defn[0]="It is defined as the number of protons or electrons.";
defn[1]="a catalyst is a substance which fastens a reaction without themselves undergoing any change.";
defn[2]="An agent able to produce positively charged hydrogen ions.";
defn[3]="A base is a substance that can combine with a proton.";
defn[4]="The energy required to break a particular bond by hompolytic process.";
defn[5]="chain reaction:reactions which proceed by means of a set of repeating cyclic steps.";
defn[6]="Linkage of two atoms by the sharing of two electrons.";
defn[7]="a substance which cannot be further subdivided by chemical methods.";
defn[8]="a naturally occuringb substance able to catalyse a chemical reaction.";
defn[9]="The study of rate of reactions.";
for(i=0;i<9;i++) { if(d.equals(name[i])) n=i;
}
out.println(defn[n]);
%>

Result:
Thus the application was implemented using AJAX.

Ex No: 13
Date:

Aim:
To develop the scenario of two web Services- an airline service and a travel agent and the travel agent is
searching for an airline using Web Services and Data base.

Algorithm:
1. Define the service's interface. This is done with WSDL

2. Implement the service. This is done with Java.

3. Define the deployment parameters. This is done with WSDD and JNDI

4. Compile everything and generate a GAR file. This is done with Ant

5. Deploy service. This is also done with a GT4 tool

Program:

package airinfo;
import java.rmi.RemoteException;
public interface MyInterface extends java.rmi.Remote
{
public String getInfo(String src,String dest)throws java.rmi.RemoteException;
}
package airinfo;
import java.sql.*;
public class TestDB implements MyInterface
{
public String getInfo(String src,String dest)
{
String str="";
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:Airways","","");
Statement s=con.createStatement();
if(src.equals("Mumbai"))
{

if(dest.equals("Pune"))
s.executeQuery("SELECT * FROM Airways_table WHERE Start_from='Mumbai'
AND Dest='Pune'");
else if(dest.equals("Chennai"))
s.executeQuery("SELECT * FROM Airways_table WHERE Start_from='Mumbai'
AND Dest='Chennai'");
}
else if(src.equals("Pune"))
{
if(dest.equals("Mumbai"))
s.executeQuery("SELECT * FROM Airways_table WHERE Start_from='Pune' AND
Dest='Mumbai'");
else if(dest.equals("Chennai"))
s.executeQuery("SELECT * FROM Airways_table WHERE Start_from='Pune' AND
Dest='Chennai'");
}
else if(src.equals("Chennai"))
{
if(dest.equals("Pune"))
s.executeQuery("SELECT * FROM Airways_table WHERE Start_from='Chennai'
AND Dest='Pune'");
else if(dest.equals("Mumbai"))

s.executeQuery("SELECT * FROM Airways_table WHERE Start_from='Chennai'


AND Dest='Mumbai'");
}
ResultSet rs=s.getResultSet();
str+="<table border=1>";
while(rs.next())
{
str+="<tr><b>";
str+="<td>";
str+=rs.getString("name");
str+="</td>";
str+="<td>";
str+=rs.getString("Time");
str+="</td>";
str+="</tr></b>";
}
str+="</table>";
}catch(ClassNotFoundException ex)
{
System.out.println(ex);
}
catch(SQLException ex)

{
System.out.println(ex);
}
return str;
}}

// This class was generated by the JAXRPC SI, do not edit.


// Contents subject to change without notice.
// JAX-RPC Standard Implementation (1.1.3, build R1)
// Generated source version: 1.1.3
package myairreservationclient;
import com.sun.xml.rpc.client.BasicService;
import com.sun.xml.rpc.encoding.*;
import com.sun.xml.rpc.encoding.simpletype.*;
import com.sun.xml.rpc.encoding.soap.*;
import com.sun.xml.rpc.encoding.literal.*;
import com.sun.xml.rpc.soap.SOAPVersion;
import com.sun.xml.rpc.wsdl.document.schema.SchemaConstants;
import javax.xml.rpc.*;
import javax.xml.rpc.encoding.*;
import javax.xml.namespace.QName;
public class AirLineReservation_SerializerRegistry implements SerializerConstants {
public AirLineReservation_SerializerRegistry()
{
}
public TypeMappingRegistry getRegistry()
{
TypeMappingRegistry registry = BasicService.createStandardTypeMappingRegistry();
TypeMapping mapping12 = registry.getTypeMapping(SOAP12Constants.NS_SOAP_ENCODING);
TypeMapping mapping = registry.getTypeMapping(SOAPConstants.NS_SOAP_ENCODING);
TypeMapping mapping2 = registry.getTypeMapping("");
{
QName type = new QName("http://tempuri.org/wsdl", "getInfo");
CombinedSerializer serializer = new
myairreservationclient.MyInterface_getInfo_RequestStruct_SOAPSerializer(type,
DONT_ENCODE_TYPE, NULLABLE, SOAPConstants.NS_SOAP_ENCODING);
serializer = new ReferenceableSerializerImpl(DONT_SERIALIZE_AS_REF, serializer,
SOAPVersion.SOAP_11);

registerSerializer(mapping,myairreservationclient.MyInterface_getInfo_RequestStruct.class, type,
serializer);
}{
QName type = new QName("http://tempuri.org/wsdl", "getInfoResponse");
CombinedSerializer serializer = new
myairreservationclient.MyInterface_getInfo_ResponseStruct_SOAPSerializer(type,
DONT_ENCODE_TYPE, NULLABLE, SOAPConstants.NS_SOAP_ENCODING);
serializer = new ReferenceableSerializerImpl(DONT_SERIALIZE_AS_REF, serializer,
SOAPVersion.SOAP_11);
registerSerializer(mapping,myairreservationclient.MyInterface_getInfo_ResponseStruct.class, type,
serializer);
}
return registry;
}
private static void registerSerializer(TypeMapping mapping, java.lang.Class javaType,
javax.xml.namespace.QName xmlType,
Serializer ser) {
mapping.register(javaType, xmlType, new SingletonSerializerFactory(ser),
new SingletonDeserializerFactory((Deserializer)ser));
}
}

// This class was generated by the JAXRPC SI, do not edit.


// Contents subject to change without notice.
// JAX-RPC Standard Implementation (1.1.3, build R1)
// Generated source version: 1.1.3
package myairreservationclient;
public class MyInterface_getInfo_ResponseStruct {
protected java.lang.String result;
public MyInterface_getInfo_ResponseStruct() {
}
public MyInterface_getInfo_ResponseStruct(java.lang.String result) {
this.result = result;
}
public java.lang.String getResult() {
return result;
}
public void setResult(java.lang.String result) {
this.result = result;
}
}
// This class was generated by the JAXRPC SI, do not edit.
// Contents subject to change without notice.
// JAX-RPC Standard Implementation (1.1.3, build R1)

// Generated source version: 1.1.3

package myairreservationclient;

import com.sun.xml.rpc.encoding.*;

import com.sun.xml.rpc.util.exception.LocalizableExceptionAdapter;

public class MyInterface_getInfo_RequestStruct_SOAPBuilder implements SOAPInstanceBuilder {


private myairreservationclient.MyInterface_getInfo_RequestStruct _instance;

private java.lang.String string_1;

private java.lang.String string_2;


private static final int mySTRING_1_INDEX = 0;
private static final int mySTRING_2_INDEX = 1;
public MyInterface_getInfo_RequestStruct_SOAPBuilder() {
}
public void setString_1(java.lang.String string_1) {
this.string_1 = string_1;
}
public void setString_2(java.lang.String string_2) {
this.string_2 = string_2;
}
public int memberGateType(int memberIndex) {
switch (memberIndex) {

case mySTRING_1_INDEX:
return GATES_INITIALIZATION | REQUIRES_CREATION;
case mySTRING_2_INDEX:
return GATES_INITIALIZATION | REQUIRES_CREATION;
default:
throw new IllegalArgumentException();
}}
public void construct() {
}
public void setMember(int index, java.lang.Object memberValue) {
try {
switch(index) {
case mySTRING_1_INDEX:
_instance.setString_1((java.lang.String)memberValue);
break;
case mySTRING_2_INDEX:
_instance.setString_2((java.lang.String)memberValue);
break;
default:
throw new java.lang.IllegalArgumentException();
}}

catch (java.lang.RuntimeException e) {
throw e;
}
catch (java.lang.Exception e) {
throw new DeserializationException(new LocalizableExceptionAdapter(e));
}}
public void initialize() {
}
public void setInstance(java.lang.Object instance) {
_instance = (myairreservationclient.MyInterface_getInfo_RequestStruct)instance;
}
public java.lang.Object getInstance() {
return _instance;
}}
// This class was generated by the JAXRPC SI, do not edit.
// Contents subject to change without notice.
// JAX-RPC Standard Implementation (1.1.3, build R1)
// Generated source version: 1.1.3
package myairreservationclient;

public interface MyInterface extends java.rmi.Remote {


public java.lang.String getInfo(java.lang.String string_1, java.lang.String string_2) throws
java.rmi.RemoteException;
}
// This class was generated by the JAXRPC SI, do not edit.
// Contents subject to change without notice.
// JAX-RPC Standard Implementation (1.1.3, build R1)
// Generated source version: 1.1.3
package myairreservationclient;
import com.sun.xml.rpc.encoding.*;
import com.sun.xml.rpc.client.ServiceExceptionImpl;
import com.sun.xml.rpc.util.exception.*;
import com.sun.xml.rpc.soap.SOAPVersion;
import com.sun.xml.rpc.client.HandlerChainImpl;
import javax.xml.rpc.*;
import javax.xml.rpc.encoding.*;
import javax.xml.rpc.handler.HandlerChain;
import javax.xml.rpc.handler.HandlerInfo;
import javax.xml.namespace.QName;

public class AirLineReservation_Impl extends com.sun.xml.rpc.client.BasicService implements


AirLineReservation {
private static final QName serviceName = new QName("http://tempuri.org/wsdl", "AirLineReservation");
private static final QName ns1_MyInterfacePort_QNAME = new QName("http://tempuri.org/wsdl",
"MyInterfacePort");
private static final Class myInterface_PortClass = myairreservationclient.MyInterface.class;
public AirLineReservation_Impl() {
super(serviceName, new QName[] {
ns1_MyInterfacePort_QNAME
},
new myairreservationclient.AirLineReservation_SerializerRegistry().getRegistry());
}
public java.rmi.Remote getPort(javax.xml.namespace.QName portName, java.lang.Class
serviceDefInterface) throws javax.xml.rpc.ServiceException {
try {
if (portName.equals(ns1_MyInterfacePort_QNAME) &&
serviceDefInterface.equals(myInterface_PortClass)) {
return getMyInterfacePort();
} } catch (Exception e) {
throw new ServiceExceptionImpl(new LocalizableExceptionAdapter(e));
}
return super.getPort(portName, serviceDefInterface);
}
public java.rmi.Remote getPort(java.lang.Class serviceDefInterface) throws
javax.xml.rpc.ServiceException {
try {
if (serviceDefInterface.equals(myInterface_PortClass)) {
return getMyInterfacePort();
}
} catch (Exception e) {
throw new ServiceExceptionImpl(new LocalizableExceptionAdapter(e));
}
return super.getPort(serviceDefInterface);
}
public myairreservationclient.MyInterface getMyInterfacePort() {
java.lang.String[] roles = new java.lang.String[] {};
HandlerChainImpl handlerChain = new
HandlerChainImpl(getHandlerRegistry().getHandlerChain(ns1_MyInterfacePort_QNAME));

handlerChain.setRoles(roles);
myairreservationclient.MyInterface_Stub stub = new
myairreservationclient.MyInterface_Stub(handlerChain);
try {
stub._initialize(super.internalTypeRegistry);
} catch (JAXRPCException e) {
throw e;
} catch (Exception e) {
throw new JAXRPCException(e.getMessage(), e);
}
return stub;
}
}

Output:
Result: Thus the program to develop the scenario of two web Services- an airline service and a travel
agent and the travel agent is searching for an airline using Web Services and Data base is written and
executed successfully.

You might also like