Internet Programming Lab Manual
Internet Programming Lab Manual
Prepared By
Mr. R.Ganesh
Private Circulation
[email protected]
Ex No: 1 WEBPAGE CONCEPTS
Date:
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>
Output:-
Result:
Thus the webpage was created using HTML.
Ex No: 2
Date:
b) Create a web page with the following
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:
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:
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 :
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:
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));
}
}}
C:\IPLAB>javac UDPServer.java
C:\IPLAB>java UDPServer
Server is Running...
Client: HelloWelcomeTerminated...
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);
}}}
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:
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:
<!—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;
}
}
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 "...";
}
}
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
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>
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);
}
}
}
To implement the three-tier application using servlets to display Student mark list perform
by the jdbc:odbc connection.
Algorithm:
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:
Result:
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.*;
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;
}
// Logical not
long accesscode = ~numericKey;
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.*;
Program:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// 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>");
out.println("<P>");
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:
<!DOCTYPE web-app
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<description>
</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>
<h2 align="center"><PRE>
</b></PRE></h2>
<br><br><pre>
</body></html>
login.html:
<html>
<body bgcolor="pink"><br><br><br>
<div align="center"><pre>
</div>
<br><br>
<div align="center">
</form>
</body>
</html>
reg.html:
<html>
<body bgcolor="pink"><br><br>
<div align="center"><pre>
</div>
<br><br>
<div align="center">
</form>
</body>
</html>
profile.html:
<html>
<body bgcolor="pink"><br><br><br>
<div align="center"><pre>
</pre><br><br>
</div>
<br><br>
<div align="center">
</form>
</body></html>
catalog.html:
<html>
<body bgcolor="pink"><br><br><br>
<div align="center"><pre>
</div>
<br><br>
<div align="center">
</form>
</body>
</html>
order.html:
<html>
<body bgcolor="pink"><br><br><br>
<div align="center"><pre>
</div>
<br><br>
<div align="center">
</form>
</body>
</html>
login.java:
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\">");
String id=req.getParameter("id");
String pwd=req.getParameter("pwd");
try
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
ResultSet rs = stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
flag=1;
if(flag==0)
else
pw.println("<h3><ul>");
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.*;
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
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
if(id.equals(rs.getString(1)))
flag=1;
if(flag==1)
else
Statement stmt1=con.createStatement();
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.*;
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\">");
String title=req.getParameter("title");
try
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("</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.*;
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\">");
String id=req.getParameter("id");
try
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
Statement stmt=con.createStatement();
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("</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.*;
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
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
Statement stmt=con.createStatement();
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)
else
Statement stmt2=con.createStatement();
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();
if(flag1==0)
{
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:
Aim:
Procedure:
Step 1:
Open tomcat/webapps
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;
Program:
ActionOne.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
System.out.println("----Action executed------");
PrintWriter pw=response.getWriter();
pw.println("HELLO WORLD");
return null;
step 3:
struts-config.xml file
< struts-config>
<action-mappings>
</action-mappings>
</struts-config>
Step 4:
web.xml
<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>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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:
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
?
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.
package com.candidjava;
import java.sql.*;
import java.io.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
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");
}
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;
?
<!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>
</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" />
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:
Algorithm:
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.
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 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
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
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
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"))
{
System.out.println(ex);
}
return str;
}}
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));
}
}
package myairreservationclient;
import com.sun.xml.rpc.encoding.*;
import com.sun.xml.rpc.util.exception.LocalizableExceptionAdapter;
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;
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.