You are on page 1of 71

JAVA & J2EE Laboratory

07MCA41

CONTENTS
SL No
1

6
7
8
9

10

11
12

Program Title

Page
No.

a) Write a JAVA Program to demonstrate Constructor


Overloading and Method overloading.
b) Write a JAVA Program to implement Inner class and
demonstrate its Access Protections.
a) Write a JAVA Program to implement Inheritance.
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.
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.
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
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
file which is then display on the screen by Client Socket
Programming).
Write a JAVA Program to implement a simple Client Server
Application using RMI.
Write a JAVA Servlet Program to implement a dynamic HTML
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
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).
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()
method(using HTTP Servlet Class).
Write a JAVA Servlet Program to implement sessions (Using
HTTP Session Interface).

Department of MCA

BMSIT

JAVA & J2EE Laboratory

13

14

07MCA41

a) Write a JAVA JSP Program to print 10 even and 10 odd


number.
b) Write a JAVA JSP Program to implement verification of a
particular user login and display a welcome page.
Write a 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.

Department of MCA

BMSIT

JAVA & J2EE Laboratory

07MCA41

OVERVIEW OF JAVA AND J2EE


Java is a open source technology developed by Sun Microsystems. It is pure object
oriented language incorporating object oriented features.
Java is a programming language
As a programming language, Java can create all kinds of applications that could create
using any conventional programming language.
Java is a development environment
As a development environment, Java technology provides you with a large suite of tools:
a compiler, an interpreter, a documentation generator, a class file packaging tool,and so
on.
Java is an application environment
Java technology applications are typically general-purpose programs that run on any
machine where the Java runtime environment (JRE) is installed.
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.
Some Features of Java
1) The Java Virtual Machine
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

Department of MCA

BMSIT

JAVA & J2EE Laboratory

07MCA41

to be platform-independent because the compilation is done for a generic machine known


as the JVM.
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.
3) Java is portable : provides same API functions or library system calls on
each system , making platform independent
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.
Phases of a Java Program
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
Task Tool to use Output
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

Department of MCA

BMSIT

JAVA & J2EE Laboratory

07MCA41

Requirement for writing Java Programs


Editors : Eclipse, Notepad, JBuilder, NetBeans
Java Development Kit ver 1.4 and above
Java Runtime Environment
Java has following topics
Java helps to create standalone application by using the following topics
1: AWT Abstract Window Toolkit :
It helps to create Graphical User Interface by using built in packages and
classes .It contains following packages
a) Java.awt.*
b) Java.event.*;
By using the above packages, and GUI components like textarea, button ,
Textfield , graphics can be drawn.
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.
5: JDBC Java Database Connectivity
It helps to create database application by making use of SQL package
.Particular database driver must be installed in the system
6: Socket Programming
It helps to create distributed application by implementing networking
Concepts. It used java.net package
7: RMI Remote Method Invocation
It is used for inter-process communication between java virtual
machines. It is used to invoke the methods of an object existing in
separate computer, it is alternative for socket programming

Department of MCA

BMSIT

JAVA & J2EE Laboratory

07MCA41

J2EE has following topics


J2EE helps to create web application by using following topics
1: DHTML- Dynamic Hypertext Markup Language
It helps to create Interface for web application by using built in tags
2: XML-Extensible Markup LANGUAGE
3: Java script
It helps to validate client information before sending the information to
the server for processing
4: SERVLETS It is a server side programming language. Here html programs are
embedded in java program , server is required to run the servlet. .
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\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

JAVA & J2EE Laboratory

07MCA41

The package used in javax.servlet and it contains 4 interfaces and 3 classes


Interfaces are ServletRequest, ServletResponse, SevletContext, ServletStub
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 .
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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

07MCA41

Installation of Tomcat server

PATH SET FOR WEB APPLICATION

Remote Method Invocation


Concept
It is used for inter-process communication for between java virtual machines
It is used to invoke the methods of an object existing on a separate computer
It also supports to create java objects
It also supports passing of objects either by reference or by copying rather than
transfer of control to different computer
It is alternative for socket programming
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

Department of MCA

BMSIT

JAVA & J2EE Laboratory

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

1) It is a way for inter-process communication between java virtual machines


2) It invokes the methods of an object existing on separate computer

Department of MCA

BMSIT

10

JAVA & J2EE Laboratory

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:

Your browser formed a connection to a Web server, requested a page and


received it.

Department of MCA

BMSIT

11

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

07MCA41

Clients and Servers


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..

Department of MCA

BMSIT

13

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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 browser breaks the URL into three parts:


The protocol ("http")
The server name ("www.howstuffworks.com")
The file name ("web-server.htm")

The browser communicates with a name server to translate the


server name, "www.howstuffworks.com," into an IP address, which it
uses to connect to that server machine.

The browser then forms a connection to the Web server at that


IP address on port 80.

Following the HTTP protocol, the browser sends 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 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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

07MCA41

OUTPUT:
C:\LJAVA>javac expdemo.java
C:\LJAVA>java expdemo
java.lang.ArithmeticException: / by zero
The statement executes

Department of MCA

BMSIT

26

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

07MCA41

PROG4B: PROGRAM TO PASS PARAMETERS TO APPLETS AND DISPLAY


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

Department of MCA

BMSIT

33

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

07MCA41

OUTPUT
C:\>javac demo5.java
C:\>java demo5

Department of MCA

BMSIT

37

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

07MCA41

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

41

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

07MCA41

public void doPost(HttpServletRequest request,HttpServletResponse


response)throws IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String str=request.getParameter("uname");
String str1=request.getParameter("pname");
out.println("<html>");
out.println("<body>");
out.println("User Name is "+str+"<br>");
out.println("Password is "+str1);
out.println("</body>");
out.println("</html>");
}
}
Store the Index.html in
C:\Program Files\Apache Group\Tomcat 4.1\webapps\ROOT
And the demo8.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/8.html

Department of MCA

BMSIT

46

JAVA & J2EE Laboratory

07MCA41

After clicking on Submit

Department of MCA

BMSIT

47

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

07MCA41

PROG10a:
JAVA SERVLET PROGRAM TO IMPLEMENT REQUEST DISPATCHER
OBJECT (USE INCLUDE() AND FORWARD() METHODS)

Department of MCA

BMSIT

50

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

07MCA41

When click on forward

Department of MCA

BMSIT

53

JAVA & J2EE Laboratory

07MCA41

When clicked on include

Department of MCA

BMSIT

54

JAVA & J2EE Laboratory

07MCA41
PROG11:

JAVA SERVLET PROGRAM TO IMPLEMENT SENDREDIRECT() METHOD.


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");
}
}

Department of MCA

BMSIT

55

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

Department of MCA

07MCA41

BMSIT

57

JAVA & J2EE Laboratory

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>");
}
}

Store the demo12.class in

Department of MCA

BMSIT

58

JAVA & J2EE Laboratory

07MCA41

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/examples/servlet/demo12

Department of MCA

BMSIT

59

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

07MCA41

Start Tomcat
Open the Browser and give path as
http://localhost:8080/13a.jsp

Department of MCA

BMSIT

61

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

07MCA41

out.println("You are now Logged in");


%>

Store the 13b.html, 13b.jsp and welcome.jsp in


C:\Program Files\Apache Group\Tomcat 4.1\webapps\ROOT
Start Tomcat
Open the Browser and give path as
http://localhost:8080/13b.html

Department of MCA

BMSIT

63

JAVA & J2EE Laboratory

Department of MCA

07MCA41

BMSIT

64

JAVA & J2EE Laboratory

Department of MCA

07MCA41

BMSIT

65

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

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

JAVA & J2EE Laboratory

07MCA41

Create a folder as LAB14 in


C:\Program Files\Apache Group\Tomcat 4.1\webapps
Store StudInfo.html, first.jsp and display.jsp in LAB14
Create subfolders under LAB14 as
WEB-INF\classes\beans
Store the Student.class in the beans folder
Start Tomcat
Open the Browser and give path as
http://localhost:8080/LAB14/StudInfo.html

Department of MCA

BMSIT

68

JAVA & J2EE Laboratory

Department of MCA

07MCA41

BMSIT

69

JAVA & J2EE Laboratory

07MCA41

Proposed Viva-Voce questions

1.
2.
3.
4.
5.
6.

what is java? What are the features of java


write a java program demonstrating access specifies
write a java program demonstrating different operators
write a java program demonstrating conditional operators
write a java program for type casting
write a java program to access a variable declared outside and inside main
function
7. write a java program to access the method by creating a object of a class
8. write a java program demonstrating wrapper class
9. what is a super class ? give program example
10. write a java program to demonstrate inner class
11. write a java program to showcase simple and multilevel inheritance
12. what is the difference between abstract class and interface and write the program
for the same
13. what is overloading and overriding and give an program example
14. what is try and catch block
15. what is finally block
16. what is exception handling and give an program example
17. what is final variable, final class, final method
18. what is an applet and explain applet life cycle
19. write a java program to pass parameter to an applet
20. write a java program for status window, getdocumentbase(),
getcodebase(),showdocument()
21. what is appletcontext()?
22. what is audioclip interface
23. what are thread and how do you create threads?
24. Write a java program to implement all thread methods
25. Explain thread synchronization with an example
26. what is producer and consumer problem
27. what is reader writer problem
28. what is event delegation model
29. what is event, event class, event source , event listener interface
30. write a java program for adapter class and inner class
31. write a java program for each of the swing components
32. what are the 2 key swing features
33. give an overview of j2ee
34. what is jdbc and explain different jdbc drivers
35. explain the JDBC process

Department of MCA

BMSIT

70

JAVA & J2EE Laboratory

07MCA41

36. write a java program for database application


37. what is metadata
38. what is servlet and explain life cycle of servlet
39. explain servlet API
40. What are the 2 types of servlet
41. write a servlet program to pass the parameter
42. how do you handle http request and http response
43. what is a cookie and write a java program to handle cookie
44. write a java program for session tracking
45. what is JSP and what are the advantages of JSP
46. what is MVC architecture
47. explain JSP tags
48. write a java program for forward, send direct, request dispatcher
49. write a java program for user session and cookies
50. what is session objects
51. what is RMI? Explain RMI process
52. what is EJB
53. Explain different types of bean with an example

Department of MCA

BMSIT

71

You might also like