You are on page 1of 152

Advanced Java Programming Manual

Ex. No: 1

Find the IP Address of the Host

Aim:
To write a program to prompt the user for a hostname and then looks
up the IP address for the hostname and displays the results
Algorithm:
1. Import java.net and java.io packages.
2. Create the class IpAdress and save file name as IpAdress.java in
your folder
3. Read the hostname using BufferedReader object.
4. Convert the host name into IPaddress object using the getByName()
method of InetAddress class.
5. Convert the IPAddress object into string using the getHostAddress()
method.
6. Display the IPAddress.
Program:
/* To find the IP Address of the host */
import java.net.*;
import java.io.*;
class IpAddress
{
public static void main(String args[])throws IOException
{
BufferedReader bin=new BufferedReader(new
InputStreamReader(System.in));
String host;
System.out.print("Enter the host name:");
host=bin.readLine();
try
{

MSPVL Polytechnic College

Page 1

Advanced Java Programming Manual


InetAddress iad=InetAddress.getByName(host);
String ip=iad.getHostAddress();
System.out.println("IP Address of the host:"+ip);
}
catch(UnknownHostException e)
{
System.out.println("Invalid host name");
}
}
}
Output: - Compile the program
G:\ cd adjava
G:\adjava>set path=G:\java\bin
G:\adjava>javac IpAddress.java
G:\adjava>java IpAddress
Enter the host name:home
IP Address of the host:192.168.1.2
G:\adjava>
Result:
The above program was executed and the output is verified

MSPVL Polytechnic College

Page 2

Advanced Java Programming Manual

Ex.No: 2

Displaying the content of Webpage

Aim:
To write a java program to read the webpage from a website and
display the contents of the webpage.
Algorithm:
1. Import java.net and java.io package.
2. Create the class IpAdress and save file name as readurl.java in your
folder
3. Using the Buffered reader object read the website address and store it
in an URL object
4. Bind the url with the Input stream using OpenStream() method of
URL class.
5. Using a while loop read the data in the Input Stream using readLine()
method and display the read string till the Input Stream is not Null.
6. Create a html file and save it as web.html in your folder
Program:
/* Read a file in an web server */
import java.net.*;
import java.io.*;
class readurl
{
public static void main(String a[])throws Exception
{
BufferedReader br1=new BufferedReader(new
InputStreamReader(System.in));
String filename;
System.out.print("Enter the webpage address:");
filename=br1.readLine();
URL myurl=new URL(filename);
MSPVL Polytechnic College

Page 3

Advanced Java Programming Manual


InputStream in=myurl.openStream();
BufferedReader br=new BufferedReader(new
InputStreamReader(in));
String str;
System.out.println(The web page Content);
System.out.println(*******************);
while((str=br.readLine())!=null)
System.out.println(str);
br.close();
}
}
Web.html:
<html>
<head> <Title>Sample web page</title> </head>
<body bgcolor=yellow>
<font size="20">This is a sample web page to be displayed

using

Java program </font>


</body>
</html>

MSPVL Polytechnic College

Page 4

Advanced Java Programming Manual


Output:
G:\ cd adjava
G:\adjava>set path=G:\java\bin
G:\adjava>javac readurl.java
G:\adjava>java readurl
Enter the webpage address:file:///g:/javapgm/web.html
The web page Content
*******************
<html>
<head> <Title>Sample web page</title> </head>
<body bgcolor=yellow>
<font size="20">This is a sample web page to be displayed
using Java program </font>
</body>
</html>
G:\adjava>

Result:
The above program was executed and the output is verified

MSPVL Polytechnic College

Page 5

Advanced Java Programming Manual

Ex. No: 3

Client /Server Interaction using TCP

Aim:
To write a java programs for TCP server and Client interaction as per
given below.
i.

A program to create TCP server to send a message to client.

ii.

A program to create TCP client to receive the message sent by


the server.

Server Program:
Algorithm:
1. Import java.net and java.io packages.
2. Create a ServerSocket object.
3. Wait for the request from the client using the accept () method.
4. When the client request is accepted create a TCP socket.
5. Open I/O streams for communication.
6. Repeatedly send to client and receive data from client using while
loop.
7. When the communication is over close all the Sockets and the
streams.
Server Program:
import java.io.*;
import java.net.*;
public class server
{
public static void main(String a[])throws IOException
{
try
{
ServerSocket s=new ServerSocket(95);
System.out.println("Server Waiting For The Client");
Socket cs=s.accept();
MSPVL Polytechnic College

Page 6

Advanced Java Programming Manual


InetAddress ia=cs.getInetAddress();
String cli=ia.getHostAddress();
System.out.println("Connected

to

the

client

with IP:"+cli);
BufferedReader in=new BufferedReader(new
InputStreamReader(cs.getInputStream()));
PrintWriter out=new PrintWriter
(cs.getOutputStream(),true);
do
{
BufferedReader din=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("To Client:");
String tocl=din.readLine();
out.println(tocl);
String st=in.readLine();
if(st.equalsIgnoreCase("Bye")||st==null)break;
System.out.println("From Client:"+st);
}while(true);
in.close();
out.close();
cs.close();
}
catch(IOException e)
{
}
}
}

MSPVL Polytechnic College

Page 7

Advanced Java Programming Manual


Client Program:
Algorithm:
1. Import java.net and java.io packages.
2. Create a Socket object and connect to the server using the host name or
the IP Address of the server.
3. Open I/O streams for communication.
4. Repeatedly receive data from the server and send data to the server
using while loop.
5. When the communication is over close all the Sockets and the streams.
Client Program:
import java.io.*;
import java.net.*;
public class client
{
public static void main(String a[])throws IOException
{
try
{
Socket con=new Socket("localHost",95);
BufferedReader in=new BufferedReader(new
InputStreamReader(con.getInputStream()));
PrintWriter out=new
PrintWriter(con.getOutputStream(),true);
while(true)
{
String s1=in.readLine();
System.out.println("From Server:"+s1);
System.out.print("Enter the messages to the
server:");
BufferedReader din=new BufferedReader(new
InputStreamReader(System.in));
String st=din.readLine();

MSPVL Polytechnic College

Page 8

Advanced Java Programming Manual


out.println(st);
if(st.equalsIgnoreCase("Bye")||st==null)break;
}
in.close();
out.close();
con.close();
}
catch(UnknownHostException e)
{
}
}
}
Steps to run the program
 Open two command prompts.
 Set the java path in both command prompt
 Compile both the programs.
 In one command prompt first run the server program.
 In another command prompt run the client program
 Interaction of the client and server can be viewed.
Server Window Output

MSPVL Polytechnic College

Page 9

Advanced Java Programming Manual


Client window output:

Result:
The above program was executed and the output is verified

MSPVL Polytechnic College

Page 10

Advanced Java Programming Manual

Ex.No: 4

Client /Server Interaction using Datagram

Aim:
To write a java programs for Datagram server and Client interaction as
per given below.
i. A program to create Datagram server to send a message to client.
ii. A program to create Datagram client to receive the message sent
by the server.
Datagram Server
Algorithm:
1. Import java.net and java.io package.
2. Create a datagram socket object.
3. Create datagram packet to send result to client using the send()
method
4. Send the data to client.
5. Repeat step 3 and 4 until process completes.
6. When process finished close the connection.
Server Program:
/* Server program using datagram */
import java.net.*;
import java.io.*;
class dataserver
{
public static DatagramSocket ds;
public static int clientport=789,serverport=790;
public static void main(String a[]) throws Exception
{
byte buffer[]=new byte[1024];
ds=new DatagramSocket(serverport);
BufferedReader dis=new BufferedReader(new
InputStreamReader(System.in));
MSPVL Polytechnic College

Page 11

Advanced Java Programming Manual


System.out.println("Client is waiting for input from
server.Type the message");
InetAddress is=InetAddress.getByName("localhost");
while(true)
{
String str=dis.readLine();
if((str==null || str.equals("end")))
break;
buffer=str.getBytes();
ds.send(new DatagramPacket
(buffer,str.length(),is,clientport));
}
}
}
Datagram Client
Algorithm:
1. Import java.net and java.io package.
2. Create a datagram socket object
3. Create datagram packet to receive data from server
4. Listen for the packet from server using the receive() method.
5. Process received packets.
6. When process finished close the connection.
Client Program:
A client program that receives the data from the server
/* A client program that receives from the user */
import java.net.*;
import java.io.*;
class dataclient
{
public static DatagramSocket ds;
public static byte buffer[]=new byte[1024];
public static int clientport=789,serverport=790;
MSPVL Polytechnic College

Page 12

Advanced Java Programming Manual


public static void main(String a[])throws Exception
{
ds=new DatagramSocket(clientport);
System.out.println("Client is waiting for server to send
data");
System.out.println("Press ctrl c to come to dos prompt");
while(true)
{
DatagramPacket p=new
DatagramPacket(buffer,buffer.length);
ds.receive(p);
String psx=new String(p.getData(),0,p.getLength());
System.out.println(psx);
}
}
}
Server window output:

MSPVL Polytechnic College

Page 13

Advanced Java Programming Manual


Client window output:

Result:
The above program was executed and the output is verified

MSPVL Polytechnic College

Page 14

Advanced Java Programming Manual


Java Networking Viva Questions
1. What is the difference between URL instance and URLConnection
instance?
A URL instance represents the location of a resource, and a
URLConnection

instance

represents

link

for

accessing

or

communicating with the resource at the location.


2. How do I make a connection to URL?
You obtain a URL instance and then invoke openConnection on
it. URLConnection is an abstract class, which means you can't directly
create instances of it using a constructor. We have to invoke
openConnection method on a URL instance, to get the right kind of
connection for your URL. Eg. URL url;
URLConnection connection;
try{ url = new URL("...");
connection = url.openConnection();
}catch (MalFormedURLException e) { }
3. What Is a Socket?
A socket is one end-point of a two-way communication link
between two programs running on the network. A socket is bound to a
port number so that the TCP layer can identify the application that
data is destined to be sent. Socket classes are used to represent the
connection between a client program and a server program. The
java.net package provides two classes--Socket and ServerSocket-which implement the client side of the connection and the server side
of the connection, respectively.
4. What is InetAddress?
InetAddress is a class in java by which we can get IP address of
any machine. Method is "public static InetAddress getLocalHost()"

MSPVL Polytechnic College

Page 15

Advanced Java Programming Manual


5. What is meant by TCP, IP, UDP?
TCP is Tranmission Control Protocol
IP - Internet Protocol
UDP - User Datagram Protocol.
6. What information is needed to create a TCP Socket?
The Local Systems IP Address and Port Number. And the
Remote System's IPAddress and Port Number.
7. What are the two important TCP Socket classes?
Socket and ServerSocket. ServerSocket is used for normal twoway socket communication. Socket class allows us to read and write
through the sockets. getInputStream() and getOutputStream() are the
two methods available in Socket class.
8. When

MalformedURLException

and

UnknownHostException

throws?
When the specified URL is not connected then the URL throw
MalformedURLException and If InetAddress? methods getByName and
getLocalHost are unable to resolve the host name they throw an
UnknownHostException.
9. The API doesn't list any constructors for InetAddress- How do I
create an InetAddress instance?
In case of InetAddress the three methods getLocalHost,
getByName, getByAllName can be used to create instances.
E.g.
InetAddress add1;
InetAddress add2;
try{
add1 = InetAddress.getByName("java.sun.com");
add2 = InetAddress.getByName("199.22.22.22");
}catch(UnknownHostException e){}

MSPVL Polytechnic College

Page 16

Advanced Java Programming Manual


10. Is it possible to get the Local host IP?
Yes. Use InetAddress's getLocalHost method.
11. What's the Factory Method?
Factory methods are merely a convention whereby static
methods in a class return an instance of that class. The InetAddress
class has no visible constructors. To create an InetAddress object, you
have to use one of the available factory methods. In InetAddress the
three methods getLocalHost, getByName, getByAllName can be used
to create instances of InetAddress.
12. Whats the difference between TCP and UDP?
These two protocols differ in the way they carry out the action of
communicating. A TCP protocol establishes a two way connection
between a pair of computers, while the UDP protocol is a one-way
message sender. The common analogy is that TCP is like making a
phone call and carrying on a two-way communication, while UDP is
like mailing a letter.
13. What is the Proxy Server?
A proxy server speaks the client side of a protocol to another
server. This is often required when clients have certain restrictions on
which servers they can connect to. And when several users are hitting
a popular web site, a proxy server can get the contents of the web
server's popular pages once, saving expensive internetwork transfers
while providing faster access to those pages to the clients.
Also, we can get multiple connections for a single server.

MSPVL Polytechnic College

Page 17

Advanced Java Programming Manual

Ex.No: 5

Database access using JDBC

Aim:
To write a java program by using JDBC to execute a SQL query for a
database and display the results.
Algorithm:
Step 1: Creating table
Create a database called student in MS Access. Within the database
create a table called stu with two fields regno and name.
Step 2: Creating DSN
Link the database created in the step1 with the Data source Name
(DSN) Mydata using the ODBC
Step 3: Writing java application
1. Import java.sql package.
2. Register the driver using the Class.forname() method.
3. Connect to the database using the Data Source Name already
defined in the ODBC with the help of DriverManager.getConnection
method().
4. Create a Statement Object.
5. Execute the select query using the executeQuery() method of
Statement and store the data in the Resultset object.
6. Using a while loop print the data in the result set.
7. Close the statement and connection.
Program:
import java.sql.*;
class demojdbc
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
MSPVL Polytechnic College

Page 18

Advanced Java Programming Manual


Connection

cn=

DriverManager.getConnection

("Jdbc:Odbc:Mydata");
System.out.println("Database connected");
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery("Select * from stu");
System.out.println("\nRegno\t Name");
while(rs.next())
System.out.println(rs.getString("regno")+"\t"
+rs.getString("name"));
st.close();
cn.close();
}
catch(ClassNotFoundException e)
{
System.out.println(e.getMessage());
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
}
Output:
G:\adjava>javac demojdbc.java
G:\adjava>java demojdbc
Database connected
Regno

Name

Gills

Dolly

Banu

Honey

Geetha

G:\adjava>
Result:
The above program was executed and the output is verified

MSPVL Polytechnic College

Page 19

Advanced Java Programming Manual

Ex.No: 6

Database access using JDBC


(Execute update Query)

Aim:
To write a java program by using JDBC to execute an update query
without using PreparedStatement and display the results.
Algorithm:
Step 1: Creating table
Create a database called student in MS Access. Within the database
create a table called stu with two fields regno and name.
Step 2: Creating DSN
Link the database created in the step1 with the Data source Name
(DSN) Mydata using the ODBC
Step 3: Writing java application
1. Import java.sql package.
2. Register the driver using the Class.forname() method.
3. Connect to the database using the Data Source Name already
defined in the ODBC with the help of DriverManager.getConnection
method().
4. Read the roll number(rno) and the name (str) to be modified
5. Define the query as a String object
query="Update stu set name= '"+str+"'where regno="+rno;
6. Create a Statement Object.
7. Execute the update query using the executeUpdate() method of
Statement object.
8. Using the value returned by the executeUpdate() method display
whether the data is updated or not.
9. Close the statement and connection.

MSPVL Polytechnic College

Page 20

Advanced Java Programming Manual


Program:
import java.sql.*;
import java.io.*;
class UpdateData
{
public static void main(String args[])throws IOException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection
("Jdbc:Odbc:Mydata");
System.out.println("Database connected");
BufferedReader bin=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter the roll number of the student:");
int rno=Integer.parseInt(bin.readLine());
System.out.print("Enter the new name:");
String str=bin.readLine();
String query="Update stu set name= '"+str
+"'where regno="+rno;
Statement st=cn.createStatement();
int flag=st.executeUpdate(query);
if(flag>0)
System.out.println("Record updated");
else
System.out.println("No record updated");
st.close();
cn.close();
}
catch(ClassNotFoundException e)
{
System.out.println(e.getMessage());
MSPVL Polytechnic College

Page 21

Advanced Java Programming Manual


}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
}
Output:
G:\adjava>javac UpdateData.java
G:\adjava>java UpdateData
Database connected
Enter the roll number of the student:8
Enter the new name: Banu Lakshmi
Record updated
Result:
The above program was executed and the output is verified

MSPVL Polytechnic College

Page 22

Advanced Java Programming Manual

Ex.No: 7

Database access using JDBC & Prepared


Statement

Aim:
To write a java program by using JDBC to execute an update query by
using PreparedStatement and display the results.
Algorithm:
Step 1: Creating table
Create a database called student in MS Access. Within the database
create a table called stu with two fields regno and name.
Step 2: Creating DSN
Link the database created in the step1 with the Data source Name
(DSN) Mydata using the ODBC
Step 3: Writing java application
1. Import java.sql package.
2. Register the driver using the Class.forname() method.
3. Connect to the database using the Data Source Name already
defined in the ODBC with the help of DriverManager.getConnection
method().
4. Read the roll number(rno) and the name (str) to be modified
5. Define the query as a String object
String query="Update stu set name=? where regno=?";
6. Create a PreparedStatement Object using prepare Statement
(query) method.
7. Using set() method set the values of the parameters in query.
8. Execute the update query using the executeUpdate() method of
PreparedStatement object.
9. Using the value returned by the executeUpdate() method display
whether the data is updated or not.
10. Close the statement and connection.

MSPVL Polytechnic College

Page 23

Advanced Java Programming Manual


Program:
import java.sql.*;
import java.io.*;
class DemoPrepare
{
public static void main(String args[])throws IOException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection
("Jdbc:Odbc:Mydata");
System.out.println("Database connected");
BufferedReader bin=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter the roll number of the student:");
int rno=Integer.parseInt(bin.readLine());
System.out.print("Enter the new name:");
String str=bin.readLine();
String query="Update stu set name=? where regno=?";
PreparedStatement pst=cn.prepareStatement(query);
pst.clearParameters();
pst.setString(1,str);
pst.setInt(2,rno);
int flag=pst.executeUpdate();
if(flag>0)
System.out.println("Record updated");
else
System.out.println("No record updated");
pst.close();
cn.close();
}
catch(ClassNotFoundException e)
MSPVL Polytechnic College

Page 24

Advanced Java Programming Manual


{
System.out.println(e.getMessage());
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
}
Output:
G:\adjava>javac DemoPrepare.java
G:\adjava>java DemoPrepare
Database connected
Enter the roll number of the student:1
Enter the new name: Nawin
Record updated
Result:
The above program was executed and the output is verified

MSPVL Polytechnic College

Page 25

Advanced Java Programming Manual

Ex.No:8 Database access using JDBC & Callable


Statement
Aim:
To write a java program to execute a stored procedure in the database
by using CallableStatement and display the results.
Algorithm:
Step 1: Creating table
Create a database called student in MS Access. Within the database
create a table called stu with two fields regno and name.
Step 2: Creating stored procedure in MS Access
1. Select the stu table.
2. Select the QueryDesign option from the create tab.
3. Close the Show Table window that appears.
4. Select the SQL view from the view option.
5. Type the query
INSERT INTO stu ( regno, name ) VALUES ([@rno], [@str]);
6. Save the query as Ins_Proc
Step 2: Creating DSN
Link the database created in the step1 with the Data source Name
(DSN) Mydata using the ODBC
Step 3: Writing java application
1. Import java.sql package.
2. Register the driver using the Class.forname() method.
3. Connect to the database using the Data Source Name already
defined in the ODBC with the help of DriverManager.getConnection
method().
4. Read the roll number(rno) and the name (str) to be inserted.
5. Define the query as a String object
String query="{call Ins_proc("+rno+","+str+")}";
6. Create a CalalbleStatement Object using prepareCall (query)
method.
MSPVL Polytechnic College

Page 26

Advanced Java Programming Manual


7. Execute the update query using the executeUpdate() method of
CalalbleStatement object.
8. Using the value returned by the executeUpdate().
9. Close the statement and connection.
Program:
import java.sql.*;
import java.io.*;
class DemoCallable
{
public static void main(String args[])throws IOException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection
("Jdbc:Odbc:Mydata");
System.out.println("Database connected");
BufferedReader bin=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Inserting data:");
System.out.print("Enter the roll number of the student:");
int rno=Integer.parseInt(bin.readLine());
System.out.print("Enter the name of the student:");
String str=bin.readLine();
String query="{call Ins_proc("+rno+","+str+")}";
CallableStatement cst=cn.prepareCall(query);
int flag=cst.executeUpdate();
if(flag>0)
System.out.println("Record Inserted");
else
System.out.println("No record Inserted");
cst.close();

MSPVL Polytechnic College

Page 27

Advanced Java Programming Manual


cn.close();
}
catch(ClassNotFoundException e)
{
System.out.println(e.getMessage());
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
}
Output:
G:\adjava>javac DemoCallable.java
G:\adjava>java DemoCallable
Database connected
Inserting data:
Enter the roll number of the student:10
Enter the name of the student:Susil
Record Inserted
Result:
The above program was executed and the output is verified

MSPVL Polytechnic College

Page 28

Advanced Java Programming Manual


JDBC Viva Questions
1. What is JDBC?
JDBC technology is an API (included in both J2SE and J2EE
releases) that provides cross-DBMS connectivity to a wide range of
SQL databases and access to other tabular data sources, such as
spreadsheets or flat files. With a JDBC technology-enabled driver, you
can connect all corporate data even in a heterogeneous environment
2. What are stored procedures?
A stored procedure is a set of statements/commands which
reside in the database. The stored procedure is precompiled. Each
Database has it's own stored procedure language,
3. What is JDBC Driver?
The JDBC Driver provides vendor-specific implementations of
the abstract classes provided by the JDBC API. This driver is used to
connect to the database.
4. What are the different JDBC drivers available?
There are mainly four type of JDBC drivers available. They are:
 Type 1 : JDBC-ODBC Bridge Driver
 Type 2: Native API Partly Java Driver
 Type 3: Network protocol Driver
 Type 4: JDBC Net pure Java Driver
5. What is the fastest type of JDBC driver?
Type 4 (JDBC Net pure Java Driver) is the fastest JDBC driver.
Type 1 and Type 3 drivers will be slower than Type 2 drivers (the
database calls are make at least three translations versus two), and
Type 4 drivers are the fastest (only one translation).
6. What are the steps involved in establishing a JDBC connection?
This action involves two steps: loading the JDBC driver and
making the connection.

MSPVL Polytechnic College

Page 29

Advanced Java Programming Manual


7. How can you load the drivers?
Loading the driver or drivers you want to use is very simple and
involves just one line of code. If, for example, you want to use the
JDBC-ODBC Bridge driver, the following code will load it:
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Your driver documentation will give you the class name to use.
For instance, if the class name is jdbc.DriverXYZ, you would load the
driver with the following line of code:
Class.forName(jdbc.DriverXYZ);
8. What will Class.forName do while loading drivers?
It is used to create an instance of a driver and register it with
the DriverManager. When you have loaded a driver, it is available for
making a connection with a DBMS.
9. How can you make the connection?
To establish a connection you need to have the appropriate
driver connect to the DBMS. The following line of code illustrates the
general idea:
String url = jdbc:odbc:Fred;
Connection con = DriverManager.getConnection(url, Fernanda,
J8?);
10. How can you create JDBC statements and what are they?
A Statement object is what sends your SQL statement to the
DBMS. You simply create a Statement object and then execute it,
supplying the appropriate execute method with the SQL statement
you want to send. For a SELECT statement, the method to use is
executeQuery. For statements that create or modify tables, the
method to use is executeUpdate. It takes an instance of an active
connection to create a Statement object. In the following example, we
use our Connection object con to create the Statement object
Statement stmt = con.createStatement();

MSPVL Polytechnic College

Page 30

Advanced Java Programming Manual


11. How can you retrieve data from the ResultSet?
JDBC returns results in a ResultSet object, so we need to
declare an instance of the class ResultSet to hold our results. The
following code demonstrates declaring the ResultSet object rs.
ResultSet rs = stmt.executeQuery(SELECT COF_NAME, PRICE
FROM

COFFEES);

String s = rs.getString(COF_NAME);
The method getString is invoked on the ResultSet object rs, so
getString() will retrieve (get) the value stored in the column
COF_NAME in the current row of rs.
12. What are the different types of Statements?
Regular statement (use createStatement method), prepared
statement (use prepareStatement method) and callable statement (use
prepareCall)
13. How can you use PreparedStatement?
This special type of statement is derived from class Statement.If
you need a Statement object to execute many times, it will normally
make sense to use a PreparedStatement object instead. The
advantage to this is that in most cases, this SQL statement will be
sent to the DBMS right away, where it will be compiled. As a result,
the PreparedStatement object contains not just an SQL statement,
but an SQL statement that has been precompiled. This means that
when the PreparedStatement is executed, the DBMS can just run the
PreparedStatements SQL statement without having to compile it
first.
PreparedStatement updateSales =
con.prepareStatement("UPDATE COFFEES SET SALES = ?
WHERE
COF_NAME LIKE ?");

MSPVL Polytechnic College

Page 31

Advanced Java Programming Manual


14. What does setAutoCommit do?
When a connection is created, it is in auto-commit mode. This
means that each individual SQL statement is treated as a
transaction and will be automatically committed right after it is
executed. The way to allow two or more statements to be grouped
into a transaction is to disable auto-commit mode:
con.setAutoCommit(false);
Once auto-commit mode is disabled, no SQL statements will be
committed until you call the method commit explicitly.
con.setAutoCommit(false);
PreparedStatement updateSales =
con.prepareStatement( "UPDATE COFFEES SET SALES = ?
WHERE COF_NAME LIKE ?");
updateSales.setInt(1,

50);

updateSales.setString

(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal =
con.prepareStatement("UPDATE

COFFEES

SET

TOTAL

TOTAL + ? WHERE COF_NAME LIKE ?");


updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);
15. How do you call a stored procedure from JDBC?
The first step is to create a CallableStatement object. As with
Statement an and PreparedStatement objects, this is done with an
open
Connection object. A CallableStatement object contains a call to a
stored procedure.
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();

MSPVL Polytechnic College

Page 32

Advanced Java Programming Manual


16. Does the JDBC-ODBC Bridge support multiple concurrent open
statements per connection?
No.You can open only one Statement object per connection
when you are using the JDBC-ODBC Bridge.
17. What is the advantage of using PreparedStatement?
If we are using PreparedStatement the execution time will be
less.The

PreparedStatement

object

contains

not

just

an

SQL

statement, but the SQL statement that has been precompiled.This


means that when the PreparedStatement is executed,the RDBMS can
just run the PreparedStatement's Sql statement without having to
compile it first.
18. How do you handle your own transaction ?
Connection Object has a method called setAutocommit(Boolean
istrue)- Default is true. Set the Parameter to false , and begin your
transaction.
19. What is the normal procedure followed by a java client to access
the db?
The database connection is created in 3 steps:
 Find a proper database URL.
 Load the database driver.
 Ask the Java DriverManager class to open a connection to
your database.
In java code, the steps are realized in code as follows:
Create a properly formatted JDBR URL for your database.
A JDBC URL has the
formjdbc:someSubProtocol://myDatabaseServer/theDatabaseN
ame
Class.forName("my.database.driver");
Connection

conn

DriverManager.getConnection

("a.JDBC.URL", "databaseLogin","databasePassword");

MSPVL Polytechnic College

Page 33

Advanced Java Programming Manual


20. What is a data source?
A DataSource class brings another level of abstraction than
directly using a connection object. Data source can be referenced by
JNDI. Data Source may point to RDBMS, file System , any DBMS etc.
21. Why can't any one invoke the ResultSet methods afterLast and
beforeFirst when the method next works?
You are probably using a driver implemented for the JDBC 1.0
API. You need to upgrade to a JDBC 2.0 driver that implements
scrollable result sets. Also be sure that your code has created
scrollable result sets and that the DBMS you are using supports
them.
22. What are the steps required to execute a query in JDBC?
First we need to create an instance of a JDBC driver or load
JDBC drivers, then we need to register this driver with DriverManager
class. Then we can open a connection. By using this connection, we
can create a statement object and this object will help us to execute
the query.
23. What is DriverManager ?
DriverManager is a class in java.sql package. It is the basic
service for managing a set of JDBC drivers.
24. What is a ResultSet ?
 Result set is a table of data representing a database result set, which
is usually generated by executing a statement that queries the
database.
 A ResultSet object maintains a cursor pointing to its current row of
data. Initially the cursor is positioned before the first row. The next
method moves the cursor to the next row, and because it returns
false when there are no more rows in the ResultSet object, it can be
used in a while loop to iterate through the result set.

MSPVL Polytechnic College

Page 34

Advanced Java Programming Manual


25. What is Connection?
 Connection class represents a connection (session) with a specific
database. SQL statements are executed and results are returned
within the context of a connection.
 A Connection object's database is able to provide information
describing its tables, its supported SQL grammar, its stored
procedures, the capabilities of this connection, and so on. This
information is obtained with the getMetaData method.
26. What is Connection pooling?
Connection pooling is a technique used for sharing server
resources among requesting clients. Connection pooling increases the
performance

of

Web

applications

by

reusing

active

database

connections instead of creating a new connection with every request.


Connection pool manager maintains a pool of open database
connections.

MSPVL Polytechnic College

Page 35

Advanced Java Programming Manual

Configuring Apache Tomcat Server to run Servlets

1. Download the Apache Tomcat Software


Go to http://tomcat.apache.org/download-60.cgi and download and
unpack the zip file for the current release build of Tomcat 6
2. Set the JAVA_HOME Variable

Next, you must set the JAVA_HOME environment variable to tell


Tomcat where to find Java. Failing to properly set this variable
prevents Tomcat from compiling JSP pages. This variable should list
the base JDK installation directory, not the bin subdirectory.

On Windows XP, you could also go to the Start menu, select Control
Panel, choose System, click on the Advanced tab, press the
Environment

Variables

button

at

the

bottom,

and

enter

the

JAVA_HOME variable and value directly.


3. Turn on Servlet Reloading
To turn on servlet reloading, edit Edit install_dir/conf/context.xml
and change
<Context>

to

<Context reloadable="true" privileged="true">


4. Enable the Invoker Servlet

The invoker servlet lets you run servlets without first making changes
to your Web application's deployment descriptor (i.e., the WEBINF/web.xml file). Instead, you just drop your servlet into WEBINF/classes and use the URL http://host/servlet/ServletName

To enable the invoker servlet, uncomment the following servlet and


servlet-mapping elements in install_dir/conf/web.xml. Do not confuse
this Apache Tomcat-specific web.xml file with the standard one that
goes in the WEB-INF directory of each Web application.
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>

MSPVL Polytechnic College

Page 36

Advanced Java Programming Manual


org.apache.catalina.servlets.InvokerServlet
</servlet-class>
...
</servlet>
...
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
5. Turn on Directory Listings (Optional)
To make this change, edit install_dir/conf/web.xml and change the
init-param value of listings for the default servlet, as below.
<servlet>
<servlet-name>default</servlet-name>
<servletclass>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
6. Set the CATALINA_HOME Variable (Optional)
Set the CATALINA_HOME environment variable to refer to the toplevel directory of the Apache Tomcat installation (e.g., C:\apachetomcat-6.0.18). This variable identifies the Tomcat installation
directory to the server.

MSPVL Polytechnic College

Page 37

Advanced Java Programming Manual

Ex.No: 9 Servlet program to display message in a browser


Aim:
To write a java servlet program to display a greeting message in the
browser by using HttpServlet.
Procedure:
Servlet Program:
1. Open the note pad.
2. Write the servlet program that extends the HttpServlet.
3. In the doGet() method write a welcome message with the help of the
println method of PrintWriter object
4. Save the file as HelloServlet.java
Running the Program:
1. Open a command prompt.
2. Go to the directory where the HelloServlet.java file is saved.
3. set CLASSPATH=.;%CATALINA_HOME%\lib\servlet-api.jar
4. Compile the file using
javac HelloServlet.java.
now you can get HelloServlet.class in your folder
5. Copy

the

HelloServlet.class

file

into

6.0.18\webapps\ROOT\WEB-INF\classes

C:\apache-tomcat-

folder

(if

the

classes

folder is not present create the folder into WEB-INF folder)


6. D:\Tomcat\apache-tomcat-6.0.20\bin in that click startup.batch
file and then click option. Now Tomcat server will be started.
7. Open

web

browser

and

invoke

the

servlet

by

typing

http://localhost:8080/servlet/HelloServlet in the Address bar.


Program:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
MSPVL Polytechnic College

Page 38

Advanced Java Programming Manual


public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException,
IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello</TITLE></HEAD>");
out.println("<BODY BGCOLOR=\"#FDF5E6\">");
out.println("<H1>Welcome to MSPVL</H1>");
out.println("</BODY>");
out.println("</HTML>");
}
}
Output:

Result:
The above program was executed and the output is verified

MSPVL Polytechnic College

Page 39

Advanced Java Programming Manual

Ex.No: 10 Servlet program to process HTML form data

Aim:
To write a servlet program to receive two numbers from a HTML form
and display their sum in the browser by using HttpServlet.
Procedure:
HTML File:
1. Open the note pad.
2. Design a html from with two text boxes to read the two numbers to be
added.
3. Let their NAME be param1 and param 2.
4. Add Submit button.
5. The ACTION attribute of the form as /servlet/Addition.
6. Save

the

html

file

as

add.html

in

the

C:\apache-tomcat-

6.0.18\webapps\ROOT folder
Servlet Program:
1. Open the note pad.
2. Write the servlet program that extends the HttpServlet.
3. In the doGet() method read the parameters sent by the HTML file
using the request.getParameter() method.
4. Add the data and print the result.
5. Save the file as Addition.java
Running the Program:
1. Open a command prompt.
2. Go to the directory where the Addition.java file is saved.
3. set CLASSPATH=.;%CATALINA_HOME%\lib\servlet-api.jar
4. Compile the file using
javac Addition.java

MSPVL Polytechnic College

Page 40

Advanced Java Programming Manual


5. Copy

the

Addition.class

file

into

C:\apache-tomcat-

6.0.18\webapps\ROOT\WEB-INF\classes folder (if the classes folder


is not present create it)
6. D:\Tomcat\apache-tomcat-6.0.20\bin in that click startup.batch
file and then click option. Now Tomcat server will be started.
7. Open

web

browser

and

invoke

the

HTML

by

typing

http:localhost:8080/add.html in the Address bar.


8. Type the values in the text boxes and click Submit button to get the
result.
Program:
<HTML>
<HEAD>
<TITLE>Collecting Three Parameters</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">INPUT TWO NUMBERS</H1>
<FORM ACTION="/servlet/Addition">
<CENTER>
<TABLE>
<TR>
<TD>First Number:</TD>
<TD><INPUT TYPE="TEXT" NAME = "param1"> </TD>
</TR>
<TR>
<TD>Second Number:</TD>
<TD><INPUT TYPE="TEXT" NAME="param2"></TD>
</TR>
</TABLE><BR><BR><BR>
<INPUT TYPE="SUBMIT" VALUE="ADD"></CENTER>
</FORM>
</BODY>
</HTML>

MSPVL Polytechnic College

Page 41

Advanced Java Programming Manual


Servlet Program:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Addition extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException,
IOException
{
int a,b,sum;
a=Integer.parseInt(request.getParameter("param1"));
b=Integer.parseInt(request.getParameter("param2"));
sum=a+b;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Adding two numbers";
out.println("<HTML> \n"+

"<BODY

BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<UL>\n" +
" <LI><B>Number 1</B>: " + a + "\n" +
" <LI><B>Number 2</B>: " +b + "\n" +
"<LI><B>Sum

</B>:"+sum+"\n"+

"</UL>\n" +
"</BODY></HTML>");
}
}

MSPVL Polytechnic College

Page 42

Advanced Java Programming Manual


Output:

Result:
The above program was executed and the output is verified

MSPVL Polytechnic College

Page 43

Advanced Java Programming Manual

Ex.No: 11 Servlet program that uses Response Redirection

Aim:
To write a servlet program to display a list of five websites in a HTML
form and visit to the selected website by using Response redirection.
Procedure:
HTML File:
1. Open the note pad.
2. Design a html form with the names of five websites.
3. The href attribute of the form as servlet/LinkTracker?link=website
address. Link is the name of the parameter referenced by the servlet.
4. Save

the

html

file

as

link.html

in

the

C:\apache-tomcat-

6.0.18\webapps\ROOT folder
Servlet Program:
1. Open the note pad.
2. Write the servlet program that extends the HttpServlet.
3. In the doGet() method read the parameters sent by the HTML file
using the request.getParameter() method.
4. Using the response.sendRedirect the requested web page is opened.
5. Save the file as LinkTracker.java
Running the Program:
1. Open a command prompt.
2. Go to the directory where the LinkTracker.java file is saved.
3. set CLASSPATH=.;%CATALINA_HOME%\lib\servlet-api.jar
4. Compile the file using
javac LinkTracker.java
5. Copy

the

LinkTracker.class

file

into

C:\apache-tomcat-

6.0.18\webapps\ROOT\WEB-INF\classes folder (if the classes folder


is not present create it)

MSPVL Polytechnic College

Page 44

Advanced Java Programming Manual


6. D:\Tomcat\apache-tomcat-6.0.20\bin in that click startup.batch
file and then click option. Now Tomcat server will be started.
7. Open

web

browser

and

invoke

the

HTML

by

typing

http://localhost:8080/link.html in the Address bar.


8. Click on the website you want to view it.
Program:
HTML File
<HTML>
<HEAD>
<title>Response redirection</title>
</HEAD>
<BODY>
<form name="f1"> <H1>Select the link you want</H1>
<UL>
<LI><A target=_blank
href="/servlet/LinkTracker?link=http://www.google.com">
Google Site</A></LI>
<LI><A target=_blank
href="/servlet/LinkTracker?link=http://www.ustudy.in">
You Study</A></LI>
<LI><A target=_blank
href="/servlet/LinkTracker?link=http://java.sun.com">
Sun Microsystems</A></LI>
<LI><A target=_blank
href="/servlet/LinkTracker?link=http://www.yahoo.com">
Yahoo</A></LI>
<li><a target=_blank
href="/servlet/LinkTracker?link=http://www.oracle.com">
Oracle</a></li></UL>
</FORM>
</BODY>
</HTML>

MSPVL Polytechnic College

Page 45

Advanced Java Programming Manual


Servlet Program:
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LinkTracker extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws IOException,
ServletException
{
String link = request.getParameter("link");
response.sendRedirect(link);
}
}
Output:

Result:
The above program was executed and the output is verified

MSPVL Polytechnic College

Page 46

Advanced Java Programming Manual

Ex.No: 12

Servlet program to manipulate cookies

Aim:
To write a Servlet program to store the user information into Cookies.
Write another program to display the above stored information by retrieving
from Cookies.
Procedure:
HTML File:
1. Open the note pad.
2. Design a HTML form with to read the username and password.
3. Add Submit button.
4. The ACTION attribute of the form as /servlet/set.
5. Save the html file as cookie.html in the C:\apache-tomcat6.0.18\webapps\ROOT folder
Servlet Program to set the Cookie:
1. Open the note pad.
2. Write the servlet program that extends the HttpServlet.
3. In the doPost() method read the parameters sent by the HTML file
(User Name and password) using the request.getParameter() method.
4. Using the read value create a Cookie object.
5. Set the cookie to the cookie object using addCookie() method.
6. Define a form which has a submit button to view the cookie set.
7. Set the ACTION attribute of the form be /servlet/getCookie.
8. Save the file as set.java
Servlet Program to read the Cookie:
1. Open the note pad.
2. Write the servlet program that extends the HttpServlet.
3. In the doPost() method read the Cookie values into Cookie object using
the getCookies() method.
4. Display the cookie values using the print method.
5. Save the file as getCookie.java
MSPVL Polytechnic College

Page 47

Advanced Java Programming Manual


Running the Program:
1. Open a command prompt.
2. Go to the directory where the set.java and getcookies files are saved.
3. set CLASSPATH=.;%CATALINA_HOME%\lib\servlet-api.jar
4. Compile the file using
javac set.java
javac getCookie.java
5. Copy the set.class and getCookie.class files into C:\apache-tomcat6.0.18\webapps\ROOT\WEB-INF\classes folder (if the classes folder
is not present create it)
6. Start Tomcat server.
7. Open

web

browser

and

invoke

the

HTML

by

typing

http://localhost:8080/cookie.html in the Address bar.


8. Give the user name and password then press the Submit button.
Program:
Cookie.html
<HTML>
<HEAD>
<TITLE>Cookies Example</TITLE>
</HEAD>
<BODY>
<CENTER>
<BODY bgcolor="white">
<H3>Cookies Example</H3>
<P>
Create a cookie to send to your browser<BR>
<H1> Login Form</H1></CENTER>
<FORM action="\servlet\set" METHOD="post">
<TABLE border=2 align=center>
<TR>
<TD>User Name: </TD>
<TD><input type=text length=20 name=user></TD>
</TR>
MSPVL Polytechnic College

Page 48

Advanced Java Programming Manual


<TR>
<TD>Password: </TD>
<Td> <input type=password length=20 name=info></TD>
</TR>
<TR>
<TD

align=center

colspan=2><input

type=submit

value="submit

form"></TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>
set.java
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.ServletException;
public class set extends HttpServlet
{
public

void

HttpServletResponse

doPost(HttpServletRequest
response)throws

request,

ServletException,

IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String name = request.getParameter("user");
String value=request.getParameter("info");
Cookie cookie = new Cookie(name,value);
response.addCookie(cookie);
pw.println("<B>MyCookie has been set the user
information ");
pw.println("<form action=\"" +
response.encodeURL("/servlet/getCookie")+

MSPVL Polytechnic College

Page 49

Advanced Java Programming Manual


"\" method=\"post\">"+
"<input type=\"submit\""+
"value=\"Display cookie value\">" + "</form>");
}
}
getCookie.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class getCookie extends HttpServlet
{
public

void

HttpServletResponse

doPost(HttpServletRequest
response)throws

request,

ServletException,

IOException
{
Cookie[] cookies = request.getCookies();
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B><table border='2'>");
pw.print("<tr><td><b>username</b></td><td><b>Secret
Code</b></td></tr>");
for (int i = 0; i < cookies.length; i++)
{
Cookie c=cookies[i];
String name = c.getName();
String value = c.getValue();
pw.print("<tr><td>" + name + "</td><td>" +
value + "</td></tr>");
}
pw.print("</table>");
}
}
MSPVL Polytechnic College

Page 50

Advanced Java Programming Manual


Output:

Result:
The above program was executed and the output is verified

MSPVL Polytechnic College

Page 51

Advanced Java Programming Manual


Servlet Viva Questions
1. What is Servlet?
A servlet is a Java technology-based Web component, managed
by a container called servlet container or servlet engine, that
generates dynamic content and interacts with web clients via a
request\/response paradigm.
2. Why is Servlet so popular?
Because servlets are platform-independent Java classes that are
compiled to platform-neutral byte code that can be loaded dynamically
into and run by a Java technology-enabled Web server.
3. What is servlet container?
The servlet container is a part of a Web server or application
server that provides the network services over which requests and
responses are sent, decodes MIME-based requests, and formats
MIME-based responses. A servlet container also contains and
manages servlets through their lifecycle.
4. Explain the life cycle methods of a Servlet?
The javax.servlet.Servlet interface defines the three methods
known as life-cycle method.public void init(ServletConfig config)
throws

ServletExceptionpublic

void

service(

ServletRequest

req,

ServletResponse res) throws ServletException, IOExceptionpublic void


destroy()First the servlet is constructed, then initialized wih the init()
method.Any request from client are handled initially by the service()
method before delegating to the doXxx() methods in the case of
HttpServlet.The servlet is removed from service, destroyed with the
destroy() methid, then garbaged collected and finalized.

MSPVL Polytechnic College

Page 52

Advanced Java Programming Manual


5. What is the difference between the getRequestDispatcher(String
path)

method of javax.servlet.ServletRequest interface and

javax.servlet.ServletContext interface?
The getRequestDispatcher(String path) method of javax. servlet.
ServletRequest interface accepts parameter the path to the resource to
be included or forwarded to, which can be relative to the request of
the calling servlet.If the path begins with a "/" it is interpreted as
relative to the current context root.The getRequestDispatcher(String
path) method of javax.servlet.ServletContext interface cannot accepts
relative paths.All path must sart with a "/" and are interpreted as
relative to curent context root.
6. Explain the directory structure of a web application.
The directory structure of a web application consists of two
parts. A private directory called WEB-INF, A public resource directory
which contains public resource folder.WEB-INF folder consists of
1.web.xml 2.classes directory 3.lib directory
7. What are the common mechanisms used for session tracking?
CookiesSSL sessionsURL- rewriting
8. Explain ServletContext.
ServletContext interface is a window for a servlet to view it's
environment.A servlet can use this interface to get information such
as

initialization

parameters

for

the

web

applicationor

servlet

container's version.Every web application has one and only one


ServletContext and is accessible to all active resource of that
application.
9. What is the difference between Difference between doGet() and
doPost()?
A doGet() method is limited with 2k of data to be sent, and
doPost() method doesn't have this limitation.A request string for
doGet()

looks

like

the

following:

http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vNdoPost()
MSPVL Polytechnic College

Page 53

Advanced Java Programming Manual


method call doesn't need a long text tail after a servlet name in a
request.All parameters are stored in a request itself, not in a request
string, and it's impossible to guess the data transmitted to a servlet
only looking at a request string.
10. What is the difference between HttpServlet and GenericServlet?
A GenericServlet has a service() method aimed to handle
requests.HttpServlet extends GenericServlet and adds support for
doGet(),

doPost(),

doHead()

methods

(HTTP

1.0)

plus

doPut(),

doOptions(), doDelete(), doTrace() methods (HTTP 1.1).Both these


classes are abstract.
11. When a client request is sent to the servlet container, how does
the container choose which servlet to invoke?
The servlet container determines which servlet to invoke based
on the configuration of its servlets, and calls it with objects
representing the request and response.
12. If a servlet is not properly initialized, what exception may be
thrown?
During initialization or service of a request, the servlet instance
can throw an UnavailableException or a ServletException.
13. Given the request path below, which are context path, servlet
path and path info?
/bookstore/education/index.html
context path: /bookstore
servlet path: /education
path info: /index.html
14. What is filter? Can filter be used as request or response?
A filter is a reusable piece of code that can transform the
content of HTTP requests,responses, and header information. Filters
do not generally create a response or respond to a request as servlets
do, rather they modify or adapt the requests for a resource, and
modify or adapt responses from a resource.
MSPVL Polytechnic College

Page 54

Advanced Java Programming Manual


15. When using servlets to build the HTML, you build a DOCTYPE
line, why do you do that?
I know all major browsers ignore it even though the HTML 3.2
and 4.0 specifications require it. But building a DOCTYPE line tells
HTML validators which version of HTML you are using so they know
which specification to check your document against. These validators
are valuable debugging services, helping you catch HTML syntax
errors.
16. Request parameter How to find whether a parameter exists in
the request object?
 boolean hasFoo = !(request.getParameter("foo") == null ||
request.getParameter("foo").equals(""));
 boolean hasParameter =
request.getParameterMap().contains(theParameter);
17. How can I send user authentication information while making
URL Connection?
You'll want to use HttpURLConnection.setRequestProperty and
set all the appropriate headers to HTTP authorization.
18. Can we use the constructor, instead of init(), to initialize
servlet?
Yes , of course you can use the constructor instead of init().
There's nothing to stop you. But you shouldn't. The original reason for
init() was that ancient versions of Java couldn't dynamically invoke
constructors with arguments, so there was no way to give the
constructur a ServletConfig. That no longer applies, but servlet
containers still will only call your no-arg constructor. So you won't
have access to a ServletConfig or ServletContext.
19. How can a servlet refresh automatically if some new data has
entered the database?
You can use a client-side Refresh or Server Push

MSPVL Polytechnic College

Page 55

Advanced Java Programming Manual


20. The code in a finally clause will never fail to execute, right?
Using System.exit(1); in try block will not allow finally code to
execute.
21. What mechanisms are used by a Servlet Container to maintain
session information?
Cookies, URL rewriting, and HTTPS protocol information are
used to maintain session information
22. Difference between GET and POST?
In GET your entire form submission can be encapsulated in one
URL, like a hyperlink. query length is limited to 260 characters, not
secure, faster, quick and easy.
In POST Your name/value pairs inside the body of the HTTP
request, which makes for a cleaner URL and imposes no size
limitations on the form's output. It is used to send a chunk of data to
the server to be processed, more versatile, most secure.
23. What is session?
The session is an object used by a servlet to track a user's
interaction with a

Web application across multiple HTTP requests.

24. What is servlet mapping?


The servlet mapping defines an association between a URL
pattern and a servlet. The mapping is used to map requests to
servlets.
25. What is servlet context?
The servlet context is an object that contains a servlet's view of
the Web application within which the servlet is running. Using the
context, a servlet can log events, obtain URL references to resources,
and set and store attributes that other servlets in the context can use.
(answer supplied by Sun's tutorial).
26. Which interface must be implemented by all servlets?
Servlet interface.
MSPVL Polytechnic College

Page 56

Advanced Java Programming Manual


27. Explain the life cycle of Servlet.
Loaded(by the container for first request or on start up if config
file suggests load-on-startup), initialized( using init()), service(service()
or doGet() or doPost()..), destroy(destroy()) and unloaded.
28. When is the servlet instance created in the life cycle of servlet?
What is the importance of configuring a servlet?
An instance of servlet is created when the servlet is loaded for
the first time in the container. Init() method is used to configure this
servlet instance. This method is called only once in the life time of a
servlet, hence it makes sense to write all those configuration details
about a servlet which are required for the whole life of a servlet in this
method.
29. Why don't we write a constructor in a servlet?
Container writes a no argument constructor for our servlet.
30. When we don't write any constructor for the servlet, how does
container create an instance of servlet?
Container creates instance of servlet by calling
Class.forName(className).newInstance().
31. Once the destroy() method is called by the container, will the
servlet

be

immediately

destroyed?

What

happens

to

the

tasks(threads) that the servlet might be executing at that time?


Yes, but Before calling the destroy() method, the servlet
container waits for the remaining threads that are executing the
servlets service() method to finish.
32. What is the difference between callling a RequestDispatcher
using ServletRequest and ServletContext?
We can give relative URL when we use ServletRequest and not
while using ServletContext.

MSPVL Polytechnic College

Page 57

Advanced Java Programming Manual


33. Why is it that we can't give relative URL's when using
ServletContext.getRequestDispatcher() when we can use the same
while calling ServletRequest.getRequestDispatcher()?
Since ServletRequest has the current request path to evaluae
the relative path while ServletContext does not.
34. What are the uses of Servlets?
A servlet can handle multiple requests concurrently, and can
synchronize requests. This allows servlets to support systems such as
on-line conferencing. Servlets can forward requests to other servers
and servlets. Thus servlets can be used to balance load among several
servers that mirror the same content, and to partition a single logical
service over several servers, according to task type or organizational
boundaries.
35. Whats the Servlet Interface?
The central abstraction in the Servlet API is the Servlet
interface. All servlets implement this interface, either directly or, more
commonly, by extending a class that implements it such as
HttpServlet. Servlets>Generic Servlet>HttpServlet>MyServlet. The
Servlet interface declares, but does not implement, methods that
manage the servlet and its communications with clients.

MSPVL Polytechnic College

Page 58

Advanced Java Programming Manual

Ex.No: 13

Java Beans program to design a counter

Aim:
To write a program in Java Beans to add a Button to the Bean and
display the number of times the button has been clicked.
Procedure:
Java File:
1. Open a note pad.
2. Write

java

program

that

extends

Panel

and

implement

ActionListener interface.
3. Write coding to add a Button to the Panel and display the number of
times a button is clicked.
4. The actionPerfomed() method increments the value of count when the
Button is clicked.
5. Save the file as button.java in a folder called counter.
6. Compile the button.java file from its parent directory to generate the
class file.
Manifest File:
1. Open a note pad.
2. Write the manifest file to include the name of the Java-Bean class.
3. Name: counter.button.class
4. Java-Bean: True
5. Save the file as button.mft
(Dont forget to add one tab space and press enter)
Creating the JAR file
1. Open the command prompt.
2. Go to the parent directory of the counter folder
3. Create the jar file. (the jar file should be in the jars folder of the bean)
D:\adjava>jar

cfm

D:\BDK\beans\jars\mybutton.jar

counter\button.mft counter\*.class
MSPVL Polytechnic College

Page 59

Advanced Java Programming Manual


Running the program:
1. Open a command prompt.
2. Go to the directory where beanbox is present (C:\beans\beanbox)
3. Type run.
4. The bean windows opens. From the the Tool box select the button
bean and drop it in the BeanBox.
5. Click the button in the bean to see the number of clicks made.
Program:
package counter;
import java.awt.*;
import java.awt.event.*;
public class button extends Panel implements ActionListener
{
int count;
Button but;
public button()
{
count = 0;
setSize(200, 100);
but = new Button("Click me");
but.addActionListener(this);
add(but);
}
public void actionPerformed(ActionEvent e)
{
count++;
repaint();
}
public void paint(Graphics g)
{
Dimension d = getSize();
Font f=new Font("Courier",Font.BOLD+Font.ITALIC,24);
int h = d.height;
int w = d.width;
g.setColor(Color.pink);
g.fillRect(0, 0, w-1, h-1);
MSPVL Polytechnic College

Page 60

Advanced Java Programming Manual


g.setFont(f);
g.setColor(new Color(0, 0, 0));
g.drawString("Click count = " + count, 50, 50);
}
}
Manifest file:
Name: counter.button.class
Java-Bean: True
Output:

Result:
The above program was executed and the output is verified.
MSPVL Polytechnic College

Page 61

Advanced Java Programming Manual


Ex.No:14 Java Beans program to handle simple Property
Aim:
Write a program for Java Bean with Simple property by using
SimpleBeanInfo class.
Procedure:
Source Java File:
1. Open a note pad.
2. Write a java program that Canvas.
3. The file has a private Boolean variable called vertical.
4. Define the getVertical() and setVertical() methods to define the
property using the Beaninfo class.
5. The program is designed in such a way that if the Boolean property
vertical is true then the spectrum is displayed in vertical format else it
is displayed in horizontal format.
6. Save the file as check.java in a folder called check.
Setting the Property of bean using Simple BeanInfo:
1. Open a note pad.
2. Write a java program that imports java.beans package
3. Define a subclass of SimpleBeanInfo called checkBeanInfo
4. Override the getPropertyDescriptors[] and define the vertical property
of the check bean.
5. Save the file as checkBeanInfo.java in a folder called check.
Compiling the java files:
1. Open the Command prompt.
2. Goto the parent directory of the check folder.
3. Compile the java files as javac check\*.java
Manifest File:
1. Open a note pad.
2. Write the manifest file to include the name of the Java-Bean class.
MSPVL Polytechnic College

Page 62

Advanced Java Programming Manual


3. Name: check.check.class
4. Java-Bean: True
5. Save the file as check.mft
(Dont forget to add one tab space and press enter)
Creating the JAR file
1. Open the command prompt.
2. Go to the parent directory of the indexcheck folder
3. Create the jar file. (the jar file should be in the jars folder of the bean)
jar cfm c:\beans\jars\spectrum.jar check\check.mft check\*.class
Running the program:
1. Open a command prompt.
2. Go to the directory where beanbox is present (C:\beans\beanbox)
3. Type run.
4. The bean windows opens. From the the Tool box select the check
bean and drop it in the BeanBox.
5. Verify the Property window and see only the Verical property is
displayed which can be toggled to true or false.
Program:
check.java
package check;
import java.awt.*;
import java.util.*;
public class check extends Canvas
{
private boolean vertical;
public check()
{
vertical=true;
setSize(100,100);
}
public boolean getVertical()
{
MSPVL Polytechnic College

Page 63

Advanced Java Programming Manual


return vertical;
}
public void setVertical(boolean vertical)
{
this.vertical=vertical;
repaint();
}
public void paint(Graphics g)
{
Color c;
float saturation=1.0f;
float brightness=1.0f;
Dimension d=getSize();
if(vertical)
{
for(int x=0;x<d.width;x++)
{
float hue=(float)x/(d.width-1);
c=Color.getHSBColor(hue,saturation,brightness);
g.setColor(c);
g.drawLine(x,0,x,d.height-1);
}
}
else
{
for(int y=0;y<d.height;y++)
{
float hue=(float)y/(d.height-1);
c=Color.getHSBColor(hue,saturation,brightness);
g.setColor(c);
g.drawLine(0,y,d.width-1,y);
}
}
}
}
MSPVL Polytechnic College

Page 64

Advanced Java Programming Manual


checkBeanInfo.java
package check;
import java.beans.*;
public class checkBeanInfo extends SimpleBeanInfo
{
private Class checkClass = check.class;
public PropertyDescriptor[] getPropertyDescriptors()
{
PropertyDescriptor str = null;
try
{
str= new PropertyDescriptor("vertical", checkClass);
str.setDisplayName("Vertical:");
}
catch (IntrospectionException e) {}
PropertyDescriptor[] result = {str};
return result;
}
}
Output:

Result:
The above program was executed and the output is verified.

MSPVL Polytechnic College

Page 65

Advanced Java Programming Manual


Ex.No:15 Java Beans program to handle Indexed Property

Aim:
To write Java Bean program with Indexed Property by using
SimpleBeanInfo class.
Procedure:
Source Java File:
1. Open a note pad.
2. Write a java program that Canvas.
3. The file has a index property called stocks.
4. Define the access methods of the Indexed property stock
public <PropertyType>[] get<PropertyName>();
public void set<PropertyName>(<PropertyType>[] value);
public <PropertyType> get<PropertyName>(int index);
public void set<PropertyName>(int index, <PropertyType> value);
5. Save the file as IndexList.java in a folder called indexcheck.
Setting the Property of bean using Simple BeanInfo:
1. Open a note pad.
2. Write a java program that imports java.beans package
3. Define a subclass of SimpleBeanInfo called IndexListBeanInfo
4. Override the getPropertyDescriptors[] and define the stock property of
the IndexCheckcheck bean.
5. Save

the

file

as

IndexCheckBeanInfo.java

in

folder

called

indexcheck.
Compiling the java files:
1. Open the Command prompt.
2. Goto the parent directory of the check folder.
3. Compile the java files as javac indexcheck\*.java

MSPVL Polytechnic College

Page 66

Advanced Java Programming Manual


Manifest File:
1. Open a note pad.
2. Write the manifest file to include the name of the Java-Bean class and
the BeanInfo class. (Dont forget to add one tab space and press enter)
3. Now save the file as myindex.mft
Creating the JAR file
1. Open the command prompt.
2. Go to the parent directory of the indexcheck folder
3. Create the jar file. (the jar file should be in the jars folder of the bean)
jar

cfm

c:\beans\jars\mystock.jar

indexcheck

indexcheck\myindex.mft

\*.class

Running the program:


1. Open a command prompt.
2. Go to the directory where beanbox is present (C:\beans\beanbox)
3. Type run.
4. The bean window opens. From the Tool box select the IndexList bean
and drop it in the BeanBox.
Program:
IndexList.java
package indexcheck;
import java.util.*;
import java.awt.*;
public class IndexList extends Canvas
{
// a vector that contains the actual stock names
protected Vector stocks = new Vector();
// constructor
public IndexList()
{
String sub[]={"C&DS", "Java","C++"};
setBackground(Color.pink);
setForeground(Color.blue);
MSPVL Polytechnic College

Page 67

Advanced Java Programming Manual


setSize(400,400);
for(int i=0;i<3;i++)
stocks.addElement(sub[i]);
}
// the get method for the StockCount property
public synchronized int getStockCount()
{
return stocks.size();
}
// get method for Stocks property array
public synchronized String[] getStocks()
{
// allocate an array of strings for the stock names
String[] s = new String[getStockCount()];
// copy the elements of the stocks Vector into the string
array,and then return the array
stocks.copyInto(s);
return s;
}
// set method for Stocks property array
public synchronized void setStocks(String[] s)
{
// set the size of the stocks vector to match the length of
the new array
stocks.setSize(s.length);
// copy the values into the stocks vector
for (int i = 0; i < s.length; i++)
{
// use the single stock set method
try
{
setStocks(i, s[i]);
repaint();
MSPVL Polytechnic College

Page 68

Advanced Java Programming Manual


}
catch (ArrayIndexOutOfBoundsException e){ }
}
}
// get method for single element of Stocks property
public synchronized String getStocks(int index)throws
ArrayIndexOutOfBoundsException
{
// make sure the index is in bounds
if (index < 0 || index >= getStockCount())
{
throw new ArrayIndexOutOfBoundsException();
}
// get the stock and return it
String s = (String)stocks.elementAt(index);
return s;
}
// set an individual element of the Stocks property array
public synchronized void setStocks(int index, String stock)
throws ArrayIndexOutOfBoundsException
{
// make sure the index is in bounds
if (index < 0 || index >= getStockCount())
{
throw new ArrayIndexOutOfBoundsException();
}
// change the stock at the specified index
stocks.setElementAt(stock, index);
repaint();
}
public void paint(Graphics g)
{
for(int i=0;i<stocks.size();i++)
MSPVL Polytechnic College

Page 69

Advanced Java Programming Manual

g.drawString("Subject"+(i+1)+":"+stocks.elementAt(i),50,100*(i+1));
}
}
IndexListBeanInfo.java
package indexcheck;
import java.beans.*;
public class IndexListBeanInfo extends SimpleBeanInfo
{
public PropertyDescriptor[] getPropertyDescriptors()
{
try
{
PropertyDescriptor ip =
new PropertyDescriptor("stocks", IndexList.class);
ip.setDisplayName("Stock :");
PropertyDescriptor[] pda = { ip };
return pda;
}
catch (IntrospectionException e)
{
return null;
}
}
}
myindex.mft
Name: indexcheck.IndexList.class
Java-Bean: True
Name: indexcheck.IndexListBeanInfo.class
Java-Bean: False

MSPVL Polytechnic College

Page 70

Advanced Java Programming Manual


Output:

Result:
The above program was executed and the output is verified

MSPVL Polytechnic College

Page 71

Advanced Java Programming Manual


Java bean Viva Question
What is Javabean?
A JavaBean is a reusable software component that is written in java
programming language. It can be visually manipulated in builder tools. A
JavaBean is often referred to simply as a Bean.
What are the importance of Java component model?
Cross platform deployment
Secured
What are the objectives of JavaBeans ?
Portable
Lightweight
Simple to create
Hostable in other components models
Able to access remote data
What is the use of Bean development kit?
The Bean development kit is a tool that allows one to configure and
interconnect a set of Beans.
What is the component of Beanbox?
When the Beanbox is started, toolbox, BeanBox and properties
window will be displayed.
Define Serialization
Serialization is the ability to save the state of several objects to a
stream. The stream is typically associated with a file.
Define Deserialization
Deserialization is the ability to restore the state of several objects from
a stream. This allows and application to start execution read a file.
Define Introspection
Introspection is the ability to obtain information about the properties,
events and methods of a Bean. It is necessary for building productive quality
beans
MSPVL Polytechnic College

Page 72

Advanced Java Programming Manual


Define BeanInfo
The BeanInfo interface in the java.beans package defines a set of
constants and methods. The simple BeanInfo class in the java.beans
package provides a default implementation.
Define Property
Property is a public attribute of a bean that affects appearance or
behavior.
What are the property types?
Simple properties
Boolean properties
Indexed properties
Bound properties
What is customization?
Customization means configuring the internal state of a bean.
What is property Editor?
A property editor is a component that edits a single property of a
certain type.

MSPVL Polytechnic College

Page 73

Advanced Java Programming Manual

Ex.No:16

Enterprise Java Beans of Session Type

Aim:
Write a program to develop a Enterprise Java Bean of "Session Bean"
type.
Procedure
Steps for Execution
1.

Create a folder called welcome and in that create two sub-directories


called beans and client.

2.

Write code for a Remote interface and save the file as Welcome.java in
the beans folder.

3.

Write code for a Home interface and save the file as WelcomeHome.java
in the beans folder.

4.

Write code for a bean class and save the file as WelcomeBean.java in the
beans folder.

5.

Write the code for client and save the file as WelcomeClient.java in the
client folder.

6.

Compile the Remote interface, the Home interface, the bean class, and
the client file.
a. Open the command prompt.
b. Move to the welcome directory.
c. Set PATH=.;%j2ee_home%\jdk\bin
d. Set classpath=.;%j2ee_home%\lib\j2ee.jar
e. Compile the java files as
javac -d . beans\*.java
javac -d . client\*.java

MSPVL Polytechnic College

Page 74

Advanced Java Programming Manual

Creating the J2EE Application


1.

Start the J2EE server as Start  All Program

 Sun Micro Systems

Application Server PE  Start Default Server


2.

Start the deploy tool utility as Start  All Program  Sun Micro Systems
Application Server PE  Deploy Tool

3.

A new application deployment tool screen will be displayed.

4.

The first thing that we need the Deployment Tool to do is create the J2EE
application, which will be bundled together in an Enterprise Application
Resource (EAR) file.

MSPVL Polytechnic College

Page 75

Advanced Java Programming Manual


5.

To create the application EAR file, from the File menu choose
NewApplication. A dialog box will be displayed, prompting you to enter
the name of the EAR file, and the application name that you want
displayed.

6.

Click Browse and select the welcome folder and give the New Application
name as WelcomeApp

7.

Click New Application and in the next window that appears Click OK to
accept the changes to this dialog.

MSPVL Polytechnic College

Page 76

Advanced Java Programming Manual


8.

Now well create the JAR file in which the session bean classes and
resources will be packaged. To do this, choose File  New  Enterprise
Bean menu item. A New Enterprise Bean Wizard appears. Click Next

9.

A screen showing a new enterprise bean wizard will be displayed. From


the combo box of Create New Jar Module in Application, select
WelcomeApp. In the JAR display name, enter WelcomeAppJar. Then
click the Edit Contents button.

MSPVL Polytechnic College

Page 77

Advanced Java Programming Manual


10. In

the Available Files panel of the dialog box shown below, navigate to the

beans directory of WelcomeApp example. Choose the Welcome.class,


WelcomeBean.class and the WelcomeHome.class, and click the Add
button. Those bean classes will appear in the Contents of <EJB Bundle>
panel as seen below:

11. Click

OK in the dialog box and then click the Next button to see the page

shown below. You will then have four drop-down lists in which to make
choices:
 From

the

Enterprise

Bean

Class

drop-down

list,

choose

beans.WelcomeBean.
 Type WelocmeJNDI in the Enterprise Bean box.
 From the Enterprise Bean Type dropdown list choose Stateless
Session.
 From

the

Remote

Home

Interface

drop-down

list,

choose

beans.WelcomeHome.
 From the Remote Interface drop-down list, choose beans.Welcome.

MSPVL Polytechnic College

Page 78

Advanced Java Programming Manual

12. Click

Next and the resulting dialog asks if you want the bean to be

exposed as a web service; Select No and click Next. The last page of the
Enterprise Bean Wizard suggests some steps to do next. Click the
Finish button to leave the wizard:

MSPVL Polytechnic College

Page 79

Advanced Java Programming Manual

13. The

Deploy tool will appear as shown below

MSPVL Polytechnic College

Page 80

Advanced Java Programming Manual


14. Select

WelcomeApp in the tree of the left hand panel and Select Sun-

specific Settings button in the right panel the Sun specific settings
window appears. In that select JNDI name in the view combo-box and
Type WelcomeJNDI field of the JNDI names table (This is the name the
client application uses in the lookup() method to obtain the beans home
reference.).Then click Close

15. Select

File
Save All .

16. Select

the WelcomeApp node from the tree on the left panel and choose

Verify J2EE Compliance from the Tools menu. You may be prompted
to save the application.

To run the verification tests against the

application, choose one of the Display options and click the OK button.
We usually choose Failures only option as shown below so that only the
failed tests show up. The Results and the Details panels show the results
of the tests and details of any problems encountered, respectively. If
there are any problems encountered, then read the Details and go to the
Deployment Tool page in which that detail is configured

and verify

whether all the fields are specified properly as detailed above.

MSPVL Polytechnic College

Page 81

Advanced Java Programming Manual

Creating & Packaging the Application Client


1.

In

the

Application

Deployment

Tool

screen,

go

to

File

New

Application Client.

MSPVL Polytechnic College

Page 82

Advanced Java Programming Manual


2.

Click Next in the Introduction wizard that appears. The New Application
Client wizard screen will be displayed as shown below: Give the Jar
Display name as WelcomeClient. And click Edit Contents button

3.

A screen saying Edit contents of WelcomeClient will be displayed. In that


select the WelcomeClient.class in the client folder and click Add and
then click Next in the wizard that appears.

MSPVL Polytechnic College

Page 83

Advanced Java Programming Manual


4.

In

the

window

that

appears

select

the

Main

class

as

Client.WelcomeClient.click Next and then click finish to return to the


main window.

Specifying the Application Client's Enterprise Bean Reference


1.

Select the WelcomeClient in the Left panel and select the EJB Refs
tab. In that click Add

MSPVL Polytechnic College

Page 84

Advanced Java Programming Manual


2.

In the Add Enterprise Bean Reference wizard provide the following


values.
 Give the Coded Name as WelcomeJNDI
 Select the EJB type as Session.
 Select the Interfaces as Session
 Select the Home Interface as beans.WelcomeHome
 Select the Remote Interface as beans.Welcome.
 In the Target EJB , select the JNDI Name option and select
WelcomeJNDI.
 Click Ok.

Deploying the J2EE Application


1. Select the WelcomeApp application.
2. Select Tools  Deploy.
3. Under Connection Settings, enter the user name and password for the
Application Server.
4. Tell deploytool to create a JAR file that contains the client stubs.
a. a.Select the Return Client JAR checkbox.
b. In the field below the checkbox, enter C:\welcome
5. Click OK.
6. In the Distribute Module dialog box, click Close when the deployment
completes.
MSPVL Polytechnic College

Page 85

Advanced Java Programming Manual

7. Verify that a stub client JAR named WelcomeAppClient.jar


resides in C:\welcome.

Running the Application Client


1.

In the command prompt go to the directory C:\Welcome

2.

set APPCPATH=c:\welcome\WelcomeAppClient.jar

3.

set path=c:\Sun\AppServer\bin

4.

Run the client as


C:\welcome>appclient -client WelcomeApp.ear -name WelcomeClient

-textauth
5.

In the terminal window, the client displays the result


Welcome to your first EJB program.

MSPVL Polytechnic College

Page 86

Advanced Java Programming Manual


Program:
WelcomeBean.java
import javax.ejb.*;
public class WelcomeBean implements SessionBean
{
public void ejbActivate()
{
System.out.println("ejbActivate()");
}
public void ejbPassivate()
{
System.out.println("ejbPassivate()");
}
public void ejbCreate()
{
System.out.println("ejbCreate()");
}
public void ejbRemove()
{
System.out.println("ejbRemove()");
}
public void setSessionContext(SessionContext ctx)
{
System.out.println("setSessionContext()");
}
public String printMessage()
{
return "Welcome to your first EJB program. ";
}
}

MSPVL Polytechnic College

Page 87

Advanced Java Programming Manual


Welcome.java
import javax.ejb.*;
import java.rmi.RemoteException;
public interface Welcome extends EJBObject
{
public String printMessage() throws RemoteException;
}
WelcomeHome.java
import javax.ejb.*;
import java.rmi.RemoteException;
public interface WelcomeHome extends EJBHome
{
public Welcome create() throws CreateException,
RemoteException;
}
WelcomeClient.java
import java.rmi.*;
import javax.naming.*;
public class WelcomeClient
{
public static void main(String args[])
{
try
{
InitialContext ic=new InitialContext();
WelcomeHome welhome =
(WelcomeHome)ic.lookup("WelcomeJNDI");
Welcome wel=welhome.create();
String retval=wel.printMessage();
System.out.println(retval);
wel.remove();
}
catch(java.rmi.RemoteException e)
{
MSPVL Polytechnic College

Page 88

Advanced Java Programming Manual


System.out.println("Remote Exception Occured" + e);
}
catch(javax.ejb.CreateException e)
{
System.out.println("Create Exception Occured" + e);
}
catch(javax.ejb.RemoveException e)
{
System.out.println("Remove Exception Occured" + e);
}
catch(javax.naming.NamingException e)
{
System.out.println("Naming Exception occured"+e);
}
}
}
Output:

Result:
The above program was executed and the output is verified.

MSPVL Polytechnic College

Page 89

Advanced Java Programming Manual


Ex.No:17

Enterprise Java Beans of Entity Type

Aim:
Write a program to develop a Enterprise Java Bean of "Entity Session
Bean" type.
Procedure
The

following

procedure

demonstrates

the

container-managed

persistence feature of entity beans. It is a very simple application in which


the user can create, find, update, and delete stocks.
This application uses two enterprise beans:


An entity bean named Stock that holds information about stocks. There
is one instance of this entity bean per stock.

A session bean named StockList that uses the Stock beans and provides
business methods to the UI that enables it to maintain the Stock beans.

Steps for Execution


1.

Create a folder called cmp and in that create two sub-directories called
beans and client.

2.

Write the coding for the following files and save it in the beans sub folder
The source files used to define the Stock entity bean
 Stock.java
 StockBean.java
 StockHome.java
The source files that define the StockList session bean
 StockList.java
 StockListBean.java
 StockListHome.java

3.

The

source

file

that

defines

the

user

interface

client

called

StockClient.java is placed in the client subfolder:

MSPVL Polytechnic College

Page 90

Advanced Java Programming Manual


4.

Compile the java file to get the class files.


f. Open the command prompt.
g. Move to the cmp directory.
h. Set PATH=.;%j2ee_home%\jdk\bin
i. Set classpath=.;%j2ee_home%\lib\j2ee.jar
j. Compile the java files as
javac -d . beans\*.java
javac -d . client\*.java

Creating the J2EE Application


1.

Start the J2EE server as Start  All Program

 Sun Micro Systems

Application Server PE  Start Default Server


2.

Start the deploy tool utility as Start  All Program  Sun Micro Systems
Application Server PE  Deploy Tool

3.

A new application deployment tool screen will be displayed.

4.

The first thing that we need the Deployment Tool to do is create the J2EE
application, which will be bundled together in an Enterprise Application
Resource (EAR) file.

MSPVL Polytechnic College

Page 91

Advanced Java Programming Manual


5.

To create the application EAR file, from the File menu choose New 
Application. A dialog box will be displayed, prompting you to enter the
name of the EAR file, and the application name that you want displayed.
Click Browse and select the cmp folder and give the New Application
name as StockListApp

6.

Click New Application and in the next window that appears Click OK to
accept the changes to this dialog.

7.

Now well create the JAR file in which the session bean classes and
resources will be packaged. To do this, choose File  New  Enterprise
Bean menu item. A New Enterprise Bean Wizard appears. Click Next

8.

A screen showing a new enterprise bean wizard will be displayed. From


the combo box of Create New Jar Module in Application, select
StockListApp. In the JAR display name, enter StockAppJar. Then click
the Edit Contents button.

MSPVL Polytechnic College

Page 92

Advanced Java Programming Manual


9.

In the Available Files panel of the dialog box shown below, navigate to the
beans directory of StockListApp example. Choose the StockList.class,
StockListBean.class and the StockListHome.class, and click the Add
button. Those bean classes will appear in the Contents of <EJB Bundle>
panel as seen below:

10. Click

OK in the dialog box and then click the Next button

MSPVL Polytechnic College

Page 93

Advanced Java Programming Manual


11. In

the page that is displayed you will then have four drop-down lists in

which to make choices:


 From the Enterprise Bean Class drop-down list, choose beans.
StockListBean.
 Type StockListEjb in the Enterprise Bean box.
 From the Enterprise Bean Type dropdown list choose Stateless
Session.
 From the Remote Home Interface drop-down list, choose beans.
StockListHome.
 From the Remote Interface drop-down list, choose beans. StockList.

12. Click

Next and the resulting dialog asks if you want the bean to be

exposed as a web service; Select No and click Next. The last page of the
Enterprise Bean Wizard suggests some steps to do next. Click the Finish
button to leave the wizard:
13. Now

create another bean JAR, for the Stock entity bean. Select File 

New  Enterprise Bean. The introduction screen appears click Next. The
following window appears.

MSPVL Polytechnic College

Page 94

Advanced Java Programming Manual

Perform the following steps:




Choose the Add to Existing JAR Module option if it isnt already


selected. This is because were going to put our entity bean in the
same bean JAR file as the session bean.

Verify that the application shown in the drop-down is StockListApp.

Then click the Edit Contents button to select only the three Stock
entity

bean

.class

files

(Stock.class,

StockBean.class,

StockHome.class) to be put into this JAR.

MSPVL Polytechnic College

Page 95

and

Advanced Java Programming Manual

14. Click

the Next button. Do the following in the window that appears

Select the Enterprise Bean Class as beans.StockBean

Set the Enterprise Bean Name as StockEjb

Select the Enterprise Bean Type as Entity

Select the Remote Home Interfaces as beans.StockHome

Select the Remote Interface as beans.

MSPVL Polytechnic College

Page 96

Advanced Java Programming Manual

15. Click
16. The


next on the Configuration Options page.

next page in this wizard is the Entity Settings page: Do the following

Select Container-Managed Persistence 2.0, from the Persistence


Management drop-down.

Mark both fields in fields to be persisted

Were going to use the ticker Symbol field as the primary key for the
Stock bean. So select tickersymbo [java.lang.String] in the Primary
Key specification by selecting the option Select an Existing Field.

Set Stock as the abstract persistence schema.

MSPVL Polytechnic College

Page 97

Advanced Java Programming Manual

17. Click
18. In

Next and click Finish

the first window select StockEjb in the left-hand panel, and the

Transactions tab on the right. The Transaction Management page should


appear: In that Container-Managed should be selected, and then select
Remote, and then Remote Home, verifying that the Transaction Attribute
of each method is set to Required.

MSPVL Polytechnic College

Page 98

Advanced Java Programming Manual


19. Now

select StockListApp in the left-hand panel, and then then select

Sun-Specific Settings in the right-hand panel and the window appears


set the following
In the JNDI Name tab:
 Give the Stock entity bean the JNDI Name ejb/beans. Stock.
 Give

the

StockList

session

bean

the

JNDI

Name

ejb/beans.StockList.

20. Select
21. Select

the File  Save All menu option.


StockListJar in the left-hand panel, and click the Sun-specific

Settings button at the bottom of the page. The Sun-specific Settings page
shown on the next page will appear, and in it well take care of some
database-related issues:
 Well be using the Derby the default database, so enter jdbc/_default
as the Database JNDI Name in the CMP Resource panel.
 Click the Create Database Mappings button.

MSPVL Polytechnic College

Page 99

Advanced Java Programming Manual

22. In

the Create Dialog Mappings dialog, make sure that:

 The Automatically Generate Necessary Tables option is selected.


 Derby is selected in the Datasource Vendor drop-down list.

MSPVL Polytechnic College

Page 100

Advanced Java Programming Manual


23. The

Sun-specfic Settings dialog

will reappear with the database table

and field names that will be used to persist the data in the Stock entity
bean. Click the Close button.

24. Save

the application by choosing the File  Save All menu item. Select

the StockListApp node from the tree on the left panel and choose Verify
J2EE Compliance from the Tools menu. Choose the Failures Only option
and click OK.
Creating & Packaging the Application Client
1.

In

the

Application

Deployment

Tool

screen,

go

to

File

New

Application Client.
2.

Click Next in the Introduction wizard that appears. The New Application
Client wizard screen will be displayed as shown below: Give the Jar
Display name as StockListClient. And click Edit Contents button

MSPVL Polytechnic College

Page 101

Advanced Java Programming Manual

3.

A screen saying Edit contents of StockListClient will be displayed. In that


select the StockClient.class in the client folder and click Add and then
click Next in the wizard that appears.

MSPVL Polytechnic College

Page 102

Advanced Java Programming Manual

4.

In the window that appears Select the Main class as Client.StockClient.


Click Next and then click finish to return to the main window.

MSPVL Polytechnic College

Page 103

Advanced Java Programming Manual


Specifying the Application Client's Enterprise Bean Reference
1.

Select the StockListClient in the Left panel and select the EJB Refs tab.
In that click Add

2.

In the Add Enterprise Bean Reference wizard provide the following


values.
 Give the Coded Name as StockListEjb
 Select the EJB type as Session.
 Select the Interfaces as Remote
 Select the Home Interface as beans. StockListHome
 Select the Remote Interface as beans. StockList.
 In the Target EJB , select the JNDI Name option and select
ejb/beans.StockList
 Click Ok.

3.

Again in the EJB Refs tab Click add .

4.

In the Add Enterprise Bean Reference wizard provide the following


values.
 Give the Coded Name as StockEjb
 Select the EJB type as entity.
 Select the Interfaces as Remote
 Select the Home Interface as beans. StockHome
 Select the Remote Interface as beans. Stock.

MSPVL Polytechnic College

Page 104

Advanced Java Programming Manual


 In the Target EJB , select the JNDI Name option and select
ejb/beans.Stock
 Click Ok.

Deploying the J2EE Application


1. Select the StockListApp application.
2. Select Tools  Deploy.
3. Under Connection Settings, enter the user name and password for the
Application Server.
4. Tell deploy tool to create a JAR file that contains the client stubs.
a. Select the Return Client JAR checkbox.
b. In the field below the checkbox, enter C:\cmp
5. Click OK.
6. In the Distribute Module dialog box, click Close when the deployment
completes.

MSPVL Polytechnic College

Page 105

Advanced Java Programming Manual

7. Verify that a stub client JAR named StockListAppClient.jar resides in


C:\cmp.
Running the Application Client
1.

In the command prompt go to the directory C:\cmp

2.

set APPCPATH= c:\cmp\StockListAppClient.jar

3.

set path=c:\Sun\AppServer\bin

4.

Run the client as


C:\cmp>appclient -client StockListApp.ear

5.

The user interface window appears which allows you to add, delete,
update the stock.

MSPVL Polytechnic College

Page 106

Advanced Java Programming Manual


Program:
Stock.java
package beans;
import java.rmi.*;
import javax.ejb.*;
public interface Stock extends EJBObject
{
/* The public business methods on the Stock bean these
include the accessor methods from the bean get the ticker. Do
not allow ticker to be set through the interface because it is the
primary key */
public String getTickerSymbol() throws RemoteException;
// get and set the name
public String getName() throws RemoteException;
public void setName(String name) throws RemoteException;
}
StockBean.java
package beans;
import javax.ejb.*;
public abstract class StockBean implements EntityBean
{
// keeps the reference to the context
EntityContext _context;
// the abstract access methods for persistent fields
public abstract String getTickerSymbol();
public abstract void setTickerSymbol(String ticker);
public abstract String getName();
public abstract void setName(String name);
// standard entity bean methods
public String ejbCreate(String ticker, String name)throws
CreateException
{

MSPVL Polytechnic College

Page 107

Advanced Java Programming Manual


setTickerSymbol(ticker);
setName(name);
return null;
}
public void ejbPostCreate(String ticker, String name)throws
CreateException { }
public void setEntityContext(EntityContext ctx)
{
_context = ctx;
}
public void unsetEntityContext()
{
_context = null;
}
public void ejbRemove() { }
public void ejbLoad() { }
public void ejbStore() { }
public void ejbPassivate() { }
public void ejbActivate() { }
}
StockHome.java
package beans;
import java.rmi.*;
import javax.ejb.*;
public interface StockHome extends EJBHome
{
// the create method for the Stock bean
public Stock create(String ticker, String name)throws
CreateException, RemoteException;
// the find by primary key method for the Stock bean
public Stock findByPrimaryKey(String ticker)throws
FinderException, RemoteException;
}
MSPVL Polytechnic College

Page 108

Advanced Java Programming Manual


StockList.java
package beans;
import java.rmi.*;
import javax.ejb.*;
public interface StockList extends EJBObject
{
// the public business methods on the Stock List bean
public String getStock(String ticker)throws FinderException,
RemoteException;
public void addStock(String ticker, String name)throws
CreateException, RemoteException;
public void updateStock(String ticker, String name)throws
FinderException, RemoteException;
public void deleteStock(String ticker)throws FinderException,
RemoteException;
}
StockListBean.java
package beans;
import javax.ejb.*;
import javax.naming.*;
import javax.rmi.*;
public class StockListBean implements SessionBean
{
/* the public business methods. these must be coded in the
remote interface also */
public String getStock(String ticker) throws FinderException
{
try
{
StockHome stockHome = getStockHome();
Stock stock = stockHome.findByPrimaryKey(ticker);
return stock.getName();
}
MSPVL Polytechnic College

Page 109

Advanced Java Programming Manual


catch (FinderException fe)
{
throw fe;
}
catch (Exception ex)
{
throw new RuntimeException(ex.getMessage());
}
}
public void addStock(String ticker, String name)throws
CreateException
{
try
{
StockHome stockHome = getStockHome();
stockHome.create(ticker, name);
}
catch (CreateException ce)
{
throw ce;
}
catch (Exception ex)
{
throw new RuntimeException(ex.getMessage());
}
}
public void updateStock(String ticker, String name)throws
FinderException
{
try
{
StockHome stockHome = getStockHome();
Stock stock = stockHome.findByPrimaryKey(ticker);
MSPVL Polytechnic College

Page 110

Advanced Java Programming Manual


stock.setName(name);
}
catch (FinderException fe)
{
throw fe;
}
catch (Exception ex)
{
throw new RuntimeException(ex.getMessage());
}
}
public void deleteStock(String ticker)throws FinderException
{
try
{
StockHome stockHome = getStockHome();
Stock stock = stockHome.findByPrimaryKey(ticker);
stock.remove();
}
catch (FinderException fe)
{
throw fe;
}
catch (Exception ex)
{
throw new RuntimeException(ex.getMessage());
}
}
private StockHome getStockHome() throws NamingException
{
// get the initial context
InitialContext initial = new InitialContext();
// get the object reference
Object objref = initial.lookup("ejb/beans.Stock");
MSPVL Polytechnic College

Page 111

Advanced Java Programming Manual


StockHome home = (StockHome)
PortableRemoteObject.narrow(objref, StockHome.class);
return home;
}
// standard ejb methods
public void ejbActivate() {}
public void ejbPassivate() {}
public void ejbRemove() {}
public void ejbCreate() {}
public void setSessionContext(SessionContext context) {}
}
StockListHome.java
package beans;
import java.rmi.*;
import javax.ejb.*;
public interface StockListHome extends EJBHome
{
// the create method for the Stock List bean.
public StockList create()throws CreateException,
RemoteException;
}
StockClient.java
package client;
import beans.*;
import javax.ejb.*;
import javax.naming.*;
import javax.rmi.*;
// general imports
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class StockClient extends JFrame implements ActionListener
MSPVL Polytechnic College

Page 112

Advanced Java Programming Manual


{
private StockList _stockList;
private JTextField _ticker = new JTextField();
private JTextField _name = new JTextField();
private JButton _get = new JButton("Get");
private JButton _add = new JButton("Add");
private JButton _update = new JButton("Update");
private JButton _delete = new JButton("Delete");
public StockClient()
{
// get the stock lister
_stockList = getStockList();
// add the title
JLabel title = new JLabel("Stock List");
title.setHorizontalAlignment(JLabel.CENTER);
getContentPane().add(title, BorderLayout.NORTH);
// add the stock label panel
JPanel stockLabelPanel = new JPanel(new GridLayout(2, 1));
stockLabelPanel.add(new JLabel("Symbol"));
stockLabelPanel.add(new JLabel("Name"));
getContentPane().add(stockLabelPanel,
BorderLayout.WEST);
// add the stock field panel
JPanel stockFieldPanel = new JPanel(new GridLayout(2, 1));
stockFieldPanel.add(_ticker);
stockFieldPanel.add(_name);
getContentPane().add(stockFieldPanel,
BorderLayout.CENTER);
// add the buttons
JPanel buttonPanel = new JPanel(new GridLayout(1, 4));
_get.addActionListener(this);
buttonPanel.add(_get);
_add.addActionListener(this);
MSPVL Polytechnic College

Page 113

Advanced Java Programming Manual


buttonPanel.add(_add);
_update.addActionListener(this);
buttonPanel.add(_update);
_delete.addActionListener(this);
buttonPanel.add(_delete);
getContentPane().add(buttonPanel,
BorderLayout.SOUTH);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{ System.exit(0);}
});
setSize(330, 130);
setVisible(true);
}
private StockList getStockList()
{
StockList stockList = null;
try
{
// Get a naming context
InitialContext jndiContext = new InitialContext();
// Get a reference to the StockList JNDI entry
Object ref = jndiContext.lookup
("ejb/beans.StockList");
// Get a reference from this to the Bean's Home
interface
StockListHome home = (StockListHome)
PortableRemoteObject.narrow(ref,
StockListHome.class);
// Create a StockList object from the Home interface
stockList = home.create();
}
MSPVL Polytechnic College

Page 114

Advanced Java Programming Manual


catch(Exception e)
{
e.printStackTrace();
}
return stockList;
}
public void actionPerformed(ActionEvent ae)
{
// if get was clicked, get the stock
if (ae.getSource() == _get)
{
getStock();
}
// if add was clicked, add the stock
if (ae.getSource() == _add)
{
addStock();
}
// if update was clicked, update the stock
if (ae.getSource() == _update)
{
updateStock();
}
// if delete was clicked, delete the stock
if (ae.getSource() == _delete)
{
deleteStock();
}
}
private void getStock()
{
// get the ticker
String ticker = _ticker.getText();
MSPVL Polytechnic College

Page 115

Advanced Java Programming Manual


if (ticker == null || ticker.length() == 0)
{
JOptionPane.showMessageDialog(this, "Ticker is
required");
return;
}
// get the stock
try
{
String name = _stockList.getStock(ticker);
_name.setText(name);
}
catch (FinderException fe)
{
JOptionPane.showMessageDialog(this, "Not
found!");
}
catch (Exception e)
{
e.printStackTrace();
}
}
private void addStock()
{
// get the ticker
String ticker = _ticker.getText();
if (ticker == null || ticker.length() == 0)
{
JOptionPane.showMessageDialog(this, "Ticker is
required");
return;
}
// get the name
String name = _name.getText();
MSPVL Polytechnic College

Page 116

Advanced Java Programming Manual


if (name == null || name.length() == 0)
{
JOptionPane.showMessageDialog(this, "Name is
required");
return;
}
// add the stock
try
{
_stockList.addStock(ticker, name);
JOptionPane.showMessageDialog(this, "Stock added!");
}
catch (CreateException fe)
{
JOptionPane.showMessageDialog(this, "Already
found!");
}
catch (Exception e)
{
e.printStackTrace();
}
}
private void updateStock()
{
// get the ticker
String ticker = _ticker.getText();
if (ticker == null || ticker.length() == 0)
{
JOptionPane.showMessageDialog(this, "Ticker is
required");
return;
}
// get the name
String name = _name.getText();
MSPVL Polytechnic College

Page 117

Advanced Java Programming Manual


if (name == null || name.length() == 0)
{
JOptionPane.showMessageDialog(this, "Name is
required");
return;
}
//update the stock
try
{
_stockList.updateStock(ticker, name);
JOptionPane.showMessageDialog(this, "Stock
updated!");
}
catch (FinderException fe)
{
JOptionPane.showMessageDialog(this, "Not
found!");
}
catch (Exception e)
{
e.printStackTrace();
}
}
private void deleteStock()
{
// get the ticker
String ticker = _ticker.getText();
if (ticker == null || ticker.length() == 0)
{
JOptionPane.showMessageDialog(this, "Ticker is
required");
return;
}
// delete the stock
try
MSPVL Polytechnic College

Page 118

Advanced Java Programming Manual


{
_stockList.deleteStock(ticker);
JOptionPane.showMessageDialog(this, "Stock
deleted!");
}
catch (FinderException fe)
{
JOptionPane.showMessageDialog(this, "Not
found!");
}
catch (Exception e)
{

e.printStackTrace();

}
public static void main(String[] args)
{
StockClient stockClient = new StockClient();
}
}
Output:

Result:
The above program was executed and the output is verified.

MSPVL Polytechnic College

Page 119

Advanced Java Programming Manual


Ex.No:18 Enterprise Java Beans of Message Driven Type

Aim:
Write a program to develop a Enterprise Java Bean of "Message Driven
Bean" type
Procedure:
Steps for Execution
1.

Create a folder called mdb and in that create two sub-directories called
msg and client.

2.

Write the coding for the SimpleMessageBean.java and save it in the msg
sub folder

3.

The

source

file

that

defines

the

user

interface

client

called

SimpleMessageClient.java is placed in the client subfolder:


4.

Compile the java file to get the class files.


a. Open the command prompt.
b. Move to the mdb directory.
c. Set PATH=.;%j2ee_home%\jdk\bin
d. Set classpath=.;%j2ee_home%\lib\j2ee.jar
e. Compile the java files as
javac -d . msg\*.java
javac -d . client\*.java

Creating the Administered Objects


1.

Start the Admin Console, as StartAll Programs  Sun Micro


Systems  Application Server PE  Admin Console

MSPVL Polytechnic College

Page 120

Advanced Java Programming Manual

2.

Enter the User name and Password in the Login page.

3.

To create the connection factory, perform the following steps:


a) In the tree component, expand the Resources node

MSPVL Polytechnic College

Page 121

Advanced Java Programming Manual


b) Then expand the JMS Resources node.
c) Select the Connection Factories node.
d) On the JMS Connection Factories page, click New. The
Create JMS Connection Factory page appears.
e) In the JNDI Name field, type jms/MyMDBQcf
f) Choose javax.jms.QueueConnectionFactory from the Type
combo box.
g) Select the Enabled checkbox.
h) Click OK.

MSPVL Polytechnic College

Page 122

Advanced Java Programming Manual

4.

To create the destination resource and link it to the physical


destination, perform the following steps:
a)

In the tree component, expand the Resources node, then


expand the JMS Resources node.

b)

Select the Destination Resources node.

c)

On the JMS Destination Resources page, click New. The


Create JMS Destination Resource page appears.

d)

In the JNDI Name field, type jms/MyQueue.

e)

Choose javax.jms.Queue from the Type combo box.

f)

Select the Enabled checkbox.

g)

In the Additional Properties area, type PhysicalQueue in the


Value field for the Name property.

h)

Click OK.

MSPVL Polytechnic College

Page 123

Advanced Java Programming Manual

MSPVL Polytechnic College

Page 124

Advanced Java Programming Manual


Creating the J2EE Application
1.

Start the J2EE server as Start  All Program

 Sun Micro Systems

Application Server PE  Start Default Server


2.

Start the deploy tool utility as Start  All Program  Sun Micro Systems
Application Server PE  Deploy Tool

3.

A new application deployment tool screen will be displayed.

4.

The first thing that we need the Deployment Tool to do is create the J2EE
application, which will be bundled together in an Enterprise Application
Resource (EAR) file.

5.

To create the application EAR file, from the File menu choose New 
Application. A dialog box will be displayed, prompting you to enter the
name of the EAR file, and the application name that you want displayed.
Click Browse and select the mdb folder and give the New Application
name as SimpleMessageApp

MSPVL Polytechnic College

Page 125

Advanced Java Programming Manual

6.

Click New Application and in the next window that appears click OK to
accept the changes to this dialog.

7.

Now well create the JAR file in which the session bean classes and
resources will be packaged. To do this, choose File  New  Enterprise
Bean menu item. A New Enterprise Bean Wizard appears. Click Next

8.

A screen showing a new enterprise bean wizard will be displayed. From


the combo box of Create New Jar Module in Application, select
SimpleMessageApp. In the JAR display name, enter SimpleMessageJar.
Then click the Edit Contents button.

MSPVL Polytechnic College

Page 126

Advanced Java Programming Manual

9.

In the Available Files panel of the dialog box shown below, navigate to the
msgdirectory

of

SimpleMessageApp.

Choose

the

SimpleMessageBean.class, and click the Add button. Those bean classes


will appear in the Contents of <EJB Bundle> panel as seen below:

10.

Click OK in the dialog box and then click the Next button

MSPVL Polytechnic College

Page 127

Advanced Java Programming Manual


11.

In the page that is displayed make the following settings


 From

the

Enterprise

Bean

Class

drop-down

list,

choose

msg.SimpleMessageBean.
 Type SimpleMessageEjb in the Enterprise Bean Name box.
 From the Enterprise Bean Type dropdown list choose MessageDriven.

12.

In the Message-Driven Bean Settings dialog, shown below, do the


following:
 Select the JMS option from the Messaging Service drop-down list
 Select javax.jms.Queue from the Destination Type drop-down list.
 Type PhysicalQueue into the Target Destination Name field.
 Type jms/MyMDBQcf in the Connection Factory JNDI Name field.
 Dont click the Next button just yet.

MSPVL Polytechnic College

Page 128

Advanced Java Programming Manual

13. Now

list

select the Non-JMS option from the Messaging Service drop-down


on

that

page.

In

the

Message-Driven

Bean

Settings

page

javax.jms.MessageListener is chosen in the Message Listener Interface


drop-down list. This is the interface that specifies the onMessage()
method:

MSPVL Polytechnic College

Page 129

Advanced Java Programming Manual


14. Use

the Add button, shown above, to add each of two Activation

Configuration Properties:
 The destinationType property, which as explained previously is
javax.jms.Queue
 The destination property, which is PhysicalQueue
The message-driven bean will listen for messages arriving at the
destination specified in these properties.
15. Now

click the Sun-specific Settings button and enter jaxr into the

Resource Adapter field as shown below, and click OK. ( A resource


adapter is analogous to a JDBC driver, and in this case allows the JMS
provider to interact with the J2EE server )

16. Click

Next and click finish in the wizard that appears.

17. After

finishing the wizard, select SimpleMessageEjb in the left panel,

and select the Transactions tab. Choose Container-Managed and let


the Transaction Attribute default to Required.

MSPVL Polytechnic College

Page 130

Advanced Java Programming Manual

18. Select

SimpleMessageJar in the left panel and MessageDestinations Tab

in the right panel and do the following:


a) Click Add.
b) Type

the

physical

destination

name

(for

this

example,

PhysicalQueue) in the Destination Name field, and press Enter.


c) Type the JNDI name of the destination resource (for this
example, jms/ MyQueue) in the JNDI Name field

MSPVL Polytechnic College

Page 131

Advanced Java Programming Manual

19. Do

File  Save All. Select SimpleMessageApp on the left, and select Sun-

Specific Settings in the right and then assign the JNDI name as
jms/MyQueue

MSPVL Polytechnic College

Page 132

Advanced Java Programming Manual


Creating & Packaging the Application Client
1.

In

the

Application

Deployment

Tool

screen,

go

to

File

New

Application Client.
2.

Click Next in the Introduction wizard that appears. The New Application
Client wizard screen will be displayed as shown below: Give the Jar
Display name as SimpleMessageClient. And click Edit Contents button

3.

A screen saying Edit contents of SimpleMessageClient will be displayed.


In that select the SimpleMessageClient.class in the client folder and click
Add and then click Next in the wizard that appears.

MSPVL Polytechnic College

Page 133

Advanced Java Programming Manual

4.

In

the

window

that

appears

Select

the

Main

class

as

Client.SimpleMessageClient. Click Next and then click finish to return to


the main window.

MSPVL Polytechnic College

Page 134

Advanced Java Programming Manual


Setting the Resource References of the client
Select the SimpleMessageClient in the Left pane and use the Resource
Refs tabbed pane on the right to specify the connection factory
references for the component.

1.

Select the Resource Refs tab.

2.

Click Add.

3.

In the Coded Name field, enter the name that matches the parameter
of the lookup method in the component code. For our example,
because the coded name should be jms/MyMDBQcf

4.

In the Type field, select the connection factory class that matches the
destination

type.

The

destination

class

in

the

code

is

javax.jms.QueueConnectionFactory, so select that class.


5.

In the Authentication field select Container.

6.

In the Sharable field, make sure that the checkbox is selected. This
choice allows the container to optimize connections.

7.

In the Sun-specific Settings area, enter the name of the connection


factory in this case, enter jms/MyMDBQcf in the JNDI Name field.

8.

Enter guest in both the User Name and the Password fields.

MSPVL Polytechnic College

Page 135

Advanced Java Programming Manual

Setting the Message Destination References


For any new application, we use the Msg Dest Refs tab to specify the
destination of messages.
1.

Select the Msg Dest Refs tab.

2.

Click Add.

3.

In the Coded Name field of the dialog box that appears, type a name
that matches the parameter of the lookup call that locates the queue
or topic. In this example, the the coded name is jms/MyQueue

4.

In the Destination Type combo box, choose the class that matches the
destination

5.

type (in this case, javax.jms.Queue).

6.

From

the

Usage

combo

box,

choose

either

Produces

or

ConsumesProduces, depending on whether this component sends


messages or both sends and receives messages. For this example,
choose Produces.
7.

In the Destination Name field, type the name of the physical


destination you created (in this case, PhysicalQueue).

MSPVL Polytechnic College

Page 136

Advanced Java Programming Manual

Setting the Message Destinations


1.

Select the Message Destinations tab.

2.

Click Add.

3.

In the Destination Name field, type the name of the destination (in this
case, PhysicalQueue) and press Return. The name also appears in the
Display Name field. The names of the components that consume and
produce messages for the destination appear in the Producers and
Consumers areas.

4.

In the JNDI Name field, type the name of the JMS resource you created
(in this case, jms/MyQueue).

MSPVL Polytechnic College

Page 137

Advanced Java Programming Manual

Deploying the J2EE Application


1. Select the simpleMessageApp application.
2. Select Tools  Deploy.
3. Under Connection Settings, enter the user name and password for the
Application Server.
4. Tell deploytool to create a JAR file that contains the client stubs.
a. Select the Return Client JAR checkbox.
b. In the field below the checkbox, enter C:\mdb
5. Click OK.
6. In the Distribute Module dialog box, click Close when the deployment
completes.

MSPVL Polytechnic College

Page 138

Advanced Java Programming Manual

7. Verify that a stub client JAR named SimpleMessageAppClient.jar resides


in C:\mdb

MSPVL Polytechnic College

Page 139

Advanced Java Programming Manual


Running the Application Client
1.

In the command prompt go to the directory C:\mdb

2.

set APPCPATH=c:\mdb\SimpleMessageAppClient.jar

3.

set path=c:\Sun\AppServer\bin

4.

Run the client as


C:\mdb>appclient -client SimpleMessageApp.ear
The client displays these lines:
Sending message: This is message 1
Sending message: This is message 2
Sending message: This is message 3
To see if the bean received the messages,
Check C:/Sun/AppServer/domains/domain1/logs/server.log.
In the server log file, the following lines should be displayed, wrapped
in logging information:
MESSAGE BEAN: Message received: This is message 1
MESSAGE BEAN: Message received: This is message 2
MESSAGE BEAN: Message received: This is message 3

Program:
package client;
import javax.jms.*;
import javax.naming.*;
public class SimpleMessageClient
{
/* The main method of the client. The client sends three messages
to the message queue and on the other hand the bean receives
these messges asynchronously from the queue.*/
public static void main(String[] args)
{

MSPVL Polytechnic College

Page 140

Advanced Java Programming Manual


Context jndiContext = null;
QueueConnectionFactory queueConnectionFactory = null;
QueueConnection queueConnection = null;
QueueSession queueSession = null;
Queue queue = null;
QueueSender queueSender = null;
TextMessage message = null;
final int NUM_MSGS = 3;
try
{
jndiContext = new InitialContext();
}
catch (NamingException e)
{
System.out.println("Could not create JNDI " + "context: "
+ e.toString());
System.exit(1);
}
try
{
queueConnectionFactory = (QueueConnectionFactory)
jndiContext.lookup("java:comp/env/jms/MyMDBQcf");
queue=(Queue)jndiContext.lookup("java:comp/env/jms
/MyQueue");
}
catch (NamingException e)
{
System.out.println("JNDI lookup failed: " +
e.toString());
System.exit(1);
}
try
{
MSPVL Polytechnic College

Page 141

Advanced Java Programming Manual


queueConnection =
queueConnectionFactory.createQueueConnection();
queueSession=

queueConnection.createQueueSession

(false,Session.AUTO_ACKNOWLEDGE);
queueSender = queueSession.createSender(queue);
message = queueSession.createTextMessage();
for (int i = 0; i < NUM_MSGS; i++)
{
message.setText("This is message " + (i + 1));
System.out.println("Sending message: "

message.getText());
queueSender.send(message);
}
}
catch (Throwable e)
{
System.out.println("Exception occurred: " +
e.toString());
}
finally
{
if (queueConnection != null)
{
try
{
queueConnection.close();
}
catch (JMSException e) {}
} // if
System.exit(0);
} // finally
} // main
} // class
MSPVL Polytechnic College

Page 142

Advanced Java Programming Manual


SimpleMessageBean.java
package msg;
import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.EJBException;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.ejb.CreateException;
import javax.naming.*;
import javax.jms.*;
public class SimpleMessageBean implements MessageDrivenBean,
MessageListener
{
private transient MessageDrivenContext mdc = null;
private Context context;
/*Default constructor. Creates a bean. Required by EJB spec. */
public SimpleMessageBean()
{
System.out.println("In
SimpleMessageBean.SimpleMessageBean()");
}
/* Sets the context for the bean */
public

void

setMessageDrivenContext(MessageDrivenContext

mdc)
{

MSPVL Polytechnic College

Page 143

Advanced Java Programming Manual


System.out.println("In " +
"SimpleMessageBean.setMessageDrivenContext()");
this.mdc = mdc;
}
/*Creates a bean. Required by EJB spec.*/
public void ejbCreate()
{
System.out.println("In SimpleMessageBean.ejbCreate()");
}
/* When the queue receives a message, the EJB container
invokes the onMessage method of the message-driven */
public void onMessage(Message inMessage)
{
TextMessage msg = null;
try
{
if (inMessage instanceof TextMessage)
{
msg = (TextMessage) inMessage;
System.out.println("MESSAGE BEAN:
Message received: "+ msg.getText());
}
else
{
System.out.println("Message of wrong type: "+
inMessage.getClass().getName());
}
}
catch (JMSException e)

MSPVL Polytechnic College

Page 144

Advanced Java Programming Manual


{

e.printStackTrace();

catch (Throwable te)


{

te.printStackTrace();

} // onMessage
/* Removes the bean. Required by EJB spec. */
public void ejbRemove()
{
System.out.println("In SimpleMessageBean.remove()");
}
} // class
Output:

Result:
The above program was executed and the output is verified.

MSPVL Polytechnic College

Page 145

Advanced Java Programming Manual


EJB Viva Questions
1. What

makes

J2EE

suitable

for

distributed

multitiered

Applications?
The J2EE platform uses a multitiered distributed application
model.Application logic is divided into components according to
function, and the various application components that make up a
J2EE application are installed on different machines depending on the
tier in the multitiered J2EE environment to which the application
component belongs.
The J2EE application parts are:
 Client-tier components run on the client machine.
 Web-tier components run on the J2EE server.
 Business-tier components run on the J2EE server.
 Enterprise information system (EIS)-tier software runs on the
EIS server.
2. What is J2EE?
J2EE is an environment for developing and deploying enterprise
applications.The J2EE platform consists of a set of services,
application programming interfaces (APIs), and protocols that provide
the functionality for developing multitiered, web-based applications.
3. What are the components of J2EE application?
A J2EE component is a self-contained functional software unit
that is assembled into a J2EE application with its related classes and
files and communicates with other components.
The J2EE specification defines the following J2EE components:
 Application clients and applets are client components.
 Java Servlet and Java Server Pages technology components
are web components.
 Enterprise JavaBeans components (enterprise beans) are
business components.
 Resource adapter components provided by EIS and tool
vendors.
MSPVL Polytechnic College

Page 146

Advanced Java Programming Manual


4. What can be considered as a web component?
J2EE

Web

pages.Servlets

components

are

Java

can

be

programming

either

servlets

language

or

JSP

classes

that

dynamically process requests and construct responses.JSP pages are


text-based documents that execute as servlets but allow a more
natural approach to creating static content.
5. What is the container?
Containers are the interface between a component and the lowlevel

platform

specific

functionality

that

supports

the

component.Before a Web, enterprise bean, or application client


component can be executed, it must be assembled into a J2EE
application and deployed into its container.
6. What are container services?
A container is a runtime support of a system-level entity.
Containers provide components with services such as:
 lifecycle management
 security
 deployment
 threading
7. What is the web container?
Servlet and JSP containers are collectively referred to as Web
containers. It manages the execution of JSP page and servlet
components for J2EE applications. Web components and their
container run on the J2EE server.
8. What is Enterprise JavaBeans (EJB) container?
It manages the execution of enterprise beans for J2EE
applications. Enterprise beans and their container run on the J2EE
server.

MSPVL Polytechnic College

Page 147

Advanced Java Programming Manual


9. How do we package J2EE components?
J2EE components are packaged separately and bundled into a
J2EE application for deployment. Each component, its related files
such as GIF and HTML files or server-side utility classes, and a
deployment descriptor are assembled into a module and added to the
J2EE application. A J2EE application is composed of one or more
enterprise bean, Web, or application client component modules. The
final enterprise solution can use one J2EE application or be made up
of two or more J2EE applications, depending on design requirements.
A J2EE application and each of its modules has its own deployment
descriptor. A deployment descriptor is an XML document with an.xml
extension that describes a components deployment settings.
10. What is a thin client?
A thin client is a lightweight interface to the application that
does not have such operations like query databases, execute complex
business rules, or connect to legacy applications.
11. What are types of J2EE clients?
Following are the types of J2EE clients:
 Applets
 Application clients
 Java Web Start-enabled rich clients, powered by Java Web
Start technology.
 Wireless clients, based on Mobile Information Device Profile
(MIDP) technology.
12. What is deployment descriptor?
A deployment descriptor is an Extensible Markup Language
(XML) text-based file with an.xml extension that describes a
components deployment settings. A J2EE application and each of its
modules has its own deployment descriptor. For example, an
enterprise bean module deployment descriptor declares transaction
attributes and security authorizations for an enterprise bean. Because
deployment descriptor information is declarative, it can be changed
MSPVL Polytechnic College

Page 148

Advanced Java Programming Manual


without modifying the bean source code. At run time, the J2EE server
reads the deployment descriptor and acts upon the component
accordingly.
13. What is the EAR file?
An EAR file is a standard JAR file with an.ear extension, named
from Enterprise ARchive file. A J2EE application with all of its
modules is delivered in EAR file.
14. What is J2EE Connector?
The J2EE Connector API is used by J2EE tools vendors and
system integrators to create resource adapters that support access to
enterprise information systems that can be plugged into any J2EE
product. Each type of database or EIS has a different resource
adapter. Note: A resource adapter is a software component that allows
J2EE application components to access and interact with the
underlying resource manager. Because a resource adapter is specific
to its resource manager, there is typically a different resource adapter
for each type of database or enterprise information system.
15. What is Java Naming and Directory Service?
The JNDI provides naming and directory functionality. It
provides applications with methods for performing standard directory
operations, such as associating attributes with objects and searching
for objects using their attributes. Using JNDI, a J2EE application can
store and retrieve any type of named Java object. Because JNDI is
independent of any specific implementations, applications can use
JNDI to access multiple naming and directory services, including
existing naming and directory services such as LDAP, NDS, DNS, and
NIS.
16. What is the Java 2 Platform, Enterprise Edition (J2EE)?
The Java 2 Platform, Enterprise Edition (J2EE) is a set of
coordinated specifications and practices that together enable solutions
for developing, deploying, and managing multi-tier server-centric
MSPVL Polytechnic College

Page 149

Advanced Java Programming Manual


applications. Building on the Java 2 Platform, Standard Edition
(J2SE), the J2EE platform adds the capabilities necessary to provide a
complete, stable, secure, and fast Java platform to the enterprise
level. It provides value by significantly reducing the cost and
complexity of developing and deploying multi-tier solutions, resulting
in services that can be rapidly deployed and easily enhanced.
17. What are the main benefits of the J2EE platform?
The J2EE platform provides the following:
 Complete Web services support:
 Faster solutions delivery time to market:
 Freedom of choice:
 Simplified connectivity:
18. What technologies are included in the J2EE platform?
The primary technologies in the J2EE platform are: Java API for
XML-Based RPC (JAX-RPC), Java Server Pages, Java Servlets,
Enterprise JavaBeans components, J2EE Connector Architecture,
J2EE Management Model, J2EE Deployment API, Java Management
Extensions (JMX), J2EE Authorization Contract for Containers, Java
API for XML Registries (JAXR), Java Message Service (JMS), Java
Naming and Directory Interface (JNDI), Java Transaction API (JTA),
CORBA, and JDBC data access API.
19. What is the J2EE 1.4 SDK?
The Java 2 SDK, Enterprise Edition 1.4 (J2EE 1.4 SDK) is a
complete package for developing and deploying J2EE 1.4 applications.
The J2EE 1.4 SDK contains the Sun Java System Application Server
Platform Edition 8, the J2SE 1.4.2 SDK, J2EE 1.4 platform API
documentation, and a slew of samples to help developers learn about
the J2EE platform and technologies and prototype J2EE applications.
The J2EE 1.4 SDK is free for both development and deployment.

MSPVL Polytechnic College

Page 150

Advanced Java Programming Manual


20. What is the J2EE module?
A J2EE module consists of one or more J2EE components for
the same container type and one component deployment descriptor of
that type. The four types of J2EE modules are
 Application client module
 Web module
 Enterprise JavaBeans module
 Resource adapter module
21. What does application client module contain?
 The application client module contains class files, an application
client deployment descriptor
 Application client modules are packaged as JAR files with a .jar
extension.
22. What does web module contain?
 The web module contains: JSP files, class files for servlets, GIF
and HTML files, and a Web deployment descriptor.
 Web modules are packaged as JAR files with a .war (Web
ARchive) extension.
23. What are the differences between Ear, Jar and War files? Under
what circumstances should we use each one?
 There are no structural differences between the files; they are all
archived using zip-jar compression. However, they are intended
for different purposes.
 Jar files (files with a .jar extension) are intended to hold generic
libraries of Java classes, resources, auxiliary files, etc.
 War files (files with a .war extension) are intended to contain
complete Web applications. In this context, a Web application is
defined as a single group of files, classes, resources, .jar files
that can be packaged and accessed as one servlet context.
 Ear files (files with a .ear extension) are intended to contain
complete enterprise applications. In this context, an enterprise

MSPVL Polytechnic College

Page 151

Advanced Java Programming Manual


application is defined as a collection of .jar files, resources,
classes, and multiple Web applications.
 Each type of file (.jar, .war, .ear) is processed uniquely by
application servers, servlet containers, EJB containers, etc.
24. What is the difference between Session bean and Entity bean ?
The Session bean and Entity bean are two main parts of EJB
container.
Session Bean
 Represents a workflow on behalf of a client
 One-to-one logical mapping to a client.
 Created and destroyed by a client
 Not permanent objects
 Lives its ejb container(generally) does not survive system
shut down
 Two types: stateless and stateful beans
Entity Bean
 Represents persistent data and behavior of this data
can be shared among multiple clients
 Persists across multiple invocations
 Findable permanent objects
 Outlives its ejb container, survives system shutdown
 Two types: container managed persistence(cmp) and bean
managed
 Persistence(bmp)

MSPVL Polytechnic College

Page 152

You might also like