Professional Documents
Culture Documents
SL No Program Title No
SL No Program Title No
07MCA41
CONTENTS
SL No
1
6
7
8
9
10
11
12
Program Title
Page
No.
Department of MCA
BMSIT
13
14
07MCA41
Department of MCA
BMSIT
07MCA41
Department of MCA
BMSIT
07MCA41
Department of MCA
BMSIT
07MCA41
Department of MCA
BMSIT
07MCA41
Servlet
1 A servlet is a mini server side program which is loaded by web server and executed in
the web browser
2 A servlet accesses request from the client, performs some task and return the result to
the client
3 servlet is preferred than other server sided programs because of a) less start up cost
b)continuous connection between server and client c)platform independent
4 All servlet programs is a java program and html tags are embedded in it
5 Servlet is of 2 types Generic servlet and http servlet
a) Http servlet runs only on http protocol
b) Generic Servlet runs on any protocol
6) Webserver like tomcat server is required to run servlet
Servlet program is a java program which is saved as .java file and it is compiled
After compiling . class file has to be copied to C:\Tomcat\webapps\examples\WEBINF\classes. Care has to be taken that tomcat server is running. Next open the
Browser give the path like http://localhost:8080/examples/servlet/servletname
Department of MCA
BMSIT
07MCA41
JSP
JSP stands for Java Server Pages. It is a server sided programming language in which
java codes are embedded in HTML tags . JSP is a advanced form of servlet where java
classes are created auomatically whenever jsp pages are executed on web server
All java pages are saved with an extension of .jsp Any web server like tomcat is required
to run any server sided pages .
There are5 types of JSP tags
1) Comment tag
This tag is used for commenting the statements
<%-This is a comment --%>
2) Declaration tag
This tag is used for declaring java declaration statements that define
variables, objects and methods
<%! Declarations %>
Department of MCA
BMSIT
07MCA41
3) Directive tag
This commands the JSP virtual engine to perform a specific task such as
importing java package required by the object and methods used in the
declaration statement
There are 3 commonly used directive tags
a) Import : used to import java packages
<%@ page import = java.sql.* ; %>
b) Include : used to insert a specific file in to the JSP program
<%@ include file =abc\temlate.html %>
c) taglib : It specifies the file that contains the tag library
<%@ taglib =abc.tld %>
4) Expression tag
This tag is used to evaluate the java expressions whose result replaces the
expression when jsp virtual engine resolves jsp tags
<%! Datatype variable name %>
5) Scriptlet tag
This contains commonly used java control statements and loops
<% control statements or loops %>
All jsp pages should be executed on web server with some port number
JSP pages should be saved in web apps folder of tomcat server
Path should be as : http://localhost:portnumber/examples/jsp/filename.jsp
Department of MCA
BMSIT
07MCA41
Department of MCA
BMSIT
07MCA41
Diagram
Client
Server
Object
-method1
-method2
Stub
Package
Remote interface uses/extends builtin interface called java.rmi.Remote
There is no method declarations in java.rmi.Remote
This interface is used to identify remote objects
Methods declared in Remote interface must have java,rmi.RemoteException
Remote objects must implement remote interface
Remote object registry is a mechanism by which client can get reference of
remote object
Execution Path
Client Program
Server Program
Interface Program
Compile client program
Compile Interface program
Type rmic remote interface name
Type start rmi registry
Run server program
Run client program
Department of MCA
BMSIT
10
07MCA41
3) Objects that want their methods to be called remotely must use remote interface
which defines remote methods
4) Remote object is an object associated with the methods that can be called from java
virtual machine , Remote Interface is an interface that declares the remote methods
for a remote object. Remote objects must implement the remote interface directly
or indirectly
5) The object that uses remote interface is called a server and the object that call
remote method is called client
6) Server and client cannot directly communicate hence proxies called stub and
Skelton is used, they are class files which acts like a proxy for client and server
respectively and they are responsible for marshalling at client side and
demarshalling at server side
Packages used are java .rmi package , java.rmi.server.UnicastRemoteObject ,
java.rmi.Naming
Any client server application using RMI must have following 4 programs
1) Client program
2) Server program
3) Interface program
4) Implementation program
The Basic Process IN WEB APPLICATION
Let's say that you are sitting at your computer, surfing the Web, and you get a
call from a friend who says, "I just read a great article! Type in this URL and
check it out. It's at http://www.howstuffworks.com/web-server.htm." So you type
that URL into your browser and press return. And magically, no matter where in
the world that URL lives, the page pops up on your screen.
At the most basic level possible, the following diagram shows the steps that
brought that page to your screen:
Department of MCA
BMSIT
11
07MCA41
If you want to get into a bit more detail on the process of getting a Web page
onto your computer screen, here are the basic steps that occurred behind the
scenes:
The browser broke the URL into three parts:
The protocol ("http")
The server name ("www.xyz.com")
The file name ("web-server.htm")
The browser communicated with a name server to translate the server
name "www.howstuffworks.com" into an IP Address, which it uses to
connect to the server machine.
The browser then formed a connection to the server at that IP address
on port 80. (We'll discuss ports later in this article.)
Following the HTTP protocol, the browser sent a GET request to the
server, asking for the file "http://www.howstuffworks.com/webserver.htm." (Note that cookies may be sent from browser to server with
the GET request -- see How Internet Cookies Work for details.)
The server then sent the HTML text for the Web page to the browser.
(Cookies may also be sent from server to browser in the header for the
page.)
The browser read the HTML tags and formatted the page onto your
screen.
So what is "the Internet"? The Internet is a gigantic collection of millions of
computers, all linked together on a computer network. The network allows all of
the computers to communicate with one another. A home computer may be
linked to the Internet using a phone-line modem, DSL or cable modem that talks
to an Internet service provider (ISP). A computer in a business or university will
usually have a network interface card (NIC) that directly connects it to a local
area network (LAN) inside the business. The business can then connect its LAN
to an ISP using a high-speed phone line like a T1 line. A T1 line can handle
approximately 1.5 million bits per second, while a normal phone line using a
modem can typically handle 30,000 to 50,000 bits per second.
ISPs then connect to larger ISPs, and the largest ISPs maintain fiber-optic
"backbones" for an entire nation or region. Backbones around the world are
connected through fiber-optic lines, undersea cablessatellite. In this way, every
computer on the Internet is connected to every other computer on the Internet.
Department of MCA
BMSIT
12
07MCA41
Department of MCA
BMSIT
13
07MCA41
IP Addresses
To keep all of these machines straight, each machine on the Internet is assigned
a unique address called an IP address. IP stands for Internet protocol, and these
addresses are 32-bit numbers, normally expressed as four "octets" in a "dotted
decimal number." A typical IP address looks like this:
216.27.61.137
The four numbers in an IP address are called octets because they can have
values between 0 and 255, which is 28 possibilities per octet.
Every machine on the Internet has a unique IP address. A server has a static IP
address that does not change very often. A home machine that is dialing up
through a modem often has an IP address that is assigned by the ISP when the
machine dials in. That IP address is unique for that session -- it may be different
the next time the machine dials in. This way, an ISP only needs one IP address
for each modem it supports, rather than for each customer.
If you are working on a Windows machine, you can view a lot of the Internet
information for your machine, including your current IP address and hostname,
with the command WINIPCFG.EXE (IPCONFIG.EXE for Windows 2000/XP). On
a UNIX machine, type nslookup at the command prompt, along with a machine
name, l- to display the IP address of the machine, and you can use the command
hostname to learn the name of your machine. (For more information on IP
addresses,
As far as the Internet's machines are concerned, an IP address is all you need to
talk to a server. For example, in your browser, you can type the URL
http://209.116.69.66 and arrive at the machine that contains the Web serve rxyz.
On some servers, the IP address alone is not sufficient, but on most large
servers it is -- keep reading for details
Domain Names
The name www.howstuffworks.com actually has three parts:
The host name ("www")
The domain name ("xyz")
The top-level domain name ("com")
Domain names within the ".com" domain are managed by the registrar called
VeriSign. VeriSign also manages ".net" domain names. Other registrars (like
RegistryPro, NeuLevel and Public Interest Registry) manage the other domains
(like .pro, .biz and .org). VeriSign creates the top-level domain names and
guarantees that all names within a top-level domain are unique. VeriSign also
maintains contact information for each site and runs the "whois" database. The
host name is created by the company hosting the domain. "www" is a very
common host name, but many places now either omit it or replace it with a
different host name that indicates a specific area of the site. For example, in
encarta.msn.com, the domain name for Microsoft's Encarta encyclopedia,
"encarta" is designated as the host name instead of "www."
Department of MCA
BMSIT
14
07MCA41
Name Servers
A set of servers called domain name servers (DNS) maps the human-readable
names to the IP addresses. These servers are simple databases that map
names to IP addresses, and they are distributed all over the Internet. Most
individual companies, ISPs and universities maintain small name servers to map
host names to IP addresses. There are also central name servers that use data
supplied by VeriSign to map domain names to IP addresses.
If you type the URL "http://www.howstuffworks.com/web-server.htm" into your
browser, your browser extracts the name "www.howstuffworks.com," passes it to
a domain name server, and the domain name server returns the correct IP
address for www.howstuffworks.com. A number of name servers may be
involved to get the right IP address. For example, in the case of
www.howstuffworks.com, the name server for the "com" top-level domain will
know the IP address for the name server that knows host names, and a separate
query to that name server, operated by the HowStuffWorks ISP, may deliver the
actual IP address for the HowStuffWorks server machine.
On a UNIX machine, you can access the same service using the nslookup
command. Simply type a name like "www.howstuffworks.com" into the command
line, and the command will query the name servers and deliver the
corresponding IP address to you.
So here it is: The Internet is made up of millions of machines, each with a unique
IP address. Many of these machines are server machines, meaning that they
provide services to other machines on the Internet. You have heard of many of
these servers: e-mail servers, Web servers, FTP servers, Gopher servers and
Telnet servers, to name a few. All of these are provided by server machines.
Ports
Any server machine makes its services available to the Internet using numbered
ports, one for each service that is available on the server. For example, if a
server machine is running a Web server and an FTP server, the Web server
would typically be available on port 80, and the FTP server would be available on
port 21. Clients connect to a service at a specific IP address and on a specific
port.
Each of the most well-known services is available at a well-known port number.
Here are some common port numbers:
echo 7
daytime 13
qotd 17 (Quote of the Day)
ftp 21
telnet 23
smtp 25 (Simple Mail Transfer, meaning e-mail)
Department of MCA
BMSIT
15
07MCA41
time 37
nameserver 53
nicname 43 (Who Is)
gopher 70
finger 79
WWW 80
If the server machine accepts connections on a port from the outside world, and
if a firewall is not protecting the port, you can connect to the port from anywhere
on the Internet and use the service. Note that there is nothing that forces, for
example, a Web server to be on port 80. If you were to set up your own machine
and load Web server software on it, you could put the Web server on port 918, or
any other unused port, if you wanted to. Then, if your machine were known as
xxx.yyy.com, someone on the Internet could connect to your server with the URL
http://xxx.yyy.com:918. The ":918" explicitly specifies the port number, and would
have to be included for someone to reach your server. When no port is specified,
the browser simply assumes that the server is using the well-known port 80.
The server sends the HTML text for the Web page to the
browser. (Cookies may also be sent from server to browser in the
header for the page.)
The browser reads the HTML tags and formats the page onto
your screen.
Department of MCA
BMSIT
16
07MCA41
PROG1A
PROGRAM TO DEMOSTRATE CONSTRUCTOR OVERLOADING
class rectangle
{
double length;
double breadth;
rectangle()
{
length=10.5;
breadth=5.5;
}
rectangle(double l,double b)
{
length=l;
breadth=b;
}
double result()
{
return(length*breadth);
}
}
class overload
{
public static void main(String args[])
{
rectangle r1=new rectangle();
rectangle r2=new rectangle(10.5,5.5);
double vol=r1.result();
System.out.println("area of rectangle1=" +vol);
vol=r2.result();
System.out.println("area of rectangle2=" +vol);
}
}
Department of MCA
BMSIT
17
07MCA41
OUTPUT:
C:\LJAVA>javac overload.java
C:\LJAVA>java overload
area of rectangle1=57.75
area of rectangle2=57.75
Department of MCA
BMSIT
18
07MCA41
PROG1A:
PROGRAM TO DEMONSTRATE METHOD OVERLOADING
class demo
{
void test()
{
System.out.println("no parameters");
}
void test(int a,int b)
{
System.out.println("a="+ a +"\t" +"b="+b);
}
void test(int a,float f)
{
System.out.println("a="+ a +"\t" +"f="+f);
}
double test (double d)
{
System.out.println("d="+d);
return d;
}
}
class prog1a
{
public static void main(String args[])
{
demo d=new demo();
d.test();
d.test(10,20);
d.test(10,3.14f);
double d2=d.test(3.56);
}
}
Department of MCA
BMSIT
19
07MCA41
OUTPUT:
C:\LJAVA>javac prog1a.java
C:\LJAVA>java prog1a
No parameters
a=10 b=20
a=10 f=3.14
d=3.56
Department of MCA
BMSIT
20
07MCA41
PROG1B:
PROGRAM TO DEMONSTRATE INNER CLASS AND ACCESS
PROTECTIONS
class parcel
{
class contents
{
private int i=10;
private int value()
{
return i;
}
}
class destination
{
private String label;
destination(String whereto)
{
label=whereto;
}
String readlabel()
{
return label;
}
}
public void ship(String dest)
{
contents c=new contents();
System.out.println("shipped" +" " + c.value() +" " + "items to" + " " +
dest);
}
public static void main(String args[])
{
parcel p=new parcel();
p.ship("mysore");
p.ship("blore");
}
}
Department of MCA
BMSIT
21
07MCA41
OUTPUT:
C:\LJAVA>javac parcel.java
C:\LJAVA>java parcel
shipped 10 items to mysore
shipped 10 items to blore
Department of MCA
BMSIT
22
07MCA41
PROG2A:
PROGRAM TO IMPLEMENT INHERITANCE
class father
{
String name;
int age;
void display()
{
System.out.println("name=" +name);
System.out.println("age="+age);
}
}
class son extends father
{
int usn;
void show()
{
System.out.println("usn=" +usn);
}
}
class inherit
{
public static void main(String args[])
{
father f=new father();
f.name="datta";
f.age=45;
son s =new son();
s.name="chethan";
s.age=17;
s.usn=12;
System.out.println(" ");
f.display();
System.out.println(" ");
s.display();
s.show();
}
}
Department of MCA
BMSIT
23
07MCA41
OUTPUT:
C:\LJAVA>javac inherit.java
C:\LJAVA>java inherit
name=datta
age=45
name=chethan
age=17
usn=12
Department of MCA
BMSIT
24
07MCA41
PROG2B:
PROGRAM TO DEMONSTRATE EXCEPTION HANDLING
class expdemo
{
public static void main(String args[])
{
try
{
int a=args.length;
int b=42/a;
System.out.println("a="+a);
try
{
if(a==1)
a=a/(a-a);
if(a==2)
{
int c[]={1};
c[43]=99;
}
}
catch(Exception e)
{
System.out.println("error="+e);
}
}
catch(Exception g)
{
System.out.println(g);
}
finally
{
System.out.println("the statement executes");
}
}
}
Department of MCA
BMSIT
25
07MCA41
OUTPUT:
C:\LJAVA>javac expdemo.java
C:\LJAVA>java expdemo
java.lang.ArithmeticException: / by zero
The statement executes
Department of MCA
BMSIT
26
07MCA41
PROG3A:
PROGRAM TO CREATE INTERFACE AND IMPLEMENT CLASS
interface Area
{
final float pi=3.14f;
float compute(float x,float y);
}
class rectangle implements Area
{
public float compute(float x,float y)
{
return(x*y);
}
}
class circle implements Area
{
public float compute(float x,float y)
{
return(pi*x*x);
}
}
class inter
{
public static void main(String args[])
{
rectangle rect=new rectangle();
circle cir=new circle();
System.out.println("area of rectangle=" +rect.compute(10,20));
System.out.println("area of circle=" +cir.compute(10,0));
}
}
OUTPUT:
C:\LJAVA>javac inter.java
C:\LJAVA>java inter
area of rectangle=200.0
area of circle=314.0
Department of MCA
BMSIT
27
07MCA41
PROG3B:
PROGRAM TO CREATE CLASS FOR EXTENDING THREADS
class Mythread extends Thread
{
Mythread(String ss)
{
super(ss);
start();
}
public void run()
{
try{
for(int i=5;i>0;i--)
{
System.out.println(getName()+" : "+i);
Thread.sleep(1000);
}}
catch(InterruptedException e){System.out.println(this.getName()+"
interrupted");}
System.out.println(this.getName()+" exiting");
}
}
class ExtendThread
{
public static void main(String ab[])
{
Thread ob1 = new Mythread("First");
Thread ob2 = new Mythread("Second");
Thread ob3 = new Mythread("Third");
System.out.println("First thread is alive : "+ob1.isAlive());
System.out.println("Second thread is alive : "+ob2.isAlive());
System.out.println("Third thread is alive : "+ob3.isAlive());
System.out.println("No.of Threads alive "+ob1.activeCount());
System.out.println("Priority of First thread "+ob1.getPriority());
System.out.println("Priority of Second thread "+ob2.getPriority());
System.out.println("Priority of Third thread "+ob3.getPriority());
ob1.setPriority(1);
ob2.setPriority(3);
ob3.setPriority(9);
try
Department of MCA
BMSIT
28
07MCA41
{
ob1.join();
ob2.join();
ob3.join();
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("First thread is alive : "+ob1.isAlive());
System.out.println("Second thread is alive : "+ob2.isAlive());
System.out.println("No.of Threads alive "+ob3.activeCount());
System.out.println("Third thread is alive : "+ob3.isAlive());
System.out.println("New Priority of First thread "+ob1.getPriority());
System.out.println("New Priority of Second thread "+ob2.getPriority());
System.out.println("New Priority of Third thread "+ob3.getPriority());
}
}
OUTPUT:
C:\LJAVA>javac ExtendThread.java
C:\LJAVA>java ExtendThread
First thread is alive : true
First : 5
Second : 5
Third : 5
Second thread is alive : true
Third thread is alive : true
No.of Threads alive 5
Priority of First thread 5
Priority of Second thread 5
Priority of Third thread 5
Third : 4
Second : 4
First : 4
Third : 3
Second : 3
First : 3
Third : 2
Second : 2
First : 2
Third : 1
Second : 1
First : 1
Department of MCA
BMSIT
29
07MCA41
Third exiting
Second exiting
First exiting
First thread is alive : false
Second thread is alive : false
No.of Threads alive 2
Third thread is alive : false
New Priority of First thread 1
New Priority of Second thread 3
New Priority of Third thread 9
Department of MCA
BMSIT
30
07MCA41
PROG4A:
PROGRAM TO CREATE SCROLLING TEXT USING APPLETS
import java.awt.*;
import java.applet.*;
import java.lang.Thread.*;
public class scroll extends Applet implements Runnable
{
Thread t=null;
String msg="good morning";
public void init()
{
t=new Thread(this);
t.start();
}
public void run()
{
try
{
char ch;
for(;;)
{
repaint();
t.sleep(100);
ch=msg.charAt(0);
msg=msg.substring(1,msg.length());
msg=msg+ch;
}
}
catch(InterruptedException e)
{
System.out.println("error");
}
}
public void paint(Graphics g)
{
Department of MCA
BMSIT
31
07MCA41
g.drawString(msg,50,10);
}
}
/*<applet code="scroll.class" width=200 height=200>
</applet>*/
OUTPUT:
C:\LJAVA>javac scroll.java
C:\LJAVA>appletviewer scroll.java
Department of MCA
BMSIT
32
07MCA41
Department of MCA
BMSIT
33
07MCA41
PROG5:
Java Program to insert data into Student database and retrieve info based on
particular queries (using JDBC, Design front end using Swings).
demo5.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.io.*;
import java.util.*;
import java.lang.*;
public class test4 extends JFrame
{
private JButton b1,b2;
private JLabel l1,l2;
private JTextField t1,t2;
public test4()
{
l1=new JLabel("Enter name");
t1=new JTextField(10);
l2=new JLabel("Enter age");
t2=new JTextField(10);
Container c=getContentPane();
c.setLayout(new FlowLayout());
c.add(l1);
c.add(t1);
c.add(l2);
c.add(t2);
b1=new JButton("add");
b2=new JButton("retrieve");
c.add(b1);
c.add(b2);
ButtonHandler handler=new ButtonHandler();
b1.addActionListener(handler);
b2.addActionListener(handler);
setSize(400,400);
show();
}
public static void main(String x[]) throws ClassNotFoundException
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
test4 app=new test4();
app.addWindowListener(new WindowAdapter()
Department of MCA
BMSIT
34
07MCA41
{
public void WindowClosing(WindowEvent e1)
{
System.exit(0);
}
});
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String x=e.getActionCommand();
if(x.equals("add"))
{
try
{
Connection cn;
ResultSet rs;
cn=DriverManager.getConnection("jdbc:odbc:ds");
String creat = "insert into abc values(?,?)";
PreparedStatement ps = cn.prepareStatement(creat);
ps.setString(1,t1.getText());
ps.setString(2,t2.getText());
ps.executeUpdate();
JOptionPane.showMessageDialog(null,
"RecordSaved");
ps.close();
cn.close();
}
catch (SQLException t)
{
System.out.println(t);
}
}
if(x.equals("retrieve"))
{
try
{
Connection cn;
Statement st;
ResultSet rs;
cn=DriverManager.getConnection("jdbc:odbc:ds");
st=cn.createStatement();
rs=st.executeQuery("select * from abc");
while(rs.next())
Department of MCA
BMSIT
35
07MCA41
{
System.out.print("Name:" +rs.getString(1)+"\t");
System.out.println("age:" +rs.getString(2)+"\t");
System.out.println("\n");
}
st.close();
cn.close();
rs.close();
}
catch (SQLException i)
{}
}
}
}
}
Department of MCA
BMSIT
36
07MCA41
OUTPUT
C:\>javac demo5.java
C:\>java demo5
Department of MCA
BMSIT
37
07MCA41
PROG6:
PROGRAM TO IMPLEMENT CLIENT SERVERUSING SOCKET
PROGRAMMING
SERVER PROGAM
import java.io.*;
import java.net.*;
public class server
{
public static void main(String args[])throws IOException
{
ServerSocket ss=null;
Socket cs=null;
InputStream is;
String inputline=new String();
byte bt[]=new byte[20];
try
{
ss=new ServerSocket(90);
System.out.println("server connected");
}
catch(Exception e)
{
System.out.println("---------------------");
System.exit(1);
}
try
{
cs=ss.accept();
System.out.println("connected to------------------"+cs);
is=cs.getInputStream();
is.read(bt);
inputline=new String(bt);
System.out.println(bt);
System.out.println(inputline);
}
catch(Exception g)
Department of MCA
BMSIT
38
07MCA41
{
System.out.println("---------------------");
System.exit(1);
}
PrintWriter out=new PrintWriter(cs.getOutputStream());
File f=new File(inputline);
if(f.exists())
{
BufferedReader d=new BufferedReader(new FileReader(inputline));
String line;
while((line=d.readLine())!=null)
{
out.println(line);
out.flush();
}
System.out.println("file send to client successfully");
}
else
{
String line="file doesnot exists";
out.println(line);
out.flush();
}
cs.close();
ss.close();
}
}
CLIENT PROGRAM.
import java.io.*;
import java.net.*;
public class client
{
public static void main(String args[])throws IOException
{
BufferedReader in=null;
OutputStream os;
Socket cs=null;
try
{
cs=new Socket(InetAddress.getLocalHost(),90);
System.out.println("client running is connected to........"+cs);
in=new BufferedReader(new InputStreamReader(cs.getInputStream()));
Department of MCA
BMSIT
39
07MCA41
}
catch(Exception e)
{}
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the filename");
String s=stdin.readLine();
os=cs.getOutputStream();
byte bt[]=s.getBytes();
os.write(bt);
String userinput;
while((userinput=in.readLine())!=null)
System.out.println(userinput);
in.close();
cs.close();
}
}
OUTPUT:
C:\LJAVA>javac server.java
C:\LJAVA>java server
server connected
connected to------------------Socket[addr=/192.168.1.3,port=1269,localport=90]
[B@8d107f
prog1a.java
file send to client successfully
C:\LJAVA>java client
client running is connected to........Socket[addr=bmsit-8eb8fe932/192.168.1.3,po
rt=90,localport=1269]
enter the filename
prog1a.java
class demo
{
void test()
{
System.out.println("no parameters");
}
void test(int a,int b)
{
System.out.println("a="+ a +"\t" +"b="+b);
}
Department of MCA
BMSIT
40
07MCA41
Department of MCA
BMSIT
41
07MCA41
PROG7:
IMPLEMENT SIMPLE CLIENT SERVER USING RMI
Interface
import java.io.*;
import java.rmi.*;
public interface AddServerIntf extends Remote
{
public int add(int x, int y) throws RemoteException;
}
Implements
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf
{
public AddServerImpl() throws RemoteException{ }
public int add(int x, int y) throws RemoteException
{
return x+y;
}
}
Server
import java.io.*;
import java.rmi.*;
public class AddServer
{
public static void main(String arg[])
{
Department of MCA
BMSIT
42
07MCA41
try
{
AddServerImpl server=new AddServerImpl();
Naming.rebind("registerme",server);
System.out.println("server is running.......");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Client
import java.io.*;
import java.rmi.*;
public class AddClient
{
public static void main(String arg[])
{
try
{
AddServerIntf
client=(AddServerIntf)Naming.lookup("registerme");
System.out.println("First no is "+arg[0]);
int x=Integer.parseInt(arg[0]);
System.out.println("second no is "+arg[1]);
int y=Integer.parseInt(arg[1]);
System.out.println("SUM= "+client.add(x,y));
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT
Store all the above file in a folder as Lab7
Open Command Prompt
C:\Documents and Settings\Administrator>cd\
Department of MCA
BMSIT
43
07MCA41
C:\>cd Lab7
C:\Lab7>javac *.java
C:\Lab7>rmic AddServerImpl
C:\Lab7>start rmiregistry
C:\Lab7>java AddServer
server is running.......
Open another Command Prompt
C:\Documents and Settings\Administrator>cd\
C:\>cd Lab7
C:\Lab7>java AddClient 5 19
First no is 5
second no is 19
SUM= 24
Department of MCA
BMSIT
44
07MCA41
PROG8:
JAVA SERVLET PROGRAM TO ACCEPT THE USERNAME AND PASSWORD
FROM A DYNAMIC HTML
Index.html
<html>
<head><title>demo8</title></head>
<body bgcolor=orange>
<form method="post" name="form1"
action="http://localhost:8080/examples/servlet/demo8">
<center><b><br><br>
Enter User Name : <input type="text" name="uname" size="10"><br>
Enter Password : <input type=password name="pname" size="10"><br><br>
<input type=button value="Submit" onclick="validate()">
</center>
<script type="text/javascript">
function validate()
{
if(document.form1.uname.value=="" || document.form1.pname.value=="")
{
alert("Fields cannot be blank");
return ;
}
document.form1.submit();
}
</script>
</form>
</body>
</html>
demo8.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class demo8 extends HttpServlet
{
Department of MCA
BMSIT
45
07MCA41
Department of MCA
BMSIT
46
07MCA41
Department of MCA
BMSIT
47
07MCA41
PROG9:
JAVA SERVLET PROGRAM TO DOWNLOAD A FILE AND DISPLAY IT ON
THE SCREEN
filedown.html
<html>
<head><title>File Download</title>
<script type="text/javascript">
function validate()
{
if(document.form1.f1.value=="")
alert("First click on browse and select the file");
else
document.form1.submit();
}
</script>
</head>
<body bgcolor="lightblue">
<form name="form1" method="get"
action="http://localhost:8080/examples/servlet/filedown">
<p><center><br><br><h1>File Downloand Program</h1><br><br>
<h3>Click on Browse and select the file</h3><br><br>
<input type="file" name="f1" size="40" ><br><br>
<input type=button value="Click to start downloading" onclick="validate()">
</center></p>
</form>
</body>
</html>
filedown.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class filedown extends HttpServlet
Department of MCA
BMSIT
48
07MCA41
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String fname = request.getParameter("f1");
File f = new File(fname);
if(f.exists())
{
out.println("<html>\n<head><title>Javaservlet</title></head>\n"+"<body>\n"+ <p><hr
size='3' style='color:red'/><font size=5pt face=verdana color=blue>Download
Completed<br>FileName:");
out.println(f.getName());
out.println("<hr size='2' style='color:green'>");
out.println("Contents of the File is:<br>");
out.println("<hr size='2' style='color:green'/><br>");
BufferedReader in = new BufferedReader(new FileReader(f));
String buf="";
while((buf = in.readLine())!= null)
{
out.write(buf);
out.flush();
out.println("<br>");
}
in.close();
out.println("<hr size='3' style='color:red'></font></p></body>\n</html>");
}
else
out.println("<h1>File Doesnot Exists\n");
}
}
Store the filedown.html in
C:\Program Files\Apache Group\Tomcat 4.1\webapps\ROOT
And the filedown.class in
C:\Program Files\Apache Group\Tomcat 4.1\webapps\examples\WEB-INF\classes
Start Tomcat
Open the Browser and give path as
http://localhost:8080/filedown.html
Department of MCA
BMSIT
49
07MCA41
PROG10a:
JAVA SERVLET PROGRAM TO IMPLEMENT REQUEST DISPATCHER
OBJECT (USE INCLUDE() AND FORWARD() METHODS)
Department of MCA
BMSIT
50
07MCA41
10a.html
<html>
<head><title>demo10a</title></head>
<body bgcolor=lightblue>
<form action=http://localhost:8080/examples/servlet/demo10a method="post">
<p><center><br><br><h1>Request Dispatcher Implementation</h1><br><br>
<input type="hidden" name="decider" value="forward">
<input type=submit value="forward">
</form>
<form action=http://localhost:8080/examples/servlet/demo10a method="post">
<center><br>
<input type="hidden" name="decider" value="include">
<input type=submit value="include">
</form>
</body>
</html>
demo10a.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class demo10a extends javax.servlet.http.HttpServlet implements
javax.servlet.Servlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
String decider=request.getParameter("decider");
RequestDispatcher rd=null;
if("forward".equals(decider))
{
rd=request.getRequestDispatcher("reg10a");
rd.forward(request,response);
}
else if("include".equals(decider))
{
rd=request.getRequestDispatcher("reg10a");
rd.include(request,response);
}
PrintWriter out=response.getWriter();
out.println("<br><center>Hai.... i am a demo10a to demonstrate request
dispatcher");
}
}
Department of MCA
BMSIT
51
07MCA41
reg10a.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class reg10a extends javax.servlet.http.HttpServlet implements
javax.servlet.Servlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<body bgcolor=pink>");
out.println("<center><h2>Hai.... this is regservlet</center></h2>");
out.println("</body>");
out.println("</html>");
}
}
Store the 10.html in
C:\Program Files\Apache Group\Tomcat 4.1\webapps\ROOT
And the demo10a.class and reg10a.class in
C:\Program Files\Apache Group\Tomcat 4.1\webapps\examples\WEB-INF\classes
Start Tomcat
Open the Browser and give path as
http://localhost:8080/10a.html
Department of MCA
BMSIT
52
07MCA41
Department of MCA
BMSIT
53
07MCA41
Department of MCA
BMSIT
54
07MCA41
PROG11:
Department of MCA
BMSIT
55
07MCA41
second.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class second extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<center><h2>Request send to the second page");
}
}
Store the demo11.html in
C:\Program Files\Apache Group\Tomcat 4.1\webapps\ROOT
And the demo11.class and second.class in
C:\Program Files\Apache Group\Tomcat 4.1\webapps\examples\WEB-INF\classes
Start Tomcat
Open the Browser and give path as
http://localhost:8080/demo11.html
Department of MCA
BMSIT
56
Department of MCA
07MCA41
BMSIT
57
07MCA41
PROG12:
JAVA SERVLET PROGRAM TO IMPLEMENT SESSIONS.
demo12.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class demo12 extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
HttpSession session=request.getSession(true);
String id=session.getId();
out.println("<html>");
out.println("<body>");
out.println("session id="+id);
out.println("<br>");
out.println("session="+session);
out.println("<br>");
Integer ival=(Integer)session.getAttribute("sessiontest.counter");
if(ival==null)
ival=new Integer(1);
else
ival=new Integer(ival.intValue()+1);
session.setAttribute("sessiontest.counter",ival);
out.println("you have visited the page "+ival+" times");
out.println("</body>");
out.println("</html>");
}
}
Department of MCA
BMSIT
58
07MCA41
Department of MCA
BMSIT
59
07MCA41
PROG13a:
JAVA JSP PROGRAM TO PRINT 10 EVEN AND 10 ODD NUMBERS.
Procedure
Write a jsp program
Copy the jsp program in root directory of tomcat server
Start the tomcat server and then run the program
13a.jsp
<html>
<body bgcolor=orange>
<%! int i,j,n; %>
<%
out.println("<br><h2>Even Numbers : <br>");
i=0;n=1;
while(n<=10)
{
out.println(i+" ");
i+=2;
n++;
}
out.println("<br><br><h2>Odd Numbers : <br>");
j=1;n=1;
while(n<=10)
{
out.println(j+" ");
j+=2;
n++;
}
%>
</body>
</html>
Store the demo13a.jsp in
C:\Program Files\Apache Group\Tomcat 4.1\webapps\ROOT
Department of MCA
BMSIT
60
07MCA41
Start Tomcat
Open the Browser and give path as
http://localhost:8080/13a.jsp
Department of MCA
BMSIT
61
07MCA41
PROG13b:
JAVA JSP PROGRAM TO IMPLEMENT VERIFICATION OF A PARTICULAR
USER LOGIN AND DISPLAY A WELCOME PAGE.
13b.html
<html>
<head><title>13b</title></head>
<form action="http://localhost:8080/13b.jsp">
<p><center><br><br><h1>Verification of a particular User login</h1><br><br>
User Name : <input type=text name="uname" size=10><br>
password : <input type=password name="pwd" size=10><br><br>
<input type=submit value=Submit>
</form>
</html>
13b.jsp
<%! String username=null,password=null; %>
<% username=request.getParameter("uname");
password=request.getParameter("pwd");
%>
<%
if(username.equals("Ritesh") && password.equals("12345"))
{
response.sendRedirect("http://localhost:8080/welcome.jsp");
}
else
out.println("<center><h2>Invalid username or password");
%>
welcome.jsp
<%
out.println("<center><h2>Welcome Ritesh<br>");
Department of MCA
BMSIT
62
07MCA41
Department of MCA
BMSIT
63
Department of MCA
07MCA41
BMSIT
64
Department of MCA
07MCA41
BMSIT
65
07MCA41
PROG14:
JAVA JSP PROGRAM TO GET STUDENT INFORMATION THROUGH A
HTML AND CREATE A JAVA BEAN CLASS, POPULATE BEAN AND
DISPLAY THE SAME INFORMATION THROUGH ANOTHER JSP.
Procedure
Writa a html program , jsp program , servlet program
Create a folder and copy all the programs in that folder
Compile the servlet program and get the class file
Create WEB-INF folder inside a folder and copy servlet program in WEB-INF
folder
Start the tomcat server and then run the program
StudInfo.html
<html>
<head><title>Student Information</title></head>
<body bgcolor=orange>
<form action ="first.jsp" method = "post">
<center><h1>Student Information</h1>
<h3>
Enter the USN : <input type = "text" name = "usn"/><br>
Student Name : <input type = "text" name = "sname"/><br>
Total Marks : <input type = "text" name = "smarks"/><br>
<input type ="submit" value ="DISPLAY" /></h3>
</center>
</form>
</body>
</html>
first.jsp
<html>
<body>
<jsp:useBean id="stud" scope="request" class="beans.Student"/>
<jsp:setProperty name="stud" property="*"/>
<jsp:forward page="display.jsp"/>
</body>
</html>
display.jsp
Department of MCA
BMSIT
66
07MCA41
<html>
<body bgcolor="pink">
<jsp:useBean id="stud" scope="request" class="beans.Student"/>
<h2>Entered Student Information</h2><br><br><h3>
Student Name : <jsp:getProperty name="stud" property="sname"/><br>
USN : <jsp:getProperty name="stud" property="usn"/><br>
Total Marks : <%out.print(stud.getsmarks());%></h3>
</body></html>
Student.java
package beans;
public class Student
{
public String sname;
public String usn;
public int smarks;
public void setsname(String e)
{
sname = e;
}
public String getsname()
{
return sname;
}
public void setusn(String en)
{
usn=en;
}
public String getusn()
{
return usn;
}
public void setsmarks(int m)
{
smarks = m;
}
public int getsmarks()
{
return smarks;
}
}
Department of MCA
BMSIT
67
07MCA41
Department of MCA
BMSIT
68
Department of MCA
07MCA41
BMSIT
69
07MCA41
1.
2.
3.
4.
5.
6.
Department of MCA
BMSIT
70
07MCA41
Department of MCA
BMSIT
71