M - SC - (CS) - 341 13 - Advaned Java Programming
M - SC - (CS) - 341 13 - Advaned Java Programming
All rights reserved. No part of this publication which is material protected by this copyright notice
may be reproduced or transmitted or utilized or stored in any form or by any means now known or
hereinafter invented, electronic, digital or mechanical, including photocopying, scanning, recording
or by any information storage or retrieval system, without prior written permission from the Alagappa
University, Karaikudi, Tamil Nadu.
Information contained in this book has been published by VIKAS® Publishing House Pvt. Ltd. and has
been obtained by its Authors from sources believed to be reliable and are correct to the best of their
knowledge. However, the Alagappa University, Publisher and its Authors shall in no event be liable for
any errors, omissions or damages arising out of use of this information and specifically disclaim any
implied warranties or merchantability or fitness for any particular use.
Work Order No. AU/DDE/DE1-238/Preparation and Printing of Course Materials/2018 Dated 30.08.2018 Copies - 500
SYLLABI-BOOK MAPPING TABLE
Advanced Java Programming
BLOCK I: INTRODUCTION
UNIT - 1: Introduction : JDBC Overview, Connection Class, MetaData Function Unit 1: Introduction to JDBC
(Pages 1-26)
UNIT - 3: Statement, ResultSet, Other JDBC Classes Unit 3: JDBC Classes and
Statements
(Pages 34-56)
UNIT - 8: Design Patterns for Properties, Events and Methods Unit 8: Design Patterns and
Event Handling
(Pages 135-163)
UNIT - 11: Reading Initialization, Parameters, Reading Servlet Parameters Unit 11: Servlet Parameters
(Pages 210-228)
UNIT - 12: Cookies, Session Tracking Unit 12: Cookies and Session
Tracking
(Pages 229-242)
UNIT - 14: AWT Classes, Working with Graphics, Color and Font Unit 14: AWT Classes and
Working with Graphics
(Pages 266-284)
CONTENTS
INTRODUCTION
BLOCK I: INTRODUCTION
UNIT 1 INTRODUCTION TO JDBC 1-26
1.0 Introduction
1.1 Objectives
1.2 JDBC: Overview
1.2.1 JDBC Drivers
1.2.2 Seven Steps to Create the JDBC Programs and Applications
1.3 JDBC Metadata API
1.4 A JDBC-Servlet Example
1.5 A JDBC-JSP Example
1.6 Answers to Check Your Progress Questions
1.7 Summary
1.8 Key Words
1.9 Self Assessment Questions and Exercises
1.10 Further Readings
UNIT 2 SQL EXCEPTION AND WARNING 27-33
2.0 Introduction
2.1 Objectives
2.2 SQL Exception and SQL Warning Concepts
2.2.1 Exception Retrieval
2.2.2 Introduction to SQL Warning
2.2.3 Special SQL Exceptions
2.3 Answers to Check Your Progress Questions
2.4 Summary
2.5 Key Words
2.6 Self Assessment Questions and Exercises
2.7 Further Readings
UNIT 3 JDBC CLASSES AND STATEMENTS 34-56
3.0 Introduction
3.1 Objectives
3.2 The java.sql Package
3.2.1 The DriverManager Class
3.2.2 The Connection Interface
3.2.3 The Statement Interface
3.2.4 The ResultSet Interface
3.2.5 The PreparedStatement Interface
3.2.6 The ResultSetMetaData Interface
3.2.7 The CallableStatement Interface
3.2.8 The SQLException Class
3.3 Answers to Check Your Progress Questions
3.4 Summary
3.5 Key Words
3.6 Self Assessment Questions and Exercises
3.7 Further Readings
Self-Instructional
Material 11
Introduction Inheritance facilitates a class to acquire the properties and functionality of
another class. It also facilitates classes to reuse the existing code. Java provides an
approach known as interface as a convenient alternative to implement multiple
inheritance. A named collection of classes is known as a package. Any number of
NOTES related classes can be grouped into a single package. There are two types of
common errors which can arise in java programs, namely compile-time and run-
time errors. These errors in Java code can be detected and removed by exhaustive
testing and debugging. Java supports input and output of data through the classes
included in the java.io package. Applets are small java programs which are
specifically designed to be used over the Web. In other words, applets provide a
programmer to develop a full-featured multimedia application. Java applets are
used to create graphical and user-interactive applications. Java supports creation
of sockets and exchange information using different protocols through the classes
defined in java.net package. Other than the standalone applications and applets,
Java also allows the creation of distributed applications using the concept of RMI
(Remote Method Invocation).
This book, Advanced Java Programming, has been written in the self-
instructional mode or SIM format wherein each unit begins with an ‘Introduction’
to the topic, followed by an outline of the ‘Objectives’. The detailed content is
then presented in a simple and organized manner, interspersed with ‘Check Your
Progress’ questions to test the student’s understanding of the topics covered. A
‘Summary’ along with a list of ‘Key Words’ and a set of ‘Self Assessment Questions
and Exercises’ is provided at the end of each unit for effective recapitulation.
Self-Instructional
12 Material
Introduction to JDBC
BLOCK - I
INTRODUCTION
NOTES
UNIT 1 INTRODUCTION TO JDBC
Structure
1.0 Introduction
1.1 Objectives
1.2 JDBC: Overview
1.2.1 JDBC Drivers
1.2.2 Seven Steps to Create the JDBC Programs and Applications
1.3 JDBC Metadata API
1.4 A JDBC-Servlet Example
1.5 A JDBC-JSP Example
1.6 Answers to Check Your Progress Questions
1.7 Summary
1.8 Key Words
1.9 Self Assessment Questions and Exercises
1.10 Further Readings
1.0 INTRODUCTION
Nowadays you are using applications that are most preferably three–tier
applications, though n-tier architecture is the necessity nowadays. Database is an
essential part of this 3-tier architecture besides the presentation and business logics.
Differentiating the storage from the main application has various advantages over
traditional inbuilt database applications.
The web applications require database to store their data. Database is an
essential part of every good application be it a standalone application or a web
application. It is equally important for both. A good application is that which can
easily connect to database and retrieve the data in the format that user wants. In
this unit, you will learn about the database connectivity and Metadata function.
1.1 OBJECTIVES
A database is an organized collection of data and a schema that provides the data
NOTES structures to hold the data. A database is very essential, by the point of view of a
web application as it will store the data, the web application will deal with. There
are various types of databases that you can see and use for your web applications.
The most preferred one is the RDBMS (Relational Database Management System).
RDBMS supports organization of data in tuples (rows) or say in a table and
provides you the functionality to define the table characteristics independently of
the actual data you’re going to store into it.
A database management system (DBMS), such as Oracle (Oracle
Corporation, licensed), MySQL (Open Source) or PostgreSQL (Open Source),
is a software package that lets you CRUD activities on both- items of data and
elements of the schema. CRUD stands for Create, Retrieve, Update and Delete
Operations on the data.
So, dealing with database is not an easy task, you need to be able to
differentiate and understand the following three aspects about databases:
The data it contains.
The structure you impose on the data in order to CRUD it efficiently.
The software that allows you to manipulate both the data itself and the
database structure (the DBMS).
You are working with databases; it means you are interacting with the
database management systems (DBMS) which can be one among the following
interactive modes:
(a) Command line interface (CLI),
(b) Using graphical user interfaces (GUIs)
(c) Programmatically through an API.
Most of the time, you use all the three methods, each for a different purpose
and need. The CLI is best enough for testing purposes and to start database with.
In contrast, the API is well suited in use in web application to interact with the
database to perform its tasks, and the GUI is used to validate the individual data
items or fix problems.
JDBC (Java Database Connectivity) is a Java technology that empowers
you to connect to any existing relational database management systems, execute
SQL commands, and process the results, all from within a Java program. JDBC is
an application programming interface between Java programs and database
Self-Instructional
2 Material
management systems –a call level interface like Oracle call Interface (OCI). Call Introduction to JDBC
level Interface means making function calls to access the features unlike SQL
statements which need to be translated by a pre compiler. JDBC APIs lets your
application to connect to any database systems to store, process and retrieve the
data using a Java class known as a JDBC Driver. And there are hundreds of such NOTES
drivers existing to connect to a number of databases that are widely used. The real
benefit that you will get using JDBC is , with just minute changes in your program
can make it compatible to work with a hell lot of database like JDBC queries that
work on an Oracle database require little or no changes to work with DB2, or
SQL Server, or any other database. JDBC also helps in quick and easy transition
from legacy systems to Web-enabled applications.
Remember, JDBC is often mistaken as an acronym of Java Database
Connectivity. It is one of the J2EE compliant technology used for connecting your
java program with databases.
In this chapter you will go through the database connectivity with your
application, whatever be it-a standalone core java application or a web application
developed using JSP and Servlets.
1.2.1 JDBC Drivers
The JDBC API lets you access databases from Java application programs. There
are basically four types of JDBC implementations (i.e., drivers) according to the
nature of connections you will wish to establish with the database(s).
1. Type1: JDBC-ODBC Bridge Driver
JDBC drivers of type 1 are actually JDBC-ODBC bridges, because they access
databases via an Open Database Connectivity (ODBC) driver. Using ODBC
requires configuring your systems data Source Name (DSN) that will represent
the target database.
When you will use MS-Access as database source, you will need to use
this driver.
2. Type 2: Native API, Partly Java Driver
JDBC drivers of type 2 use vendor-specific, native, client-side libraries. In this the
JDBC API calls are converted into the native vendor specific, C/C++ API calls
that are unique to the databases. In other words, they act as interface to non-Java
functions provided by the DBMS vendor, which in turn act as interfaces to the
databases. These drivers are more efficient compared to those of type 1, but you
can only use them locally and hence not applicable for web applications.
Self-Instructional
Material 3
Introduction to JDBC The OCI (Oracle call Interface) driver is an example of this type.
NOTES
Fig. 1.1 Implementation of JDBC Type 2 and JDBC Type 4 Drivers which are the Most
Popular of all the JDBC Drivers
Self-Instructional
4 Material
Class.forName(“connect.microsoft.MicrosoftDriver”);//for Introduction to JDBC
Microsoft DB2
Class.forName(“oracle.jdbc.driver.OracleDriver”);//for
Oracle Database
Class.forName(“com.sybase.jdbc.SybDriver”);//for Sybase NOTES
} catch(ClassNotFoundException cnfe) {
System.err.println(“Error loading driver: “ + cnfe);
}
Note: This method takes a string representing a fully qualified classname
(i.e., one that includes package names) and loads the corresponding class.
This call could throw a ClassNotFoundException, so it should be inside a
try/catch block.
You can place your JDBC driver file (JAR file) in the WEB-INF/lib directory
for deployment of your web application. However, the administrator may
choose to move the JAR file to a common library directory on the server.
2. Define the connection URL: In JDBC, a connection URL specifies the
server host, port, and database name with which to establish a connection.
It specifies the location of the database.
String host = “databasehost.yourcompany.com”;
String dbName = “someName”;
int port = 8033;//it can be anything that your server
works on.
//for Oracle database
String oracleURL = “jdbc:oracle:thin:@” + host + “:” +
port + “:” + dbName;
Self-Instructional
Material 5
Introduction to JDBC 4. Create a statement object. Creating a Statement object enables you to
send queries and commands to the database.
String query = “ SELECT col1, col2, col3 FROM tableName”;
NOTES ResultSet resultSet = statement.executeQuery(query);
5. Execute a query or update. Given a Statement object, you can send
SQL statements to the database by using the execute, executeQuery,
executeUpdate, or executeBatch methods.
The following list summarizes commonly used methods in the Statement
class.
i. executeQuery(): Executes an SQL query and returns the data in a
ResultSet. The ResultSet may be empty, but never null.
ii. executeUpdate(): Used to execute UPDATE, INSERT, or DELETE
commands. Returns the number of rows affected, which could be
zero. Also provides support for Data Definition Language (DDL)
commands, for example, CREATE TABLE, DROP TABLE, and
ALTER TABLE.
iii. executeBatch(): Executes a group of commands as a unit, returning
an array with the update counts for each command. Use addBatch to
add a command to the batch group.
Note that vendors are not required to implement this method in their driver
to be JDBC compliant.
6. Process the results. When a database query is executed, a ResultSet is
returned. The ResultSet represents a set of rows and columns that you can
process by calls to next and various getXxx() methods like getInt() or
getString() methods.
Here is an example that prints the values of the first two columns and the
first name and last name, for all rows of a ResultSet.
while (resultSet.next()) {
System.out.println(resultSet.getString(1) + “ “ +
resultSet.getString(2) + “ “ +
resultSet.getString(“firstname”) + “ “
resultSet.getString(“lastname”));
}
Note: It is advised to use the column name instead of the column index
when you access the columns of a ResultSet. Why? So that, restructuring
the table does not affect the ResultSet that is to be retrieved.
7. Close the connection. When you are finished performing queries and
processing results, you should close the connection, releasing resources to
the database.
Self-Instructional
6 Material
To close the connection explicitly, you have to do: Introduction to JDBC
connection.close ();
Closing the connection also closes the corresponding Statement and
ResultSet objects. NOTES
You should postpone closing the connection if you expect to perform
additional database operations, since the overhead of opening a connection is
usually large.
JDBC 2.0 has provided some more flexibility. The main is the use of Java
Naming and Directory Interface (JNDI).An API that helps an application to look
up a Data Source object by name from a naming service, rather than hard-coding
driver class name and database URL in the program, thereby providing the flexibility
to port the database.
JDBC 2.0 result sets have more capabilities. The result set derived can be
accessed in random order rather than sequentially from start to finish. They can be
updated and have the updates propagated back to the underlying table.
Now you will see the implementation of these steps in the servlet and JSP
programs.
The JDBC API consists of two important interfaces that help in retrieving the
metadata information, they are: 1. DatabaseMetaData and 2. ResultSetMetaData.
The java.sql package houses these interfaces, you have to import the java.sql
package to use these ones. DatabaseMetaData interface is meant for retrieving
database information like its capabilities and structure while the ResultSetMetaData
interface is considered if you want to retrieve the information about SQL queries
like some specific information about its size and types of column used,etc. Let’s
get them in details as these are the key constituents of the package.
DatabaseMetaData
DatabaseMetaData interface is used for retrieving database information like its
capabilities and structure and this information is required by the database vendor.
So, it is implemented by the database vendor and provided along with the native
JDBC driver. Native JDBC drivers are built on top of the database. By
implementing this interface, database vendors provide comprehensive information
about the database as a whole, such as table name, indexes, product name, version,
and so forth. There are a number of methods declared in this interface to retrieve
various metadata information associated with the database.
Self-Instructional
Material 7
Introduction to JDBC Example 1.1: To illustrate the concept of Metadata interface.
package org.mano.example;
import java.sql.Connection;
NOTES
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
}
}
}
}
ResultSetMetaData
This interface provides metadata information about the structure of
the ResultSet object, such as finding out number of columns, its name, type and
length, table names, whether a column is readable/writable, searchable, and so
on.
Example 1.2: To illustrate the use of ResultSet object.
package org.mano.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
try {
conn = DriverManager.getConnection(URL,
USERNAME, PASSWORD);
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);
rsmd = rs.getMetaData();
if (rsmd != null) {
int cols = rsmd.getColumnCount();
System.out.println(“Number of Columns: “ +
cols);
System.out.println(“Table Name: “ +
rsmd.getTableName(1));
System.out.println(“Catalog Name: “ +
rsmd.getCatalogName(1));
System.out.println
(“—————————————————————”);
for (int i = 1; i <= cols; i++) {
System.out.println(“Class Name: “ +
rsmd.getColumnClassName(i));
System.out.println(“Column Name: “ +
rsmd.getColumnName(i));
System.out.println(“Column Type Name: “ +
rsmd.getColumnTypeName(i));
System.out.println
(“———————————————————”);
}
} else {
System.out.println(“ResultSetMetadata not
supported”);
}
}
}
}
}
ParameterMetaData
ParameterMetadata objects are used to retrieve information about the parameter
markers in a PreparedStatement object. The metadata information refers to the
types and properties of the parameter used, such as getting the fully qualified Java
class name, parameter count, its types, designated precision specified by the column
size, and the like.
Example 1.3: To illustate the use of ParameterMetaData objects.
package org.mano.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;
try {
NOTES
conn = DriverManager.getConnection(URL,
USERNAME, PASSWORD);
pstmt = conn.prepareStatement(SQL);
pmd = pstmt.getParameterMetaData();
if (pmd != null) {
System.out.println(“Parameter Count: “ +
pmd.getParameterCount());
} else {
System.out.println(“ParameterMetadata not
supported by the database”);
}
}
}
}
}
RowSetMetaData
The RowSetMetaData interface is a part of the javax.sql package and is a sub-
implementation of the ResultSetMetaData interface. An object of this class provides
information about columns in a RowSetobject. The RowSet interface provides
support for the JDBC API for JavaBeans component model. As a result, it has
properties and supports the technique of JavaBeans event notification.
RowSetMetadataprovides the information about the columns in a RowSet object
and can be used to find out about the number of columns contained in a rowset or
the type of data each column contains. It is crucial to understand the working
mechanism of the RowSet object to fully appreciate the use of RowSetMetaData.
Delineating the rowset mechanism is outside the scope of this article; however,
readers may refer the article “Working with the JDBC RowSet API” to get an
Self-Instructional
12 Material
idea of the Rowset API. However, this is not going to stop us from getting a glimpse Introduction to JDBC
of RowSetMetaData in action.
Example 1.4: Showing the use of RowSetMetaData interface.
package org.mano.example; NOTES
import java.sql.SQLException;
import javax.sql.RowSetMetaData;
import javax.sql.rowset.WebRowSet;
import com.sun.rowset.WebRowSetImpl;
try {
Class.forName(“com.mysql.jdbc.Driver”);
rowSet = new WebRowSetImpl();
rowSet.setUrl(URL);
rowSet.setUsername(USERNAME);
rowSet.setPassword(PASSWORD);
rowSet.setCommand(SQL);
rowSet.execute();
Self-Instructional
Material 13
Introduction to JDBC System.out.println(“Column Name: “ +
rsmd.getColumnName(i) +
“ Type: “ + rsmd.getColumnTypeName(i));
} else {
NOTES
System.out.println(“RowSetMetadata not
supported”);
}
}
}
}
}
JDBC Metadata APIs are indispensable for creating most commercial
database applications. They are particularly useful for creating customized database
solutions such as generating a GUI-based data browser application. For example,
one can create dynamic a GUI-based table structure according to the metadata
information retrieved from the database. Refer to the Java API documentation for
more information on the APIs and their functionality.
1. index.html- the front controller of the application ,from here the table name
is taken from the user whose data he wants to view.
2. ServletJdbcOracleConnect.java – The business logic that will contain NOTES
the method of retrieving the data from the table and also display it in certain
form like a table.
3. web.xml- the deployment descriptor for the web application .
2. Prerequisites
(a) Set the classpath to servlet-api.jar so that the servlet can be compiled.
(b) Create the DSN named as “vph” and associate an MS-Access file with it
which will work as the repository here.
(c) Create the web application folder and use the directory structure to put the
files in appropriate folders.
Once you are set with all the above prerequisites, compile the servlet and
place the .class file in the classes folder in WEB-INF folder. Place all other files
properly in their respective folders. Finally deploy the application on the server
and run using the appropriate URL.
ServletJdbcOracleConnect.java
import java.io.*;
import java.sql. *;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletJdbcOracleConnect extends HttpServlet
{
p ro tect ed vo id d oPos t (H t t pS er v l et Re qu e st
req,HttpServletResponse res)throws ServletException,
IOException
{
PrintWriter pw=res.getWriter();
res.setContentType(“text/html”);
String tb=req.getParameter(“table”);
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Conne c tion con =D river M an ag er . g et Co nn e c tio n
(“jdbc:odbc:vph”,””,””);
Statement st=con.createStatement();
Self-Instructional
Material 15
Introduction to JDBC System.out.println(“connection established
successfully...!!”);
ResultSet rs=st.executeQuery(“Select * from “+tb);
pw.println(“<table border=1>”);
NOTES while(rs.next())
{
pw.println(“<tr><td>”+rs.getString(1)+”</
t d > < t d > ” + r s . g e t S t r i n g ( 2 ) + ” < /
td>”+”<td>”+rs.getString(3)+”</td></tr>”); }
pw.println(“</table>”);
pw.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
Example of Database Program using Servlet and Oracle Database
The basic steps have already been discussed while explaining about the Servlet
and MS Access database connectivity. You are advised to follow the initial steps
as they are except the making of the DSN. An additional step that you need to
follow here is:
1. Set the classpath of servlet-api.jar or else your servlet will not compile.
2. Just remember to set the classpath to ojdbc14.jar and ojdbc14_g.jar
file and also copy only ojdbc14.jar in the lib folder of Tomcat.
(a) The servlet will use ojdbc14.jar file which is in the classpath, for
compiling the application,
(b) ojdbc14.jar file in lib folder will be used at the time of running the
servlet application by the server.
index.html
<Html>
<head><title>Servlet-JDBC Example</title></head>
<body>
<form action=”JdbcShow” method=”post”>
Enter Table Name : <input type=”text” name=”table”>
<input type=”submit” value=”Display”>
</form>
</body>
</html>
Self-Instructional
16 Material
ServletJdbcOracleConnect.java Introduction to JDBC
import java.io.*;
import java.sql. *;
import javax.servlet.*; NOTES
import javax.servlet.http.*;
public class ServletJdbcOracleConnect extends HttpServlet
{
p ro tect ed vo id d oPos t (H t t pS er v l et Re qu e st
req,HttpServletResponse res)throws ServletException,
IOException
{
PrintWriter pw=res.getWriter();
res.setContentType(“text/html”);
String tb=req.getParameter(“table”);
try
{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Connection con=DriverManager.getConnection
(“jdbc:oracle:thin:@localhost:1521:XE”,”system”,”admin”);
Statement st=con.createStatement();
System.out.println(“connection established
successfully...!!”);
ResultSet rs=st.executeQuery(“Select * from “+tb);
pw.println(“<table border=1>”);
while(rs.next())
{
pw.println(“<tr><td>”+rs.getString(1)+”</
t d > < t d > ” + r s . g e t S t r i n g ( 2 ) + ” < /
td>”+”<td>”+rs.getString(3)+”</td></tr>”); }
pw.println(“</table>”);
pw.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
web.xml
<web-app>
<servlet>
Self-Instructional
Material 17
Introduction to JDBC <servlet-name>ServletDBConnect</servlet-name>
<servlet-class> ServletJdbcOracleConnect </servlet-
class>
</servlet>
NOTES <servlet-mapping>
<servlet-name>ServletDBConnect</servlet-name>
<url-pattern>/JdbcShow</url-pattern>
</servlet-mapping>
</web-app>
Here, you will use the testing method i.e. using the type 1 JDBC-ODBC
bridge drivers implementation for connecting the JSP program with MS-ACESS
using DSN name “vph”. And you should have an MS-Access file containing the
following information in table as following columns: userid, password, sname,
eid, addr. Insert some test data also so that you don’t get confused about not
getting the result from the database.
JdbcInsert.jsp
<%@page import=”java.sql.*” pageEncoding=”UTF-8"
contentType=”text/html”%>
<html> <head>
<title>JDBC connectivity with JSP</title> </
head>
<body>
<%
String usrid=request.getParameter(“userid”);
String pwd=request.getParameter(“password”);
String nam=request.getParameter(“sname”);
String eid=request.getParameter(“eid”);
String addres=request.getParameter(“addr”);
try
{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Connectioncon=DriverManager.getConnection(“jdbc:
oracle:thin:@localhost:1521:XE”,”system”,”admin”
);
/* Passing argument through the question mark */
PreparedStatement ps=con.prepareStatement(“insert into
login values(?,?,?,?,?)”) ;
ps.setString(1,usrid);
ps.setString(2,pwd);
ps.setString(3,nam);
ps.setString(4,addres);
ps.setString(5,eid);
int i=ps.executeUpdate(); /*Set the Update query
command */
if(i!=0)
Self-Instructional
Material 21
Introduction to JDBC {
response.sendRedirect(“index.jsp?msg=Thank You for
registering !”);
}
NOTES else
{
response.sendRedirect(“JdbcInsert.jsp?msg=Insertion
Failed!! “);
}
con.close();
}
catch(Exception ex)
{
out.println(ex);
}
%>
</body>
</html>
Code Explanation
The above code is used to insert record in to the database by accessing data from
the entry form. You should notice the changes made in the Class.forName() method
and the Connection class here.They have now the drivers specific to Oracle databse.
The PreparedStatement is used to pass the DML insert command to store the
record in the database. Now, you will set the string at the particular database filed.
This is the update program that is used to update existing records in the database.
Once the database entry is updated, you are redirected to the index.jsp page, the
front-controller page or else it is redirected to the JdbcInsert.jsp page.
JdbcUpdate.jsp
<%@page contentType=”text/html”%>
<%@page pageEncoding=”UTF-8"%>
<%@ page import=”java.sql.*” %>
<html>
<head>
<title>JSP Update Page</title>
</head>
<body>
<%
String uid=(String)session.getAttribute(“userid”);
String p=request.getParameter(“password1”);
Self-Instructional
22 Material
String n=request.getParameter(“name1”); Introduction to JDBC
String e=request.getParameter(“eid”);
String a=request.getParameter(“address”);
try{
NOTES
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Connection con=DriverManager. getConnection
(“jdbc:oracle:thin:@localhost:1521:XE”, ”system”,”admin”
);
PreparedStatement ps=con.prepareStatement(“update
login set password1=?,name1=?,eid=?,address=? where
userid=?”);
ps.setString(1,p);
ps.setString(2,n);
ps.setString(3,e);
ps.setString(4,a);
ps.setString(5,uid);
int i=ps.executeUpdate();
if(i!=0)
{
response.sendRedirect(“index.jsp?msg=
Profile Updated Successfully!”);
}
else
{
response.sendRedirect(“pUpdate.jsp?msg=
ProfileUpdationFailed.PleaseTryagain!!!!”);
}
con.close();
}
catch(Exception ex){
out.println(ex);
}
%>
</body>
</html>
Self-Instructional
Material 23
Introduction to JDBC
1.6 ANSWERS TO CHECK YOUR PROGRESS
QUESTIONS
1.7 SUMMARY
Short-Answer Questions
1. What is database management system and what is it used for?
2. Discuss about Java Database Connectivity and its utility.
3. Discuss the types of JDBC implementations.
4. What do you mean by JDBC metadata API?
Long-Answer Questions
1. “JDBC (Java Database Connectivity) is a Java technology that empowers
you to connect to any existing relational database management systems,
execute SQL commands, and process the results, all from within a Java
program.” Explain in detail.
2. Explain in detail about JDBC drivers and its types.
3. How are of JDBC Type 2 and JDBC Type 4 drivers implemented? Also
tell which are the most popular of all the JDBC Drivers? Support your
answer with an illustration from the text.
Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.
Self-Instructional
26 Material
SQL Exception
WARNING
NOTES
Structure
2.0 Introduction
2.1 Objectives
2.2 SQL Exception and SQL Warning Concepts
2.2.1 Exception Retrieval
2.2.2 Introduction to SQL Warning
2.2.3 Special SQL Exceptions
2.3 Answers to Check Your Progress Questions
2.4 Summary
2.5 Key Words
2.6 Self Assessment Questions and Exercises
2.7 Further Readings
2.0 INTRODUCTION
In this unit, you will learn about the exceptions and warning in SQL. An exception
is an error condition that occurs during a program execution. SQL supports
programmers to catch such conditions using exception block in the program. It
also helps take an appropriate action against the error condition. Exceptions are
raised by the database server automatically whenever there is any internal database
error, but exceptions can be raised explicitly by the programmer too.
2.1 OBJECTIVES
Self-Instructional
Material 27
SQL Exception that can be used for considering and isolating the root cause of the error occurrence.
and Warning
The information isolated is:
An error description: The error description is contained within the
String object that is retrieved by calling SQLException.getMessage()
NOTES
method.
A SQLState code: A SQLState code is a String object that consists of
total 5 alphanumeric characters. It is recovered by calling the method
SQLException.getSQLState()..
An error code: An error code is an integer value used in the identification
of the error that actually initiated the SQLException instance to be thrown.
Retrieval of the error can be done by just calling the method
SQLException.getErrorCode().
A cause: Sometimes you might be interested in finding the causal relation
consisting one or more Throwable objects probably that might have caused
the SQLException instance to be thrown. SO, to navigate this chain of
causes, getCause() method is to be used recursively until you get a null
value.GetCause() method belong to the SQLException class.
A reference to any chained exceptions: Retrieval of the chained
exceptions can be done by calling the SQLException.getNextException()
method on the exception that was thrown.
2.2.1 Exception Retrieval
Use the method printSQLException() to display the error information .The
information that gets displayed consists of the followings - SQLState, error code,
error description, and the cause if there exists any and any other exception that is
cause a result, in the chain.
public static void printSQLException(SQLException ex) {
e.printStackTrace(System.err);
System.err.println(“SQLState: “ +
((SQLException)e).getSQLState());
System.err.println(“Error Code: “ +
((SQLException)e).getErrorCode());
System.err.println(“Message: “ + e.getMessage());
Self-Instructional
28 Material
SQL Exception
and Warning
Throwable t = ex.getCause();
while(t != null) {
System.out.println(“Cause: “ + t);
NOTES
t = t.getCause();
}
}
}
}
}
For example, if you call the method CoffeesTable.dropTable with Java DB
as your DBMS, the table COFFEES does not exist, and you remove the call
to JDBCTutorialUtilities.ignoreSQLException, the output will be similar to the
following:
SQLState: 42Y55
Error Code: 30000
Message: ‘DROP TABLE’ cannot be performed on
‘TESTDB.COFFEES’ because it does not exist.
Instead of outputting SQLException information, you could instead first
retrieve the SQLState then process the SQLException accordingly. For example,
the method JDBCTutorialUtilities.ignoreSQLException returns true if
the SQLState is equal to code 42Y55 (and you are using Java DB as your DBMS),
which causes JDBCTutorialUtilities.printSQLException to ignore
the SQLException:
public static boolean ignoreSQLException(String sqlState)
{
if (sqlState == null) {
System.out.println(“The SQL state is not defined!”);
return false;
}
if (warning != null) {
System.out.println(“\n—Warning—\n”);
Self-Instructional
30 Material
One of the most common of all the warnings you might encounter is the SQL Exception
and Warning
DataTruncation warning, which inherits the SQLWarning class. What is more
common in all the DataTruncation objects is that they have a SQLState of 01004,
which is for depicting the problem regarding reading or writing data in
database. Using the DataTruncation methods you can easily find out in which NOTES
column or parameter data got truncated, state of the transaction whether on a
read or write operation, total number of bytes transferred, etc.
2.2.3 Special SQL Exceptions
While dealing with JDBC operations, sometimes you may fall upon the subclass
of SQLException that might be corresponding to a common SQLState or some
common error state which is not associated with any specific SQLState class
value. These are special SQLExceptions and can be the sub class of any one
amongst the followings classes: SQLNonTransientException class,
SQLTransientException class, or SQLRecoverableException class. Understanding
of these may enable you to code more portable error-handling codes for your
applications.
Some more Subclasses of SQL Exception
Apart from the ones mentioned above, there a few more special ones, some
subclasses of SQLException that can also be seen thrown in the application:
BatchUpdateException is thrown when there occurs any error during a
batch update operation providing the exception information as provided
by SQLException, and also total number of the update counts for all
statements that were successfully executed before the error occurred during
the update.
When one or more client information properties could not be set on
Connection, then an exception is thrown- SQLClientInfoException .
SQLClientInfoException consists of a list of client information properties
and some basic exception information provided by SQLException .
1. SQLWarning objects are used to take care of all the database access
warnings to be displayed.
Self-Instructional
Material 31
SQL Exception 2. When a warning is generated its object consists of the following: objects of
and Warning
interfaces like Connection interface, a Statement interface and/or
a ResultSet interface object.
NOTES
2.4 SUMMARY
Error Description: The String object is retrieved that contains this detailed
description. This is done by calling the method SQLException.getMessage(). NOTES
SQLState Code: It is a String object that consists of five alphanumeric
characters and is retrieved by calling the method
SQLException.getSQLState.
Error Code: This is an integer value that basically helps in the identification
of the error that initiated the SQLException instance to be thrown.
Short-Answer Questions
1. What do you understand by SQL exception?
2. Write a short note to analyze the SQL warning.
3. Discuss some specially categorized SQL exceptions.
Long-Answer Questions
1. “Whenever JDBC is unable to interact with a data source, it results in an
error and hence throws an instance of SQL Exception as opposed to
Exception.” Discuss.
2. What are SQL Warnings? When are they used? Explain in detail.
3. “The JDBC driver might throw a subclass of SQLException corresponding
to a common SQLState or some common error state that is not anywhere
associated with a specific SQLState class value.” Discuss.
Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.
Self-Instructional
Material 33
JDBC Classes and
Statements
UNIT 3 JDBC CLASSES AND
STATEMENTS
NOTES
Structure
3.0 Introduction
3.1 Objectives
3.2 The java.sql Package
3.2.1 The DriverManager Class
3.2.2 The Connection Interface
3.2.3 The Statement Interface
3.2.4 The ResultSet Interface
3.2.5 The PreparedStatement Interface
3.2.6 The ResultSetMetaData Interface
3.2.7 The CallableStatement Interface
3.2.8 The SQLException Class
3.3 Answers to Check Your Progress Questions
3.4 Summary
3.5 Key Words
3.6 Self Assessment Questions and Exercises
3.7 Further Readings
3.0 INTRODUCTION
The JDBC interface is contained in the java.sql and javax.sql packages. You must
import these packages in your programs if you want to use database to store its
data. It consists mainly of interfaces rather than concrete classes as each vendor’s
implementation is different rather say specific to their particular database protocol.
In this unit, you will study about JDBC classes, statements and interfaces.
3.1 OBJECTIVES
Self-Instructional
34 Material
JDBC Classes and
3.2 THE JAVA.SQL PACKAGE Statements
Self-Instructional
Material 35
JDBC Classes and void setLogWriter(PrintWriter out): It sets
Statements
PrintWriter object that is used by all the drivers and
DriverManager.
Boolean jdbcCompliant(): It returns True or False depending
NOTES
on whether this driver is a genuine JDBC CompliantTM driver.
DriverPropertyInfo[] getPropertyInfo(String
url, Properties Info): It provides the information about
the possible properties for the current driver.
int getMajorVersion(): It returns the major driver’s version
number.
int getMinorVersion(): It returns the minor driver’s version
number.
3.2.2 The Connection Interface
The Connection interface helps to establish a connection with the required
database. Other than establishing connection, it provides lot of functionality including
transaction management, maintaining database sessions and creating SQL
statements. This interface does not provide its object with garbage collection rather
all the objects have to be closed explicitly or should themselves be garbage collected
and once the connection is closed no other request can be made for the database.
A Connection’s database is able to provide information about its tables, its SQL
grammar, the capabilities of this connection, stored procedures, and so on.
Some of the commonly used methods of connection interface are as follows:
void close(): This method closes database connection associated
with Connection’s object and releases JDBC resources.
For example, consider this statement.
con.close();
where,
con is an instance of connection interface.
Statement createStatement(): This method creates a
Statement object which is used to send SQL statement to the
database. It is usually used when SQL statement without parameters is
to be executed.
void clearWarnings(): This method clears all the warnings
reported for the connection object.
CallableStatement prepareCall(String sql):
This method creates an instance of CallableStatement which
is used to handle database stored procedures.
Self-Instructional
36 Material
void commit(): It completes and makes all the changes made JDBC Classes and
Statements
since last commit or rollback permanent in database and releases all the
database lock held by the current connection.
PreparedStatement prepareStatement(String
NOTES
sql): This method creates PreparedStatement object which
is used to create SQL statement specified in string sql. It is usually
used when parameterized SQL statement is to be executed.
DatabaseMetaData getMetaData(): It retrieves the meta
data related to the current connection’s database.
boolean isClosed(): It checks whether the connection is
closed.
boolean getAutoCommit(): It retrieves the current auto
commit mode for the current connection object.
void rollback(): It rollbacks all the changes made since last
commit or rollback.
SQLWarning getWarning(): It returns the first warning
reported by the calls made on current connection’s object.
3.2.3 The Statement Interface
The Statement interface provides methods that are used to execute static
SQL statements. Using the object of this interface, one can assemble multiple
SQL statements into batch and can be submitted to the database for batch
processing. The SQL statements are queries, insertions, updates and deletions
etc.
Some of the methods of the Statement interface are as follows:
void close(): This method closes database connections associated
with Statement’s object and releases JDBC resources.
boolean execute(String sql): This method is used to
execute an SQL statement that might produce multiple result sets or
multiple counts. It returns true if multiple result sets are produced and
returns false if multiple counts are generated.
int executeUpdate(String sql): This method is used
to execute an SQL statement that gives information about number of
affected rows. For example, if we execute the statements like INSERT,
DELETE, the result will only be a number of rows affected.
ResultSet executeQuery(String sql): This method
executes a query and returns a ResultSet object. A result set is just
like a table containing the resultant data.
Self-Instructional
Material 37
JDBC Classes and ResultSet getResultSet(): This method returns the first
Statements
result set or multiple count generated on the execution of
execute(String sql) method. If there is no result set, it returns
null value.
NOTES
int getUpdateCount(): After the execution of the
execute(String sql) method updates counts may be
generated. This method returns the first update count and clears it. More
update counts can be retrieved by getMoreResults(). Note
that this method returns value -1 if there is no update count or when
only result sets are generated on execution of execute(String
sql) method.
boolean getMoreResults(): This method is used to retrieve
the next result set in multiple result set or to the next count in multiple
update count generated on execution of execute(String
sql)method. It returns a true value if multiple sets are available and
returns a false value if multiple update counts are available.
void addBatch(String sql): This method is used to add
an SQL statement to the current set of statements.
void cancel(): This method is used to cancel the current
Statement’s object if the driver and the DBMS supports aborting
an SQL statement.
void clearBatch(): This method is used to clear all the
statements present in the set of SQL statements held by the
Statement’s object.
void setFetchSize(int rows): This method is used to
inform the JDBC driver about the maximum number of rows that should
be fetched at once from the database when large number of rows are
required.
void setFetchDirection(int direction): This
method is to inform the JDBC driver about the direction in which the
rows has to be processed.
int getFetchDirection(): This method returns the direction
for fetching and processing the rows from the database.
int getFetchSize(): This method returns the default fetch
size of rows for result sets.
int getMaxFieldSize(): This method returns the maximum
number of bytes allowed for the particular column value.
int getMaxRows(): This method returns the maximum number
of rows that a ResultSet object can hold.
Self-Instructional
38 Material
int getQueryTimeout(): This method returns the number of JDBC Classes and
Statements
seconds a driver should wait for the execution of the Statement’s
object.
int getresultSetType(): This method returns the type for
NOTES
the result set generated by the Statement’s object.
void setEscapeProcessing(boolean enable): This
method sets the escape processing on or off.
void setCursorName(String name): This method defines
the name for the cursor that will be used for the execution of statements
of the Statement’s object.
void setQueryTimeout(int second): This method is
used to set the time for which JDBC driver has to wait for the execution
of the Statement’s object. The time is specified in seconds.
3.2.4 The ResultSet Interface
The execution of SQL statement results in table which consists of rows and columns
containing the resultant data. The data can be retrieved from the table by using
methods of the ResultSet interface. The ResultSet object is automatically
closed when its corresponding Statement object is closed. It maintains a
cursor that points to the current row and can used to access any row. Initially, the
cursor points to the first row. There are several methods that can be used to move
the cursor to the desired row. Some methods of the ResultSet interface are
as follows:
boolean first(): This method is used to move the ResultSet
cursor to the first row in the data.
boolean next(): This method is used to move the ResultSet
cursor to the next row of the data. Initially, the ResultSet cursor is
pointed before the first row. It returns the false value if there are no more
rows in the ResultSet object.
boolean absolute(int row): This method moves the
ResultSet cursor to the given row specified as an argument of the
method.
void deleteRow(): This method deletes the current row from the
data.
int getType(): This method returns the type of the current
ResultSet object.
String getString(int index): This method returns the string
value that is stored in the column indicated by the column number, index.
For example, if the value of index is 2 then it will return the value stored in
second column number.
Self-Instructional
Material 39
JDBC Classes and String getString(String column): This method returns
Statements
the string value that is stored in the column indicated by the column name
column.
float getFloat(String column): This method returns the
NOTES
value of the specified column in the current row as a float.
boolean last(): This method moves the cursor to the last row in
the data.
boolean isLast(): This method tells whether the cursor is on the
last row of the data.
Time getTime(int columnIndex): This method returns the
value of the specified column in the current row as java.sql.Time
object.
void updateDate(int columnIndex,Date x): This
method updates the specified column with the java.sql.Date value
passed as an argument.
boolean wasNull(): This method returns whether the last column
read had a value of SQL null.
void refreshRow(): This method refreshes the current row with
the latest values from the database.
void insertRow(): This method inserts the values of the insert row
into the Resultset object and into the database.
int getRow(): This method returns the current row number of the
ResultSet object.
boolean isAfterLast(): This method informs whether the cursor
is after the last row in the data.
boolean isBeforeFirst(): This method informs whether the
cursor is before the first row in the data.
Array getArray(String column_name): This method returns
the value of the specified column of the current row in the data as an Array
object.
byte getByte(String column_name): This method returns
the value of the specified column of the current row in the data as a byte.
Date getDate(String column_name): This method returns
the value of the specified column in the current row as java.sql.Date
object.
URL getURL(String column_name): This method returns the
value of the specified column in the current row as java.net.URL
object.
Self-Instructional
40 Material
void deleteRow(): This method deletes the current row from JDBC Classes and
Statements
ResultSet object and also from the corresponding database. When
the cursor is on the insert row, this method cannot be called.
Date getDate(int column_index, Calendar cal):
NOTES
This method returns the value of the specified column on the current row of
in the data as java.sql.Date object.
Time getTime(int column_index, Calendar cal):
This method returns the value of the specified column in the current row as
java.sql.Time object.
Timestamp getTimestamp(int column_index,
Calendar cal): This method returns the value of the specified column
in the current row as java.sql.Timestamp object.
Example 3.1: A program to establish connection and retrieve data from Student
database
import java.sql.*;
public class SimpleJDBCProgram
{
public static void main(String args[])
{
try
{
//loading the driver class
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
//defines the datasource for the driver
String url = “jdbc:odbc:ITLESL”;
Self-Instructional
42 Material
5. In this example, st.executeQuery is used to execute the JDBC Classes and
Statements
SELECT statement of SQL. The try{..} catch {..} is
used to catch any exceptions that may arise as a result of executing this
query statement. The result of this query may consist of set of tuples,
which is assigned to rs object of type ResultSet. Initially, it places NOTES
the cursor at the beginning of the first tuple. The statement rs.next()
moves the cursor to the next tuple.
6. The next() method is used to fetch one tuple at a time from the result
set rs. The statement int roll = rs.getInt(“Roll”);
is used to access data from the database and
System.out.println(“Roll No :”+ roll); is used
to display data.
7. The connection must be closed after it is no more required at the end of
the procedure. The statement rs.close(), st.close(),
con.close() closes all the open connections.
3.2.5 The PreparedStatement Interface
PreparedStatement interface extends the Statement interface so it
has access to all the methods of Statement interface. It is used to execute
precompiled parameterised SQL statements. This helps statements to execute
much faster thus increases the efficiency of the program. It allows you to specify
SQL query, in which unknown values are replaced by ‘?’. The user provides the
unknown values later at the run-time. The setString() and setInt()
methods can be used to specify the values for the parameters. To understand the
concept of prepared statement, consider the following statements.
PreparedStatement ps = con.prepareStatement(“INSERT INTO
Student
VALUES(?,?,?)”);
ps.setString(1, “A010”); //assigns value to first
//attribute
ps.setInt(2, 90); //assigns value to second
//attribute
ps.setString(3, “A”); //assigns value to third
//attribute
ps.executeUpdate();
The values can be assigned to the corresponding attributes through variable
name also instead of using literal values representing index value. Like,
setString() and setInt() methods, there are various methods for setting
value of other data type. Some of these are setBoolean(), setFloat(),
s e t B y t e ( ) , s e t D a t e ( ) , etc. The method v o i d
clearParameters() can be used to clear all the values held currently in
the parameters.
Self-Instructional
Material 43
JDBC Classes and Note: The methods e x e c u t e ( ) , e x e c u t e Q u e r y ( ) and
Statements
e x e c u t e Up d a t e ( ) have same functionality as the methods of
Statement interface, but with a difference that here no parameters are
passed.
NOTES
Example 3.2: A program to demonstrate implementation of
PreparedStatement interface
import java.io.*;
import java.sql.*;
public class ExamplePreparedStatement
{
public static void main(String args[])
{
Connection con=null;
int i = 0;
try
{
Class.
forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
con=
DriverManager.getConnection(“jdbc:odbc:Emp”);
Statement st = con.createStatement();
PreparedStatement ps =
con.prepareStatement(“
INSERT INTO Employee VALUES(?,?,?,?,?)”);
ps.setInt(1,8);
ps.setString(2,”Meenu”);
ps.setString(3,”IT”);
ps.setString(4,”SE”);
ps.setInt(5,30000);
i = ps.executeUpdate();
System.out.println(“
Number of rows effected:” +i);
ResultSet rs = st.executeQuery(“
select * from Employee”);
System.out.print(“Eno ”);
System.out.print(“Name ”);
System.out.print(“Depatment ”);
System.out.print(“Designation ”);
System.out.println(“Salary ”);
System.out.println(“
Self-Instructional
44 Material
——————————————————————-”); JDBC Classes and
Statements
while(rs.next())
{
System.out.print(rs.getString(“ENumber”));
NOTES
System.out.print(“ ”);
System.out.print(rs.getString(“EName”));
System.out.print(“ ”);
System.out.
print(rs.getString(“Department”));
System.out.print(“ ”);
System.out.
print(rs.getString(“Designation”));
System.out.print(“ ”);
System.out.
println(rs.getString(“Salary”));
}
rs.close();
System.in.read();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
The output of the program is
Number of rows effected: 1
————————Employee Details—————————————
Eno Name Department Designation Salary
—————————————————————————————
1 Prem IT PL 30000
2 Samee IT SSE 29500
3 Preeti IT TL 29500
4 Mili IT SE 28000
5 Niti Math TL 28000
6 Surabhi IT SE 25000
7 Milendu IT SE 25000
8 Meenu IT SE 30000
Self-Instructional
Material 45
JDBC Classes and 3.2.6 The ResultSetMetaData Interface
Statements
The ResultSetMetaData interface provides methods that allow you to
get metadata for the resultset, that is, the number, types and properties of the
NOTES columns in a ResultSet object. This information is used to collect the data
with same semantics but stored in different databases in different formats.
To get this information of columns in the ResultSet object using methods
of the ResultSetMetaData interface, it is required to invoke the
getMetaData() method of the ResultSet object that returns a reference
to an object of type ResultSetMetaData.
Some of the methods of ResultSetMetaData interface are as
follows:
int getColumnCount(): This method returns the number of
columns in the resultset.
String getColumnName(int index): This method returns
the name of column specified by index value index in the resultset.
int getColumnType(int index): This method returns
the type of column specified by index value index in the resultset.
Example 3.3: A program to demonstrate implementation of
ResultSetMetaData and ResultSet interface
import java.sql.*;
class ExampleResultSetMetaData
{
public static void main(String args[])
{
Connection con;
Statement stmt;
ResultSet rs;
try
{
Class.forName(“
sun.jdbc.odbc.JdbcOdbcDriver”);
con =
DriverManager.getConnection(“jdbc:odbc:Emp”);
stmt = con.createStatement();
rs = stmt.
executeQuery(“Select * from Employee WHERE
Department=’Math’”);
ResultSetMetaData rsmd = rs.getMetaData();
int col = rsmd.getColumnCount();
Self-Instructional
46 Material
//returns number of columns JDBC Classes and
Statements
int row = 1;
while(rs.next())
{
NOTES
System.out.println(“Row “ + row + “: “);
for(int i = 1; i <= col; i++)
{
System.out.print(“ Column “ + i + “: “);
System.out.println(rs.getString(i));
}
System.out.println(“ “);
row++;
}
stmt.close();
con.close();
}
catch(Exception e)
{
System.err.print(“ClassNotFoundException: “);
System.err.println(e.getMessage());
}
}
}
The output of the program is
Row 1:
Column 1: 5
Column 2: Niti
Column 3: Math
Column 4: TL
Column 5: 28000
3.2.7 The CallableStatement Interface
The CallableStatement interface which is derived from the
PreparedStatement interface is used to execute remote SQL stored
procedures on the database. It can return one ResultSet or multiple
ResultSet objects.
Stored Procedures
Stored procedure is stored in the database and is used by the applications to
access the database. It is usually used to put together the commonly used operations
that are to be performed on the database. The stored procedure can be called by
Self-Instructional
Material 47
JDBC Classes and using JDBC CallableStatement interface. For example, consider this
Statements
procedure without parameters.
CREATE PROCEDURE Employee_Details
AS
NOTES
BEGIN —Start of a procedure
SELECT ENumber, EName, Designation, Salary FROM Employee;
END —End of a procedure
Stored procedures can be called with the parameters and these parameters
are of two types namely, IN and OUT. IN parameters are used to pass data to the
stored procedure and OUT parameters hold the values returned by the stored
procedure. The OUT parameter can be registered by using following method of
CallableStatement object:
registerOutParameter(2, Types.Integer)
In this statement, the first parameter indicates the index position of the OUT
parameter and second parameter indicates its type.
Consider the following stored procedure with one IN and one OUT
parameter.
CREATE PROCEDURE Emp_Details
@EmpName Char(30),
@EmpSalary Int Out
AS
BEGIN
SELECT EmpSalary = Salary FROM Employee WHERE EName =
EmpName;
END
Invoking Stored Procedure Using CallableStatement Interface
JDBC allows calling stored procedure using CallableStatement interface.
The statement for calling the stored procedure can be parameterized or non-
parameterized.
The syntax for the calling stored procedure without parameter is as follows:
“{call procedure_name}”
The syntax for the calling stored procedure with parameters is as follows:
“{call procedure_name(?,?,…,?)}”
This interface inherits some method from other interfaces such as
PreparedStatement interface and Statement interface.
Some of the methods of CallableStatement interface are as
follows:
String getString(int parameter_index): This
method returns the value of the specified JDBC CHAR, VARCHAR, or
Self-Instructional LONGVARCHAR parameter as a String in Java.
48 Material
int getInt(int parameter_index): This method returns JDBC Classes and
Statements
the value of the specified JDBC INTEGER parameter as an int in
Java.
int getFloat(int parameter_index): This method
NOTES
returns the value of the specified JDBC FLOAT parameter as a float
in Java.
int getDate(int parameter_index): This method returns
the value of the specified JDBC D A T E parameter as a
java.sql.Date object.
int getTime(int parameter_index): This method returns
the value of the specified JDBC T I M E parameter as a
java.sql.Time object.
void registerOutParameter(int
parameter_Index, int sqlType): This method is used
to register the specified OUT parameter to the JDBC type sqlType.
void setString(int parameter_index, String
x): This method sets the string value of the specified column.
void setTime(String parameter, Time t): This
method sets the specified parameter with the value of
java.sql.Time.
void setTimestamp(String parameter, Timestamp
ts): This method sets the specified parameter with the value of
java.sql.Timestamp.
void setNull(String parameter, int type):
This method sets the value of the specified parameter to SQL null.
void wasNull(): This method checks whether the last OUT
parameter returned was SQL null.
void setDate(String parameter, Date x): This
method sets the specified parameter with the value of
java.sql.Date.
void setBoolean(String parmeter, boolean b):
This method sets the value of the specified parameter with the given
boolean value.
void setByte(String parameter, byte b): This
method sets the value of the specified parameter with the given byte
value.
void setObject(String parameter, Object obj):
This method sets the value of the specified parameter with the given
object.
Self-Instructional
Material 49
JDBC Classes and Example 3.4: A program to demonstrate the calling of a stored procedure without
Statements
parameters
import java.io.*;
import java.sql.*;
NOTES
public class ExampleProcedure1
{
public static void main(String[] args)
{
Connection con=null;
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
//loads driver
con=Driver
Manager.getConnection(“jdbc:odbc:Emp”);
//establishes connection
CallableStatement cst=null;
//creates CallableStatement object
cst=con.prepareCall(“{call Employee_Details}”);
//procedure is invoked
ResultSet rs=cst.executeQuery();
//executes the procedure call and
//creates ResultSet object
System.out.println(“ENumber “);
System.out.print(“EName “);
System.out.print(“Designation “);
System.out.print(“Salary”);
//displays data till there are no more rows
while(rs.next())
{
System.out.println(rs.getString(1));
System.out.print(“ “);
System.out.print(rs.getString(2));
System.out.print(“ “);
System.out.print(rs.getString(3));
System.out.print(“ “);
System.out.print(rs.getString(4));
}
//closes the connection
Self-Instructional
50 Material
rs.close(); JDBC Classes and
Statements
cst.close();
con.close();
}
NOTES
catch(Exception e)
{
System.out.println(“Exception occured”);
}
}
}
The output of the program is
ENumber EName Designation Salary
1 Prem PL 30000
2 Samee SSE 29500
3 Preeti TL 29500
4 Mili SE 28000
5 Niti TL 28000
6 Surabhi SE 25000
7 Milendu SE 25000
Example 3.5: A program to demonstrate the calling of a stored procedure with
parameter
import java.io.*;
import java.sql.*;
public class ExampleProcedure
{
public static void main(String[] args)
{
Connection con=null;
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
//loads driver
con=
DriverManager.getConnection(“jdbc:odbc:Emp”);
//establishes connection
CallableStatement cst=null;
//creates CallableStatement object
cst=con.prepareCall(“{call Emp_Details(?,?)}”);
//procedure is invoked
cst.setString(1, “Shannaya”) Self-Instructional
Material 51
JDBC Classes and //sets the value of IN parameter
Statements
cst.registerOutParameter(2, Types.INTEGER);
//registers the OUT parameter
cst.executeQuery();
NOTES
//executes the procedure call
int sal = cst.getInt(2);
//get the value of OUT parameter
System.out.println(“
Salary of the Employee is: “+sal+” pm”);
//closes the connection
cst.close();
con.close();
}
catch(Exception e)
{
System.out.println(“Exception occured”);
}
}
}
3.2.8 The SQLException Class
While accessing the database, the developer may encounter various types of errors.
If any JDBC object encounters an error, it throws the SQLException. The
SQLException class extends the java.lang.Exception class. Some
of the methods of the SQLException class are as follows:
SQLException getNextException(): This method is used
to obtain the next exception object in the chain of errors (if any exists).
String getSQLState(): This method provides the information
about the state of SQL, which helps in taking appropriate decisions.
int getErrorCode(): This method provides information about
the vendor specific errors whose meaning is defined by the driver vendor
only.
void setNextException(): This method is used to add an
SQLException object at the end of chain of errors.
Example 3.6: A program to demonstrate how exceptions related to JDBC are
handled
import java.io.*;
import java.sql.*;
public class FinalExceptionExample
{
Self-Instructional
52 Material
public static void main(String args[]) JDBC Classes and
Statements
{
Connection con=null;
try
NOTES
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
con=Driver
Manager.getConnection(“jdbc:odbc:Emp”);
Statement st = con.createStatement();
ResultSet rs =
st.executeQuery(“select * from EmployeeDB”);
System.out.print(“Employee Number ”);
System.out.print(“Employee Name ”);
System.out.print(“Department ”);
System.out.print(“Designation ”);
System.out.println(“Salary ”);
System.out.println(“
——————————— ——————————-”);
while(rs.next())
{
System.out.print(rs.getString(“ENumber”));
System.out.print(“ ”);
System.out.print(rs.getString(“EName”));
System.out.print(“ ”);
System.out.
print(rs.getString(“Department”));
System.out.print(“ ”);
System.out.
print(rs.getString(“Designation”));
System.out.print(“ ”);
System.out.println(rs.getString(“Salary”));
}
rs.close();
}
catch(SQLException e)
{
while(e != null)
{
Self-Instructional
Material 53
JDBC Classes and System.out.println(“\nSQL Exception:”);
Statements
System.out.println(e.getMessage());
System.out.
println(“SQL State: ” + e.getSQLState());
NOTES
System.out.
println(“Error Code: ” + e.getErrorCode());
e = e.getNextException();
}
}
catch(ClassNotFoundException cnfe)
{
System.out.println(cnfe.getMessage());
}
}
}
The output of the program is
SQL Exception:
[Microsoft][SQL Server Native Client 10.0][SQL
Server]Invalid object name ‘EmployeeDB’.
SQL State: S0002
Error Code: 208
Note that if Class.forName() syntax is used for registering the driver,
you may encounter the ClassNotFoundException. This type of exception
is encountered if the class loader is unable to find the specified database driver.
NOTES
3.4 SUMMARY
NOTES
3.6 SELF ASSESSMENT QUESTIONS AND
EXERCISES
Short-Answer Questions
1. Write a note on DriverManager class.
2. Discuss the methods of connection class.
3. List the various methods in statement interface.
Long-Answer Questions
1. What are the different methods of DriverManager class? Explain.
2. What is a connection interface? Also, discuss list the various methods
of connection interface.
3. Explain the various methods of statement interface.
4. What is ResultSet interface? Explain its methods.
5. Write a note on:
(i) ResultSetMetaData interface
(ii) CallableStatement interface
(iii) SQLException class
Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.
Self-Instructional
56 Material
InetAddress, TCP/IP
BLOCK - II Client and Server Sockets
INETADDRESS
NOTES
UNIT 4 INETADDRESS, TCP/IP
CLIENT AND SERVER
SOCKETS
Structure
4.0 Introduction
4.1 Objectives
4.2 The InetAddress Class
4.3 Getter Methods
4.4 Inet4Address and Inet6Address
4.5 Using IP Addresses and InetAddress
4.6 Networking Protocols
4.7 Ports and Sockets
4.7.1 Using TCP/IP Sockets
4.8 Answers to Check Your Progress Questions
4.9 Summary
4.10 Key Words
4.11 Self Assessment Questions and Exercises
4.12 Further Readings
4.0 INTRODUCTION
In this unit, you will learn about the Transmission Control Protocol and Internet
Address Protocol to transfer information between the client and the server over
the network. You will also learn about ports, which allow a user to request a Web
page from the server and socket that helps in maintaining the uninterrupted
connection between the two. In addition, you also learn how to use TCP/IP sockets
in a Java program to establish a connection between the client and the server.
4.1 OBJECTIVES
Self-Instructional
58 Material
Output: InetAddress, TCP/IP
Client and Server Sockets
NOTES
The InetAddress class contains four getter methods that return the hostname
as a string and the IP address as both a string and a byte array:
public String getHostName()
public String getCanonicalHostName()
public byte[] getAddress()
public String getHostAddress()
There are no corresponding setHostName() and setAddress()
methods, which means that packages outside of java.net can’t change an
InetAddress object’s fields behind its back. This makes InetAddress
immutable and thus thread safe.
The getHostName() method returns a String that contains the
name of the host with the IP address represented by this InetAddress object.
If the machine in question doesn’t have a hostname or if the security manager
prevents the name from being determined, a dotted quad format of the numeric IP
address is returned. For example:
InetAddress machine = InetAddress.getLocalHost();
String localhost = machine.getHostName();
Self-Instructional
Material 61
InetAddress, TCP/IP The getCanonicalHostName() method is similar, but it’s a bit
Client and Server Sockets
more aggressive about contacting DNS. getHostName() will only call DNS
if it doesn’t think it already knows the hostname.
getCanonicalHostName() calls DNS if it can, and may replace the
NOTES existing cached hostname. For example:
InetAddress machine = InetAddress.getLocalHost();
String localhost = machine.getCanonicalHostName();
The getCanonicalHostName() method is particularly useful when
you’re starting with a dotted quad IP address rather than the hostname. The
example given below converts the dotted quad address 208.201.239.37 into a
hostname by using InetAddress.getByName() and then applying
getCanonicalHostName() on the resulting object.
Example 4.3: To find the hostname using the given address.
import java.net.*;
Self-Instructional
62 Material
} catch (UnknownHostException ex) { InetAddress, TCP/IP
Client and Server Sockets
System.out.println(“I’m sorry. I don’t know my
own address.”);
}
} NOTES
}
Result:
% java MyAddress
My address is 152.2.22.14.
Of course, the exact output depends on where the program is run.
If you want to know the IP address of a machine (and you rarely do), then
use the getAddress() method, which returns an IP address as an array of
bytes in network byte order. The most significant byte (i.e., the first byte in the
address’s dotted quad form) is the first byte in the array, or element zero. To be
ready for IPv6 addresses, try not to assume anything about the length of this array.
If you need to know the length of the array, use the array’s length field:
InetAddress me = InetAddress.getLocalHost();
byte[] address = me.getAddress();
The bytes returned are unsigned, which poses a problem. Unlike C, Java
doesn’t have an unsigned byte primitive data type. Bytes with values higher than
127 are treated as negative numbers. Therefore, if you want to do anything with
the bytes returned by getAddress(), you need to promote the bytes to
ints and make appropriate adjustments. Here’s one way to do it:
int unsignedByte = signedByte < 0 ? signedByte + 256 :
signedByte;
Here, signedByte may be either positive or negative. The conditional
operator ? tests whether signedByte is negative. If it is, 256 is added to
signedByte to make it positive. Otherwise, it’s left alone. signedByte is
automatically promoted to an int before the addition is performed, so wraparound
is not a problem.
One reason to look at the raw bytes of an IP address is to determine the
type of the address. Test the number of bytes in the array returned by
getAddress() to determine whether you’re dealing with an IPv4 or IPv6
address.
Example 4.5: To determine whether an IP address is of v4 or v6.
import java.net.*;
try {
InetAddress address =
InetAddress.getByName(args[0]);
if (address.isAnyLocalAddress()) {
System.out.println(address + “ is a wildcard
address.”);
}
if (address.isLoopbackAddress()) {
System.out.println(address + “ is loopback
address.”);
}
if (address.isLinkLocalAddress()) {
System.out.println(address + “ is a link-local
address.”);
} else if (address.isSiteLocalAddress()) {
System.out.println(address + “ is a site-local
address.”);
} else {
System.out.println(address + “ is a global
address.”);
}
if (address.isMulticastAddress()) {
if (address.isMCGlobal()) {
Self-Instructional
66 Material
System.out.println(address + “ is a global InetAddress, TCP/IP
multicast address.”); Client and Server Sockets
} else if (address.isMCOrgLocal()) {
System.out.println(address
+ “ is an organization wide multicast NOTES
address.”);
} else if (address.isMCSiteLocal()) {
System.out.println(address + “ is a site wide
multicast
address.”);
} else if (address.isMCLinkLocal()) {
System.out.println(address + “ is a subnet
wide multicast
address.”);
} else if (address.isMCNodeLocal()) {
System.out.println(address
+ “ is an interface-local multicast
address.”);
} else {
System.out.println(address + “ is an unknown
multicast
address type.”);
}
} else {
System.out.println(address + “ is a unicast
address.”);
}
} catch (UnknownHostException ex) {
System.err.println(“Could not resolve “ +
args[0]);
}
}
}
Here’s the output from an IPv4 and IPv6 address:
$ java IPCharacteristics 127.0.0.1
/127.0.0.1 is loopback address.
/127.0.0.1 is a global address.
/127.0.0.1 is a unicast address.
$ java IPCharacteristics 192.168.254.32
/192.168.254.32 is a site-local address.
/192.168.254.32 is a unicast address.
$ java IPCharacteristics www.
Self-Instructional
Material 67
InetAddress, TCP/IP www./208.201.239.37 is a global address.
Client and Server Sockets
www./208.201.239.37 is a unicast address.
$ java IPCharacteristics 224.0.2.1
/224.0.2.1 is a global address.
NOTES
/224.0.2.1 is a global multicast address.
$ java IPCharacteristics FF01:0:0:0:0:0:0:1
/ff01:0:0:0:0:0:0:1 is a global address.
/ff01:0:0:0:0:0:0:1 is an interface-local multicast
address.
$ java IPCharacteristics FF05:0:0:0:0:0:0:101
/ff05:0:0:0:0:0:0:101 is a global address.
/ff05:0:0:0:0:0:0:101 is a site wide multicast address.
$ java IPCharacteristics 0::1
/0:0:0:0:0:0:0:1 is loopback address.
/0:0:0:0:0:0:0:1 is a global address.
/0:0:0:0:0:0:0:1 is a unicast address.
Testing Reachability
The InetAddress class has two isReachable() methods that test whether
a particular node is reachable from the current host (i.e., whether a network
connection can be made). Connections can be blocked for many reasons, including
firewalls, proxy servers, misbehaving routers, and broken cables, or simply because
the remote host is not turned on when you try to connect.
public boolean isReachable(int timeout) throws
IOException
public boolean isReachable(NetworkInterface interface,
int ttl, int timeout)
throws IOException
These methods attempt to use traceroute (more specifically, ICMP echo
requests) to find out if the specified address is reachable. If the host responds
within timeout milliseconds, the methods return true; otherwise, they return
false. An IOException will be thrown if there’s a network error. The second
variant also lets you specify the local network interface the connection is made
from and the “time-to-live” (the maximum number of network hops the connection
will attempt before being discarded).
Object Methods
Like every other class, java.net.InetAddress inherits from
java.lang.Object. Thus, it has access to all the methods of that class. It
overrides three methods to provide more specialized behavior:
public boolean equals(Object o)
public int hashCode()
Self-Instructional public String toString()
68 Material
An object is equal to an InetAddress object only if it is itself an instance InetAddress, TCP/IP
Client and Server Sockets
of the InetAddress class and it has the same IP address. It does not need to
have the same hostname. Thus, an InetAddress object for www.ibiblio.org
is equal to an InetAddress object for www.cafeaulait.org because both
names refer to the same IP address. The example below creates InetAddress NOTES
objects for www.ibiblio.org and helios.ibiblio.org and then tells you whether
they’re the same machine.
Example4.7 To check whether www.ibiblio.org and helios.ibiblio.org are same?
import java.net.*;
Internet address, also known as the Internet Protocol (IP) address, is a unique
Self-Instructional
address assigned to each computer. The Internet address consists of a 32-bit
70 Material
number that is divided into 4 fields of 8-bits each, separated by periods. An example InetAddress, TCP/IP
Client and Server Sockets
of an IP address is 192.168.0.134. You can connect to the Internet directly
or using an Internet Service Provider (ISP). When you are directly connecting to
the Internet, services are provided at a permanent IP address. However, when the
connection is made using an ISP, a temporary IP address is assigned for each NOTES
session.
It is difficult to remember different IP addresses while connecting to the
Internet. You can use Domain Naming Service (DNS) for addressing this problem
that are also known as URLs. DNS maps an IP address to a string of characters.
For example, www.demo.com is the DNS name for the IP address,
128.227.182.12.
Various Java classes enable you to implement networking in Java.
InetAddress is a class present in the java.net package that can
encapsulate the IP address of your computer to prevent the misuse of your computer
resources. You use InetAddress in your class by creating an object using
factory methods. The classes, for which the constructors are not available, you
use static methods, also known as factory methods that return an object of the
class. The InetAddress class uses two such methods, static InetAddress
getLocalHost() and static InetAddress getByName (String
hostname). The first method returns an InetAddress object representing
the local host and the second method returns an InetAddress for the host
passed as a parameter for the method. The following program code shows how to
create the InetAddress object:
Creating the InetAddress object
import java.net.*;
public class InternetAddress
{
public static void main(String args[])
{
try
{
InetAddress localaddr =
InetAddress.getLocalHost();
A networking protocol is a set of standard rules that provides the standard for
information exchange over the network. You create network programs in Java by
creating sockets that use networking protocols, such as TCP/IP and UDP. Various
other networking protocols, such as HTTP, FTP and Simple Mail Transfer Protocol
(SMTP) are used in connecting to the Internet.
Web browsers and Web servers use HTTP to communicate with each other.
HTTP is a TCP/IP application layer protocol that enables you to establish
connectivity between the client and server for developing Web-based applications.
The HTTP protocol is based on the request/response model. When you select a
Web page, the Web browser establishes connection with the TCP/IP port and
Self-Instructional
72 Material
transmits an HTTP header requesting the selected Web page. The Web server InetAddress, TCP/IP
Client and Server Sockets
provides a response to the Web browser including that HTTP header along with
the requested data.
The HTTP protocol functions in a manner that is similar to that of the Gopher
NOTES
protocol. Earlier, the use of Gopher was limited to the retrieval of textual information
only. The Gopher protocol is now modified to handle text as well as graphics.
The TCP/IP protocol consists of a set of rules for exchanging information
between applications, across networks. TCP is a connection-oriented, faithful
service that transmits information in the form of packets. The TCP/IP protocol
sends the packets to their intended destinations and the recipient sends an
acknowledgement to the sender on receiving the packets. The sender retransmits
the data, if the acknowledgement is not received.
UDP works as a datagram service between the clients and server. Datagram
is a unit of information that consists of a frame and the frame in turn consists of a
set of bits. UDP provides fast and connectionless transportation of packets. The
UDP protocol is not a reliable protocol, as it does not guarantee the delivery of
packets. The data sent through the UDP protocol contains the recipient’s address
and transfers the data without establishing a connection between the sender and
the recipient.
The Internet Inter-Object Request Broker (ORB) Protocol (IIOP) facilitates
communication between different objects located on a network. It enables the
different network objects to invoke one another using Common ORB Architecture
(CORBA). CORBA enables you to automate many network programming
processes, such as object registration, location and activation. CORBA is an
emerging infrastructure that is provided by the Object Management Group (OMG).
CORBA provides strategy of writing client and server programs in C, C++, Java
or any other language.
IIOP is used in the client/server architecture that synchronizes the languages
of client and server objects for communication between them. IIOP specified the
meaning of clients and servers used for information exchange. It is also used for
clients and servers development using different application programming languages
to interact with one another.
A port is a numeric address that requests for a Web page using different protocols.
A 16-bit number, ranging from 0 to 65535, represents ports. Each protocol is
assigned a specific port number through which a client makes a request. Various
protocols, with their port numbers, are:
Transmission Control Protocol/ Internet Protocol (TCP/IP): Consists
of TCP and UDP protocol that are used to exchange the data over a network.
The TCP/IP protocol reserves the port number 1024.
Self-Instructional
Material 73
InetAddress, TCP/IP File Transfer Protocol (FTP): Enables the transfer of files efficiently and
Client and Server Sockets
reliably between computers. FTP reserves the port number 21.
Telnet: Provides an interactive, text-based communication between a client
and server. The telnet protocol reserves the port number 23.
NOTES
Finger: Enables the file transfer for clients using the FTP protocol. The
finger protocol reserves the port number 79.
Hyper Text Transfer Protocol (HTTP): Enables the interaction of clients
with the Internet. The HTTP protocol reserves the port number 80.
Ports are categorized as either well known or ephemeral. The well-known
port, also known as privileged port, is created on the server side. The port number
of a well-known port is less than 1024. The ephemeral port, also known as transient
or temporary port, is created on the client side when a client wants to connect to
a server. The ephemeral port is chosen at random and is destroyed when the client
application terminates. The port number of the ephemeral port is greater than
1023. Java uses mainly TCP and UDP protocols for making connection requests.
Figure 4.1 shows how the data is passed to an application across the
network.
Self-Instructional
74 Material
Figure 4.2 shows how the connection is established between client and InetAddress, TCP/IP
Client and Server Sockets
server.
NOTES
You create network programs in Java using the java.net package. The
java.net package provides the Socket class that creates a client socket
and the ServerSocket class that enables servers to listen for client requests
and accept their connections. The code for implementing socket connection is:
Implementing Socket Connection
Socket mySocketConnection;
try
{
mySocketConnection = new Socket(“www.banner.com” ,
1201);
}
catch(IOException e)
{
System.out.println(“Exception is:” +e);
}
The above code creates the socket object, mySocketConnection,
at port number 1201. The code displays an error message, if it is unable to create
a socket object.
4.7.1 Using TCP/IP Sockets
TCP/IP sockets transfer the data over the network using the TCP/IP. TCP sockets
establish the connection between the host computers first and then start sending
the data. This connection is terminated automatically, when the data has been sent
to the specified host. Java provides two types of TCP/IP sockets, client and socket.
The client socket is used to connect the client to the server. The client socket
is created when you create an object of the Socket class. The Socket class
Self-Instructional
Material 75
InetAddress, TCP/IP is a member of the java.net package. The Socket class provides two
Client and Server Sockets
constructors for creating the client socket. The two constructors are:
Socket(String HostName, int PortNumber): Creates
a client socket that connects the local host to the named host of the
NOTES
specified port number. This type of constructor throws two Java
exceptions, such as U n K n o w n H o s t E x c e p t i o n and
IOException.
Socket(InetAddress IPAdress, int
PortNumber): Creates a client socket using the existing host, which
has a specified IP address and port number. IP address is the object of
the InetAddress class that represents the IP address of the existing
host and PortNumber represents its port number. This type of
constructor throws a Java exception, such as IOException.
The server socket is used for creating a server application, which enables a
server to communicate with the client. The server socket is created using the
ServerSocket class. The ServerSocket class is a member of the
java.net package. The ServerSocket class provides three constructors
for creating the server sockets. The three constructors are:
ServerSocket(int PortNumber): Creates a server socket
for the specified port number that has a fixed queue length of 50. The
queue length determines how many client connections the system can
accept at a time.
ServerSocket(int PortNumber, int MAXQueue):
Creates a server socket for the specified port number with the specified
queue length. The MAXQueue parameter represents the maximum queue
length as integer type.
ServerSocket(int PortNumber, int MAXQueue,
InetAddress LocalAddress): Creates a server socket for
the specified port number and the specified local host address.
LocalAddress represents the object of the InetAddress class
that specifies the IP address of that local host.
You can examine the status and the input/output stream associated with the
socket using the socket methods.
Self-Instructional
76 Material
Table 4.1 describes the various socket methods. InetAddress, TCP/IP
Client and Server Sockets
Table 4.1 Socket Methods
Methods Description
getInetAddress() Returns the IP address of the host computer. NOTES
getPort() Returns the port number of the host computer.
getLocalPort() Returns the port number of the local host.
getInputStream() Returns the input stream that is associated
with the socket.
getOutputStream() Returns the output stream that is associated
with the socket.
close() Closes the socket connection.
Self-Instructional
Material 77
InetAddress, TCP/IP socket = server_socket.accept();
Client and Server Sockets
System.out.println(“TCPClient has been
connected :”+ socket);
// Receives the message from the
NOTES TCPclient system
DataInputStream dstream = new
DataInputStream(socket.getInputStream());
// Sends the message to the TCPclient
system
PrintStream pstream = new PrintStream
(socket.getOutputStream());
pstream.println(“Hello! TCPServer
here.”);
pstream.close();
socket.close(); // Terminate the
connection
}
catch(SocketException se)
{
System.out.println(“Error in server
socket “+ se.getMessage());
}
catch(Exception e)
{
System.out.println(“Error in server
starting”+ e.getMessage()) ;
}
Self-Instructional
Material 79
InetAddress, TCP/IP }
Client and Server Sockets
finally
{
try
NOTES
{
socket.close(); // Closes the socket
}
catch(IOException ioe)
{
System.out.println(“ Socket closing
Errors:” + ioe.getMessage());
}
} // End finally block
} // End the main() method
} // End the TCPClient class
The above code shows how to create a client socket that can communicate
with the server of port number 1050. The client socket communicates with the
server using the methods, g e t I n p u t S t r e a m ( ) and
getOutputstream(). You can run the client and server program after
successfully compiling both the program.
Figure 4.3 shows the output.
Figure 4.4 shows the output of the client and server program.
Self-Instructional
80 Material
InetAddress, TCP/IP
4.8 ANSWERS TO CHECK YOUR PROGRESS Client and Server Sockets
QUESTIONS
1. The getHostName () methods returns a string that contains the name NOTES
of the host with the IP address represented by the InetAddress object.
2. The isAnyLocalAddress() method returns true if the address is a
wildcard address, false otherwise.
3. Internet address, also known as Internet protocol (IP) address, is a unique
address assigned to each computer.
4. The client socket is used to connect the client to the server.
4.9 SUMMARY
The InetAddress class does not have any public constructors. Rather,
InetAddress has static factory methods that connect to a DNS server to
resolve a hostname.
The InetAddress class contains four getter methods that return the hostname
as a string and the IP address as both a string and a byte array.
IPv4 addresses in the range 224.0.0.0 to 239.255.255.255 are multicast
addresses that send to several subscribed hosts at once.
The InetAddress class has two isReachable() methods that test whether a
particular node is reachable from the current host.
Internet address, also known as Internet protocol (IP) address, is a unique
address assigned to each computer.
It is difficult to remember different IP addresses while connecting to the
Internet. You can use Domain Naming Service (DNS) for addressing this
problem that are also known as URLs.
A networking protocol is a set of standard rules that provides the standard
for information exchange over the network.
A port is a numeric address that requests for a Web page using different
protocols.
TCP/IP sockets transfer the data over the network using the TCP/IP. TCP
sockets establish the connection between the host computers first and then
start sending the data.
The server program creates a server socket that can communicate with the
client socket using TCP/IP. The TCPServer class creates a server socket
by using an object of the ServerSocket class.
The client program creates a client socket that can communicate with the
server socket using TCP/IP. The TCPClient class creates a client socket
Self-Instructional
using an object of the Socket class. Material 81
InetAddress, TCP/IP
Client and Server Sockets 4.10 KEY WORDS
Short-Answer Questions
1. Write a note on InetAddress.
2. What are the features of Networking?
3. What are client and server sockets?
4. What are the different types of gether methods?
Long-Answer Questions
1. Why do you need sockets in networking?
2. Explain the different types of addresses.
3. Write Java programs to create a chat application using the TCP/IP server
socket. In this application, a client can communicate with the server or
server can communicate with the client.
4. Write a code to implement socket connection.
5. What are the various methods of TCP/IP socket?
Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.
Self-Instructional
82 Material
URL Connection and
DATAGRAMS
NOTES
Structure
5.0 Introduction
5.1 Objectives
5.2 URL and URL Connection Classes
5.3 Using UDP Sockets
5.3.1 Creating a Server Program
5.3.2 Creating a Client Program
5.4 Answers to Check Your Progress Questions
5.5 Summary
5.6 Key Words
5.7 Self Assessment Questions and Exercises
5.8 Further Readings
5.0 INTRODUCTION
5.1 OBJECTIVES
Self-Instructional
Material 83
URL Connection and
Datagrams 5.2 URL AND URL CONNECTION CLASSES
Uniform Resource Locator (URL) represents the address of a Web page, which
NOTES enables you to find a resource on the Internet. You can access a specific Website
by typing its URL in the address bar of the Web browser. A URL is represented as
a string that explains the resource you are using on the Internet. For example,
www.google.com is a search engine, which you simply type in the address
bar for accessing information about any topic. The components of a URL are:
(i) Filename: Specifies the name of the file you are accessing.
(ii) Directory Name: Specifies the location of the file.
(iii) Host Name: Specifies the Internet host contacted for retrieving requested
documents.
(iv) Access Method: Specifies the protocol used for accessing the documents,
such as HTTP and FTP.
An example of a URL is http://www.utoronto.com/
webdocs/HTMLdocs/ New.html. In this URL, http is the protocol
used and locations are separated by forward slashes and colon (:). Protocol
identifiers can be FTP, Gopher, File and News that specify the address of the
resource on the Internet.
The java.net package provides the URL class that enables you to
create an instance of URL. The URL object refers to the address of the Internet
resource you want to access. The code to implement a URL in a class is:
URL myURL = new URL(“http://www.banner.com/”);
The above code shows the creation of URL object, myURL, for fetching
the Internet resource, www.banner.com.
You need to use various methods using which you can extract the protocol,
host name, port number and file name from the URL object. Table 5.1 lists the
various methods of the URL class.
Table 5.1 Various Methods of URL Class
Methods Description
getFile() Retrieves the name of file.
GetHost() Retrieves the host name included in URL string.
getPort() Retrieves the port number of the destination computer that
is connected with the URL.
getProtocol() Retrieves the protocol of the URL that is used as an
identifier.
getContent() Retrieves the content of the URL.
getRef() Retrieves the reference of the URL.
You can implement the URL in your defined class and use various methods.
The following program code shows how to implement URL:
Self-Instructional
84 Material
Implementing URL URL Connection and
Datagrams
import java.net.*;
import java.io.*;
public class newURL NOTES
{
public static void main(String args[])throws Exception
{
URL myURL = new URL(“http://www.utoronto.com/webdocs/
HTMLdocs/New.html”);
System.out.println(“Protocol used: “ +
myURL.getProtocol());
System.out.println(“Host name: “ + myURL.getHost());
System.out.println(“Port number: “ + myURL.getPort());
System.out.println(“File name: “ + myURL.getFile());
}
}
The above code shows retrieving the protocol, host name, port number and
the file name of the given URL. Figure 5.1 shows the output generated by the new
URL class.
Self-Instructional
Material 85
URL Connection and Table 5.2 Various Methods of the URLConnection Class
Datagrams
Methods Description
getContentEncoding() Retrieves the data encoding that is used for data
transfer.
NOTES getContentLength() Retrieves the length of a URL string in bytes.
getContentType() Retrieves the content type of a URL, such as
MIME type data.
getExpiration() Retrieves the time of expiration of a URL.
getLastModified() Retrieves the last modified data of a URL.
URLConnection Ucon=myURL.openConnection();
BufferedReader br = new BufferedReader(new
InputStreamReader(Ucon.getInputStream()));
String istream;
while ((istream = br.readLine()) != null)
System.out.println(istream);
br.close();//stream close
//Declaration of Content type variable
String CntType=Ucon.getContentType();
System.out.println(“Format of the page content
is:” +CntType);
long EXP=Ucon.getExpiration();
System.out.println(“URL Expiration is:”+EXP);
//for storing length of content type
int Clen=Ucon.getContentLength();
System.out.println(“Length of page is:”+Clen);
//Declaration input stream type variable
}
}
Self-Instructional
86 Material
The above code shows the contents of page mentioned in the URL. The URL Connection and
Datagrams
code also shows the days of expiration of URL and the length of page. Figure 5.2
shows the output generated by implementing the URLTest.java class.
NOTES
UDP sockets exchange data over the network by using the User Datagram Protocol
(UDP). UDP is a connectionless protocol that can send data in the form of data
bundles called as datagram that consists of the destination address. UDP is a less
reliable protocol than TCP/IP because it cannot create a connection between the
host computers. UDP sockets are used for sending data without establishing a
connection between the host computers. Java provides two classes for creating a
UDP socket, DatagramPacket and DatagramSocket.
The DatagramPacket class creates the datagram packet that stores
information in the form of an array. The datagram packets can be transmitted over
the network using the UDP. Java provides two constructors for the
DatagramPacket class. The two constructors are:
(i) DatagramPacket(byte data[], int size): Creates
datagram packets of specified size. The parameter, data[]
represents an array that stores the information. The parameter, size,
indicates the maximum size of packet that can be transmitted over the
network.
(ii) DatagramPacket(byte data[], int size,
InetAddress IPAddress, int port): Creates the
datagram packets of specified size, IP address and port number. The
parameter, IPAddress, represents the IP address of the target
host and parameter port represents the port number of the target host.
The DatagramSocket class creates a socket that controls the
transmission of datagram packets across the network. The object of the
DatagramSocket class always throws an exception, SocketException
at the time of datagram packet transmission over the network. Java provides two
types of DatagramSocket constructors for creating the socket. The two
constructors are:
(i) DatagramSocket(): Creates a default socket that transmits a
datagram packet across the network.
(ii) DatagramSocket(int port): Creates a socket that can
transmit a datagram packet to the host of specified port number across
the network. Self-Instructional
Material 87
URL Connection and You can send or receive the datagram across the network using the datagram
Datagrams
methods. There are several methods for accessing the state of the datagram packet.
Table 5.3 describes the various socket methods.
Table 5.3 Datagram Methods
NOTES
Method Descriptions
send(DatagramPacket dp) Sends the datagram packet to the specified host.
Receive(DatagramPacket Retrieves the datagram packet from the
dp) specified host.
getLength() Returns the length of the datagram packet.
getAddress() Returns the IP address of local host.
getPort() Returns the port number of the specified host.
close() Closes the socket connection.
System.exit(0);
}
dpacket = new DatagramPacket(data, NOTES
data.length);
try
{
dsocket.receive(dpacket);
}
catch(IOException ioe)
{
System.out.println(“Input/Output Error “+
ioe.getMessage() );
System.exit(0);
}
msgRecieve = new String (dpacket.getData(),0);
System.out.println(“Message Returned : “+
msgRecieve.trim());
} // End the main() method
} // End the UDPClient class
The above code shows how to create a client socket and datagram packets
that can be transmitted to the server of port number 1050. The datagram packet
is transmitted using the send() method and received using the receive()
method.
You can run the client and server program after successfully compiling both
the programs. The server program runs on the server computer and the client
program runs on the client computer.
Figure 5.3 shows the output of the program that uses the UDP server.
Figure 5.4 shows the output of the program that uses the UDP client.
Self-Instructional
Material 91
URL Connection and This UDPServer class waits for receiving the datagram packets from
Datagrams
the UDPclient class after starting the server. The UDPClient class sends
the datagram packet, when you pass the IP address and message packet as
parameter. The server receives that datagram packet and again waits for the next
NOTES datagram packet if next datagram packets are not available.
5.5 SUMMARY
Short-Answer Questions
1. What are DatagramSockets?
2. Write a note on URL and its class
3. Discuss DatagramSockets and their use.
4. Discuss the functionality of URL Connection Class.
Long-Answer Questions
1. Analyse the commonly used methods of URL class.
2. Differentiate between DatagramPacket and DatagramSocket.
3. How do you Display the source code of a webpage by URLConnecton
class? Support your answer with the help of an example.
Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.
Self-Instructional
Material 93
Client and Server
Applications Using RMI
UNIT 6 CLIENT AND SERVER
APPLICATIONS USING RMI
NOTES
Structure
6.0 Introduction
6.1 Objectives
6.2 N-Tier Architecture
6.3 Overview of RMI
6.4 Distributed Object Technologies
6.5 Locating and Loading Remote Classes
6.6 Locating Remote Objects
6.7 Enabling Remote Method Class
6.8 Creating a Client Class
6.9 Transferring Non Remote Objects
6.10 Handling Exceptions
6.11 Executing RMI
6.12 Implementing Callbacks
6.13 Distributing the RMI Application
6.14 Using Applets with RMI
6.14.1 Defining Server Class
6.14.2 Defining Remote Interfaces
6.14.3 Defining Client Class
6.14.4 Creating the HTML File
6.14.5 Executing the RMI with Applet
6.15 RMI Architecture
6.15.1 Application Layer
6.15.2 Proxy Layer
6.15.3 Transport Layer
6.16 Socket versus RMI Programming
6.17 Answers to Check Your Progress Questions
6.18 Summary
6.19 Key Words
6.20 Self Assessment Questions and Exercises
6.21 Further Readings
6.0 INTRODUCTION
This unit introduces the concept of distributed architecture using N-Tier and
distributed object technologies. In this unit, you will learn how to locate and load
Java classes on a remote machine. After loading the remote classes, you need to
create and locate objects of the remote machines. You will learn how to enable the
remote method class to listen to a client request.
Self-Instructional
94 Material
You can implement callbacks from a server to the client to send error Client and Server
Applications Using RMI
messages and acknowledgements. You can also distribute the application over the
network to implement RMI on distributed systems. RMI can be integrated with
applets to enhance user interactivity. This unit also describes various layers in the
RMI architecture such as application layer, proxy layer, remote reference layer NOTES
and transport layer. In addition, you will learn the differences between socket
programming and RMI programming.
6.1 OBJECTIVES
Web Client
Web Business Database
Server Logic Server
(Presentation) Server
Self-Instructional
Material 95
Client and Server The above figure shows the Web server at the first tier of the client server
Applications Using RMI
architecture. The second tier consists of the business logic server and the N-tier
consists of the database server that sends response to all the queries sent by the
clients.
NOTES
6.3 OVERVIEW OF RMI
Distributed applications contain objects that are distributed over a network. The
objects communicate with each other using a standard protocol such as TCP/IP.
The client object sends a request in the form of a message to the object present on
the server. The server reads the client request to collect the information about
fulfilling the request such as the name of the method called by the client and the
parameters required by the method. The answer to the request is returned to the
client.
In a client/server architecture, the request of the client object and the response
from the server object are converted to an intermediate format such as name/
value pairs. The intermediate format used to represent the messages is dependent
on the technology used to create the client and server objects. Hence, it becomes
important to know the technology used to create client and server objects. For
example, the intermediate format to send messages between two objects such as
a client and a server, written in Java, is different from the format used in case if
either client or server object is written in C++. If the client object is created in
Java, then either the server object can be created in Java or it can be created using
other technology such as C++. If the server objects are not created in Java, the
communication between the client and the server is difficult as both the client and
the server objects use different technology. In this case, Common Object Request
Broker Architecture (CORBA) is used. CORBA like RMI makes possible the
communication between the client and the server objects written in different
technologies. CORBA specifies the mechanisms to transfer data. However,
CORBA is difficult to implement and is slow in performance too.
In the second case, if both client and server objects are written in Java, then
you do not need to consider the complexities while implementing CORBA. Sun
Microsystems has developed RMI, specifically designed to be used when both
the client and server objects are written in Java. RMI like CORBA enables transfer
of data between the client and the server objects. As compared to CORBA, RMI
is easier to perceive and use.
In RMI, the Java object that calls a method remotely is called the client
object. The remote Java object whose method is invoked is called the server
object. In RMI however, the client/server terminology applies to only single method
call. The server object for an earlier call can become the client in the next call if it
calls a method remotely on a Java object present on a different computer.
Self-Instructional
96 Material
Client and Server
6.4 DISTRIBUTED OBJECT TECHNOLOGIES Applications Using RMI
In Remote Method Invocation (RMI), if you have the rights to access a Java
object present on a different computer over a network, then you can call the NOTES
methods defined in it. The accessible Java object is called a distributed object.
Therefore using RMI, you can distribute the objects over a network that can
communicate with each other. RMI is identical to Remote Procedure Call (RPC)
used in C/C++ to call methods remotely over a network.
You need to pass parameters over the network to call the method of a
remote object. The process of passing the parameters to the remote object is
called parameter passing. When the client object is calling a method of the server
object, this call is similar to the normal method call of Java programming language.
Therefore, the remote method call may need to transfer parameters to the server
object also. The parameters to be passed are stored in a proxy object called a
stub. It contains all the parameters required for the method call. The stub object is
stored on the client machine.
The process of encoding the parameters to be stored in the stub object is
called parameter marshalling. The purpose of parameter marshalling is to convert
the parameters into an appropriate format so that they can be transported from
one Java Virtual Machine (JVM) to another. A stub object contains all the marshalled
parameters, a message describing the method to be called and a remote object
identifier to identify the remote object whose method needs to be called.
The stub passes the information it contains to the server automatically. At
the server, a receiver object, called as skeleton, receives all the information contained
in the stub. The receiver object performs the following actions to fulfill the client
request:
1. Retrieves all the parameters from the stub object.
2. Locates the object that is called.
3. Calls the method of the object.
4. Collects the result after executing the method.
5. Sends the result back to the client.
The client stub object then receives the result of the execution of the remote
method sent back by the server.
Whenever an application loads new data from another location over a
network, security becomes important to protect the application from viruses. As a
result, you need to use a security manager, which is a security mechanism, in the
client that manages all the security issues.
Self-Instructional
Material 97
Client and Server
Applications Using RMI 6.5 LOCATING AND LOADING REMOTE
CLASSES
NOTES Locating and loading remote classes include creating and checking the RMI
application. You need to check the RMI application on both the client and server
computers by placing the required files of the application, which contains the client
classes, server classes and required interfaces at both client and server location.
An RMI application contains more than one file, which is required by the client
objects or the server objects. The client object needs the files to know about the
methods present in the server class. The server object needs the files to get
information about the client itself. In addition, the client uses a special lookup
mechanism to locate the objects on the server.
interface Customer extends Remote{
public String[] customerDetails() throws
RemoteException;
}
You can create an RMI application either on a single computer or on a set
of computers connected through a network. However, the network services such
as TCP/IP protocol should be available to test a RMI application on a single
computer after creating it. The client calls the method that is present on the server
so it should have the required information about the methods present in the server
class. To inform the client about the required information, you need to create an
interface that is shared between the client and the server. The interface contains
the signatures of those methods that the client can access of the remote server.
The code to create an interface that represents a remote object is:
In the above code, the interface, Customer, is defined for remote objects.
The Customer interface extends the Remote interface. All the interfaces for remote
objects must extend the Remote interface that is defined in the java.rmi
package. All the methods of this interface must throw RemoteException
because the remote method calls are very sensitive to network errors and there is
great possibility for the failure of the network call. In case of failure, the remote
method will throw RemoteException. The Customer interface must be
available to client as well as to server, as both of them share the interface.
On the server machine, there must be a class available that contains the
methods defined in the remote interface. If there is no such class, you need to
create it by extending the UnicastRemoteObject class. The class that
extends the UnicastRemote Object class acts as the server for remote
interface. The UnicastRemoteObject class provides the functionality to
make an object remotely accessible. The following program code shows how to
extend the UnicastRemoteObject class:
Self-Instructional
98 Material
Creating a Server Class for Remote Client Client and Server
Applications Using RMI
public class CustomerImpl extends UnicastRemoteObject
implements Customer{
public CustomerImpl() throws RemoteException{
//The constructor is also throwing
NOTES
// RemoteException
}
public String[] customerDetails(){
…
}
}
The above code shows the CustomerImpl class that extends the
UnicastRemote Object class and implements the Customer remote
interface created earlier. The constructor of this class is also throwing the
RemoteException. As this class implements the Customer remote interface,
it also defines the customerDetails() method of the Customer remote
interface.
Every server class needs to extend the RemoteServer class of the
java.rmi.server package, but this class does not define any method, as
it is an abstract class. However, the UnicastRemoteObject class extends
the RemoteServer class and defines all its methods. This is why the
CustomerImpl class created earlier extends the
UnicastRemoteObject class.
Figure 6.2 shows the inheritance hierarchy in UnicastRemoteObject
class.
Self-Instructional
Material 99
Client and Server This figure shows the RemoteObject class that extends the Object
Applications Using RMI
class and implements the Remote interface. The RemoteServer class extends
the RemoteObject class. The RemoteServer class is an abstract class
as it contains only method signatures. The UnicastRemoteObject class
NOTES extends the RemoteServer class and defines all the methods of the
RemoteServer class.
The server class that you define extends the UnicastRemoteObject
class. The client can access the server class using the TCP/IP protocol.
The client class uses a stub that implements the remote interface to access
the server object. The code to access the server object:
Customer c = …;
String[] s = c.customerDetails();
for( int i=0; i<str.length(); i++)
System.out.println( s[i] );
In the above code, a reference to the stub object of Customer interface is
created that is used to access the method of the server. When the client invokes
the Customer interface method using the stub object reference, a request is sent to
the server object through the network. On the server, the skeleton object receives
the request and invokes the required method by parsing the request message. The
result of the execution of the method is returned to the client.
Table 6.1 describes the naming conventions that you can use while creating
an RMI application.
Table 6.1 Naming Conventions
Impl suffix Represents the server class that implements the remote
interface.
Server suffix Represents the class that creates the server objects.
Client suffix Represents the client program that accesses the remote
methods.
_Stub suffix Represents the name of the stub class.
_Skel suffix Represents the name of the skeleton class.
You need to create a stub class for the CustomerImpl class because
this class implements the Remote interface. You need to create a stub class for
those classes that implement the Remote interface. The rmic tool is used to create
Self-Instructional
100 Material
the stub classes automatically. The code to create the stub class for the Client and Server
Applications Using RMI
CustomerImpl class using the rmic tool is:
rmic CustomerImpl
The above code creates two classes, a stub class and a skeleton class. NOTES
However, before using the rmic tool to create the stub class, you need to compile
the Java source files such as CustomerImpl class using the javac utility.
The client uses a stub object to access the remote object that exists on the server,
but how can the client get the stub object. The stub object must be registered
somewhere by the server to enable the client to access it. The simple method for
the client to access a stub object is to call a remote method of another server
object that returns the stub object. The RMI library contains the utility,
rmiregistry, to register the stub objects, which is also called the bootstrap
registry service. The server registers objects at the bootstrap registry service and
the client uses this bootstrap registry service to get the stub objects. You can
register a server object to bootstrap registry service by passing the bootstrap
registry service a name, which is used by the client to access the stub object using
the lookup mechanism and a reference to the object that needs to be registered.
The code to register a CustomerImpl object is:
CustomerImpl ci = new CustomerImpl(“first”);
Naming.bind(“Customer1”, ci);
In the above code, the reference, ci, to the CustomerImpl class is
passed to the bootstrap registry service. The bind() static method of the
Naming class is used to register the object. Customer1 represents the name
for the registered object. Try to specify unique names that are not used earlier to
register some other remote objects. The client gets a stub object by specifying the
server and object name. The following code shows how to get a stub object:
Customer c = (Customer)Naming.lookup(“rmi://ServerName/
Customer1”);
In the above code, the ServerName represents the name of the server.
If you are testing the application locally, then you have to use localhost instead of
ServerName in the lookup() method. The string, localhost refers
to the local computer if the server object is running on the same machine where the
client is running. Customer1 represents the name used by the server to register
the remote object. The lookup() static method of the Naming class is used to
locate the remote object. The parameter of the lookup() method represents
a RMI URL that starts with rmi://, followed by the server name, an optional
port number, a slash and then a name of the remote object as shown in the above
code. The default port number is 1099.
Self-Instructional
Material 101
Client and Server
Applications Using RMI 6.7 ENABLING REMOTE METHOD CLASS
implements Customer{
public CustomerImpl(String firstName, String
middleName, String lastName) throws RemoteException{
this.firstName = firstName; this.middleName =
middleName; this.lastName = lastName;
}
public String getFullName() throws RemoteException{
if(middleName == “”)
return “The fullname is : “ + firstName+ “ “+ lastName;
else
return “The fullname is : “ + firstName+ “ “+
middleName+ “ “+ lastName;
}
private String firstName, middleName, lastName;
}
The above code shows the CustomerImpl class that is a server class
as it extends the UnicastRemoteObject class. This class defines the
getFullName() method of the Customer remote interface. The
getFullName() method of the CustomerImpl class returns the full
name of the customer as a String object. The following program code shows the
CustomerServer class that will bind the CustomerImpl objects to
the bootstrap registry service:
Self-Instructional
102 Material
Registering CustomerImpl Objects Client and Server
Applications Using RMI
import java.rmi.*;
import java.rmi.server.*; import sun.applet.*;
public class CustomerServer{
NOTES
public static void main(String arg[]){ try{
System.out.println(“Implementing server”);
CustomerImpl c1 = new CustomerImpl(“Lalit”, “”,
“Kapoor”);
CustomerImpl c2 = new CustomerImpl(“Sumit”, “Kr.”,
“Sharma”);
System.out.println(“Binding remote server objects to
Bootstrap Registry Service”);
Naming.rebind(“Lalit”, c1); Naming.rebind(“Sumit”, c2);
System.out.println(“Binding complete,
Server is ready”);
}catch(Exception e){ System.out.println(“Error : “+e);
}
}
}
In the above code, the Naming.rebind() method is used to register
objects, Lalit and Sumit, to the bootstrap registry service. After creating the classes
required to start the server, you need to compile all the classes. Save all Customer,
CustomerImpl and CustomerServer files in a single directory and
compile all the files. After compiling the files, you need to create the stub class. To
create the stub class, use the rmic tool, as shown in the following code:
rmic CustomerImpl
The above code will create stub and skeleton classes automatically. After
they are created, use the rmiregistry tool to invoke the bootstrap registry
service. The following code shows how to start the bootstrap registry service in
Windows from the DOS prompt:
start rmiregistry
In the above code, the start command of the Windows operating system is
used to start the bootstrap registry service in a new window. The following code
shows how to start the bootstrap registry service in Unix:
rmiregistry &
After starting the rmiregistry, you can start the server. The code to start the server
is:
java CustomerServer
The above code starts the server represented by CustomerServer. A
separate thread starts that runs indefinitely when the objects of a class that extends
the UnicastRemoteObject class is created. The main() method of the
CustomerServer class runs indefinitely. Therefore, the CustomerServer
class runs indefinitely to allow the clients to send request to it. Self-Instructional
Material 103
Client and Server
Applications Using RMI
Check Your Progress
1. What does the N-tier architecture allow a programmer to do?
NOTES 2. What do distributed applications contain?
The client needs to capture a stub object to send requests to the object present on
the server. The lookup() method of the Naming class is used to get the stub
of the remote object. The client to call the methods defined in the server object
then uses the stub object. The reference to the stub object is of remote interface
type defined for the server. Therefore, the client can access the method signature
defined in the remote interface. The following program code shows the
CustomerClient class that retrieves the stub to the registered objects:
Creating the CustomerClient Class
import java.rmi.*;
import java.rmi.server.*; public class CustomerClient{
public static void main(String arg[]){
System.setSecurityManager( new
RMISecurityManager());H
String url = “rmi://localhost/”; try{
Customer c1 = (Customer)Naming.lookup(url+”Lalit”);
Customer c2 = (Customer)Naming.lookup(url+”Sumit”);
System.out.println(c1.getFullName());
System.out.println(c2.getFullName());
}catch(Exception e){ System.out.println(“Error : “+ e);
}
System.exit(0);
}
}
The above code shows the CustomerClient class. The first statement
in the m a i n ( ) method is used to create an object of the
SecurityManager() class that will handle all the security issues for the
client The SecurityManager object is important because the RMI clients
can load the stub classes from other locations such as RMI servers. The Security
Manager restricts the client from violating any permission granted to the server.
For example, the client cannot access files at the server computer that the server
object can access. The client cannot manipulate files from the server’s file system
because of the S e c u r i t y M a n a g e r object. After creating the
SecurityManager object, the getFullName() method of both the
Self-Instructional
104 Material
stub objects are executed. The exit() method is used to terminate the client Client and Server
Applications Using RMI
program.
To enable the client to connect to the server object, you need to supply the
policy file. The policy file enables the client to get any network connection. The
NOTES
code to give the network permission to the client between port numbers 1024 to
65535 is:
grant{
permission java.net.SocketPermission “*:1024-65535”,
“connect”;
};
The above code gives SocketPermission to the client. Save this
file in the C:/Windows folder as java.policy.
Save the CustomerClient class in the folder where the server classes
are stored. Then move to that folder, compile the client class and execute it. The
output when the CustomerClient class executes is:
The fullname is: Lalit Kapoor
The fullname is Sumit Kr. Sharma. The above code shows the output
of the CustomerClient class. The client calls the getFullName()
method of the server class that returns a String object representing the full name of
the registered Customer objects.
You can pass and retrieve any object through a remote call including those that
implement the Remote interface. For example, in the CustomerClient class,
the getFullName() method returns a String object that does not implement
the Remote interface. This is because the client gets a copy of the String object.
A nonremote object is an object of that class that does not implement the
Remote interface. Whenever a nonremote object needs to be passed from one
JVM to another, the JVM creates a copy of the object and sends it over the
network. The RMI mechanism uses the serialization mechanism to send objects
across the network. The RMI mechanism creates multiple copies of nonremote
objects if they implement the Serializable interface.
Note: The remote objects are passed as stubs across the network, but the nonremote
objects are copied using the Serialization mechanism.
In case of passing remote object, only the methods defined in the remote
interface can be accessed through the stub. The client cannot access any method
of the class that is not defined in the remote interface. The stubs are generated only
for the classes that implement the Remote interface. If the subclass does not
implement the Remote interface but the superclass does, then only the methods of
the superclass are accessible to the client. Self-Instructional
Material 105
Client and Server
Applications Using RMI 6.10 HANDLING EXCEPTIONS
Self-Instructional
106 Material
The above code shows the Client class. The Naming.lookup() Client and Server
Applications Using RMI
method throws NotBoundException so it is caught using the try catch
block. Similarly, the remote method invocation to the getTotal() method of
the Server class throws a RemoteException, so it is also encapsulated
inside the try catch block. NOTES
All the files in the Customer application created earlier are stored locally in a
folder to find any error in the RMI application. You should always test your
application locally before deploying it on the network. You need to save the files at
both the client and the server computer of the RMI application to make it a
distributed application.
Before saving the files at the client and server computer, create two folders,
client and server, on the local computer. The client folder will store all the files
required by the client object and the server folder would store all the files related
to server object.
For example, in the Customer application created earlier, the following files
will be stored in the server folder:
CustomerServer.class: This file represents the class used to
create server objects.
CustomerImpl.class: This file represents the server class used
to implement remote interface.
Customer.class: This file represents the name of the remote
interface.
CustomerImpl_Stub.class: This file represents the name of
the Stub class.
The CustomerImpl.class file is used to define methods that are
required to access the methods define in the remote interface. The methods defined
in the remote interface are implemented by extending the
UnicastRemoteObject. The UnicastRemoteObject provides
functionality to make the objects available from the remote machines.
The client needs to define an interface that contains the signatures of the
methods of the server class available to the client to be accessed. This interface
gives access to the client to access the methods defined in the server. The interface
enables the client to use the remote object’s method as if it is a local method.
After saving the above files in the server folder, you need to store files in the
client folder. Store the following files in the client folder:
CustomerClient.java: This file represents the client programs
that accesses the remote methods.
Self-Instructional
Material 107
Client and Server CustomerClient.class: This file represents the client program
Applications Using RMI
that accesses the remote method.
Customer.class: This file represents the name of the remote
interface.
NOTES
Move the client folder to the client computer. Create a policy file on the
client computer to enable the client to make network connections. You need to
change the RMI URL in the CustomerClient.java file to enable the
client to access the server.
Open the CustomerClient.java file and change the RMI URL
by specifying the name or the IP address of the server in place of localhost. The
new URL will enable the client to access the server. The code to represent the
RMI URL to access the server with IP address 192.168.0.124 is:
String url = “rmi://192.168.0.124/”;
After changing the URL, compile the source file again and run the client
program. The client will receive a reference to the stub object of the registered
server object using the bootstrap registry service. The Naming.lookup()
method will look for the registered objects and will return a stub object for it. The
client will use that stub to execute the remote server object methods.
The server itself can make a remote call back to the client such as sending a
warning for an error, a progress feedback or sending a message from one client to
another. To enable the server to call the methods of a client, the client also needs
to work like an RMI server. However, the client class cannot extend the
UnicastRemoteObject class of the java.rmi.server package
because only the server class extends the UnicastRemteObject class.
To enable the server to connect to the client, the client must make itself available
to receive the calls from the server. The exportObject() method of the
UnicastRemoteObject class makes the client available to receive the
incoming calls from the server. The syntax to use the exportObject method
is:
public static RemoteStub exportObject(Remote obj) throws
RemoteException
In the above syntax, the exportObject() method takes a Remote
object as parameter and returns a RemoteStub object. The remote object,
obj passed as parameter becomes available to receive calls from the server.
The exportObject() method is a static method.
Self-Instructional
108 Material
Client and Server
6.13 DISTRIBUTING THE RMI APPLICATION Applications Using RMI
To execute the RMI application over the network, you need to place the required
class files at the locations that can be accessed by the server and the clients. The NOTES
files that are required by the server are:
Remote interfaces definitions
Stubs classes
Skeletons classes
All other server classes
The following class files should be available for the client:
Stubs classes
Remote interface definitions
Server classes of objects used required by the client (such as return
values)
All other client classes
In addition to the above requirements, you also need to make a change in
the Client class code. In the Client.java class, you need to change the
rmi string from rmi://localhost/server to rmi://
ServerName/server. Here, ServerName represents the name of the
server where the bootstrap registry service is running. For example,
192.168.0.124 represents a name of the server, so a valid rmi string is
rmi://192.168.0.124/server. You can also specify a port number
that the server is using to fulfill the client request after the server name. The code to
show the rmi string that contains the default port number, 1099, with the server
name is:
rmi://192.168.0.124:1099/server
The port number is optional to be specified in the rmi string. The default
port number, 1099, is used when no port number is specified.
You can also create applets to represents the RMI clients. All the required files for
the applet must be stored in the same host that contains the Web page. The applet
can make network connections to only that host, which contains the applet.
Therefore, you need to store all the server objects on the same host that contains
the Web page. The server must contain Web pages, stub classes, server objects,
applet file and the RMI registry.
Self-Instructional
Material 109
Client and Server 6.14.1 Defining Server Class
Applications Using RMI
The Server Class extends the UnicastRemoteObject class of the rmi
package. The Server class is initially compiled with javac to create .class
NOTES files. Then the server .class is compiled using the rmic compiler to
generate the stub and skeleton class files. The Server.class defines the
basic functioning of the method on the remote machine and throws runtime
exception.
import java.rmi.registry.LocateRegistry; import
java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject; public
class Server implements RemoteInterface
{
public String getMessage()
{
return “Using RMI with applet”;
}
LocateRegistry.getRegistry(getCodeBase().getHost(),
RemoteInterface.REGISTRY_PORT);
RemoteInterface remoteReference = (RemoteInterface)
registry.lookup(RemoteInterface.REGISTRY_NAME);
add(new Label(remoteReference.getMessage()));
}
catch (Exception e)
{
Self-Instructional
Material 111
Client and Server throw new RuntimeException(e);
Applications Using RMI
}
}
}
NOTES
In the above code, the registry.lookup method obtains an object
handle and listens to the default port. The Naming.lookup method must be
type cast to the Remote Interface.
Save the file in the folder where the Client file is stored and compile the file.
After compiling the file, create the stub and skeleton files for the ClientApplet
class.
6.14.4 Creating the HTML File
To pass the name of the client from the server to the applet, you need to pass the
client name as the parameter to the applet. To pass the parameter to the applet,
you need to create the Applet.html file. The following program code shows
the content of the Applet.html file:
Showing the ClientApplet.html File
<?xml version=”1.0" encoding=”UTF-8"?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//
EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-
strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”
xml:lang=”en” lang=”en”>
<head>
<title>’Using RMI with Applet’</title>
</head>
<body>
<h1>”Simple example of using RMI with Applet”</h1>
<p>
This example simply demonstrates the use of applets in
Remote Method Invocation.
</p>
<p>
<!—[if !IE]>—>
<object classid=”java:ClientApplet.class”
type=”application/x-java-applet” height=”250"
width=”250" >
Self-Instructional
112 Material
<!—<![endif]—> Client and Server
Applications Using RMI
<object classid=”clsid:8AD9C840-044E-11D1-B3E9-
00805F499D93"
height=”50" width=”150" >
<param name=”code” value=”ClientApplet” /> NOTES
</object>
<!—[if !IE]>—>
</object>
<!—<![endif]—>
</p>
</body>
</html>
The name of the client is passed in the <param> tag, which the client
retrieves using the getParameter() method. The name of the client is
accessed using it.
6.14.5 Executing the RMI with Applet
1. Compile the java source files Server.java, ClientApplet.java
and RemoteInterface.java to generate the Sever.class,
ClientApplet.class and RemoteInterface.class files.
2. Compile the Server.class file with the rmic compiler using the
following command at the prompt:
rmic –v1.2 Server
3. Start the rmi registry on port 3273 using the following command:
start rmi registry 3273
4. Start the server using the following command:
start java server
This will start the program on the server side.
Figure 6.3 shows the command line to execute the RMI.
Self-Instructional
Material 113
Client and Server 5. Open web browser such as Internet Explorer and view the
Applications Using RMI
applet.html file. Figure 6.4 shows the output
NOTES
During the Remote Method Invocation (RMI) call, the client requests a service
from a server and the server processes the request. RMI classes extend an interface
that helps in implementing the remote service based on the concept of classes.
The RMI architecture defines the implementation of object class on a remote
JVM that is based on various abstract layers such as:
Application layer
Proxy layer
Remote reference layer
Transport layer
All the above layers are independent of each other and you can amend
these layers according to your requirement. RMI is initiated when a method is
called at the client end, which requires a service. The request for service passes
through these abstract layers and then reaches the server side. Figure 6.5 shows
the RMI architecture.
Self-Instructional
114 Material
Client and Server
Applications Using RMI
NOTES
Self-Instructional
Material 115
Client and Server 6.15.3 Transport Layer
Applications Using RMI
The transport layer performs the tasks of managing the connection between the
client and the remote server machines. The transport layer receives request from
NOTES the remote reference layer at the client side and transmits the request to the remote
reference layer at the server side. In addition to establishing the connection between
the client and server machine, the transport layer needs to manage and monitor
the connection between the two. Transport layers manage the connection between
the client and server, which are based on various transport protocols such as
TCP/IP protocol.
Table 6.2 lists the difference between the socket programming and RMI
programming.
Table 6.2 Socket programming and RMI programming
Self-Instructional
116 Material
Client and Server
Applications Using RMI
Check Your Progress
3. What happens in case of a passing remote object?
4. Which class is the parent class of all the RMI specific exception classes? NOTES
6.18 SUMMARY
Self-Instructional
Material 117
Client and Server The client needs to capture a stub object to send requests to the object
Applications Using RMI
present on the server.
You can pass and retrieve any object through a remote call including those
that implement the Remote interface.
NOTES
In case of passing remote object, only the methods defined in the remote
interface can be accessed through the stub.
In any distributed application, catching exception is a difficult and mandatory
process because an exception can occur at the client object or the server
object or an exception can be raised because of a network error.
The Remote Exception class is the parent class of all the RMI specific
exception classes.
All the files in the Customer application created earlier are stored locally in
a folder to find any error in the RMI application.
Before saving the files at the client and server computer, create two folders,
client and server, on the local computer.
The client needs to define an interface that contains the signatures of the
methods of the server class available to the client to be accessed.
The server itself can make a remote call back to the client such as sending
a warning for an error, a progress feedback or sending a message from one
client to another.
To execute the RMI application over the network, you need to place the
required class files at the locations that can be accessed by the server and
the clients.
The Server Class extends the UnicastRemoteObject class of the
rmi package. The Server class is initially compiled with javac to
create .class files.
The registry is a remote objects that maps the String names passed to it to
the remote objects.
To pass the name of the client from the server to the applet, you need to
pass the client name as the parameter to the applet.
During the Remote Method Invocation (RMI) call, the client requests a
service from a server and the server processes the request.
Application layer is used to define Java programs written on the client side
and the server side to call a remote method.
The transport layer performs the tasks of managing the connection between
the client and the remote server machines.
Self-Instructional
118 Material
Client and Server
6.19 KEY WORDS Applications Using RMI
Short-Answer Questions
1. Name the four types of Exception thrown by RMI object methods.
2. List the files that are required by the server.
3. Write down the Abstract layers of RMI architecture.
4. What is the major difference between Socket programming and RMI
programming?
5. Name the tool to create the skeleton classes automatically.
Long-Answer Questions
1. What is RMI?
2. How are parameters passed from the client to the server?
3. Which class is extended to create an RMI server?
4. Which tool is used to create the stub and skeleton classes automatically?
5. Where and how the server registers the objects?
6. What is the Callback mechanism?
7. Write a program to implement RMI where the remote method is used to
display the sum of two numbers passed as command line arguments during
execution of the program at the client side.
8. Write a program to display Hello World message while implementing RMI
using applets.
Self-Instructional
Material 119
Client and Server
Applications Using RMI 6.21 FURTHER READINGS
Naughton, Patrick and Herbert Schildt, The Complete Reference Java 2, Third
NOTES Edition.
Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.
Self-Instructional
120 Material
BDK and JAR Files
BLOCK - III
BDK AND DESIGN PATTERNS
NOTES
UNIT 7 BDK AND JAR FILES
Structure
7.0 Introduction
7.1 Objectives
7.2 Java Beans
7.3 Java Archive File (JAR)
7.4 Introspection
7.5 Answers to Check Your Progress Questions
7.6 Summary
7.7 Key Words
7.8 Self Assessment Questions and Exercises
7.9 Further Readings
7.0 INTRODUCTION
A Java Bean is a specially constructed java class written in the Java and coded
according to the JavaBeans API specifications. A bean encapsulates many objects
into one object, so we can access this object from multiple places. Moreover, it
provides the easy maintenance. JavaBeans can also be referred to as Java classes
which adhere to an extremely simple coding convention. In this unit, you will learn
about Bean development, JAR and introspection in detail.
7.1 OBJECTIVES
Self-Instructional
Material 121
BDK and JAR Files applets, applications etc. These core components have the characteristics of
reusability and are self-contained and are known as beans.
The official definition of a bean, as given in the Java Beans specification, is:
“A bean is a reusable software component based on Sun’s JavaBeans specification
NOTES
that can be manipulated visually in a builder tool.”
These software components or beans are developed, but run and reused
everywhere as per the requirements .There are various softwares like NetBeans
,JBuilder , BDK , etc. which can help you out to unleash the power of beans –
reusability. The JavaBeans component architecture is backed upon by the set of
APIs called the JavaBeans API specification that deals with the internal
sophistication of this model.
Java Beans are dynamic components and also very crucial implementations
to be dealt with. Dynamic in the sense that you can easily change their nature and
customize them as per your need .For this the design mode of a builder tool can
be used for visual manipulation. Simply, choose a bean from the toolbox, drag and
drop it into a form, restructure its appearance and behaviour, define its interaction
with other beans, and combine it with other beans into an applet, application, or a
new bean.
Some Bean Facts
1. A Java Bean is a reusable and self-contained software component that
inherits the basic implementations from sun’s java bean specification.
2. A Java Bean is a not only reusable but also customizable and can be easily
manipulated visually in a builder tool.
3. The Builder tool is an application development tool which helps you to
build new beans or reuse the pre-existing ones to develop an application
visually.
4. Java Beans help to create simple components first which can be then
reutilised to produce comparatively some more complex components or
applications using the builder tools like NetBeans etc.
5. These builder tools are moreover like IDEs that determine a bean’s features
like its properties, methods, and events .The process of discovering these
facts about the beans is called introspection. There are two ways for Beans
support introspection:
(i) Just adhere to some specific rules, known as design patterns, when
naming bean features. The Introspector class checks the beans for
these design patterns explore out all the bean features.
(ii) And the other method is to explicitly provide all the basic information
like property, method, and event information with a related bean
information class. A bean information class implements the Bean
Self-Instructional
122 Material
Info interface. A BeanInfoclass explicitly lists those bean features that BDK and JAR Files
Self-Instructional
124 Material
The Java Bean components can exist in either of the following three phases BDK and JAR Files
Self-Instructional
Material 125
BDK and JAR Files Features of a Java Bean
1. Java bean supports “introspection”; it helps a builder tool analyse how a
bean works by inspecting its features.
NOTES 2. Java bean provides support for “customization” so that a developer can
easily customise the appearance and behaviour of a Java Bean and create
a new from the existing one.
3. Java beans supports “events” that act as a glue to bind two or more beans.
4. Java beans have “properties” that can be used for both customization and
for programmatic use.
5. Java beans support “persistence”, which is a mechanism of storing the
bean state initially and restoring later on need.
Self-Instructional
126 Material
Identifying BDK Components BDK and JAR Files
Execute the run.bat file of BDK to start the BDK development environment.
NOTES
Fig. 7.2 Run.bat file of BDK to start the BDK development environment
Now, you will learn about the different components of the bean development
kit.
1. ToolBox window: A window that consists of the lists of sample
JavaBeans of BDK available to be reused to build up an application.
Self-Instructional
Material 127
BDK and JAR Files Below is the figure that shows the ToolBox window with various pre-
built beans:
NOTES
Self-Instructional
130 Material
BDK and JAR Files
7.3 JAVA ARCHIVE FILE (JAR)
JAR file allows you to efficiently deploy a set of classes and their associated
resources. JAR file makes it much easier to deliver, install, and download. It is NOTES
compressed. The files of a Java Bean application are compressed and grouped as
JAR files to reduce the size and the download time of the files.
The syntax to create a JAR file from the command prompt is:
jar <options> <file_names>
The file_names is a list of files for a Java Bean application that are stored in
the JAR file.
The various options that you can specify while creating a JAR file are:
c: Indicates the new JAR file is created.
f: Indicates that the first file in the file_names list is the name of the JAR
file.
m:Indicates that the second file in the file_names list is the name of the
manifest file.
t: Indicates that all the files and resources in the JAR file are to be displayed
in a tabular format.
v: Indicates that the JAR file should generate a verbose output.
x: Indicates that the files and resources of a JAR file are to be extracted.
o: Indicates that the JAR file should not be compressed.
m:Indicates that the manifest file is not created.
Self-Instructional
Material 131
BDK and JAR Files
7.4 INTROSPECTION
Introspection is a technique which helps to retrieve the vital information about the
NOTES Java beans like what features does it have(bean properties), how it will
behave(bean methods) and what it can really be used for (bean events) etc.
Introspection is actually an analysis of bean capabilities so as to know what the
bean is capabale to do. Implementation of introspection is an automatic process in
bean builder tool to introspect which properties, methods, and events a bean
supports. It is an eminent process, without which you can never imagine to unleash
the real power of a Java Bean and utilize it further.
BDK Introspection
To automatically analyse the properties of a Java Bean, BDK Introspection is
done. It allows the builder tool to analyse the functioning of the bean. It can be
defined as the mechanism that allows the bean classes to publish their operations
and properties that they support along with a meta-mechanism which leads to the
discovery of such mechanisms. Introspection can be defined as the technique of
obtaining information about bean properties, events and methods or in short, it is
the analysis of bean capabilities as what it can do.
There are two ways in which the developer of a Bean can indicate which of
its properties, events, and methods should be exposed by the builder tool.
1. First one uses the mechanism of naming conventions that allows the
introspection mechanisms to infer information about a Bean.
2. Secondly, an additional class which contains the basic information is
provided that explicitly provides this information to the builder tools.
Self-Instructional
132 Material
2. A Java Bean is a reusable and self-contained software component that inherits BDK and JAR Files
7.6 SUMMARY
Self-Instructional
Material 133
BDK and JAR Files
7.7 KEY WORDS
Short-Answer Questions
1. What are Java Beans? Discuss its uses.
2. Discuss the benefits of using Java Beans.
3. Analyse the Composition of a Java Bean.
Long-Answer Questions
1. Explain the power and capabilities of Java Bean.
2. Write a detailed note on Java Archive File (JAR) file.
3. What are the components of a Java Bean? Support your answer with a
diagrammatic representation.
Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.
Self-Instructional
134 Material
Design Patterns and
EVENT HANDLING
NOTES
Structure
8.0 Introduction
8.1 Objectives
8.2 Design patterns for Java Bean Properties
8.3 Introducing Event Handling
8.3.1 Event Classes
8.3.2 Sources of Events
8.3.3 Event Listener Interfaces
8.4 Process of Handling Events
8.4.1 ActionListener
8.4.2 AdjustmentListener
8.4.3 MouseListener
8.4.4 MouseMotionListener
8.4.5 WindowListener
8.4.6 KeyListener
8.5 Answers to Check Your Progress Questions
8.6 Summary
8.7 Key Words
8.8 Self Assessment Questions and Exercises
8.9 Further Readings
8.0 INTRODUCTION
8.1 OBJECTIVES
NOTES Defining a bean’s state means defining a property which can depict its state. A
bean property can be considered as a named attribute of a bean that can be used
to define its behaviour or appearance like colour, label, font, font size, and display
size, etc. Bean’s properties are private data members of the Java Bean classes
and can be used to take input from a user that can be implemented to customize a
Java Bean accordingly. These bean properties can access and determine the values
of various attributes, which in return define the behaviour of a Java Bean. On the
basis of the values they deal with, the number of values they take, the Java Beans
Properties can be listed as followings:
1. Simple properties
2. Boolean properties
3. Indexed properties
4. Bound Properties
5. Constrained Properties
Simple Properties
These properties are called simple as they have only a single value and are simple
to use. The getter and setter methods - getXXX() and setXXX() methods are
used to retrieve and specify values. A read/write property has both of these getter
and setter methods to access its values. The getXXX() methods are used to read
the value of the property specified while the setXXX() methods are used to set
the value of the property as defined. The getter and setter methods are also called
accessor methods and are used to set the property.
The syntax of get method is:
public return_type get<PropertyName>()
public T getN();
public void setN(T arg)
N is the name of the property and T is its type
Ex:
public double getWeight()
{
return Weight;
}
Read only property has only a get method.
The syntax of set method is:
public void set<PropertyName>(data_type value)
Self-Instructional
136 Material
Ex: Design Patterns and
Event Handling
public void setWeight(double d)
{
Weight=d;
NOTES
}
Note: The write only property has only a set method.
Boolean Properties
We know there are two specific Boolean values that are used in programs - True
and False. Hence, the property that is used to denote/use either of these values is
known as the Boolean Property of the bean.
Syntax
Let N be the name of the property and T be the type of the value then
public boolean isN();
public void setN(boolean parameter);
public Boolean getN();
public boolean is<PropertyName>()
public boolean get<PropertyName>()
First or second pattern can be used to retrieve the value of a Boolean.
public void set<PropertyName>(boolean value)
For getting the values isN() and getN() methods are used and for setting the
Boolean values setN() method is used.
Ex:
public boolean dotted=false;
public boolean isDotted()
{
return dotted;
}
public void setDotted(boolean dotted)
{
this.dotted=dotted;
}
Indexed Properties
Some bean properties contains multiple values. These properties are called Indexed
Properties. Suppose a property holds an array of values, then such a property is
an indexed property. An indexed property may expose set/get methods to read/
write one element in the array (so-called ’index getter/setter’) and/or so-called
’array getter/setter’ which read/write the entire array. Indexed Properties enable
you to set or retrieve the values from an array of property values. Indexed Properties
are retrieved using the following get methods: Self-Instructional
Material 137
Design Patterns and Syntax: public int[] get<PropertyName>()
Event Handling
Ex:
private double data[];
public double getData(int index)
NOTES
{
return data[index];
}
Syntax: public property_datatype get<PropertyName> (int
index)
Ex:
public void setData(int index,double value)
{
Data[index]=value;
}
**Indexed Properties are specified using the following
set methods:
changes.addPropertyChangeListener(p);
}
NOTES
public void
removePrertyChangeListener(PropertyChangeListener p)
{
changes.removePropertyChangeListener(p);
}
PropertyChangeListener is an interface declared in the java.beans package
having only one method i.e public void propertyChange(PropertyChangeEvent
e ) .Those who wish to be notified about the property changes must implement
this interface explixcitly..
public interface PropertyChangeListener extends
EventListener
{
public void propertyChange(PropertyChangeEvent e );
}
Constrained Properties
Constrained means “making more restrictive” .Constrained properties hence are
specifically restrictive and are implemented using the PropertyChangeEvent class,
and generates an event when its value is modified. The event thus generated is then
delegated to objects that had pre-registered to get any notification about the change
in the value of the property. These objects have the ability to veto the proposed
change and are capable of rejecting any unwanted changes.
Constrained properties are secure properties as they are protected from
being modified by other Java Bean classes. Constrained Properties are registered
with an external event listener that has the ability to either approve or reject the
change in the value of a constrained property. Constrained Properties can be
retrieved using the getter methods. The prototype of the get method is:
Syntax: public string get<ConstrainedPropertyName> ()
It can be specified using the set method. The prototype of the set method is:
Syntax: public string set<ConstrainedPropertyName> (String
str)throws PropertyVetoException
Self-Instructional
Material 139
Design Patterns and
Event Handling 8.3 INTRODUCING EVENT HANDLING
An event occurs when there is a change in the active state of components, such as
NOTES buttons and text boxes. Examples of events are when the end user clicks a button
or enters text in a textbox. Event handling is the process to monitor any change in
the state of an object and perform a corresponding action. These actions are
created in form of modules or functions and can further lead to events.
This unit describes the classes and interfaces in Java for handling events.
This unit explains the process to handle events. It also explains how to implement
the several interfaces provided by Java to handle events. This unit describes the
Adapter classes and how Adapter classes can be used for handling events.
Fundamentals of Event Handling in Java
Java uses a model called the event delegation model to handle events. Java provides
several event classes, such as ActionEvent and ItemEvent that define
event objects. A different event object represents a different type of an event, for
example ActionEvent class represents the event where an end user clicks a
button. The object of an ItemEvent class may represent the selection of a
radio button. Java also provides several interfaces that allow you to monitor events
that occur when the end user interacts with the Java Abstract Window Toolkit
(AWT) components.
Event Delegation Approach
The event delegation model defines the standards and mechanisms to handle events
in Java. The event delegation model is made up of three components:
Source: Generates an event.
Event: Describes the change in the source and is generated by the source.
Event Listener: Receives and processes an event.
The user interface generates the event and the event listeners. Both the
events and event listeners are a part of the application logic that handles the events.
The event delegation model handles these events and event listeners separately. In
the event delegation model, a listener can receive an event notification after it is
registered with the source.
Events are the objects in an event delegation model that are generated when
the end user interacts with the AWT components, such as buttons, checkboxes
and text fields. Events are also generated from end-user input through the keyboard
and mouse. A source generates an event when the internal state of an object
changes. The source also registers event listeners so that the event listeners can
receive notification when an event is generated. Event listener is an object that
waits for an event to occur. When an event is triggered, an event listener is notified
by the source to which it is registered. Event listeners implement methods that
receive events and perform actions corresponding to events. Figure 8.1 shows the
Self-Instructional event delegation model.
140 Material
Design Patterns and
Event Handling
NOTES
Self-Instructional
142 Material
Design Patterns and
InputMethod Contains INPUT_METHOD_FIRST Event Handling
Event information about INPUT_METHOD_TEXT_
text, which is CHANGED
composed using an
input method. If the CARET_POSITION_CHANGED
text changes, then
NOTES
INPUT_METHOD_LAST
the input method
sends an event to the
event handler.
Self-Instructional
Material 143
Design Patterns and
Event Handling MouseWheel Is generated when WHEEL_BLOCK_SCROLL
Event an end user rotates
WHEEL_UNIT_SCROLL
the mouse wheel.
MouseWheelEve
nt is the subclass of
NOTES the MouseEvent
class.
Self-Instructional
146 Material
Design Patterns and
WindowFocus Defines two methods, addWindowFocus
Event Handling
Listener windowGainedFocus() Listener(ref);
and windowLostFocus()
that receive an argument of
the WindowEvent class.
NOTES
WindowListener Defines seven methods: addWindowListener
windowActivated(), (ref);
windowDeactivated(),
windowIconified(),
windowDeiconified(),
windowClosed(),
windowOpened(),
windowClosing(). All
these methods receive an
argument of the
WindowEvent class.
The delegation model explains how event handling takes place in Java. You can
map the event delegation model to the actual Java statements that are used for
handling events. For example, when an end user clicks an AWT button, a message
is displayed in the text field. The source in this case is the AWT button that the end
user interacts with. The event listener that receives and processes the button click
event in the example is the ActionListener interface. The class you will
create to handle this event should implement the ActionListener interface.
The A c t i o n L i s t e n e r interface defines a single method,
actionPerformed() that you will need to define within the class. The syntax
of the user-defined class to handle event is:
public class EventExample extends Applet implements
ActionListener
{
public void init()
{
}
public void actionPerformed(ActionEvent ae)
{
}
}
The above syntax shows a class that implements the ActionListener
interface and defines the actionPerformed() method.
Self-Instructional
Material 147
Design Patterns and You will need to register the ActionListener interface to the button
Event Handling
after creating the AWT button. The addActionListener(reference)
method is used for registering the ActionListener interface. The syntax of
the user-defined class to register event is:
NOTES public class EventExample extends Applet implements
ActionListener
{
Button b1;
public void init()
{
b1=new Button(“Message”);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
}
}
The above syntax shows how to use the
addActionListener()method to register the AWT button, which is the
source to the ActionListener interface, which is the event listener.
The following program code shows the complete program to display a
message in the text field when a button is clicked:
Using Event Handling
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code=”EventExamp” width=200 height=200>
</applet>*/
public class EventExamp extends Applet implements
ActionListener
{
TextField t1;
Button b1;
public void init()
{
t1=new TextField(20);
b1=new Button(“Message”);
b1.addActionListener(this);
add(t1);
add(b1);
Self-Instructional
148 Material
} Design Patterns and
Event Handling
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
NOTES
{
t1.setText(“Event Handling in Java”);
}
}
}
The above code shows a process defined in the actionPerformed()
method that displays a message in the Text Field. The object, ae, is the object of
the ActionEvent class that is received by the actionPerformed()
method when the button click event occurs.
Figure 8.2 shows the output.
8.4.1 ActionListener
The ActionListener interface declares a method that is called when an
action event is generated. The method defined in ActionListener interface
is a single method, void actionPerformed(ActionEvent ae). You
use the ActionListener interface when you handle events, such as clicking
AWT buttons. The addActionListener() method enables tracing a button
object for the occurrence of an action event. The following program code shows
how to implement the ActionListener interface:
Implementing ActionListener Interface
import java.awt.*;
import java.awt.event.*;
Self-Instructional
Material 149
Design Patterns and import java.applet.*;
Event Handling
/*<applet code=actlistn height=300 width=300>
</applet>*/
public class actlistn extends Applet implements
NOTES ActionListener
{
Button b1,b2,b3,b4;
public void init()
{
b1=new Button(“RED”);
b1.setBackground(Color.red);
b2=new Button(“BLUE”);
b2.setBackground(Color.blue);
b3=new Button(“GREEN”);
b3.setBackground(Color.green);
b4=new Button(“YELLOW”);
b4.setBackground(Color.yellow);
setLayout(new BorderLayout());
add(b1,”North”);
add(b2,”South”);
add(b3,”East”);
add(b4,”West”);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
Object ob=ae.getSource();
if(ob==b1)
setBackground(Color.red);
if(ob==b2)
setBackground(Color.blue);
if(ob==b3)
setBackground(Color.green);
if(ob==b4)
setBackground(Color.yellow);
}
}
Self-Instructional
150 Material
The above program code shows implementing the ActionListener Design Patterns and
Event Handling
with the instances of AWT Button class. Border layout is set to the applet window
and four button objects, RED, BLUE, GREEN and YELLOW are created. When
you click a button the color of background of the window changes to the color of
the button label. Figure 8.3 shows the output of the above program code. NOTES
8.4.2 AdjustmentListener
Adjustmentlistener is responsible for handling all the events that are
generated when an end user moves the scrollbar. The various integer constants
used by the adjustment listener method are:
BLOCK_DECREMENT
BLOCK_INCREMENT
TRACK
UNIT_DECREMENT
UNIT_INCREMENT
ADJUSTMENT_VALUE_CHANGED
8.4.3 MouseListener
The MouseListener interface defines five methods for handling different
operations that are associated with a mouse. These methods are:
void mouseClicked(MouseEvent me): Is invoked when
you click a mouse button.
Self-Instructional
Material 151
Design Patterns and void mouseEntered(MouseEvent me): Is invoked when the
Event Handling
mouse enters an AWT object to which the mouse event is associated.
void mouseExited(MouseEvent me): Is invoked when the
mouse leaves an AWT object to which the mouse event is associated.
NOTES
void mousePressed(MouseEvent me): Is invoked when the
mouse key is pressed.
void mouseReleased(MouseEvent me): Is invoked when
the mouse key is released.
The addMouseListener() method is used for monitoring an AWT
object for the occurrence of a mouse event. The following program code shows
how to implement the MouseListener interface:
Implementing the MouseListener Interface
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code = mouslstn width = 400 height = 300></
applet>*/
public class mouslstn extends Applet implements
MouseListener
{
String msg=””;
int mx = 0, my = 0;
public void init()
{
addMouseListener(this);
}
Self-Instructional
154 Material
} Design Patterns and
Event Handling
public void mouseMoved(MouseEvent me)
{}
NOTES
public void update(Graphics g)
{
paint(g);
}
Self-Instructional
Material 155
Design Patterns and 8.4.5 WindowListener
Event Handling
The WindowListener interface defines seven methods for handling window
events. An application of the WindowListener interface is to close a Frame
NOTES window. The seven methods of the WindowListener interface are:
void windowActivated(WindowEvent we): Is invoked
when a window is activated.
void windowDeactivated(WindowEvent we): Is invoked
when a window is deactivated.
void windowOpened(WindowEvent we): Is invoked when a
window is opened.
void windowClosed(WindowEvent we): Is invoked when a
window is closed.
void windowClosing(WindowEvent we): Is invoked when
an end user clicks the close button in a window.
void windowIconified(WindowEvent we): Is invoked
when a window is minimized.
void windowDeiconified(WindowEvent we): Is invoked
when a window is restored.
The addWindowListener() method enables monitoring a window
for the occurrence of a window event. The following program code shows how to
implement the WindowListener interface:
Implementing the WindowListener Interface
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class windowlistn extends Frame implements
WindowListener
{
Label l1,l2;
TextField t1,t2;
Button b1;
public windowlistn()
{
super(“Implementing Window Listener”);
setLayout(new GridLayout(4,2));
l1=new Label(“Name”);
l2=new Label(“Password”);
Self-Instructional
156 Material
t1=new TextField(10); Design Patterns and
Event Handling
t2=new TextField(10);
t3.setEchoChar(‘*’);
b1=new Button(“Send”);
NOTES
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
addWindowListener(this);
}
public static void main(String ar[])
{
windowlistn d=new windowlistn();
d.setSize(400,400);
d.setVisible(true);
}
public void windowClosing(WindowEvent we)
{
this.setVisible(false);
System.exit(0);
}
public void windowActivated(WindowEvent we)
{}
public void windowDeactivated(WindowEvent we)
{}
public void windowOpened(WindowEvent we)
{}
public void windowClosed(WindowEvent we)
{}
public void windowIconified(WindowEvent we)
{}
public void windowDeiconified(WindowEvent we)
{}
}
The above code shows closing a Frame window using the
WindowListener interface. The windowClosing() method uses the
setVisible method to close the frame window. The System.exit(0)
method stops the program from running.
Self-Instructional
Material 157
Design Patterns and Figure 8.6 shows the output.
Event Handling
NOTES
8.4.6 KeyListener
The KeyListener interface declares methods that handle input from the
keyboard. The methods defined in the KeyListener interface are:
void keyPressed(KeyEvent ke): Is called when an end user
presses a key on the keyboard.
void keyReleased(KeyEvent ke): Is called when an end
user releases a key on the keyboard.
void keyTyped(KeyEvent ke): Is called when an end user
types a key on the keyboard, which is the operation of pressing and releasing
the key in one fast action.
The requestFocus() method of the Component class has to be
included in your program for receiving keyboard events. The
addKeylistener() method is used for monitoring keyboard events on
objects. The following program code shows how to use the KeyListener
interface for handling events:
Implementing the KeyListener Interface
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=”test” width=”300" height=”200">
</applet>*/
Self-Instructional
158 Material
public class test extends Applet implements KeyListener Design Patterns and
Event Handling
{
String msg[]={“”,””,””,””,””,””,””,””,””,””};
int x=15;
NOTES
int c=x;
int y=15;
int i=0;
public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke)
{
System.out.println(msg);
if(c<200)
{
c=c+5;
msg[i]+=ke.getKeyChar();
System.out.println(msg);
}
else
{
x=15;
y=y+20;
c=x;
i=i+1;
msg[i]+=ke.getKeyChar();
}
if(i>9)
{
for(int k=0;k<10;k++)
{
msg[0]=””;
}
x=15;
y=15;
c=x;
i=0;
Self-Instructional
Material 159
Design Patterns and }
Event Handling
repaint();
}
public void keyReleased(KeyEvent ke)
NOTES
{}
public void keyTyped(KeyEvent ke)
{
}
public void paint(Graphics g)
{
g.drawString(msg[i],x,y);
System.out.println(msg);
}
public void update(Graphics g)
{
paint(g);
}
}
The above code shows implementing the KeyListener Interface for
accepting input from the keyboard to the applet window. The getKeyChar()
method enables taking input from the keyboard and displaying the information in
the applet window. The keyPressed method is used for defining the statements
that are run when an end user enters input from the keyboard.
Figure 8.7 shows the output.
1. Event are activities that interrupts the normal flow of the current ongoing
activity.
2. Constrained Properties are the properties that are protected from being
changed by other Java Beans.
3. The ActionListener interface declares a method that is called when
an action event is generated. The method defined in ActionListener
interface is a single method, void a c t i o n P e r f o r m e d
(ActionEvent ae).
4. The addMouseListener() method is used for monitoring an AWT
object for the occurrence of a mouse event.
8.6 SUMMARY
Defining a bean’s state means defining a property which can depict its state.
A bean property can be considered as a named attribute of a bean that can
be used to define its behaviour or appearance like colour, label, font, font
size, and display size, etc.
An event occurs when there is a change in the active state of components
such as buttons and text boxes.
The event delegation model defines the standards and mechanisms to handle
events in Java.
Events are the objects in an event delegation model that are generated when
the end user interacts with the AWT components such as buttons,
checkboxes and text fields. Events are also generated from end-user input
through the keyboard and mouse.
The EventObject class is the super class for handling all events. This
class exists in the package, java.util.
Self-Instructional
Material 161
Design Patterns and AWT components such as buttons and text boxes are the sources of events.
Event Handling
The event listeners are the interfaces in Java that define the methods for
handling events.
NOTES The ActionListener interface declares a method that is called when
an action event is generated. The method defined in ActionListener
interface is a single method, void a c t i o n P e r f o r m e d
(ActionEvent ae).
The addMouseListener() method is used for monitoring an AWT
object for the occurrence of a mouse event.
MouseMotionListener is another built-in interface for handling
mouse events. This interface handles events that are associated with the
movement of the mouse.
An application of the WindowListener interface is to close a Frame
window.
Short-Answer Question
1. What do you understand by event delegation model in Java Beans?
2. How do you create event listeners?
3. What are the design patterns for Java Bean properties?
Long-Answer Questions
1. Write a detailed note on indexed properties.
2. What are events? How do you create custom events?
3. Write a detailed note on simple properties.
Self-Instructional
162 Material
Design Patterns and
8.9 FURTHER READINGS Event Handling
Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill. NOTES
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.
Self-Instructional
Material 163
Bean Properties and
Persistence
UNIT 9 BEAN PROPERTIES AND
PERSISTENCE
NOTES
Structure
9.0 Introduction
9.1 Objectives
9.2 Bound and Constrained Properties
9.2.1 Persistence
9.2.2 Customization
9.2.3 Bean Conventions
9.2.4 A Simple Bean
9.3 The Java Beans API
9.4 Answers to Check Your Progress Questions
9.5 Summary
9.6 Key Words
9.7 Self Assessment Questions and Exercises
9.8 Further Readings
9.0 INTRODUCTION
A Java Bean property is constrained when any change to that property can be
vetoed. Usually an outside object exercises the right to veto. However, in some
cases the Bean itself can also veto a property change. The JavaBeans API provides
an event mechanism. This mechanism is very similar to the bound property
mechanism that allows objects to veto a Bean’s property changes. The design
pattern for setting and getting constrained properties is similar to the design pattern
for properties that are not constrained. The difference is that the set method declares
that it throws the exception. In this unit you will study about Constrained Properties
9.1 OBJECTIVES
A bound property is a property that generates an event when its value is changed.
A bean provides this notification by following methods.
Self-Instructional
164 Material
public void Bean Properties and
addPropertyChangeListener(PropertyChangeListener p) Persistence
{
changes.addPropertyChangeListener (p);
NOTES
//provides notification when an attempt is made
//to change the bound property
}
public void
removePropertyChangeListener(PropertyChangeListener p)
{
changes.removePropertyChangeListener (p);
//to remove listener
}
Note: The PropertyChangeListener is an interface that is declared in java.beans
package.
A constrained property is a property that notifies other objects or
components when attempts are made to change their values. When other component
is not agreed to the change of the property it throws
PropertyVetoException. Following are the methods provided by
constrained properties.
public void addVetoableChangeListener
(VetoableChangeListener v)
{
vetos.addVetoableChangeListener (v);
}
public void removeVetoableChangeListener
(VetoableChangeListener v)
{
vetos.removeVetoableChangeListener (v);
}
9.2.1 Persistence
As stated earlier, a bean is a reusable software component that can be used in
other applications. To use it in other applications and to make it portable, its state
should be saved to the non volatile storage from where it can be retrieved later.
The process of saving the current state of bean is referred to as persistence.
Persistence can be achieved by serializing a bean. A bean can be serialized
by implementing the java.io.Serializable interface. This interface is
a marker interface that makes serialization automatic. In case a bean does not
implement the java.io.Serializable interface, serialization must be
Self-Instructional
Material 165
Bean Properties and provided explicitly by implementing the java.io.Externalizable
Persistence
interface.
Note: Object serialization is a method of converting an object into data stream.
Self-Instructional
166 Material
ename = s; Bean Properties and
Persistence
}
public int getEid()
{
NOTES
return eid;
}
public void setEid(int i)
{
eid = i;
}
}
The explanation of this program is as follows:
The statement package com.start.bean.test is the
package statement.
The statement public class SimpleBeanExample
implements java.io.Serializable defines a class
named S i m p l e B e a n E x a m p l e that implements the
Serializable interface to provide persistence to the bean. Note
that the Serializable interface does not contain any method.
The statements private String Ename = null and
private int Eid = 0 declare properties of the bean. The
properties are declared private, thus, are not accessible directly by other
classes.
The statement public SimpleBeanExample(){} creates
an empty constructor. For behaving Java class as a bean, this is the
basic requirement.
The methods getEname()and setEname()are the getter and
setter methods respectively of property Ename.
Like any other Java class file, compile the bean. Upon compilation,
SimpleBeanExample.class file will be created.
The classes and interfaces related to the development of beans are contained in
the package java.beans. The beans use only few classes while running in an
application. For example, the event classes are used by beans that generate
PropertyChangeEvent and VetoableChangeEvent. Most of the
classes in this package are used by a bean editor to customize and put beans
together to create an application. These classes enable the bean editor creating a
user interface that can be used by a developer to customize the bean.
Self-Instructional
Material 167
Bean Properties and Table 9.1 The Interfaces Defined in java.beans Package
Persistence
Interface Description
AppletInitializer It is designed to provide a mechanism for the
NOTES initialization of Java Beans that are applets.
BeanInfo It is implemented to provide explicit information
about the methods, properties, events, etc., of a
Bean.
Customizer It provides a complete custom GUI using which a
Java Bean can be customized.
DesignMode It allows determining whether a Bean is executing
in design mode.
ExceptionListener A method exceptionThrown of this interface is
invoked when an internal exceptions occurs.
PropertyChangeListener A method PropertyChangeEvent of this
interface gets fired whenever a bean changes a
bound property.
PropertyEditor It provides support for GUIs that allow users to
change a property value of a given type.
VetoableChangeListener A method VetoableChangeEvent of this
interface is invoked whenever a bean changes a
constrained property.
Visibility It enables a bean to run on servers where a GUI is
not available.
Class Description
BeanDescriptor It provides Bean specific information
including its Java class, its displayName,
etc.
Beans It provides methods to obtain general
information about a Bean.
DefaultPersistenceDelegate It is a concrete implementation of the
abstract PersistenceDelegate class
and is the delegate used by default for
classes about which no information is
available.
Encoder It is used to create streams that encode
the state of a collection of Java Beans in
terms of their public APIs.
EventHandler It provides support for dynamically
generating event listeners.
EventSetDescriptor It describes a group of events that a given
Java bean generates.
Self-Instructional
168 Material
Expression It encapsulates a call to a method that Bean Properties and
Persistence
returns a result.
FeatureDescriptor It is the base class for
PropertyDescriptor,
EventSetDescriptor, and NOTES
MethodDescriptor class.
IndexedPropertyChangeEvent An event of this type gets fired whenever
a Bean changes a bound indexed property.
IndexedPropertyDescriptor It describes a property that acts like an
array and has an indexed read and/or
indexed write method to access specific
elements of the array.
Introspector It provides a standard way to analyze
about the properties, events, and methods
supported by a Bean.
MethodDescriptor It describes a method that a Bean
supports for external access from other
components.
ParameterDescriptor It allows bean developer to provide
additional information about the
parameters of a method.
PersistenceDelegate It is used to express the state of an
instance of a given class in terms of the
methods in the class’s public API.
PropertyChangeEvent An event of this type is fired whenever a
bean changes a bound or constrained
property.
PropertyChangeListenerProxy It extends the EventListenerProxy
for implementing
PropertyChangeListener.
PropertyChangeSupport It is a utility class that is used by beans
that support bound properties.
PropertyDescriptor It describes one property that a Bean
exports using a pair of accessor methods.
PropertyEditorManager It is used to locate a property editor for
any given type name.
PropertyEditorSupport It provides functionality that helps in
building property editors.
SimpleBeanInfo It is a support class that helps to write
BeanInfo classes easily.
Statement It encapsulates a call to a method.
VetoableChangeListenerProxy It extends the EventListenerProxy
for associating a
VetoableChangeListener with a
constrained property.
Self-Instructional
Material 169
Bean Properties and VetoableChangeSupport It is a utility class that is used by beans
Persistence
that support constrained properties.
XMLDecoder It is used to read XML documents
created using the XMLEncoder .
NOTES XMLEncoder It allows to write a Bean to an XML
document.
IntrospectionException An IntrospectionException is
thrown when an exception occurs during
Introspection.
PropertyVetoException A PropertyVetoException is
thrown when a change to a property
indicates an unacceptable value.
9.5 SUMMARY
Self-Instructional
170 Material
Bean Properties and
9.6 KEY WORDS Persistence
Short-Answer Question
1. Define bound property.
2. What are constrained properties?
3. How will you achieve persistence?
Long-Answer Questions
1. Explain the methods provided by the constrained properties.
2. Explain the interfaces defined in java.beans package.
3. What are the classes defined in java.beans package? Explain.
Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.
Self-Instructional
Material 171
Java Servlets
BLOCK - I
SERVLETS
NOTES
UNIT 10 JAVA SERVLETS
Structure
10.0 Introduction
10.1 Objectives
10.2 Introduction to Java Servlets
10.2.1 Servlets Vs CGI
10.3 Servlet Developmental History
10.4 Prerequisites for Servlets
10.4.1 HTML
10.4.2 Servers
10.4.3 Servlet Container
10.4.4 Installing and Configuring the Apache Tomcat Server
10.4.5 Starting and Stopping Tomcat
10.4.6 Testing Tomcat
10.5 Basics of Servlets
10.5.1 The Java Servlet API
10.5.2 Servlet Life Cycle
10.6 Coding a Servlet
10.6.1 GenericServlet Class
10.6.2 An Example of GenericServlet Class implementation
10.6.3 The Dissection
10.6.4 Output
10.7 Http Servlet Class
10.7.1 Methods of Http Servlet Class
10.7.2 An Example of Http Servlet Class implementation
10.7.3 The Dissection
10.8 The First Run
10.9 First Web Application Using Servlet
10.10 A Web Application based on HTML Web Page and Servlet
10.11 A Web Application Handling User Inputs via Forms Using Servlets
10.12 Answers to Check Your Progress Questions
10.13 Summary
10.14 Key Words
10.15 Self Assessment Questions and Exercises
10.16 Further Readings
10.0 INTRODUCTION
Java servlets are the Java programs that are used to handle server-side operations
in client-server architecture. CGI scripts were used prior to Java servlet for client-
server computing. This unit discusses the servlet life cycle using various methods
Self-Instructional
172 Material
such as init(), service() and destroy(). It then describes the Java Servlets
generic servlets that are used to service the client request and http servlets, which
are used to service the server request.
NOTES
10.1 OBJECTIVES
Java has become an undoubtedly the best language for server side programming
due to Java Servlets. Java Servlets provide a standard way of server extension-
i.e. Servlets extend the functionality of the web servers to support dynamic content
generation. They reside in a Servlet container and generate dynamic contents in
response to client requests. The primary purpose of the Servlet specification is to
define a secure and robust mechanism for sending contents to a client as defined
by the Client/Server model. Servlets are most popularly used for generating dynamic
contents on the Web and have native support for HTTP. So, Servlets are now
essential parts of large web projects called web applications.
Java Servlets can be defined as the java programs, with an inbuilt support
to HTTP for getting requests and sending responses, which are implemented at
the server side for processing and creating dynamic contents for the client. These
are specialized java programs which do not have any main method, as their
implementation is the functionality of the web server where they reside. Java servlets
have native support to HTTP, and this is the biggest advantage that servlets have
used for their popularity by interweaving a complete specification across it.
With the introduction of the J2EE specification for enterprise applications,
Servlets have substituted every possible technology available for server side
programming as the primary interface for thin-client (browsers are universally
available thin clients) based web applications. The existing technologies like CGI,
ASP, and PHP did the same thing as Servlets–i.e. they too helped servers handle
Self-Instructional
Material 173
Java Servlets the client request and dynamically create responses accordingly, but Java Servlets
have some major advantages above all. A few of them can be highlighted as follows:
Servlets are persistent between invocations; hence improve the
performance drastically relative to CGI programs.
NOTES
Servlets are cent-percent portable across all the major operating systems
and servers available in the market.
Servlets pertains to J2EE specification, hence has access to all the Java
APIs be it Java Beans or database connectivity using JDBC APIs.
Java Servlets have always stood as a top performer in providing an efficient
and powerful solution for creating dynamic content for the Web. Hence, they are
also considered as the fundamental building block of mainstream server-side Java.
The efficiency and the power that Servlets have, has come from the use of
Java as a platform and from interaction with a Servlet container.
The Java platform provides a Servlet developer with robust APIs, object-
orientated programming methodology, platform independence, I18N
(Internationalization), strict types, garbage collection and above all, the security
features of the Java Virtual Machine (JVM). To complement this, the Servlet
container provides life cycle management, process to share and manage application-
wide resources, and help interact with a web server properly. This combination of
Java API support and Servlet container together makes Servlets a super desirable
technology for server-side programming.
So let’s begin with the Java Servlets basics and understand the key APIs of
Java Servlets that make them work. The latest version of Java Servlets is 3.1.
Self-Instructional
174 Material
10.2.1 Servlets Vs CGI Java Servlets
The table below explains why Servlets out performed CGI, the first server side
technology?
Table 10.1 Servlets Vs CGI NOTES
1. Servlets can link directly to the Web 1. CGI cannot directly link to Web
server. server.
2. Servlets can share data among each 2. CGI does not provide sharing
other. property.
3. Servlets can perform session tracking 3. CGI cannot perform session
and caching of previous tracking and caching of previous
computations. computations.
4. Servlets are portable. 4. CGI is not portable.
5. In Servlets, the Java Virtual Machine 5. In CGI, each request is handled by
stays up, and each request is handled a heavyweight operating system
by a lightweight Java thread. process.
6. Servlets automatically parse and 6. CGI need explicit parsing and
decode the HTML form data. decoding of the HTML form data.
7. Servlets can read and set HTTP 7. CGI cannot read and set HTTP
headers, handle cookies, tracking headers, handle cookies, tracking
sessions. sessions.
8. Servlets is platform independent, 8. CGI is platform dependent.
robust.
9. Follow OOPS principle as it is a Java 9. No such support for OOPS in
Specification. CGI.
10. Servlets do not support multiple 10. CGI Supports Multiple Languages
languages except Java. like C,C++,Perl etc.
The Servlets that we use today are far more powerful and dynamic than the one
that laid the foundation of the robust, multithreaded Server Side programming in
1970.Servlet specification has taken a long journey to reach to this level, and still
there are advancements and modifications that are continuing so that it can make
pace with the contemporary technological changes.
Self-Instructional
Material 175
Java Servlets The developmental history of Java Servlets can be seen in the table below:
Table 10.2 Servlet Developmental History
Servlet 2.4 J2EE 1.4, Nov 2003 Servlets now require HTTP/1.1 and J2SE
J2SE 1.3 (Java 2 Platform, Standard Edition) 1.3,
and can work with J2EE 1.4
ServletRequest has new methods to
observe the client connection
New support for internationalization and
charset choice
RequestDispatcher has new features and
clarifications
New ServletRequest listener classes and
methods
A deprecated SingleThreadModel
HttpSession details and interaction with
logins has been clarified
Class loading and welcome-file behavior
has been clarified
The web.xml file now uses XML Schema
and has added a slew of new elements
Servlet 2.3 J2EE 1.3, Aug 2001 1. Servlets now require JDK 1.2 or later
J2SE 1.2 2. A filter mechanism has been created
(finally!)
3. Application lifecycle events have
been added
4. New internationalization support has
been added
5. The technique to express inter-JAR
dependencies has been formalized
6. Rules for class loading have been
clarified
7. New error and security attributes
have been added
8. The HttpUtils class has been
deprecated
9. Various new helpful methods have
been added
10. Several DTD behaviors have been
expanded and clarified
Self-Instructional
176 Material
Servlet 2.2 J2EE 1.2, Mid 1999 Servlets are now part of the Java Java Servlets
J2SE 1.2 2 Platform, Enterprise Edition
specification
Servlets now embrace the notion
of pluggable Web applications,
which can be configured and NOTES
deployed in a server-independent
manner
Rules have been provided that
define how Servlets can be
distributed across multiple back-
end servers
Response output buffering has
been added
Control over HTTP headers has
been enhanced
New styles of request dispatching
have been added
More advanced error handling
can now be used
Several method signatures have
been changed to keep the API
consistent
Servlet 2.1 Unspecified Nov 1998 The API has been "cleaned up" to
make method names more
consistent and predictable
Servlets can now delegate request
handling to other server
components
Servlets can now share
information using their
ServletContext
There's a new way to abstract
servlet resources
Servlets now have more control
over session management
No direct servlet references
Servlet 2.0 JDK 1.1 1997-1998 Part of Java Servlet Development Kit 2.0
Servlet 1.0 June 1997 First specification release
Servlets are java programs, with an inbuilt support to HTTP for getting requests
and sending responses. Hence, one should be well acquainted with the Java
programming syntax and semantics apart from knowledge of HTTP methods. In
the previous chapter, enough material has been provided on HTTP and its methods.
Though we are going to program a server on client-server architecture, the language
of communication between the server and the client will be HTML, so one should
also know the basics of HTML as well for proper formatting of the display pages
(the responses). There is one more technology-XML (eXtensible Markup
Language) that you should know, though just a little but it will surely help in proper
execution of the Servlets. XML works as the interface between the Servlet and
the Server. A web.xml file is created for a Servlet which has the configuration
Self-Instructional
Material 177
Java Servlets details of the servlet that the server uses for its execution. Even if there is a single
error in the xml, then also your servlet will not execute as Server will not have the
information regarding the servlet. A separate chapter on XML has been included
in the book which will provide all that you need, so it will not be discussed here.
NOTES
So, the prerequisites for understanding the Servlets can be summarized as:
1. Java Programming syntax and semantics for coding the Servlets.
2. HTML Basics for form handling and response generation.
3. XML Basics for configuration of Servlet.
4. HTTP protocols and all its methods.
5. Server Basics like starting, deployment mechanics and shutting down
the Server along with server setup and configurations.
You will have to be well versed in Java Programming language before
proceeding further as it will be difficult for you to understand the logics and the
code. HTTP has already been discussed in the previous chapter. You will learn
about the other preliminaries like HTML, Servers, and XML in the coming sections
in the book. Now let’s see HTML in brief in this section itself aiding to the
understanding of servlet properly.
10.4.1 HTML
In this section, only the tags that have been used in the examples have been stated.
You will learn about the tags and their description here and uses in the examples of
the servlets.
HTML tag Description
1. <html>, </html>
Compulsory Tag
These tags mark the start and the end of an HTML document.
Every HTML document must start with this tag and also end with this
tag.
2. <head>, </head>
Optional Tag
This tag marks the start and end of the head section of an HTML
document.
3. <title>, </title>
Optional Tag
This tag is used to mark a title element. The text between the start and
end tags is shown in the title bar of the browser window.
Self-Instructional
178 Material
4. <body>, </body> Java Servlets
Compulsory Tag
This tag marks the start and end of the body section of an HTML
document which contains the content to be displayed on the web page. NOTES
The content of the document is provided between these tags.
5. <h1>, </h1>; <h2>, </h2> ; <h3>, </h3>
Optional Tags
These tags format the text between them as a level-1 heading,level-2
heading and level-3 heading respectively.
6. <form action=”url”, method=”method”> </form>
Optional Tags
This tag marks the start of a form. The action attribute specifies the
name of the page, servlet, etc. where the form is posted to. The method
attribute can be GET or POST; it indicates the type of HTTP request
sent to the server.
</form> Marks the end of the form. It is compulsory to close.
7. <input type=”type”, name=”name”>
Optional Tag
This tag helps to create an input field.
Specify type=”text” to create a text field or type=”submit” to create a
Submit button.
The name attribute provides the name you use in the program to retrieve
the data entered by the user.
8.
Represents a non breaking space.
Note: Try to create HTML web pages before implementing these tags in the Servlets
for better understanding and also run them on the browser for getting the realistic
feel.
10.4.2 Servers
Servlets do not have a main () method like their counterparts in core Java-the
applets or any simple Java program. So it is the server or the container who has to
take care of the proper execution of the servlet by invoking the Servlet methods.
As the servlet program will run only on a server, you should be familiar with the
various servers available and their configurations to run a servlet. So you might be
having a question why Servlets run only in a server and not as a standalone
application? It is because the Servlets form the extended API of Java Specifications
and are not bundled with the Java Standard Development Kit. Servers have the
Self-Instructional
Material 179
Java Servlets APIs that support the servlet execution and manage the various requirements of a
servlet hence it should be kept in the server context. Various servers that can be
used are as follows:
1. Oracle Weblogic Server
NOTES
2. J2EE server
3. Apache Tomcat HTTP Server
4. Jetty
5. JBoss
6. Glassfish Servers
10.4.3 Servlet Container
A servlet container is the application software that is used to run servlets. A servlet
container uses a Java Virtual Machine (JVM) to run servlet code as requested by
a web server. The main task of the Servlet container is to help a servlet properly
complete their lifecycle and perform specific tasks. The servlet container is also
responsible for managing user sessions, class loading, servlet contexts, servlet
configuration information, servlet persistence, and temporary storage apart from
the basic servlet lifecycle. As interaction with servlets occurs through a web browser,
these servlet engines aren’t useful on their own.
There are different types of servlet containers on the basis of their uses.
Some of them simply work as add-ons to existing web servers like JServ. Apache
JServ is a Servlets container (based on Servlet 2.0 Specification) that adds servlet
capability to the Apache Web Server. Some servlet engines include embedded
web servers like Jetty server and IBM’s WebSphere. Finally, there are some
more servlet engines that can be used either as standalone web servers or connected
to other servers, like Apache Tomcat server.
Apache Tomcat is the reference implementation for the Servlet API , all the
examples in this chapter have been tested using it.
So, in this section we will discuss the servers and their configurations as
needed. The most popular one to be used is Apaches Tomcat Server, though it
just acts as a container providing the servlet a support to all its life cycle methods-
i.e. can cater the basic needs of a servlet. But when it comes to high level support
like for connection pooling, database configurations, etc., Tomcat has an extreme
limitation. As Tomcat is a basic server, it can be used for general testing and
debugging the Servlets. And if any additional support is required it can be fulfilled
using Apache Tomcat HTTP server.
10.4.4 Installing and Configuring the Apache Tomcat Server
If you want to run servlet programs on your computer, you have to install a special
program called a servlet engine to convert your computer into a server which is
Self-Instructional
180 Material
capable of running the Servlets. The best-known and easily configurable servlet Java Servlets
engine is Apache Tomcat, which is open source software freely distributed by the
Apache Software Foundation at http://tomcat.apache.org.Tomcat simply works
as a basic web server. In actual production environments, Tomcat is usually used
in combination with a specialized web server, such as Apache’s HTTP Server. NOTES
Here are the steps you can follow to set up Tomcat
1. Download an executable setup from the Apache website (http://
tomcat.apache.org).
2. Double Click and install the setup. as instructed
Self-Instructional
Material 181
Java Servlets
NOTES
Fig. 10.4 Select all the options and then click on the Next Button
Change the Http/1.1 connector Port as 8888(If you wish you can keep
the same but it should not conflict with any existing application on the system.If
you wish give username and pasword also.click on the Next Button once you
are done.
Self-Instructional
182 Material
Java Servlets
NOTES
Fig. 10.6 Select the path of the Java SE. Click Next button
Self-Instructional
Material 183
Java Servlets
NOTES
Fig. 10.8 Now, you are ready for rocking. The Tomcat has successfully installed. Just
Click on Finish button. And you should see this
Fig. 10.9 If the progress completes without any error then your tomcat is ready to serve
as the server
3. Copy the “servlet-api.jar” file to the jre\lib\ext folder in your JDK root or
simply you can copy the address of servlet-api.jar to the environment variable
“classpath”. I prefer the latter. If you skip this step or copy the servlet-
api.jar file to the wrong place, you can’t compile your servlet programs. If
you get compiler messages complaining that the javax.servlet package
doesn’t exist, double-
Check this step to make sure you performed it right.
10.4.5 Starting and Stopping Tomcat
After you have successfully installed and configured Tomcat,
Go to Program Files => ApacheSoftwareFoundations =>Tomcat =>bin
=>Click on Tomcat7w.exe .
You will see the following window.
Self-Instructional
184 Material
Java Servlets
NOTES
Fig. 10.10 If this window displays Service Status: started then it means your tomcat is
running. If you wish to stop the services click on Stop and Apply.
Java Servlets can be defined as some platform independent, robust server side
NOTES programs coded in Java. These programs execute inside an application server or
a Java enabled web server. Some define servlet as a protocol used for execution
of server side java programs. Servlets can be regarded as server side applets also
as these are loaded and executed within the JVM of the server used which is
pretty similar to the applets which are loaded and executed within the JVM of the
browser (web client).Since no GUI is needed for Servlets, as they run inside a
server, they are often termed as faceless objects.
What CGI programs could not do, Servlets have performed them very
well-be it providing security, persistence between invocations or servicing a large
number of requests efficiently, Servlets have been the number one choice of the
web developers for all scenarios.
Servlets implement a request-response methodology, wherein the client
application sends a request to the server, server then forwards this request to the
servlet which generates responses according to the client’s requests and in due
course Servlets can also communicate with external resources like database servers
etc for fulfilling the client’s requests. These responses are then channeled to the
server which finally displays them to the client with additions like forms, etc.
The power of Java Servlets comes from the Java Servlet API which is a
standard interface between web server and web clients. These APIs are confined
only to the server, so are not present in the standard Java development Toolkits.
The Java Servlet API is a set of predefined Java classes which provides a standard
interface between client and the server.
The Java Servlet API is an extension API, which is not bundled or distributed
with the Java SDK; rather it is available as an additional package in any of the
servers-Tomcat, Weblogic, and Jetty etc as servlet-api.jar. Only thing that you
have to do is to show the operating system the path to that package so that operating
system can include them when required.
10.5.1 The Java Servlet API
The Java Servlet API is a set of Java classes, interfaces and methods which defines
a standard interface between a client and a web server. It is the specification that
every server and servlet has to comply with for proper execution of the Servlets.
We will be using the Java Servlet Development Kit API (JSDK) V2.1 conventions
throughout this chapter.
The Java Servlet API comprises of two packages:
javax.servlet
javax.servlet.http
Self-Instructional
186 Material
1. javax.servlet package Java Servlets
This javax.servlet package consists of the classes and interfaces that support generic
protocol independent Servlets. These Servlets include support to many protocols,
like HTTP and FTP. NOTES
This package consists of the main interface-the Servlet interface that contains
the basic lifecycle methods of a servlet which every servlet must implement.
GenericServlet class implements the Servlet interface. Hence, the implementation
of these life cycle methods (init (), service () and destroy ()) are itself provided in
a GenericServlet class except the service () method. This is because the task that
a servlet need to perform is to be written inside the service () method which is in
the discretion of the programmer not the server.
So, whatever you wish to do, you have to write it in the service () method
overriding it in your servlet by extending the GenericServlet class. If necessary,
you can override the remaining methods also. There are several interfaces and
classes found in this javax.servlet package.
They are as follows:
Interfaces:
1. Servlet interface: It is the main interface that every Servlet must implement.
It defines the key methods that a Servlet container calls to control the Servlet.
2. ServletRequest interface: This interface provides the methods to gather
information from a client request.
3. ServletResponse interface: This interface helps to provide various
methods to create and send the response to the client’s request.
Self-Instructional
Material 187
Java Servlets 4. ServletConfig interface: This interface allows the servlet container to
pass the configuration related information to a servlet.
5. ServletContext interface: This interface allows the servlet to communicate
with its container. Also called Communication Interface.
NOTES
6. SingleThreadModel interface: This interface is used to make a servlet
service one request at a time. Though it has been deprecated, it can be still
used in development.
Classes:
1. Abstract Class GenericServlet: Every Servlet has to extend this abstract
class as this class implements all the methods of the Servlet interface except
the service () method. This is protocol independent class. This abstract
class also implements the ServletConfig interface which allows the servlet
container to pass configuration related information to the servlet.
2. ServletInputStream: This class provides an input stream for reading
requests from the client.
3. ServletOutputStream:This class provides an output stream for writing
the responses to a client.
4. ServletException: A general exception class to signal servlet runtime errors
and exceptions.
5. UnavailableException:An exception class to signal that a servlet is
permanently or temporarily unavailable.
2. javax.servlet. http package
The Web content is basically accessed via the HyperText Transfer Protocol (HTTP).
A basic Servlet knows nothing about HTTP, but there is a special implementation
of Servlet, javax.servlet.http.Http Servlet that is designed especially for it and it is
found inside the javax.servlet.http package.
This javax.servlet.http package consists of classes that extend the base
package (javax.servlet) functionality to provide support to HTTP protocol and its
methods like GET and POST. If you wish to write a servlet from scratch, this
package will provide you the required classes and interfaces.
There are several interfaces and classes found in this javax.servlet.http
package. They are as follows:
1. Abstract class Http Servlet: This abstract class extends the
GenericServlet class and is used for implementing HTTP Servlets, i.e.
Servlets which use HTTP for requests and responses. Basically, it
provides stubs for the doHttpRequestMethodName() methods which
Self-Instructional
188 Material
correspond to the HTTP methods used in the request (GET, POST, Java Servlets
Self-Instructional
Material 189
Java Servlets
NOTES
Also, this phase can be used for the creation of I/O intensive resources like
database connectivity for multiple invocations. It is a onetime initialization process
that prepares the Servlet to service the client’s requests properly and helps in
improving the performance dramatically.
The initialization phase is represented in Servlet as init () method. All the
Servlets must comply with the implementation of the javax.servlet.Servlet interface,
which consists the init () method definition. As execution of servlet is managed by
the servlet container or the server, init () method is invoked by the container or the
server when the Servlet is loaded, to provide all the resources it requires just once
at its loading time.
The init () method is invoked before servicing any client request and is
called only once per cycle when a Servlet is first loaded onto the server and does
not invoke if the same Servlet is called again and again which improves the
throughput drastically for multiple invocations from clients. After the initialization
phase the server marks the Servlet as available for service.
The init () method has the following prototype:
Public void init (ServletConfig config) throws
ServletException
{
\\ the initialization code (database connections etc.)
}
(b) Service Phase
For each request coming for a servlet, servlet container calls a service () method
for performing the task.The Servlet activity is coded inside the service () method,
which represents the service phase of a Servlet. The service () method can have
access to all the resources acquired by the Servlet at the initialization time. The
service () method is defined in the javax.servlet.Servlet interface .Hence if you
want your Servlet to perform any task then either your Servlet needs to implement
this javax.servlet.Servlet interface or extend a class implementing the
javax.servlet.Servlet interface and override the service () method. The easiest
Self-Instructional
190 Material
way is to extend a class that implements the javax.servlet.Servlet interface as this Java Servlets
will reduce the pain of implementing all the methods of the javax.servlet.Servlet
interface.
The service () method takes two parameters: a javax.servlet.ServletRequest
NOTES
and a javax.servlet.ServletResponse object. The service () method is invoked
once per request.The javax.servlet.ServletRequest object represents a client’s
request for the dynamic resources whereas the javax.servlet.ServletResponse object
represents the Servlet’s response to the requests sent by client. There are two
types of service method, one is public and other one is protected. The service ()
method has following implementation.
1. public void service(ServletRequest request,ServletResponse
response)
The purpose of this public method is to dispatch the request to the
protected service method by converting the request and response object
into HTTP type.
2. protected void service(Http ServletRequest request, Http
ServletResponse response)
This method receives the request from the public service() method. It
dispatches the request to the doXXX() method depending on the incoming http
request type.
The service () method has the following prototype:
Public void service (ServletRequest srq, ServletResponse
srp) throws ServletException
{
//Service code here…
}
(c) Destruction Phase
When a Servlet has serviced the client’s requests properly and is no longer needed
further, then the container removes the Servlet and all the resources are taken
away from the Servlet so that they could be used by other server dependents.
The server may decide to remove a previously loaded servlet instance,
perhaps because it is explicitly asked to do so by the server administrator, or
perhaps because the servlet is idle for a long time. Before it does, however, it calls
the servlet’s destroy method. This method gives your servlet a chance to close
database connections, halt background threads, write cookie lists or hit counts to
disk, and perform other such cleanup activities. Be aware, however, that it is
possible for the Web Destruction phase is marked by the destroy () method of the
Servlet interface which is called by the container for removing the Servlet whose
task has been completed and is not further required by the application. This method
is also just performed once, at last.
Self-Instructional
Material 191
Java Servlets The destroy () method has the following prototype:
Public void destroy ()
{
//Anything that you wish to be terminated/closed
NOTES
}
By proper use of the initialization, service, and destruction phases of the
Servlet life cycle, a Servlet can efficiently manage application resources. During
initialization a Servlet loads everything it needs to use for servicing requests. The
resources are then readily used during the service phase and can then be cleaned
up in the destruction phase. These three events form the Servlet life cycle, but in
practice there are some more methods which are needed by advanced programmers.
The unique feature to be noted here is that the initialization and the destruction
processes are performed only once whereas the service can be performed many
times as per client requests to the Servlet. Actually service () method is loaded
only once onto the server like init () and destroy () methods. But upon a new
request for the same Servlet every time after it has been loaded, a new service
thread is created which does the processing and returns the responses. This is the
feature in addition to the security feature which has helped Servlets outperform
the CGI applications and become the king of web applications.
Every Servlet that is to be written must pertain to the J2EE specifications, and
must implement the javax.servlet.Servlet interface. Implementing this interface means
getting access to the life cycle methods of a Servlet and some methods for sharing
the resources. You need to override these methods for performing the task.
The Servlet interface consists of five basic methods:
1. public void init(ServletConfig config)
2. public void service(ServletRequest srq, ServletResponse srp)
3. public void destroy()
4. public ServletConfig getServletConfig()
5. public String getServletInfo()
You need to override the service () method only for making the servlet do
the task, and hence it is unnecessary to override all the other methods when you
Self-Instructional
192 Material
do not require anything extra to be done while implementing the Servlet interface Java Servlets
If you are to work with the Web, you need to work with the protocol it uses-the
HTTP and its method-Get, POST etc. GenericServlet is independent to any
protocol, hence has a limitation that you should override the service () method
Self-Instructional
194 Material
only, irrespective of the methods used in the communication-the GET and the Java Servlets
POST methods. Though this is a benefit that you do not have to worry about the
communication protocol but on the other hand it is resource exploitation as the
methods of HTTP have different data load and characteristics.
NOTES
This is overcome in Java Servlets by the extension of the base package
javax.servlet to javax.servlet. http, with add on capabilities of handling the HTTP
protocol and all its methods. Also, Http Servlet class is devised which extends the
GenericServlet Class that comprises of methods for handling the HTTP protocol
specific data. Http Servlet is a subclass of GenericServlet class with add-on features
to support the web protocol HTTP. It is also abstract class. Http Servlet class
provides support to the methods of HTTP also, providing a number of helper
methods like doGet(), doPost(),doTrace(),doPut() etc. These methods can easily
handle the specific types of HTTP requests-be it GET, POST, PUT or Delete.
The execution of these methods is controlled by the service () method. The service
() method tracks the kind of request made by the client and invokes the
corresponding method to perform the task. Though there are total of seven such
helper methods, only one of them is invoked according to the request specification
by the server. There may be a scenario when you may need to call more than one
in your servlet, then you need to override them such that they call each other.
10.7.1 Methods of Http Servlet Class
GenericServlet is too generic to be used with the basic methods only. Hence, the
Http Servlet class is the main class that you will see being used in the chapter as it
provides everything that is needed to create good servlets with maximum capabilities.
As Http Servlet class extends GenericServlet, it comprises of the basic
servlet lifecycle methods plus some additional helper methods specific to HTTP
protocol and Servlet configurations.
Self-Instructional
Material 195
Java Servlets 1. Servlet Lifecycle Methods
i) init()-This is the initialization method that is called once ,when the servlet
first loads onto the server .This method provides the essential resources
NOTES needed by the servlet.
ii) destroy()-This method is also called once by the servlet container to de-
allocate the resources used by servlet during its execution, after its work is
completed.
iii) service()-You will never override this method while using the Http Servlet
class as there are other methods equivalent to this with specific functionalities
which has been discussed in the next section. Service () method gets
differentiated into various sub methods according to the HTTP requests,
they are doXXX() methods where XXX represent the HTTP request
methods. There are two types of service method, one is public and other
one is protected. The service () method has following implementation.
Fig.10.15 Service() method handling the dispatch methods doGet() & doPost()
Self-Instructional
196 Material
2. protected void doPost(Http ServletRequest request, Http Java Servlets
ServletResponse response)
Similar to doGet() method, it also gets invoked by the web container and it
handles the POST request.
NOTES
3. protected void doHead(Http ServletRequest request, Http
ServletResponse response)
It handles the HEAD request.
4. protected void doOptions(Http ServletRequest request, Http
ServletResponse response)
Performs the HTTP OPTIONS operation; the default implementation of
this method automatically determines what HTTP Options are supported.
5. protected void doPut(Http ServletRequest request, Http ServletResponse
response)
Performs the HTTP PUT operation; the default implementation reports an
HTTP BAD_REQUEST error.
6. protected void doTrace (Http ServletRequest request, Http
ServletResponse response)
Performs the HTTP TRACE operation; the default implementation of this
method causes a response with a message containing all of the headers sent
in the trace request.
7. protected void doDelete(Http ServletRequest request, Http
ServletResponse response):
Performs the HTTP DELETE operation; the default implementation reports
an HTTP BAD_REQUEST error.
3. Method related to Servlet Configuration
book, you will find the use of Http Servlet Class the most as it provides greater
functionality and implementations than the others.
There are many other advanced but essential interfaces and classes that you
NOTES
need to be going through in the servlets. But to understand their mechanics, you
need to first understand the technique of running a servlet successfully. Once you
have run a servlet properly, it will be easier for you to get on with some advanced
concepts like servlet collaborations, servlet context and configurations.
Well, you have now learned the basics of the servlet, but there are a few things still
left before you have the first run of your servlet. These are the key things that you
should learn before running any Servlet.
They are as follows:
1. The Directory Structure Of The Web Application
2. The Deployment Descriptor(web.xml)
3. Servlet Code Compilation(Getting the .class file)
1. The Directory Structure Of The Web Application
Whatever structure a web application displays on the browser, on disk, it is merely
a directory with various sub directories that help get the online structure. The
parent directory contains a subdirectory called WEB-INF, and whatever other
content is required for the application like HTML pages and other static resources.
The WEB-INF directory contains a classes directory (containing application
code), a lib directory (containing application JAR files), and a deployment descriptor
called web.xml. It can be shown in diagram as follows:
NOTES
Self-Instructional
200 Material
</servlet> Java Servlets
<servlet-mapping>
<servlet-name>Manager</servlet-name>
<url-pattern>/mgt</url-pattern>
NOTES
</servlet-mapping>
</web-app>
3. Servlet Code Compilation(Getting the .class file)
Servlets are java classes, and they too need to be compiled before they are executed
by JVM just like simple java programs. The process of compiling a java servlet is
similar to that of an ordinary java program i.e. using the default “javac” utility at the
command prompt. Only thing to consider is setting the path to servlet-api.jar,
which consists of the complete specification for java Servlet. The easiest way is to
copy servlet-api.jar from the tomcat lib folder to Java program folder, or set the
environment variable class path to the jar archive.
Now, you are ready to get started with your first Servlet. Let’s kick start
writing Servlets and develop new web applications.
The step wise mechanism of creating a web application for your use and
understanding is given below:
Algorithm:
Step1: Create a directory structure of the web application.
Step2: Write a Servlet code. Save it with .java extension.
Step3: Compile the Servlet to obtain the .class file. Place this .class file into
the classes folder in the WEB-INF (web descriptor) folder of the
application.
Step4: Create the deployment descriptor i.e. web.xml file according to the
servlets. Place this XML file in the WEB-INF folder of the application.
Step5: Start the Tomcat Server.
Step6: Deploy the application on the web server by placing the public folder
into the C:\Program Files\Apache Software Foundation\Tomcat
7.0\webapps folder.
Step7: Test the application by giving the relative URL on the browser.
For example : localhost:8888/Servlet1/fts1
Now you will see the execution of a servlet according to the steps mentioned
above.
Self-Instructional
Material 201
Java Servlets Implementation
Step1: Create the directory structure of the web application as discussed in
the previous section.
NOTES Step2: Write the Servlet file, FirstTestServlet.java.
FirstTestServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstTestServlet extends Http Servlet {
public void doGet(Http ServletRequest request, Http
ServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println(“If You are viewing me on the browser,means
your servlet has successfully deployed and
executed.Congratsss!”);
}
}
Step3: Compile the Servlet to obtain the .class file. Place this .class file into
the classes folder in the WEB-INF (web descriptor) folder of the
application.
Step4: Create the deployment descriptor i.e. web.xml file according to the
servlets. Place this XML file in the WEB-INF folder of the application.
web.xml
<?xml version=”1.0" encoding=”ISO-8859-1"?>
<web-app >
<servlet>
<servlet-name>FTS</servlet-name>
<servlet-class>FirstTestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FTS</servlet-name>
<url-pattern>/fts1</url-pattern>
</servlet-mapping>
</web-app>
Step5 Start the tomcat server as directed in the previous sections.
Step6: Deploy the application on the web server.
Self-Instructional
202 Material
Deployment can be defined as the process of loading the application files Java Servlets
on to the server, so that the server can provide an execution environment to them
and the web application expose out all its features. There are two ways of deploying
the web application and its files on to the server, viz.1.Hot Deployment and 2.Cold
Deployment. NOTES
Output:
You must have now successfully deployed and executed your first Servlet
only application. You can create a complete web application using servlets only; it
will be a monotonous application. And you also know that a web application
consists of varieties of web pages – some in HTML, some as Servlets which may
interact with each other for the proper functioning of the web application. So, an
interactive web application will make a judicious use of servlets, HTML pages,
etc. The presentation will be completely dependent on HTML and the business
logic will depend upon the servlet used in such web applications. You will witness
the simplest of the web application developed using HTML page and a servlet in
the coming section.
A simple step wise implementation for your use and understanding is given below:
Algorithm:
Step1: Create a directory structure of the web application.
Step2: Write an HTML web page .Save it with .htm or .html extensions.
Place this HTML page into the parent directory parallel to WEB-INF
folder.
Step3: Write a Servlet code. Save it with .java extension.
Step4: Compile the Servlet to obtain the .class file. Place this .class file into
the classes folder in the WEB-INF (web descriptor) folder of the
application.
Step5: Create the deployment descriptor i.e. web.xml file according to the
servlets. Place this XML file in the WEB-INF folder of the application.
Step6: Deploy the application on the web server.
Self-Instructional
Material 203
Java Servlets Now you will see the execution of a servlet according to the steps mentioned
above. Check that the HTML page is properly saved along with the XML file.
Now you will see the execution of a servlet according to the steps mentioned
above.
NOTES
Implementation
Index.html
<HTML><BODY>
<A HREF=”hbs”>Click Here! < /A>
</BODY>
</HTML>
Place this file in the parent folder, keeping it parallel to the WEB-INF folder.
Note: A folder which has WEB-INF folder in it is considered as the public folder
for the web application.
HtmlBasedServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HtmlBasedServlet extends Http Servlet {
public void doGet(Http ServletRequest request, Http
ServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println(“<HTML><HEAD><TITLE>”);
out.println(“SERVLET WITH HTML OUTPUT”);
out.println(“</TITLE></HEAD><BODY BGCOLOR=RED>”);
out.println(“If You are viewing me on the browser,
means your servlet has successfully deployed and
executed. Congratsss!”);
out.println(“</BODY></HTML>”);
}
Save, compile and place the .class file in the classes folder in the WEB-INF
directory.
web.xml
<?xml version=”1.0" encoding=”ISO-8859-1"?>
<web-app >
<servlet>
<servlet-name>HBS</servlet-name>
Self-Instructional
204 Material
<servlet-class>HtmlBasedServlet</servlet-class> Java Servlets
</servlet>
<servlet-mapping>
<servlet-name>HBS</servlet-name>
NOTES
<url-pattern>/hbs</url-pattern>
</servlet-mapping>
</web-app>
Save and place the web.xml file inside the WEB-INF folder in the parent
folder. Now your application is ready for the deployment. You can use either of
the deployment methods-Hot Deployment or Cold Deployment. Deploy and
execute on the web browser and enjoy!
These Servlets are static Servlets as these will be displaying plain texts or
HTML output only, but you want more, interactive applications, one which will
take input from the user and do the task accordingly. These will be considered as
the dynamic servlets. You will see the dynamic servlets in action in the coming
section.
Interactivity on the web can only be felt when the web application is getting input
from the user and the web application is performing the specified task. To achieve
this there are various mechanisms, as you are a learner now, a small form based
web application will be discussed so that you get the insight and create your own
application learning this. The steps will be the same as followed in the previous
sections 10.9 and 10.10.
This is the extension of the web application you have just created in the
previous section using HTML web page.
Implementation
FormGenerator.html
<HTML>
<HEAD>
<TITLE>FormGenerator</TITLE>
</HEAD>
<BODY BGCOLOR=”#5D35E6">
<H1 ALIGN=”CENTER”>Collecting Three Parameters</H1>
<FORM ACTION=”FormHandler”>
Name: <INPUT TYPE=”TEXT” NAME=”parameter1"><BR>
Class: <INPUT TYPE=”TEXT” NAME=”parameter2"><BR>
Self-Instructional
Material 205
Java Servlets RollNo: <INPUT TYPE=”TEXT” NAME=”parameter3"><BR>
<CENTER><INPUT TYPE=”SUBMIT”></CENTER>
</FORM>
</BODY>
NOTES
</HTML>
FormHandlingServlet.java
// Servlet that reads form data and displays in HTMl
text format.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FormHandlingServletEx extends Http Servlet
{
public void doGet(Http ServletRequest request, Http
ServletResponse response)
throws ServletException, IOException
{
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
out.println(“<BODY BGCOLOR=\”#F6E5E6\”>\n” +
“<H1 ALIGN=\”CENTER\”>” + title + “</H1>\n” +
“<UL>\n” +
“ <LI><B>Name: </B>: “+
request.getParameter(“parameter1”) + “\n” +
“ <LI><B>Class:</B>: “+
request.getParameter(“parameter2”) + “\n” +
“ <LI><B>RollNo.:</B>: “+
request.getParameter(“parameter3”) + “\n” +
“</UL>\n” +”</BODY></HTML>”);}
}
web.xml
<?xml version=”1.0" encoding=”ISO-8859-1"?>
<web-app >
<servlet>
<servlet-name>FHSE</servlet-name>
<servlet-class> FormHandlingServletEx</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>FHSE</servlet-name>
Self-Instructional
206 Material
<url-pattern>/FormHandler</url-pattern> Java Servlets
</servlet-mapping>
</web-app>
NOTES
Check Your Progress
3. What is a Servlet invoked by?
4. What is a Http Servlet?
10.13 SUMMARY
Java has become an undoubtedly the best language for server side
programming due to Java Servlets.
Java Servlets have always stood as a top performer in providing an efficient
and powerful solution for creating dynamic content for the Web.
The Java platform provides a Servlet developer with robust APIs, object-
orientated programming methodology, platform independence, I18N
(Internationalization), strict types, garbage collection and above all, the
security features of the Java Virtual Machine (JVM).
Servlets are java programs, with an inbuilt support to HTTP for getting
requests and sending responses.
A web.xml file is created for a Servlet which has the configuration details of
the servlet that the server uses for its execution.
Servlets do not have a main () method like their counterparts in core Java-
the applets or any simple Java program.
A servlet container is the application software that is used to run servlets.
Tomcat is a basic server, it can be used for general testing and debugging
the Servlets.
Self-Instructional
Material 207
Java Servlets If you want to run servlet programs on your computer, you have to install a
special program called a servlet engine to convert your computer into a
server which is capable of running the Servlets.
Java Servlets can be defined as some platform independent, robust server
NOTES
side programs coded in Java.
The power of Java Servlets comes from the Java Servlet API which is a
standard interface between web server and web clients.
The Java Servlet API is a set of Java classes, interfaces and methods which
defines a standard interface between a client and a web server.
This javax.servlet package consists of the classes and interfaces that support
generic protocol independent Servlets.
Every Servlet has to extend this abstract class as this class implements all
the methods of the Servlet interface except the service () method.
The Web content is basically accessed via the HyperText Transfer Protocol
(HTTP).
Every Servlet that is to be written must pertain to the J2EE specifications,
and must implement the javax.servlet.Servlet interface.
You need to override the service () method only for making the servlet do
the task.
As Generic Servlet is protocol independent, in many occasions you may
need to code Servlets for specific protocols-like HTTP, then for that you
need additional packages and classes.
Http Servlet is a subclass of GenericServlet class with add-on features to
support the web protocol HTTP.
GenericServlet is too generic to be used with the basic methods only. Hence,
the Http Servlet class is the main class that you will see being used in the
chapter as it provides everything that is needed to create good servlets with
maximum capabilities.
A Servlet is invoked by the server, so the server should know what servlet
looks like and what does it require.
init(): This is the initialization method that is called once ,when the servlet
first loads onto the server .This method provides the essential resources
needed by the servlet.
destroy(): This method is also called once by the servlet container to de-
allocate the resources used by servlet during its execution, after its work is
completed.
Self-Instructional
208 Material
Java Servlets
10.15 SELF ASSESSMENT QUESTIONS AND
EXERCISES
Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.
Self-Instructional
Material 209
Servlet Parameters
11.0 INTRODUCTION
Java Servlet, as the name suggests is a Java technology under J2EE flavor of Java
that has changed the web scenario completely, especially with its security and
multithreading capabilities. Servlets outperformed and replaced CGI, the first server
side technology to provide dynamic capabilities to the web and became the world
leader in Sever Side Programming. Servlets are really very powerful. They also
form the basis for the Java Server Pages (JSP), the web scripting language that is
popularly used in web programming. Behind every JSP that executes is a servlet
always. You will see varieties of implementations of servlets as you proceed with
the chapter and understand the underlying concepts as well. In this unit you will
learn about reading initialization, parameters, and reading servlet parameters.
11.1 OBJECTIVES
Self-Instructional
210 Material
Servlet Parameters
11.2 UNDERSTANDING THE SERVLET REQUESTS
AND SERVLET RESPONSES MECHANISM
Working with any client–server technology is to carefully deal with the requests NOTES
and responses, the prime mechanism of interaction between the two. Request and
responses are used Request and responses are used for communication between
the client and the server it interacts with. A client application shoots the requests as
received from the user interface to the server using some protocols for
accomplishing some task. The server takes up the request and then after processing
the request, it reverts back with appropriate response to the client application.
Similar paradigm is used in Servlets as well. This section will help you understand
the requests and responses as you may need to deal with in your Servlets.
Servlet Requests
For processing a request, a Servlet requires some specific information like
configuration and context information about the request so as to process it properly.
The Servlet API has provided two interfaces-
1. ServletRequest interface
2. HttpServletRequest interface
Both of these interfaces are of great help while devising servlets and provide
the server access to the information as needed for processing. When a Servlet is
asked to handle a request, the server passes it a request object that implements
one of these interfaces. With this object, the servlet can distinguish between the
actual request (e.g., protocol, URL, type), access parts of the raw request (e.g.,
headers, input stream), and get any client-specific request parameters (e.g., form
variables, extra path information).
If you are creating servlets implementing the Servlet Interface ,then do not
forget to consider ServletRequest Interface for creating the request object. Or
else if you are using the HttpServlet, then use HttpServletRequest for the accessing
the request object.
ServletRequest Interface
ServletRequest Interface defines an object that takes the client request information
to a Servlet. The Servlet container creates a ServletRequest object and passes it
as an argument to the Servlet’s service method.
Information delegated by the ServletRequest object includes data including
parameter name and values, attributes, and an input stream. Interfaces that extend
ServletRequest can provide additional protocol-specific data (for example, HTTP
data is provided by HttpServletRequest).
Self-Instructional
Material 211
Servlet Parameters Table 11.1 shows some useful methods of ServletRequest interface.
Table 11.1 Useful Methods of ServletRequest Interface
Methods Description
NOTES Object getAttribute(String name) Return attribute set on request object by name
Enumeration getAttributeName() Return an Enumeration containing the names of the
attributes available in this request
int getContentLength() Return size of request body
int getContentType() Return media type of request content
ServletInputStream Returns a input stream for reading binary data
getInputStream()
String getParameter(String name) Returns value of parameter by name
String getLocalAddr() Returns the Internet Protocol(IP) address of the
interface on which the request was received
Enumeration getParameterNames() Returns an enumeration of all parameter names
String[] getParameterValues(String Returns an array of String objects containing all of
name) the values the given request parameter has, or null if
the parameter does not exist
ServletContext getServletContext() Return the servlet context of current request.
String getServerName() Returns the host name of the server to which the
request was sent
int getServerPort() Returns the port number to which the request was
sent
boolean isSecure() Returns a boolean indicating whether this request
was made using a secure channel, such as HTTPS.
void removeAttribute(String name) Removes an attribute from this request
void setAttribute(String name, Stores an attribute in this request
Object o)
HttpServletRequest Interface
This interface extends the ServletRequest interface and provides request information
for HTTP.So, it extends an old legacy apart from some new special methods
handling HTTP-specific request data apart from the existing ServletRequest
interface.. The Servlet container creates an HttpServletRequest object and passes
it as an argument to the Servlet’s service methods (doGet, doPost, etc). For
example, the getHeaderNames() returns an enumeration of the names of all the
HTTP headers submitted with a request, while getHeader() returns a particular
header value.
Methods Description
String returns the portion of the request URI that indicates the
getContextPath() context of the request
Cookies getCookies() returns an array containing all of the Cookie objects the NOTES
client sent with this request
String returns the query string that is contained in the request
getQueryString() URL after the path
HttpSession returns the current HttpSession associated with this
getSession() request or, if there is no current session and create is
true, returns a new session
String getMethod() Returns the name of the HTTP method with which this
request was made, for example, GET, POST, or PUT.
Part getPart(String gets the Part with the given name
name)
String getPathInfo() returns any extra path information associated with the
URL the client sent when it made this request.
String getServletPath() returns the part of this request's URL that calls the
servlet
Self-Instructional
Material 213
Servlet Parameters <servlet-name>ServletEx</servlet-name>
<url-pattern>/paramcheck</url-pattern>
</servlet-mapping>
</web-app>
NOTES
HttpServletRequestEx.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
For every request that comes to the server, the servlet has to send back
some response as a token of processing the request successfully. Responses can
be one liner, like a status code simply, or a description that includes all the three-
a status code, any number of HTTP headers, and a response body as in the HTTP
For Servlet responses, Java Servlet API has provided two basic interfaces
that can be used to create and manipulate a Servlet’s output.
They are:
1. ServletResponse Interface
2. HttpServletResponse interface
ServletResponse Interface
This interface defines an object to help a Servlet in sending a response to the
client. The servlet container creates a ServletResponse object and passes it as an
Self-Instructional argument to the Servlet’s service method.
214 Material
If you wish to send binary data in a MIME body response, you need to use Servlet Parameters
Methods Description
PrintWriter getWriter() Returns a PrintWriter object that can send
character text to the client.
void setBufferSize(int size) Sets the preferred buffer size for the body of the
response
void setContentLength(int len) Sets the length of the content body in the
response In HTTP servlets, this method sets the
HTTP Content-Length header
void setContentType(String type) Sets the content type of the response being sent
to the client before sending the respond.
void setBufferSize(int size) Sets the preferred buffer size for the body of the
response.
boolean isCommitted() Returns a boolean indicating if the response has
been committed
void setLocale(Locale loc) Sets the locale of the response, if the response
has not been committed yet.
Self-Instructional
Material 215
Servlet Parameters certain header has already been set. setStatus() or sendError() methods can be
used to specify the status code sent back to the server.
HttpServletResponse interface also defines a list of integer constants that
represent specific status codes. Don’t worry about setting a status code, as the
NOTES
default code is 200 (“OK”), meaning that the servlet sent a normal response.
Table 11.4 Methods of HttpServletResponse Interface
Methods Description
void addCookie(Cookie cookie) adds the specified cookie to the response.
void sendRedirect(String location) Sends a temporary redirect response to the
client using the specified redirect location
URL and clears the buffer
void setHeader(String name, String value) sets a response header with the given name
and value
void setStatus(int sc) sets the status code for this response
void sendError(int sc, String msg) sends an error response to the client using
the specified status and clears the buffer
“What can a single servlet do?” Just a specific task will be the answer. But in the
real world, single servlets have no use at all. What you really need is the grouping
together of various servlets to form an application which may consist of servlets,
shared objects, and other resource files, such as HTML and JSPs. And this is only
possible when these servlets interact with each other; communicate with each
other in a certain context by sharing their resources at application level.
There are various scenarios that discuss the implementation of the servlet
interactions, they are as follows:
1. Servlet collaboration: Combining two or more servlets such that either
they delegate the responses or collaborate to produce a common
response is called Servlet Collaboration. The two techniques for servlet
collaboration are servlet filtering and chaining. Here, multiple Servlets
collaborate for producing a single response for a client. The Servlets
themselves are not really interacting directly with each other; rather, the
web application server is responsible for binding the servlets together.
Self-Instructional
216 Material
2. Calling servlets from servlets: Since servlets are Java programs, Servlet Parameters
they can do anything a standard Java program can do, such as make a
network connection. In this way, we have implicit servlet interaction.
Additionally, because a servlet is just a Java class, we can instantiate
and call a servlet’s public methods. NOTES
3. Response redirection: We can redirect the servlet response to another
application resource, such as another servlet or an error page (HTML
or JSP).
4. Request dispatching: Through the RequestDispatcher object, we can
forward a request to another servlet, which can handle the request and
return the response. Additionally, we can include directly another servlet’s
response within the context of a calling servlet. We can use request
dispatching to dispatch the handling to another active application
resource.
5. Resource usage: We can interact with an application’s resources
through the servlet context. The ServletContext object allows us access
to these resources through the getResource() method.
6. Sharing of objects in scope: There are three levels of object scope
for a servlet. Application scope is between all servlets in the same
application, and is accessed through the ServletContext object. User
session objects are accessed through the HttpSession object, and request
level objects through the servlet request.
As you are getting into the basics of Servlet, you will just require some basic
servlet interactions like sharing of resources, response redirection, and request
dispatching.
Sharing of Resources
It is easy to create a servlet which displays information. You have done it.
Sometimes, you may be asked to share the common resources of a server among
all the servlets. Then to achieve this ,you will have to get help of the following
interfaces:
(a) ServletConfig Interface
(b) ServletContext Interface
ServletConfig
The javax.servlet.ServletConfig interface provides a support to pass information
to a servlet during initialization by getting configuration information from web.xml
(Deployment Descriptor). A servlet configuration object is used by a servlet container
to pass the information to a servlet during initialization.
This ServletConfig object is created when the web container first initializes
the Servlet. There exists only one ServletConfig object per servlet. Essentially, it is
Self-Instructional
Material 217
Servlet Parameters used to pass the deploy time information to the servlet that you do not want to
hardcode into the servlet.
Methods of ServletConfig
NOTES String getInitParameter(String name)
This method returns a String value initialized parameter, or NULL if the
parameter does not exist.
Enumeration getInitParameterNames():
This method returns the names of the servlet’s initialization parameters as
an Enumeration of String objects, or an empty Enumeration if the servlet
has no initialization parameters.
ServletContext getServletContext()
This method returns a reference to the ServletContext
String getServletName()
This method returns the name of the servlet instance.
Whenever an explicit initialization parameter is to be used in the Servlet ,it
needs to be provided in the web.xml file in the sub element of Servlet <init-
param>…</init-param> inside the web application. You can see the implementation
in the example below which illustrates an example on using ServletConfig Interface
to get the parameters from the web.xml.
Example 11.1:
// Servlet Config program to get a parameter from the
web.xml.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ConfigServletEx extends HttpServlet {
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
ServletConfig config=getServletConfig();
String driver=config.getInitParameter(“driver”);
out.print(“Driver is: ”+driver);
out.close(); } }
web.xml
<web-app>
<servlet>
<servlet-name>CSE</servlet-name>
<servlet-class> ConfigServletEx </servlet-class>
Self-Instructional <init-param>
218 Material
<param-name>driver</param-name> Servlet Parameters
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-
value>
</init-param>
</servlet> NOTES
<servlet-mapping>
<servlet-name> ConfigServletEx </servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
ServletContext
The javax.servlet.ServletContext interface primarily provides the reference to the
web application in which the servlets execute. It allows servlets to access server
information, and there exists only one ServletContext for each web application on
the server. Through the ServletContext interface, a Servlet can access any raw
input streams to web application resources, a way to virtual directory translation
(a common mechanism for logging information) and an application scope for binding
objects. The container vendors may provide different implementations of
ServletContext objects, but with the same functionality as defined by the
ServletContext interface.
ServletContext interface basically works as the communication interface
for the servlets of a web application .It works like a bulletin board for all the
servlets of a web application and differs with every web application. A
ServletContext object gets created as soon as the web application is deployed
onto the server with everything that is common to all within the application context.
Self-Instructional
Material 219
Servlet Parameters Just similar to ServletConfig, all the parameters of this ServletContext are set
once in the deployment descriptor.
You need to use this interface and its methods, if you wish to share the
common resources with all the servlets of a web application.
NOTES
Using ServletContext, servlets can be:
Used to provide communication between Servlets
Used to get access to configuration information like initialization
parameters from web.xml.
Used for sharing attributes with other servlets in the context(within the
context of web application)
Used to get configuration information from web.xml
Important Methods of ServletContext Interface
Methods Description
Object getAttribute(String name) Rreturns the container attribute with
the given name, or NULL if there is
no attribute by that name.
String getInitParameter(String name) Returns parameter value for the
specified parameter name, or NULL
if the parameter does not exist
Enumeration getInitParameterNames() Returns the names of the context's
initialization parameters as an
Enumeration of String objects
void setAttribute(String name,Object obj) Set an object with the given attribute
name in the application scope
void removeAttribute(String name) Removes the attribute with the
specified name from the application
context
Response Redirection
Response redirection, also referred to as URL redirection, means calling a servlet
from another servlet and transferring the entire response to it. This is also. A very
handy technique if you wish to redirect your clients to your application which has
been relocated or shifted from its address to a new location onto the web. Also, it
can help you to provide your client content from an old location without any overhead
and any additional effort. Servlet API has provided the sendRedirect() method to
serve this purpose.
Self-Instructional
220 Material
Servlet Parameters
NOTES
sendRedirect() Method
sendRedirect() method redirects the response to another resource. This method
actually makes the client (browser) to create a new request to get to the resource.
The client can see the new url in the browser. sendRedirect() accepts relative
URL, so it can go for resources inside or outside the server.
Example 11.2: Demonstrating the usage of sendRedirect()
MyServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
Self-Instructional
Material 221
Servlet Parameters Servlet Collaboration
Servlet collaboration or specifically servlet communication is a very powerful feature
of Java Servlets. It helps forwarding the clients request to a new servlet and also
NOTES helps in including the response of one servlet in that of the other servlets. A single
client’s request can move across many Servlets and/or to any other resource in
the Web Application. This complete process well occurs on the server-side and,
unlike response redirection, does not mandate for any action from a client or extra
information sent between the client and server. This can be achieved through the
javax.servlet.RequestDispatcher object. You can call an appropriate instance of a
RequestDispatcher object by calling either of the following methods of a
ServletRequest interface:
getRequestDispatcher(java.lang.String path)
The getRequestDispatcher() method returns the RequestDispatcher object
for a given path. The path value may lead to any resource in the Web
Application and must start from the root directory, “/”.
getNamedDispatcher(java.lang.String name)
The getNamedDispatcher() method returns the RequestDispatcher object
for the named Servlet. Valid names are defined by the servlet-name elements
of web.xml.
A RequestDispatcher object provides two methods for including different
resources and for forwarding a request to a different resource.
forward (javax.servlet.ServletRequest, javax.servlet.ServletResponse)
The forward () method delegates a request and response to the resource
of the RequestDispatcher object. A call to the forward () method may be
used only if no content has been previously sent to a client. No further data
can be sent to the client after the forward has completed.
NOTES
Self-Instructional
224 Material
out.close(); Servlet Parameters
}
}
}
NOTES
web.xml
<web-app>
<servlet>
<servlet-name>VS</servlet-name>
<servlet-class>ValidateServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>WS</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>VS</servlet-name>
<url-pattern>/Validate</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WS</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Index.html</welcome-file>
</welcome-file-list>
</web-app>
Self-Instructional
Material 225
Servlet Parameters 2. Combining two or more servlets such that either they delegate the responses
or collaborate to produce a common response is called Servlet
Collaboration.
3. Response redirection pertains basically to calling a servlet from another
NOTES
servlet and transferring the response to it.
11.7 SUMMARY
Self-Instructional
226 Material
Since servlets are Java programs, they can do anything a standard Java Servlet Parameters
program can do, such as make a network connection. In this way, we have
implicit servlet interaction.
Through the RequestDispatcher object, we can forward a request to another
NOTES
servlet, which can handle the request and return the response.
The javax.servlet.ServletConfig interface provides a support to pass
information to a servlet during initialization by getting configuration information
from web.xml (Deployment Descriptor).
The javax.servlet.ServletContext interface primarily provides the reference
to the web application in which the servlets execute.
Response redirection pertains basically to calling a servlet from another
servlet and transferring the response to it.
Servlet collaboration or specifically servlet communication is a very powerful
feature of Java Servlets.
Short-Answer Question
1. What do you understand by Servlet Responses?
2. Discuss some useful methods of ServletRequest Interface.
3. Analyse HttpServletResponse Interface and its functionality.
4. Explain servlets interactions and their use.
Long-Answer Questions
1. Explain the methods of ServletConfig.
2. Explain the ServletContext. State few examples.
3. Share and explain some examples demonstrating usage of
RequestDispatcher interface.
Self-Instructional
Material 227
Servlet Parameters
11.10 FURTHER READINGS
Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
NOTES Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.
Self-Instructional
228 Material
Cookies and Session
TRACKING
NOTES
Structure
12.0 Introduction
12.1 Objectives
12.2 Session Management/Tracking
12.3 Servlet Debugging
12.4 Answers to Check Your Progress Questions
12.5 Summary
12.6 Key Words
12.7 Self Assessment Questions and Exercises
12.8 Further Readings
12.0 INTRODUCTION
In this unit, you will learn about the session management with the session tracking
Servlet APIs and various other methods. Session management is essential in every
e-commerce web applications so as to keep track of their user’s preferences and
the site visitors. Session tracking is the mechanism of identifying the user, if he
revisits the website and storing his state throughout his stay on the website.
12.1 OBJECTIVES
The Web knows only one protocol for communication, HTTP but it is stateless.
HTTP protocol cannot save the session state information of the client it just can
exchange requests from the client, and response from the server till the connection
between them is open. Once the connection is closed/lost, server forgets the client
Self-Instructional
Material 229
Cookies and Session as nothing about the client was conveyed to it .And if the same client requests
Tracking
again to the same server then, the server will treat it as a new ,fresh request with
no relation to the previous activity. This is why HTTP is considered as stateless
and useless protocol for session management. So, to accomplish the session
NOTES management, it cannot be used.
The second option is to use server to maintain the state and session, but the
server itself cannot do anything, it cannot automatically maintain contextual
information about the clients.
Now, the problem is, “How to maintain the session and the context
information about the client?” You need to answer this question if you are building
an E-Com website.
So there are basically two ways that you can use to track the client and they
are discussed below:
1. Client Side Session Tracking
Utilizing the client side applications (like browsers) to store the client information
and then creating a mechanism to send the information to the server so that it
recognizes the client is generally referred to as Client Side Session tracking. It
involves the following methods:
Using Cookies,
Implementing URL rewriting,
Including hidden form fields
Advantages of Cookie
It is the simplest technique of maintaining the state.
Cookie are maintained at client side so no server side overhead.
All server side technology and all web servers, application servers support
cookies.
Persistent cookies can remember client data during session and after session
with expiry time.
Limitations of Cookie
It will not work if cookie is disabled from the browser.
Self-Instructional
Material 231
Cookies and Session Cookies are text files, hence not secure. Anyone can change this file.
Tracking
Cookies cannot store java objects as values; they only store text or string.
The Cookie Class
NOTES
The javax.servlet.http.Cookie class provides the functionality of using cookies.
Cookies are created using Cookie class present in Servlet API. Cookies are added
to response object using the addCookie() method. This addCookie() method
reverts with the cookie information over the HTTP response stream back to the
server. getCookies() method is used access the cookies that are added to response
object returning from the client.
In HttpSession technique, the Servlet container implicitly generates a cookies
for transferring the session ID between server and client. Apart from container
generated cookie a servlet programmer can also generate cookies explicitly for
storing the client information.
Cookie class provides some constructor and methods for cookies which
have been tabulated below:
Constructors of Cookie Class
Constructor Description
Cookie() Used for constructs a cookie.
Cookie(String name, String value) Used for constructs a cookie with a
specified name and value.
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Note: In this web.xml, you can see there are two Servlets given with their respective
URL patterns mapped accordingly.
Activity: Try using three Servlets and the session management using cookies.
URL Rewriting
URL rewriting is one of the best methods that can be implemented to track a
session when cookies do not work on the browsers or cookies have been disabled
by the user. With this approach, the client appends some extra data at the end of
each URL that identifies the session. On receiving the appended identifier, the
server associates it with the data it has stored about that session. And like this the
server tracks the user.
This can be elaborated by the example,with http:/file.html;jsessionid=x12,
the session information is attached as jsessionid=x12.
However, it has most of the same problems as cookies, namely, that the
server-side program has a lot of straightforward but tedious processing to do. In
addition, you have to be very careful that every URL that references your site and
Self-Instructional
234 Material
is returned to the user (even by indirect means like Location fields in server redirects) Cookies and Session
Tracking
has the extra information appended. And, if the user leaves the session and comes
back via a bookmark or link, the session information can be lost.
Hidden Form Fields NOTES
As the name suggest, these are the HTML form fields that are hidden in the forms.
Every time the form is submitted to the server ,these hidden fields provide the
information regarding the session.
HTML forms fields have the following syntax:
<INPUT TYPE=”HIDDEN” NAME=”session” VALUE=”...”>
This syntax specifies that, when the form is submitted, the specified name
and value are included in the GET or POST data and sent to the server .Then the
server can identify the client by the information. This hidden field can be used to
store information about the session but has the major shortcoming that it will work
only if every page is dynamically generated by the form submission. Hence, hidden
form fields do not provide enough support to general session tracking. These are
beneficial only when you need to track the user for some certain activities.
HttpSession Interface-The Session Tracking API
You have seen various methods for tracking the user activities form cookies to
hidden form fields, but Servlets provide a marvelous technical solution: the
HttpSession API. This high-level interface, HttpSession interface has advantages
over cookies or URL rewriting and most interestingly it works on top of cookies
or URL rewriting.
Using sessions in Servlets is very clear .It involves the following mechanism:
Looking up the session object associated with the current request,
Creating a new session object when necessary,
Looking up information associated with a session,
Storing information in a session, and
Discarding completed or abandoned sessions.
With cookies the session can be managed easily. But if any URLs is returned
to the clients that reference your site and URL rewriting is being used, then the
session information need to be attached to the URLs so that it could be used to
track the client.
1. Looking up the HttpSession object associated with
the current request
Looking up of the HttpSession object can be done by calling the getSession()
method of HttpServletRequest. If getSession() returns null, this means that the
user is not already participating in a session, so you can create a new session. But
what exactly happened behind the scenes- the system extracts a user ID from a
Self-Instructional
Material 235
Cookies and Session cookie or appended URL data, and uses it as a key to look up into a table of
Tracking
previously created HttpSession objects.
2. Creating a new session
NOTES You can easily create a new session and also check if it’s a new one or the existing
one. HttpSession APIs provide an option to automatically create a new session if
one doesn’t already exist. What you have to do is to pass “true” to getSession()
method like this:
HttpSession session = request.getSession(true);
And if you wish know whether the session already existed or is a newly created
one.Just use the method isNew() to check.If it returns true then the session object
is new else it is one from the pool.
3. Looking up information associated with a session and storing them
HttpSession objects reside on the server and are automatically associated with
the client by a hidden mechanism like cookies or URL rewriting. These session
objects use a built-in data structure to you store any number of keys and associated
values using the setAttributes() method. Like as shown below
HttpSession session = request.getSession(true);
PurchasedItems purchItems =
(PurchasedItems)session.getAttribute(“PurchasedItem”);
if (purchItems == null) // No purchItems already in
session
{
purchItems = new PurchasedItems();
session.setAttribute(“PurchasedItems”, purchItems);
}
doSomethingWith(purchItems);
All the attribute names in a given session can be listed by calling the
getValueNames () method, which returns an array of strings. And you can use
getAttributeName,it returns an Enumeration, just like the getHeaderNames() and
getParameter Names() methods of HttpServletRequest.
Methods of HttpSession Interface
1. public void HttpSession.setAttribute(String name, Object value)
This method adds data to a session object.
2. public Object HttpSession.getAttribute(String name)
You can use the given method to retrieve an object from a session
3. public Enumeration HttpSession.getAttributeNames()
You can use this method to get the names of all objects in a session
Self-Instructional
236 Material
4. public void HttpSession.removeAttribute(String name) Cookies and Session
Tracking
You can use this method to remove an object from a session.
5. boolean isNew()
Returns true if the client does not yet know about the session or if the client NOTES
chooses not to join the session.
6. void invalidate()
Invalidates this session then unbinds any objects bound to it.
7. long getCreationTime()
Returns the time when this session was created, measured in milliseconds
since midnight January 1, 1970 GMT.
8. long getLastAccessedTime()
Returns the last time the client sent a request associated with this session, as
the number of milliseconds since midnight January 1, 1970 GMT, and
marked by the time the container received the request.
Note: The use of these methods can be seen in the application discussed as example.
Deprecated methods since API 2.2 (NOT IN USE NOW)
(i) putValue(),
(ii) getValue();
(iii) getValueNames();
(iv) removeValue()
A Web Page Visit-Counter Servlet
A real feel of the servlet use can be taken once you run it on the browser. Down
below is the complete code of an application illustrating use of HttpSession APIs.
Just deploy the application as instructed in previous section.
VisitCounterServletEx.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class VisitCounterServletEx extends HttpServlet
{
public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
PrintWriter out = resp.getWriter();
resp.setContentType(“text/html”);
HttpSession thisUser = req.getSession(true);
Integer visits; Self-Instructional
Material 237
Cookies and Session if (!thisUser.isNew()) { //Don’t check newly created
Tracking sessions
visits =
(Integer)thisUser.getValue(“visitcounter.visits”);
NOTES if(visits == null)
visits = new Integer(1);
else
visits = new Integer(visits.intValue() + 1);
}
else
visits = new Integer(1);
// Put the new count in the session
thisUser.putValue(“visitcounter.visits”, visits);
// Finally, display the results and give them the
session ID too
out.println(“<HTML><HEAD><TITLE>Visit Counter</TITLE></
HEAD>”);
out.println(“<BODY>You have visited this page “ +
visits + “ time[s]”);
out.println(“since your last session expired.”);
out.println(“Your Session ID is “ + thisUser.getId());
out.println(“</BODY></HTML>”);
}}
web.xml
<?xml version=”1.0" encoding=”ISO-8859-1"?>
<web-app >
<servlet>
<servlet-name>VCSE</servlet-name>
<servlet-class>VisitCounterServletEx</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>VCSE</servlet-name>
<url-pattern>/fts1</url-pattern>
</servlet-mapping>
</web-app>
Output:
What you will see is a statement on the browser about how many times you have
visited the page since you page last expired. Every refreshing to the URL will
increase the number of visits.
Self-Instructional
238 Material
Activity: Try to open the web page in multiple browsers in the same system. Cookies and Session
Tracking
Find the results and make conclusions. Also try implementing in your application.
12.5 SUMMARY
The Web knows only one protocol for communication, HTTP but it is
stateless.
Session management is essential in every E-Com web applications so as to
keep track of their user’s preferences and the site visitors.
Utilizing the client side applications (like browsers) to store the client
information and then creating a mechanism to send the information to the
server so that it recognizes the client is generally referred to as Client Side
Session tracking.
This is an excellent solution and is the most widely used approach for session
handling.
In HttpSession technique, the Servlet container implicitly generates a cookies
for transferring the session ID between server and client.
URL rewriting is one of the best methods that can be implemented to track
a session when cookies do not work on the browsers or cookies have
been disabled by the user.
Self-Instructional
240 Material
Looking up of the HttpSession object can be done by calling the getSession() Cookies and Session
Tracking
method of HttpServletRequest.
You can easily create a new session and also check if it’s a new one or the
existing one.
NOTES
A real feel of the servlet use can be taken once you run it on the browser.
Many times you do not get what was intended from the Servlets, it may be
because you did not code well or it may be because of some bugs in the
programs.
The easiest technique is to insert a couple of print statements to find out
which line of code generated the error.
The integrated development environments (IDEs) have advanced debugging
tools that can be integrated with your servlet and JSP container. But an
expertise in these IDE is a must for this.
Sometimes, we make minor mistakes in writing the web.xml for the servlets,
like missing to write any parenthesis or writing the names of the Servlet
class in the descriptor.
Short-Answer Questions
1. What do you understand by session management and tracking?
2. Explain about client side session tracking.
3. Analyse the server side session tracking.
Long-Answer Questions
1. Explain how to look up the HttpSession object associated with the current
request.
2. What are the advantage of cookies? Explain.
3. What do you mean by the the hidden form fields?
4. What do you mean by Http session interface and the session tracking API?
Self-Instructional
Material 241
Cookies and Session
Tracking 12.8 FURTHER READINGS
Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
NOTES Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.
Self-Instructional
242 Material
Java Interface
COMPONENTS
NOTES
Structure
13.0 Introduction
13.1 Objectives
13.2 Swing Components and Containers
13.2.1 Swing Components (JComponent Class)
13.2.2 Swing Containers
13.3 Creating a Swing Applet and Application
13.4 User Interface Components
13.4.1 JApplet
13.4.2 JFrame
13.4.3 Label
13.4.4 Button
13.4.5 ToggleButton
13.4.6 CheckBox
13.4.7 TextField
13.4.8 TextArea
13.4.9 RadioButton
13.4.10 Panel
13.4.11 ScrollPane
13.4.12 ComboBox
13.4.13 JTree Class
13.5 Programming using Panes
13.5.1 Layered Panes
13.5.2 Split Panes
13.5.3 Tabbed Panes
13.6 JTable
13.7 Answers to Check Your Progress Questions
13.8 Summary
13.9 Key Words
13.10 Self Assessment Questions and Exercises
13.11 Further Readings
13.0 INTRODUCTION
In this unit, you will learn about the various components of swing. Swing, a part of
Java Federation Classes (JFC) is the next generation GUI toolkit that allows us to
develop large scale enterprise applications in Java. It is a set of classes which
provides many powerful and flexible components for creating graphical user
interface. Earlier, the concept of Swing did not exist in Java and the user interfaces
were built by using the Java’s original GUI system, AWT. Because of the limitations
of the AWT, Swing was introduced in 1997 by the Sun Microsystems. It provides
new and improved components that enhance the look and functionality of GUIs.
Self-Instructional
Material 243
Java Interface
Components 13.1 OBJECTIVES
Like AWT GUI, Swing GUI is also based on the concept of components and
containers. A container is a type of component that can hold other components. A
component must always be placed within a container. A container can also hold
other containers, thus, they can be organized in a hierarchy. This class hierarchy is
similar to that of AWT but in Swing, the name of class is preceded by ‘J’.
13.2.1 Swing Components (JComponent Class)
Swing component is an independent control, such as button, label, text field, etc.
They need a container to display themselves. Swing components are derived from
JComponent class. JComponent provides the functionality common for
all components. JComponent inherits the AWT class Container and
Component. Thus, a Swing component and AWT component are compatible
with each other. Table 13.1 lists the classes required for creating various Swing
components (including those used as containers).
Table 13.1 List of Classes for Swing Components
Self-Instructional
244 Material
13.2.2 Swing Containers Java Interface
Components
There are two types of containers namely, top-level containers and lightweight
containers.
Top-Level Containers NOTES
A top-level container, as the name suggests, lies at the top of the containment
hierarchy. The top-level containers are JFrame, JApplet, and JDialog.
These containers do not inherit JComponent class but inherit the AWT
classes’ Component and Container. These containers are heavyweight
components. The most commonly used containers are JFrame and JApplet.
Each top-level container defines a set of panes. JRootPane is a special
container which extends JComponent and manages the appearance of
JApplet and JFrame objects. It contains a fixed set of panes, namely, glass
pane, content pane, and layered pane.
Glass Pane: A glass pane is a top-level pane which covers all other
panes. By default, it is a transparent instance of JPanel class. It is
used to handle the mouse events affecting the entire container.
Layered Pane: A layered pane is an instance of JLayeredPane
class. It holds a container called the content pane and an optional menu
bar.
Content Pane: A content pane is a pane which is used to hold the
components. All the visual components like buttons, labels are added to
content pane. By default, it is an opaque instance of JPanel class
and uses border layout. The content pane is accessed via
getContentPane() method of JApplet and JFrame classes.
Note: In AWT, the components are directly added to the applet or frame window,
however, in Swing, they are required to be added to the content pane.
Lightweight Containers
Lightweight containers lie next to the top-level containers in the containment
hierarchy. They inherit JComponent. One of the examples of lightweight
container is JPanel. As lightweight container can be contained within another
container, they can be used to organize and manage groups of related components.
The sample program given below shows an example to write a Swing application.
It uses two Swing components: JFrame (top-level container) and JButton
(component which creates a push button).
Self-Instructional
Material 245
Java Interface Example 13.1: A program to demonstrate the creation of a Swing application.
Components
import javax.swing.*;
class MySwingDemo extends JApplet
{
NOTES
public static void main(String str[])
{
//creates a new frame
JFrame jf = new JFrame(“Swing application”);
//specify the initial size of the frame
jf.setSize(300,125);
//Terminates the program
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
//create a new button
JButton b1 = new JButton(“Click”);
//Adding button to the frame
jf.add(b1);
//Display the frame
jf.setVisible(true);
}
}
Swing programs are compiled and executed like any other Java application.
The program given in Example 13.1 can be compiled by using the following
command.
javac MySwingDemo.java
To execute the program, following command is used.
java MySwingDemo
The output of the program is
By, default when user clicks the close button, the window is removed from
the display; however, the application is not terminated. The application still occupies
space in memory, which is not required in most of the cases. To terminate the
application when user clicks the close button of the top-level window, the
setDefaultCloseOperation() method is used.
13.4.3 Label
A label is a simple control which is used to display text (non-editable) on the
window. Since it does not possess any user interactive feature, it is considered as
a passive control. A label is an object of JLabel class.
Some of the constructors defined by JLabel class are as follows:
JLabel()
JLabel(String string)
JLabel(String string, int align)
where,
string is the text used for the label
align specifies the horizontal alignment of the text contained in the label,
and can have one of the following values: LEFT, RIGHT, CENTER, LEADING
or TRAILING Self-Instructional
Material 249
Java Interface 13.4.4 Button
Components
A button, also known as push button, is an active control that has a 3-dimensional
appearance. It triggers an event when it is clicked or activated. Swing also provides
NOTES an ability to associate an icon, a string, or both with the buttons. A push button is
an object of JButton class.
Some of the constructors defined by JButton class are as follows:
JButton()
JButton(Icon icon)
JButton(String string)
where,
string represents the string used for the button
icon represents the icon used for the button
Note: All the buttons are derived from AbstractButton class.
13.4.5 ToggleButton
Swing provides a variant of push button called ToggleButton which has
two states: pushed and released. When ToggleButton is pressed for the
first time, it remains pressed and it is released only when it is pressed for the
second time. This button toggles between pushed and released state.
ToggleButton is an object of JToggleButton class.
Some of the constructors defined by JToggleButton class are as
follows:
JToggleButton()
JToggleButton(String string)
JToggleButton(String string, boolean state)
where,
string specifies the text
state can have one of the two values: true, if the button is initially
selected, otherwise false (default value)
13.4.6 CheckBox
A checkBox is a control that consists of a combination of a small box and a
label. The label provides the description of the box with which it is associated. It
is a two-state control having states true (checked) and false (unchecked).
The state of a CheckBox can be changed by clicking on it. A CheckBox is an
object of JCheckBox class.
Some of the constructors defined by JCheckBox class are as follows:
JCheckBox()
JCheckBox(String string)
Self-Instructional
JCheckBox(String string, boolean isSelected)
250 Material
where, Java Interface
Components
string is the text used as a label for the CheckBox
isSelected is used to set the initial state of the CheckBox. If it is
true, the CheckBox is checked, otherwise it is unchecked. The default state NOTES
of the CheckBox is false.
13.4.7 TextField
TextField control creates a single-line text area. The TextField allows
the user to enter and edit the text using cut, copy and paste keys, arrow keys and
mouse selections. It is an object of JTextField class which is a subclass of
JTextComponent.
Some of the constructors defined by JTextField class are as follows:
JTextField()
JTextField(int cols)
JTextField(String string, int cols)
JTextField(String string)
where,
string is the initial string contained in the text field
cols is the width of the text field in terms of columns
13.4.8 TextArea
The TextArea creates a multi-line text area. It does not provide scrolling
facility; however, scroll bars can be added by adding the JTextArea in
JScrollPane container. A TextArea is an object of JTextArea class
which is a subclass of JComponent.
Some of the constructors defined by JTextArea class are as follows:
JTextArea()
JTextArea(String str1)
JTextArea(int rows, int cols)
JTextArea(String str1, int rows, int cols)
where,
str1 is the initial string contained in TextArea
rows represents the height of the TextArea or the maximum rows a
text area can have
cols represents the width of the text area, that is, the maximum number
of characters each line of the text area can contain
13.4.9 RadioButton
Radio buttons are a group of buttons, in which, only one radio button can be
selected at one time. That is, when you select any one RadioButton, then the
Self-Instructional
Material 251
Java Interface other selected RadioButton will get deselected automatically. A
Components
RadioButton is an object of JRadioButton class.
Some of the constructors defined by JRadioButton class are as follows:
NOTES JRadioButton()
JRadioButton(String string)
JRadioButton(String string, boolean state)
where,
string specifies the text
state can have one of the two values: true, if the button is initially
selected, otherwise false (default value)
Note: Button groups (javax.swing.ButtonGroup) are used in combination with
radio buttons to ensure that only one radio button is selected at a time.
13.4.10 Panel
Panel is a container to hold different Swing components. One can add any number
of components to a panel and there can be multiple panels in the same frame. It
also supports double buffering which is used in animation to avoid flickering. In
double buffering, object is first written to an off-screen memory before display
and then switched over to the panel. Flow layout is the default layout for the panel.
A panel is an object of class JPanel which is present in package
javax.swing.
Some of the constructors defined by JPanel class are as follows:
JPanel()
JPanel(boolean isDoubleBuffered)
JPanel(LayoutManager layout)
JPanel(LayoutManager layout, boolean isDoubleBuffered)
where,
isDoubleBuffered defines whether the panel is double buffered or
not. It can have one of the values: true (double buffered) or false (not double
buffered)
layout defines the layout of the panel
13.4.11 ScrollPane
A ScrollPane is a container that represents a small area to view other
component. If the component is larger than the visible area, ScrollPane
provides horizontal and/or vertical scroll bars automatically for scrolling the
components through the pane. A ScrollPane is an object of the
JScrollPane class which extends JComponent.
Some of the constructors defined by JScrollPane class are as follows:
JSrollPane()
Self-Instructional JScrollPane(Component component)
252 Material
JScrollPane(int ver, int hor) Java Interface
Components
JScrollPane(Component component, int ver, int hor)
where,
component is the component to be added to the ScrollPane NOTES
ver and hor specify the policies to display the vertical and horizontal
scroll bar, respectively. Some of the standard policies are:
H O R I Z O N T A L _ S C R O L L B A R _ A L W A Y S ,
HO RIZO NTAL _SCR OLL BAR_AS_N EEDED,
V E R T I C A L _ S C R O L L B A R _ A L W A Y S ,
VERTICAL_SCROLLBAR_AS_NEEDED
Note: JScrollPane is a lightweight container.
13.4.12 ComboBox
A ComboBox is a combination of a list component and text field component. It
can consist of more than one item, however, displays only one item at any point of
time. It also allows user to type their selection. Unlike list component, combo box
allows user to select only one item at a time. A ComboBox is an object of
JComboBox class.
Some of the constructors defined by JComboBox class are as follows:
JComboBox()
JComboBox(Object combodata[])
where,
combodata represents the array of Object type that displays the
elements
Example 13.3: A program to demonstrate the use of JComboBox class
import java.awt.*;
import javax.swing.*;
public class ComboBoxExample extends JApplet
{
ComboBoxExample()
{
JFrame jf=new JFrame(“Example of ComboBox”);
JPanel jp1=new JPanel(new GridLayout(5,2));
JPanel jp2=new JPanel();
JPanel jp3=new JPanel(new GridLayout(2,2));
JLabel jl1,jl2,jl3,jl4;
JTextField jt1,jt2,jt3,jt4,jt5;
JButton jb1,jb2;
JComboBox jc1;
jl1=new JLabel(“ Name:”);
jl2=new JLabel(“Address:”); Self-Instructional
Material 253
Java Interface jl3=new JLabel(“Contact:”);
Components
jl4=new JLabel(“Country:”);
jt1=new JTextField(20);
jt2=new JTextField();
NOTES
jt3=new JTextField();
jt4=new JTextField();
jt5=new JTextField();
jb1=new JButton(“Submit”);
jb1.setSize(3,4);
jb2=new JButton(“Cancel”);
jc1=new JComboBox();
//creating an instance
//of ComboBox
jc1.addItem(“India”);
jc1.addItem(“USA”);
jc1.addItem(“UK”);
jc1.addItem(“Sri lanka”);
jc1.addItem(“China”);
jc1.addItem(“Nepal”);
jp1.add(jl1);
jp1.add(jt1);
jp1.add(jl2);
jp1.add(jt2);
jp1.add(jl3);
jp1.add(jt3);
jp1.add(jl4);
jp1.add(jc1);
jp2.add(jb1);
jp2.add(jb2);
jp3.add(jp1);
jp3.add(jp2);
jf.add(jp3);
jf.setVisible(true);
jf.setSize(400,300);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
ComboBoxExample combo= new ComboBoxExample();
}
Self-Instructional
}
254 Material
The output of the program is Java Interface
Components
NOTES
Self-Instructional
Material 255
Java Interface Methods
Components
The various methods are:
add(Object node)
NOTES This method is invoked by the root node in order to add a node to the root node.
getNewLeadSelectionPath()
Each node present in the tree contains data or element. When one selects an item,
this method is used to return the path that describes the position of the element in
the tree. This method returns a TreePath object.
getLastPathcomponent()
This method returns the item or element that is selected by the user.
getPathCount()
This method is invoked to know the number of paths available to the particular
node.
In this section, we will discuss working the various pane classes, namely,
JLayeredPane, JTabbedPane and JSplitPane.
13.5.1 Layered Panes
A layered pane is a Swing container which is used to hold the various components
using the concept of layers. The components present in the upper layer overlaps
the components present in the lower layer. The layered pane is created using the
J L a y e r e d P a n e class. The only constructor of this class is
JLayeredPane().
Example 13.4: A program to demonstrate the use of JLayeredPane class
import java.awt.*;
import javax.swing.*;
class LayerExample extends JApplet
{
JFrame jf ;
JLayeredPane LPane;
Self-Instructional JButton first, second, third;
256 Material
LayerExample() Java Interface
Components
{
jf = new JFrame(“Layered Pane Example”);
LPane = new JLayeredPane();
NOTES
jf.getContentPane().add(LPane);
first = new JButton(“First”);
first.setBackground(Color.red);
first.setBounds(50,30,100,100);
second = new JButton(“Second”);
second.setBackground(Color.yellow);
second.setBounds(140,60,100,100);
third = new JButton(“Third”);
third.setBackground(Color.green);
third.setBounds(230,90,100,100);
LPane.add(first, new Integer(3));
LPane.add(second, new Integer(2));
LPane.add(third, new Integer(1));
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setSize(400,300);
jf.setVisible(true);
}
public static void main(String args[])
{
LayerExample le = new LayerExample();
}
}
The output of the program is
Self-Instructional
Material 257
Java Interface 13.5.2 Split Panes
Components
A split pane is a lightweight container that allows you to arrange two components
(only two) side by side horizontally or vertically in a single pane. The display areas
NOTES of both the components can also be adjusted at the runtime by the user. A split
pane is an object of JSplitPane class.
Some of the constructors defined by JSplitPane class are as follows:
JSplitPane()
JSpliPane(int orientation, boolean continuousLayout)
JSplitPane(int orientation, Component TopOrLeft, Component
BottomOrRight)
JSplitPane(int orientation, boolean continuousLayout ,
Component TopOrLeft, Component BottomOrRight)
where,
orientation specifies how components will be arranged—can have
one of the two values: HORIZONTAL_SPLIT and VERTICAL_SPLIT
continuousLayout can have one of the two values: true, if the
components are resizable when divider is moved, otherwise false (default value)
jf.getContentPane().add(SPane, BorderLayout.
CENTER);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE); NOTES
jf.setSize(400,300);
jf.setVisible(true);
}
public static void main(String args[])
{
SplitExample se = new SplitExample();
}
}
The output of the program is
jf.getContentPane().add(TPane, BorderLayout.
CENTER);
lab1 = new JLabel(“Select city:”);
city1 = new JCheckBox(“Chennai”,true);
city2 = new JCheckBox(“Mumbai”);
lab2 = new JLabel(“Select state:”);
state1 = new JCheckBox(“Tamil Nadu”, true);
state2 = new JCheckBox(“Maharashtra”);
panel1 = new JPanel(new GridLayout(1,3));
panel2 = new JPanel(new GridLayout(1,3));
Self-Instructional
260 Material
panel1.add(lab1); Java Interface
Components
panel1.add(city1);
panel1.add(city2);
panel2.add(lab2);
NOTES
panel2.add(state1);
panel2.add(state2);
TPane.addTab(“Cities”, panel1);
TPane.addTab(“States”, panel2);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setSize(400,200);
jf.setVisible(true);
}
public static void main(String args[])
{
TabbedExample se = new TabbedExample();
}
}
The output of the program is
Self-Instructional
Material 261
Java Interface
Components 13.6 JTable
A table is used to display data in the form of rows and columns. It can also allow
NOTES editing of data which is optional. By default, the columns of a table can be resized.
It can be accomplished by dragging the mouse along with their boundaries. The
columns can also be dragged to a new position. A table is an object of class
JTable which is a subclass of JComponent.
Some of the constructors defined by the JTable class are as follows:
JTable()
JTable(int rows, int cols)
JTable(Object[][] rowData, colNames)
where,
rows represents the number of rows with empty cells
cols represents the number of columns with empty cells
rowData represents the two-dimensional array containing the data of
rows
colNames specifies the name of the columns
Example 13.7: A program to demonstrate the use of a table
import javax.swing.*;
class SwingTable extends JApplet
{
public static void main(String str[])
{
JFrame jf = new JFrame(“Demo of table”);
String data[][] = {
{“1”, “Premashis”, “89%”},
{“2”, “Preeti”, “88%”},
{“3”, “Pooja”, “87%”},
{“4”, “Niti”, “86%”},
{“5”, “Shruti”, “85%”},
{“6”, “Vriti”, “84%”},
{“7”, “Surender”, “83%”},
{“8”, “Rajesh”, “82%”},
{“9”, “Raja”, “81%”},
{“10”, “Meenu”, “80%”},
{“11”, “Uma”, “79%”}
};
String fields[] = {“
Self-Instructional
262 Material
RollNumber”, “Name”, “Percentage”}; Java Interface
Components
JTable jt = new JTable(data,fields);
JScrollPane pane = new JScrollPane(jt);
jf.add(pane);
NOTES
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setSize(300,200);
jf.setVisible(true);
}
}
The output of the program is
1. There are two types of containers namely, top-level containers and lightweight
containers.
2. JApplet is a class that represents the Swing applet. It is a subclass of Applet
class and must be extended by all the applets that use Swing.
3. Panel is a container to hold different Swing components. One can add any
number of components to a panel and there can be multiple panels in the
same frame.
Self-Instructional
Material 263
Java Interface 4. A layered pane is a Swing container which is used to hold the various
Components
components using the concept of layers.
5. A split pane is a lightweight container that allows you to arrange two
components (only two) side by side horizontally or vertically in a single
NOTES
pane.
13.8 SUMMARY
Like AWT GUI, Swing GUI is also based on the concept of components
and containers. A container is a type of component that can hold other
components.
Swing component is an independent control, such as button, label, text
field, etc. They need a container to display themselves. Swing components
are derived from JComponent class.
There are two types of containers namely, top-level containers and
lightweight containers.
A top-level container, as the name suggests, lies at the top of the containment
hierarchy. The top-level containers are JFrame, JApplet, and
JDialog. These containers do not inherit JComponent class but
inherit the AWT classes’ Component and Container.
Lightweight containers lie next to the top-level containers in the containment
hierarchy. They inherit JComponent.
JApplet is a class that represents the Swing applet. It is a subclass of Applet
class and must be extended by all the applets that use Swing.
A button, also known as push button, is an active control that has a 3-
dimensional appearance. It triggers an event when it is clicked or activated.
Swing provides a variant of push button called ToggleButton which
has two states: pushed and released. When ToggleButton is pressed
for the first time, it remains pressed and it is released only when it is pressed
for the second time.
A ScrollPane is a container that represents a small area to view other
component.
A ComboBox is a combination of a list component and text field
component. It can consist of more than one item, however, displays only
one item at any point of time.
A table is an object of class JTable which is a subclass of
JComponent.
Self-Instructional
264 Material
Java Interface
13.9 KEY WORDS Components
Short-Answer Questions
1. What are swing components and containers?
2. What are the constructors defined by JPanel?
3. Write a note on JTabbedPane and JSplitPane.
Long-Answer Questions
1. Explain the top-level containers.
2. Write a program to demonstrate the creation of swing application.
3. Explain the following interface components.
(i) JApplet
(ii) JTable
(iii) JTree
(iv) Button
Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.
Self-Instructional
Material 265
AWT Classes and
Working with Graphics
UNIT 14 AWT CLASSES AND
WORKING WITH
NOTES
GRAPHICS
Structure
14.0 Introduction
14.1 Objectives
14.2 Introducing Abstract Window Toolkit
14.2.1 Component Class
14.2.2 Container Class
14.3 Working with Graphics
14.3.1 Using Graphics Class
14.3.2 Using Color Class
14.3.3 Using Font Class
14.3.4 Using Image Class
14.4 Answers to Check Your Progress Questions
14.5 Summary
14.6 Key Words
14.7 Self Assessment Questions and Exercises
14.8 Further Readings
14.0 INTRODUCTION
In this unit, you will learn about the AWT (Abstract Window Toolkit). Abstract
Window Toolkit provides several graphics, windowing and user interface tools
which are used to develop GUI of applets as well as stand-alone applications
running in GUI environment. In order to use the classes and interfaces defined in
AWT, java.awt.* package needs to be imported. You will also learn how
to create applet that uses various classes to draw shapes, images and display text.
14.1 OBJECTIVES
Self-Instructional
266 Material
AWT Classes and
14.2 INTRODUCING ABSTRACT WINDOW Working with Graphics
TOOLKIT
An end user interacts with applications via an interface. Java Development Kit NOTES
(JDK) provides a package called the Abstract Window Toolkit (AWT) that enables
you to design user-friendly interfaces. The AWT package is a collection of classes
and methods that allow an end user to design and manage Graphical User Interface
(GUI) based applications. AWT is used to support Applet windows and it also
helps in creating independent windows, such as frame window or panel window
that run in GUI environment.
This unit describes the different classes of the AWT package. It explains
how to create and set properties for a frame window. This unit also discusses how
to manage fonts and colors in a frame window. The unit explains how to design
and implement graphics, such as lines, rectangles, ellipses and polygons in a frame
window or panel.
AWT is Java’s largest package and can be included in Java program by
giving the java.awt.* statement. It is a part of Java Foundation Classes
(JFC). AWT has 63 classes and 14 interfaces used for creating user interfaces.
You can use AWT classes and interfaces to design and manage components, such
as lines, rectangles, ellipses, polygons, text boxes, command buttons, lists, menus
and scroll bars.
Features of the AWT package are:
It provides graphics and imaging tools that enable you to develop GUI.
It provides layout managers that enable an end user to develop window
layouts.
It supports event handling. For example, an error occurred in between
execution of a program.
The java.awt package contains all the classes used for developing
graphical interfaces. These classes are organized in a hierarchical order. Figure
14.1 shows the hierarchy of classes in the java.awt package.
The above figure shows the multi-level inheritance structure of AWT classes
and subclasses. Multi-level inheritance means that a derived class has more than
one base class, for example, Frame class is derived from Window class, which
is derived from the Container class. Component class and Container
class are the two important classes of AWT package. Component class
Consists of subclasses and methods for creating Components, such as
command button, text boxes and labels. The container class enables you to create
objects, such as frames that contain components.
Self-Instructional
Material 267
AWT Classes and
Working with Graphics
NOTES
All other classes are the subclasses of these two classes. Each subclass
inherits the characteristics of its super class. Apart from inheriting the functionality
of the upper class, it also has some additional functionality that is unique to its
level.
14.2.1 Component Class
Component class is at the top of the AWT inheritance class hierarchy. It is the
super class and all other classes in the hierarchy inherit its characteristics directly
or indirectly. Component class is an abstract class that encapsulates all the
properties of a visual component or object.
Component class defines various methods that are used to handle events,
define the layout of component, providing content of the component and repainting
the window in between the execution of the program. The methods that the objects
of the components class use include:
void setSize (int width, int height): Defines the
size of a component in terms of width and size.
void setLocation (int x, int y): Specifies the
location of a component, in the window, at the position specified by the
x and y coordinates.
void setBounds (int x, int y, int width, int
height): Sets the bounds of a component in terms of position x & y
Self-Instructional and size in terms of width and height.
268 Material
void setForeground (Color B): Sets the foreground AWT Classes and
Working with Graphics
color of the component.
void setBackground (Color B): Sets the background
color of the component.
NOTES
14.2.2 Container Class
Container class is the subclass of Component class and its objects inherit
all the characteristics of the Component class. Therefore, container objects
can also be used as component objects. The objects of Container class are
also known as containers. This class supports nested container objects. You can
place one container object inside another container object, if required.
It is the function of the container object to determine the position of other
component objects that it contains. Layout managers are responsible for performing
this function.
Containers use the add() function to nest other components inside it.
Methods that are used to manipulate components on container objects are:
void add (object o): Nests a component or an object inside
a container.
void remove (object o): Removes a component or an
object from a container.
void removeALL(): Removes all the components or objects that
are placed inside a container.
Panel Class
Panel is a subclass of the Container class and is used for organizing
components. Panel class inherits methods from its super class rather than defining
them. Panel class uses the add() method to nest components inside it.
Panel class is the super class of Applet class. Panel class does not
contain border, title bar or menu bar. It supports nested panel objects. A panel
container object can have more than one panel and different panels can have
different layouts.
In addition to the add() method, the methods that the Panel class uses
are:
panel(): Creates an object of the Panel class.
setLocation(): Determines the position of a component inside
the panel.
setSize(): Sets the size of a component in terms of width and
height.
setBounds(): Sets the bounds of a component in terms of position
and size.
Self-Instructional
Material 269
AWT Classes and Window Class
Working with Graphics
Window is another subclass of the Container class. Its objects are called
windows and they are the top-level containers. Window objects are not contained
NOTES in any other object.
You can place window objects directly on the desktop. The Window
class has two subclasses, frames and dialog.
The methods used by the Window class include:
void pack(): Adjusts the layout of a window according to the size
and number of components it holds.
void show(): Displays a window on the screen and places the
window on the top of other windows that may be open on the desktop.
void dispose(): Deallocates the memory allotted to a window.
Frame Class
Frame is the subclass of the Window class. The frame class enables you to
create pop-up windows. Frame class is an important class of AWT that enables
an end user to create stand-alone applications. Frame window has a border, title
bar and menu bar. Default layout for frame is border layout. Its objects respond to
mouse, keyboard and focus events.
Frame objects are created either through an Applet program or through any
other Java program using its constructor. If a frame object is created in an applet,
it displays a message like Java Applet Window. Objects can be added to a frame
using the add() method.
Canvas Class
Canvas class is another type of Window class and is used to create blank
windows. Canvas objects are used for the drawing purpose only, but they can
enable an end user to create customized components. Canvas constructor takes
no arguments and creates an empty drawing area. Canvas class does not define
any method. It inherits the paint() method from the Component class that
needs to be overridden to provide the drawing functionality.
Java also allows creating applet that uses various classes to draw figures of different
shapes, add images, display text in different fonts and styles, use and create various
colors, etc. Some of these classes are discussed in this section.
14.3.1 Using Graphics Class
The Graphics class provides different methods to draw and fill various shapes.
Self-Instructional
270 Material
Drawing Lines AWT Classes and
Working with Graphics
A line can be drawn using the drawLine() method of the Graphics class.
This method takes four parameters which represent the coordinates of the end
points of the line. NOTES
The general form of the drawLine() method is
void drawLine(int a1, int b1, int a2, int b2)
where,
a1, b1 is the coordinate of the starting points of the line
a2, b2 is the coordinate of the starting points of the line
For example, the statement gra.drawLine(20,100,90,100)
will draw a straight line from the coordinate point (20,100) to (90,100)
as shown in Figure 14.2.
30 (height)
50 (width)
Note that the drawRect() method draws only the boundary of the
rectangle. To draw a solid (filled) rectangle, fillRect() method is used. This
method also takes four parameters similar to the drawRect() method. Self-Instructional
Material 271
AWT Classes and To draw a solid rectangle the having same parameters as above, you can
Working with Graphics
use the statement gra.fillRect(20,20,50,30) which draws the
rectangle as shown in Figure 14.4.
30 (height)
50 (width)
Fig. 14.4 A Filled Rectangle with Width 50 pixels and Height 30 pixels
w(width)
xdia, ydia (arc)
where,
xdia is the diameter of the rounding arc (along X-axis)
ydia is the diameter of the rounding arc (along Y-axis)
Similarly, a rounded filled rectangle can be drawn using
drawfillRoundRect() method. This method also takes six parameters
similar to the drawRoundRect() method.
Note: All the shapes are drawn relative to the Java’s coordinate system. The
origin (0, 0) of the coordinate system is located at its upper-left corner such that
the positive x values are to its right and the positive y values are to its bottom.
Drawing and Filling Ellipses and Circles
An ellipse can be drawn using the drawOval() method. The ellipse is drawn
within an imaginary bounding rectangle. This method takes four arguments in which
the first two represent the top left corner of the bounding rectangle and the next
Self-Instructional
272 Material
two represent the width and height of the oval or the bounding rectangle (see AWT Classes and
Working with Graphics
Figure 14.6).
The general form of the drawOval() method is
void drawOval(int a1, int b1, int w, int h) NOTES
where,
a1, b1 is the coordinate of the top left corner of the bounding rectangle.
w is the width of the bounding rectangle.
h is the height of the bounding rectangle.
height
width
Similarly, a circle can be drawn using this method but the dimension of
width and height should be the same. That is, the bounding rectangle must be a
square.
Similar to rectangle methods, the drawOval() method draws the
boundary of an oval and the fillOval() method draws a solid oval.
Drawing Arcs
An arc can be drawn using the drawArc() method. This method takes six
arguments in which the first four are the same as the arguments of the
drawoval() method and the next two represent the starting angle of the arc
and the sweep angle around the arc, respectively.
The general form of the drawArc() method is
void drawArc(int a1, int b1, int w, int h, int strt_angle,
int sweep_angle)
where,
a1,b1 is the coordinate of the top left corner of the bounding rectangle.
w is the width of the bounding rectangle.
h is the height of the bounding rectangle.
strt_angle is the starting angle of the arc (in degrees).
sweep_angle is the number of degrees (angular distance) around the arc (in
degrees).
The arc shown in Figure 14.7 has the starting angle as 00 degrees and sweep angle
as 1350.
Self-Instructional
Material 273
AWT Classes and 90o
Working with Graphics Arc
180o 135o
NOTES
0o
270o
You can also draw filled arcs using the fillArc() method.
Drawing Polygons
A polygon is a closed geometrical figure, which can have any number of sides. A
polygon can be drawn by using the drawPolygon() method. This method
takes the three parameters.
The general form of the drawPolygon() method is
void drawPolygon(int a[], int b[], int n)
where,
a[] is the array of integers having x-coordinates.
b[] is the array of integers having y-coordinates.
n is the total number of coordinate points required to draw a polygon.
(a1, b1) (a2, b2)
(a3, b3)
(a6, b6)
gra.drawOval(0,125,80,40);
gra.fillOval(120,125,80,40);
gra.drawArc(240,125,80,40,0,180);
gra.fillArc(370,125,80,40,0,180);
int x[]={100,150,200,170,130,100};
int y[]={250,200,250,300,300,250};
int n=x.length;
gra.drawPolygon(x,y,n);
gra.drawOval(270,200,80,80);
gra.fillOval(380,200,80,80);
gra.drawLine(480,50,480,350);
}
}
The HTML code for GraphicsExample is
<HTML>
<HEAD>
</HEAD>
<BODY>
<CENTER>
<APPLET
CODE=”GraphicsExample.class”
WIDTH =”600"
HEIGHT=”350>
</APPLET>
</CENTER>
</BODY>
</HTML>
Self-Instructional
Material 275
AWT Classes and The output of the HTML code is as follows:
Working with Graphics
NOTES
Self-Instructional
Material 277
AWT Classes and The HTML code for ColorExample is
Working with Graphics
<HTML>
<HEAD>
</HEAD>
NOTES
<BODY>
<CENTER>
<APPLET
CODE=”ColorExample.class”
WIDTH =”600"
HEIGHT=”250">
</APPLET>
</CENTER>
</BODY>
</HTML>
Self-Instructional
278 Material
Some other methods of Font class are listed in Table 14.1 AWT Classes and
Working with Graphics
Table 14.1 Methods of Font class
Method Description
static Font getFont() returns the currently selected font NOTES
int getSize() returns the size of the font
String getName() returns the name of the font
int getStyle() returns the style of the font
String getFamily() returns the name of the family of the font
}
}
The HTML code for FontExample is
<HTML>
<HEAD>
</HEAD>
<BODY>
<CENTER>
<APPLET
CODE=”FontExample.class”
WIDTH =”600"
HEIGHT=”250">
Self-Instructional
Material 279
AWT Classes and </APPLET>
Working with Graphics
</CENTER>
</BODY>
</HTML>
NOTES
The output of the HTML code is as follows:
Self-Instructional
Material 281
AWT Classes and
Working with Graphics
Check Your Progress
1. What are the two important classes of AWT package?
NOTES 2. Define container class.
3. Which method is used to draw an image on an applet?
1. Component class and container class are the two important classes of
AWT package.
2. Container class is the subclass of component class and its objects
inherit all the characteristics of the component class.
3. The Image class is used to load and display images. To load an image,
the getImage()method of the Image class is used and to display the
image the drawImage() method of the Graphics class is used.
14.5 SUMMARY
Self-Instructional
282 Material
The Font class is used to apply different font styles to the text. AWT Classes and
Working with Graphics
The Image class is used to load and display images. The Graphics
class also provides methods to add images to the applet.
NOTES
14.6 KEY WORDS
Short-Answer Questions
1. Discuss the features of AWT package.
2. Write a note on.
(i) Panel class
(ii) Window class
(iii) Frame class
(iv) Canvas class
Long-Answer Questions
1. Explain the hierarchy of classes in the java.awt package.
2. Explain the various methods of component and container class.
3. Write a program to display the following output:
Self-Instructional
Material 283
AWT Classes and
Working with Graphics 14.8 FURTHER READINGS
Schildt, Herbert. 2006. Java: The Complete Reference, 7th edition. New Delhi:
NOTES Tata McGraw-Hill.
Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd
edition. California: O’Reilly Media.
Self-Instructional
284 Material