Java Lab Prog With Explanation
Java Lab Prog With Explanation
CONTENTS
Page
SL No Program Title
No.
a) Write a JAVA Program to demonstrate Constructor
Overloading and Method overloading.
1
b) Write a JAVA Program to implement Inner class and
demonstrate its Access Protections.
a) Write a JAVA Program to implement Inheritance.
2 b) Write a JAVA Program to implement Exception Handling
(Using Nested try catch and finally).
a) Write a JAVA Program to create an Interface and implement
it in a class.
3 b) Write a JAVA Program to create a class (extending Thread)
and use methods Thread class to change name, priority, ---- of
the current Thread and display the same.
a) Write a JAVA Program to create a Scrolling Text using JAVA
Applets.
4
b) Write a JAVA Program to pass parameters to Applets and
display the same.
Write a JAVA Program to insert data into Student DATA BASE
5 and retrieve info base on particular queries(Using JDBC Design
Front end using Swings).
Write a JAVA Program to implement Client Server (Client
requests a file, Server responds to client with contents of that
6
file which is then display on the screen by Client – Socket
Programming).
Write a JAVA Program to implement a simple Client Server
7
Application using RMI.
Write a JAVA Servlet Program to implement a dynamic HTML
8 using Servlet (user name and password should be accepted
using HTML and displayed using a Servlet).
Write a JAVA Servlet Program to Download a file and display it
9 on the screen (A link has to be provided in HTML, when the link
is clicked corresponding file has to be displayed on Screen)
a) Write a JAVA Servlet Program to implement
RequestDispatcher object (use include() and forward()
methods).
10
b) Write a JAVA Servlet Program to implement and demonstrate
get() and Post
methods(Using HTTP Servlet Class).
Write a JAVA Servlet Program to implement sendRedirect()
11
method(using HTTP Servlet Class).
Write a JAVA Servlet Program to implement sessions (Using
12
HTTP Session Interface).
The Java Virtual Machine is a system that loads, verifies and executes java bytecodes .
The java virtual machine is an imaginary machine that is implemented by emulating
software on a real machine. The JVM provides the hardware platform specifications to
which you compile all Java technology code. This specification enables the Java software
to be platform-independent because the compilation is done for a generic machine known
as the JVM. A bytecode is a special machine language that can be understood by the Java
Virtual Machine (JVM). The bytecode is independent of any particular computer
hardware, so any computer with a Java interpreter can execute the compiled Java
program, no matter what type of computer the program was compiled on
Generally, the java developer writes the java program and stores the program in a .java
file. The java compiler translates this java program file into a .class file consisting of
bytecodes. The bytecodes comprise the instruction set for the java virtual machine.The
format of the bytecode is as follows:
<opcode><…parameters>
The length of the opcode is one byte long(hence name bytecode).At present Java Virtual
machine has about 220 bytecode instructions.
The java virtual machine modules are usually written n C,C++ or in Assembly language
for an operating system.
2) A bytecode is a special machine language that can be understood by the Java Virtual
Machine (JVM). The bytecode is independent of any particular computer hardware, so
any computer with a Java interpreter can execute the compiled Java program, no matter
what type of computer the program was compiled on.
4)Garbage Collection
Many programming languages allows a programmer to allocate memory during runtime.
However, after using that allocated memory, there should be a way to deallocate that
memory block in order for other programs to use it again. In C, C++ and other languages
the programmer is responsible for this. This can be difficult at times since there can be
instances wherein the programmers forget to deallocate memory and therefore result to
what we call memory leaks.
In Java, the programmer is freed from the burden of having to deallocate that memory
themselves by having what we call the garbage collection thread. The garbage collection
thread is responsible for freeing any memory that can be freed. This happens
automatically during the lifetime of the Java program. Code security is attained in Java
through the implementation of its Java Runtime Environment (JRE). The JRE runs code
compiled for a JVM and performs class loading (through the class loader), code
verification (through the bytecode verifier) and finally code execution.
The following figure describes the process of compiling and executing a Java program.
The first step in creating a Java program is by writing your programs in a text editor.
Examples of text editors you can use are notepad, vi, emacs, etc. This file is stored in a
disk file with the extension .java.
After creating and saving your Java program, compile the program by using the Java
Compiler. The output of this process is a file of Java bytecodes with the file extension
.class.
The .class file is then interpreted by the Java interpreter that converts the bytecodes into
the machine language of the particular computer
Write the program Any text editor File with .java extension
Compile the program Java Compiler File with .class extension
(Java bytecodes)Run the program Java Interpreter Program Output
2: Threads
It helps to create multithreaded applications
3: Applets
A java applet is a small program embedded in web page and it will be
run when that page is browsed in web browser. To draw applet, applet
package must be imported
4: Swings
It contains advanced GUI components like progress basr, advanced layouts , border
shapes, blinks etc. It contains Javax.swing package.
6: Socket Programming
It helps to create distributed application by implementing networking
Concepts. It used java.net package
3: Java script
It helps to validate client information before sending the information to
the server for processing
5: JSP –Java Server Pages- This technology helps to create server side application. Any
server is required to run JSP.Tools required to run JSP are
jsdk, tomcat server. and configuring the server is also required.
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\WEB-
INF\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
SRQ-It gets the input stream from the client,collects the header information, extracts the
path and query information from the user
SRP- It is used for getting outputstream directed at the client, used to send information
about error, status to the client
SC-It allows you to find out the information about the the environment in which client is
running like coding format, language, connection, session id,date,content lengthetc
Classes are Servlet, ServletInputStream, ServletOutputStream
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 .
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
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
Features
Objects calling the methods must use remote interface
Methods are called as remote methods and remote methods are defined by remote
interfaces
Object that uses a remote interface is called server
Object that calls remote methods is called client
Remote object => object associated with methods that can be called form other
computer
Remote Interface => interface that defines remote methods for remote object
Diagram
Client Server
Stub Object
-method1
-method2
Package
Remote interface uses/extends builtin interface called java.rmi.Remote
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
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
Any client –server application using RMI must have following 4 programs
1) Client program
2) Server program
3) Interface program
4) Implementation program
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:
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/web-
server.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.
In general, all of the machines on the Internet can be categorized as two types:
servers and clients. Those machines that provide services (like Web servers or
FTP servers) to other machines are servers. And the machines that are used to
connect to those services are clients. When you connect to Yahoo! at
www.yahoo.com to read a page, Yahoo! is providing a machine (probably a
cluster of very large machines), for use on the Internet, to service your request.
Yahoo! is providing a server. Your machine, on the other hand, is probably
providing no services to anyone else on the Internet. Therefore, it is a user
machine, also known as a client. It is possible and common for a machine to be
both a server and a client, but for our purposes here you can think of most
machines as one or the other.
A server machine may provide one or more services on the Internet. For
example, a server machine might have software running on it that allows it to act
as a Web server, an e-mail server and an FTP server. Clients that come to a
server machine do so with a specific intent, so clients direct their requests to a
specific software server running on the overall server machine. For example, if
you are running a Web browser on your machine, it will most likely want to talk to
the Web server on the server machine. Your Telnet application will want to talk to
the Telnet server, your e-mail application will talk to the e-mail server, and so on..
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."
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)
• 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.
PROG1A
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);
}
}
OUTPUT:
C:\LJAVA>javac overload.java
C:\LJAVA>java overload
area of rectangle1=57.75
area of rectangle2=57.75
PROG1A:
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);
}
}
OUTPUT:
C:\LJAVA>javac prog1a.java
C:\LJAVA>java prog1a
No parameters
a=10 b=20
a=10 f=3.14
d=3.56
PROG1B:
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");
}
}
OUTPUT:
C:\LJAVA>javac parcel.java
C:\LJAVA>java parcel
PROG2A:
OUTPUT:
C:\LJAVA>javac inherit.java
C:\LJAVA>java inherit
name=datta
age=45
name=chethan
age=17
usn=12
PROG2B:
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");
}
}
}
OUTPUT:
C:\LJAVA>javac expdemo.java
C:\LJAVA>java expdemo
java.lang.ArithmeticException: / by zero
The statement executes
PROG3A:
interface Area
{
final float pi=3.14f;
float compute(float x,float y);
}
OUTPUT:
C:\LJAVA>javac inter.java
C:\LJAVA>java inter
area of rectangle=200.0
area of circle=314.0
PROG3B:
{
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
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
PROG4A:
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)
{
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
import java.awt.*;
import java.applet.*;
/*<applet code="pardemo.class" width=100 height=100>
<param name="message" value="goodmorning">
</applet>*/
public class pardemo extends Applet
{
String msg;
public void init()
{
msg=getParameter("message");
}
public void paint(Graphics g)
{
g.drawString(msg,10,20);
}
}
OUTPUT:
C:\LJAVA>javac pardemo.java
C:\LJAVA>appletviewer pardemo.java
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()
{
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())
{
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)
{}
}
}
}
}
OUTPUT
C:\>javac demo5.java
C:\>java demo5
PROG6:
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)
{
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.*;
}
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);
}
PROG7:
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[])
{
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
C:\>cd Lab7
C:\Lab7>javac *.java
C:\Lab7>rmic AddServerImpl
C:\Lab7>start rmiregistry
C:\Lab7>java AddServer
server is running.......
C:\>cd Lab7
C:\Lab7>java AddClient 5 19
First no is 5
second no is 19
SUM= 24
PROG8:
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
{
Start Tomcat
http://localhost:8080/8.html
PROG9:
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
{
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");
}
}
Start Tomcat
http://localhost:8080/filedown.html
PROG10a:
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");
}
}
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>");
}
}
Start Tomcat
Open the Browser and give path as
http://localhost:8080/10a.html
PROG11:
demo11.html
<html>
<head><title>demo11</title></head>
<form action="http://localhost:8080/examples/servlet/demo11">
<p><center><br><br><h1>Implementation of sendRedirect()</h1><br><br>
<select name="typevalue">
<option>first</option>
<option>second</option>
</select>
<input type=submit value=submit>
</center>
</form>
</html>
demo11.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class demo11 extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String type=request.getParameter("typevalue");
if(type.equals("first"))
out.println("<center><h2>Request send to the first page");
else
response.sendRedirect("http://localhost:8080/examples/servlet/second");
}
}
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");
}
}
Start Tomcat
Open the Browser and give path as
http://localhost:8080/demo11.html
PROG12:
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>");
}
}
Start Tomcat
Open the Browser and give path as
http://localhost:8080/examples/servlet/demo12
PROG13a:
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>
Start Tomcat
Open the Browser and give path as
http://localhost:8080/13a.jsp
PROG13b:
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
welcome.jsp
<%
out.println("<center><h2>Welcome Ritesh<br>");
Start Tomcat
Open the Browser and give path as
http://localhost:8080/13b.html
PROG14:
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
<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;
}
}
Start Tomcat
Open the Browser and give path as
http://localhost:8080/LAB14/StudInfo.html