0% found this document useful (0 votes)
228 views31 pages

Lesson 8 - Swing and JDBC: Notes

- The document discusses Swing and JDBC in Java. - Swing is a GUI toolkit that is used to create graphical user interfaces. It has many widgets and is lightweight. - JDBC is a Java API that allows Java code to connect to and interact with databases. It provides methods for querying and updating data. - An example shows how to create a basic window in Swing using JFrame.

Uploaded by

Afzal Husain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
228 views31 pages

Lesson 8 - Swing and JDBC: Notes

- The document discusses Swing and JDBC in Java. - Swing is a GUI toolkit that is used to create graphical user interfaces. It has many widgets and is lightweight. - JDBC is a Java API that allows Java code to connect to and interact with databases. It provides methods for querying and updating data. - An example shows how to create a basic window in Swing using JFrame.

Uploaded by

Afzal Husain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Lesson 8 - Swing and JDBC

LESSON 8 - SWING AND JDBC Notes

CONTENTS
Learning Objectives
Overview
8.1 Basics of Swing
8.2 JDBC
Summary
Keywords
Self-Assessment Questions
Further Readings

LEARNING OBJECTIVES
After studying this lesson, you should be able to:
z Learn basics of swing in Java
z Understand the JDBC and its working

OVERVIEW
In the previous lesson, you have learnt about generic methods, generic classes
arrays and working with applets and applet GUI.
In this lesson, you will study the JDBC, it is a Java-based data access
technology (Java Standard Edition platform) from Oracle Corporation. Do you
know that this technology is an API for the Java programming language that
defines how a client may access a database. It provides methods for querying
and updating data in a database.
In this lesson, you will also learn about the basics of swing in Java and
working with JDBC in detail.

8.1 BASICS OF SWING


Swing library is an official Java GUI toolkit released by Sun Microsystems. It
is used to create Graphical user interfaces with Java.
The main characteristics of the swing toolkit are as follows:
z Platform independent
z Customizable

147
Web Programming

Notes z Extensible
z Configurable
z Lightweight
The Swing API has 18 public packages. They are as follows:
z javax.accessibility
z javax.swing
z javax.swing.border
z javax.swing.colorchooser
z javax.swing.event
z javax.swing.filechooser
z javax.swing.plaf
z javax.swing.plaf.basic
z javax.swing.plaf.metal
z javax.swing.plaf.multi
z javax.swing.plaf.synth
z javax.swing.table
z javax.swing.text
z javax.swing.text.html
z javax.swing.text.html.parser
z javax.swing.text.rtf
z javax.swing.tree
z javax.swing.undo
Swing is an advanced GUI toolkit. It has a rich set of widgets. From basic
widgets like buttons, labels, scrollbars to advanced widgets like trees and
tables. Swing itself is written in Java.

Swing is a part of JFC (Java Foundation Classes).


It is a collection of packages for creating full featured desktop applications.
JFC consists of AWT, Swing, Accessibility, Java 2D, and drag and drop.
Swing was released in 1997 with JDK 1.2. It is a mature toolkit.
The Java platform has Java2D library, which enables developers to create
advanced 2D graphics and imaging.

148
Lesson 8 - Swing and JDBC

There are basically two types of widget toolkits: Notes


z Lightweight
z Heavyweight
A heavyweight toolkit uses OS's API to draw the widgets. For example
Borland's VCL is a heavyweight toolkit. It depends on WIN32 API, the built in
Windows application programming interface. On UNIX systems, we have
GTK+ toolkit, which is built on top of X11 library.

Swing is a lightweight toolkit. It paints its own widgets. Similarly


does the Qt4 toolkit.
SWT Library
There is also another GUI library for the Java programming language. It is
called SWT, the standard widget toolkit.

The SWT library was initially developed by the IBM


Corporation.
Now it is an open source project maintained by the Eclipse community. The
SWT is an example of a heavyweight toolkit. It lets the underlying OS to create
GUI. SWT uses the java native interface to do the job.

Example: We will show a basic window on the screen.


package com.zetcode;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class SimpleExample extends JFrame {

public SimpleExample() {

setTitle("Simple example");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

149
Web Programming

Notes public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
SimpleExample ex = new SimpleExample();
ex.setVisible(true);
}
});
}
}
While this code is very short, the application window can do quite a lot. It can
be resized, maximized, minimized. All the complexity that comes with it has
been hidden from the application programmer.
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
Here, we import Swing classes that will be used in the code example.
public class Example extends JFrame {
The example class inherits from the JFrame widget. JFrame is a toplevel
container. In the container, we put other widgets.
setTitle("Simple example");
Here, we set the title of the window using the setTitle() method.
setSize(300, 200);
This code will resize the window to be 300px wide and 200px tall.
setLocationRelativeTo(null);
This line will center the window on the screen.
setDefaultCloseOperation(EXIT_ON_CLOSE);
This method will close the window, if we click on the close button of the
titlebar. By default nothing happens.
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
SimpleExample ex = new SimpleExample();
ex.setVisible(true);
}
});
We create an instance of our code example and make it visible on the screen.

150
Lesson 8 - Swing and JDBC

Notes
The invokeLater() method places the application on the Swing
Event Queue.
It is used to ensure that all GUI updates are concurrency-safe. In other words, it
is to prevent GUI from hanging in certain situations.

Figure 8.1: Simple Example

Quit Button
In our next example, we will have a button. When we click on the button, the
application terminates.
package com.zetcode;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class QuitButtonExample extends JFrame {
public QuitButtonExample() {
initUI();
}
private void initUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
JButton quitButton = new JButton("Quit");
quitButton.setBounds(50, 60, 80, 30);
quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {

151
Web Programming

Notes System.exit(0);
}
});
panel.add(quitButton);
setTitle("Quit button");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
QuitButtonExample ex = new QuitButtonExample();
ex.setVisible(true);
}
});
}
}
We position a JButton on the window. We will add an action listener to this
button.
public QuitButtonExample() {
initUI();
}
It is a good programming practice to put the code that creates the GUI inside a
specific method.
JPanel panel = new JPanel();
getContentPane().add(panel);
We create a JPanel component. It is a generic lightweight container. We add
the JPanel to the JFrame.
panel.setLayout(null);
By default, the JPanel has a FlowLayout manager. The layout manager is used
to place widgets onto the containers.

If we call setLayout(null) we can position our components


absolutely.
For this, we use the setBounds() method.
JButton quitButton = new JButton("Quit");
quitButton.setBounds(50, 60, 80, 30);

152
Lesson 8 - Swing and JDBC

Here we create a button. We position it by calling the setBounds() method. Notes


quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
We add an action listener. The action listener will be called, when we perform
an action on the button. In our case, if we click on the button. The click will
terminate the application.
panel.add(quitButton);
In order to show the quit button, we must add it to the panel.

Figure 8.2: Quit Button

Learning Activity
Suppose there is a class inherited from the JFrame widget. How it
can be positioned in the screen effectively?

8.2 JDBC
The Java JDBC API enables Java applications to connect to relational
databases via a standard API, so your Java applications become independent
(almost) of the database the application uses.

Figure 8.3: Java Application Using JDBC to Connect to a Database

153
Web Programming

Notes JDBC standardizes how to connect to a database, how to execute queries


against it, how to navigate the result of such a query, and how to execute
updates in the database. JDBC does not standardize the SQL sent to the
database. This may still vary from database to database.
This JDBC tutorial covers the version of JDBC available in Java 6. The tutorial
will not cover every single detail of the JDBC API, but focus on the most
commonly used features. The rest you can read about in the JavaDoc's
afterwards. Once you have a good understanding of JDBC, reading the last
details in the JavaDoc or elsewhere, will not be so hard.
The JDBC library includes APIs for each of the tasks commonly associated
with database usage:
z Making a connection to a database
z Creating SQL or MySQL statements
z Executing that SQL or MySQL queries in the database
z Viewing and Modifying the resulting records
Fundamentally, JDBC is a specification that provides a complete set of
interfaces that allows for portable access to an underlying database. Java can be
used to write different types of executables, such as:
z Java Applications
z Java Applets
z Java Servlets
z Java Server Pages (JSPs)
z Enterprise JavaBeans (EJBs)
All of these different executables are able to use a JDBC driver to access a
database and take advantage of the stored data.

JDBC provides the same capabilities as ODBC, allowing Java


programs to contain database-independent code.
Pre-requisite
Before progressing on you need to have good understanding on the following
two subjects:
z Core JAVA Programming
z SQL or MySQL Database

154
Lesson 8 - Swing and JDBC

JDBC Architecture Notes


The JDBC API supports both two-tier and three-tier processing models for
database access but in general JDBC Architecture consists of two layers:
z JDBC API: This provides the application-to-JDBC Manager connection.
z JDBC Driver API: This supports the JDBC Manager-to-Driver
Connection.
The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each
data source. The driver manager is capable of supporting multiple concurrent
drivers connected to multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver
manager with respect to the JDBC drivers and the Java application:

Figure 8.4: JDBC Architecture

Common JDBC Components


The JDBC API provides the following interfaces and classes:
z Driver Manager: This class manages a list of database drivers. Matches
connection requests from the java application with the proper database
driver using communication subprotocol. The first driver that recognizes a
certain subprotocol under JDBC will be used to establish a database
Connection.

155
Web Programming

Notes z Driver: This interface handles the communications with the database
server. You will interact directly with Driver objects very rarely. Instead,
you use DriverManager objects, which manage objects of this type. It also
abstracts the details associated with working with Driver objects.
z Connection: This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all
communication with database is through connection object only.
z Statement: You use objects created from this interface to submit the SQL
statements to the database. Some derived interfaces accept parameters in
addition to executing stored procedures.
z ResultSet: These objects hold data retrieved from a database after you
execute an SQL query using Statement objects. It acts as an iterator to
allow you to move through its data.
z SQLException: This class handles any errors that occur in a database
application.
The JDBC 4.0 Packages
The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the
latest JDBC version at the time of writing this tutorial. It offers the main
classes for interacting with your data sources.
The new features in these packages include changes in the following areas:
z Automatic database driver loading
z Exception handling improvements
z Enhanced BLOB/CLOB functionality
z Connection and statement interface enhancements
z National character set support
z SQL ROWID access
z SQL 2003 XML data type support
z Annotations
After you've installed the appropriate driver, it's time to establish a database
connection using JDBC.
The programming involved to establish a JDBC connection is fairly simple.
Here are these simple four steps:
z Import JDBC Packages: Add import statements to your Java program to
import required classes in your Java code.
z Register JDBC Driver: This step causes the JVM to load the desired driver
implementation into memory so it can fulfill your JDBC requests.

156
Lesson 8 - Swing and JDBC

z Database URL Formulation: This is to create a properly formatted address Notes


that points to the database to which you wish to connect.
z Create Connection Object: Finally, code a call to the DriverManager
object's getConnection( ) method to establish actual database connection.
Import JDBC Packages
The import statements tell the Java compiler where to find the classes you
reference in your code and are placed at the very beginning of your source
code.
To use the standard JDBC package, which allows you to select, insert, update,
and delete data in SQL tables, add the following imports to your source code:
import java.sql.* ; // for standard JDBC programs
import java.math.* ; // for BigDecimal and BigInteger support
Register JDBC Driver
You must register your driver in your program before you use it. Registering
the driver is the process by which the Oracle driver's class file is loaded into
memory so it can be utilized as an implementation of the JDBC interfaces.
You need to do this registration only once in your program. You can register a
driver in one of two ways.
Approach (I) – Class.forName()
The most common approach to register a driver is to use Java's
Class.forName() method to dynamically load the driver's class file into
memory, which automatically registers it. This method is preferable because it
allows you to make the driver registration configurable and portable.
The following example uses Class.forName( ) to register the Oracle driver:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
You can use getInstance() method to work around noncompliant JVMs, but
then you'll have to code for two extra Exceptions as follows:
try {

Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
}
catch(ClassNotFoundException ex) {

157
Web Programming

Notes System.out.println("Error: unable to load driver class!");


System.exit(1);
catch(IllegalAccessException ex) {
System.out.println("Error: access problem while loading!");
System.exit(2);
catch(InstantiationException ex) {
System.out.println("Error: unable to instantiate driver!");
System.exit(3);
}

Approach (II) – DriverManager.registerDriver()


The second approach you can use to register a driver is to use the static
DriverManager.registerDriver() method.
You should use the registerDriver() method if you are using a non-JDK
compliant JVM, such as the one provided by Microsoft.
The following example uses registerDriver() to register the Oracle driver:
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}

Database URL Formulation


After you've loaded the driver, you can establish a connection using the
DriverManager.getConnection() method. For easy reference, let me list the
three overloaded DriverManager.getConnection() methods:
z getConnection(String url)
z getConnection(String url, Properties prop)
z getConnection(String url, String user, String password)
Here each form requires a database URL. A database URL is an address that
points to your database.
Formulating a database URL is where most of the problems associated with
establishing a connection occur.

158
Lesson 8 - Swing and JDBC

Following table lists down popular JDBC driver names and database URL. Notes
Table 8.1: Popular JDBC Drivers
RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port
Number:databaseName
DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port
Number/databaseName

All the highlighted part in URL format is static and you need to change only
remaining part as per your database setup.
Create Connection Object
Using a Database URL with a Username and Password
Here is listed down three forms of DriverManager.getConnection() method
to create a connection object. The most commonly used form of
getConnection() requires you to pass a database URL, a username, and a
password.
Assuming you are using Oracle's thin driver, you'll specify a
host:port:databaseName value for the database portion of the URL.
If you have a host at TCP/IP address 192.0.0.1 with a host name of amrood,
and your Oracle listener is configured to listen on port 1521, and your database
name is EMP, then complete database URL would then be:
jdbc:oracle:thin:@amrood:1521:EMP
Now you have to call getConnection() method with appropriate username and
password to get a Connection object as follows:
String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);

Using only a database URL


A second form of the DriverManager.getConnection( ) method requires only a
database URL:
DriverManager.getConnection(String url);
However, in this case, the database URL includes the username and password
and has the following general form:
jdbc:oracle:driver:username/password@database
So the above connection can be created as follows:
String URL =
"jdbc:oracle:thin:username/password@amrood:1521:EMP";
Connection conn = DriverManager.getConnection(URL);

159
Web Programming

Notes Using a Database URL and a Properties Object


A third form of the DriverManager.getConnection( ) method requires a
database URL and a Properties object:
DriverManager.getConnection(String url, Properties info);
A Properties object holds a set of keyword-value pairs. It's used to pass driver
properties to the driver during a call to the getConnection() method.
To make the same connection made by the previous examples, use the
following code:
import java.util.*;

String URL = "jdbc:oracle:thin:@amrood:1521:EMP";


Properties info = new Properties( );
info.put( "user", "username" );
info.put( "password", "password" );

Connection conn = DriverManager.getConnection(URL, info);

Closing JDBC Connections


At the end of your JDBC program, it is required explicitly close all the
connections to the database to end each database session. However, if you
forget, Java's garbage collector will close the connection when it cleans up
stale objects.
Relying on garbage collection, especially in database programming, is very
poor programming practice. You should make a habit of always closing the
connection with the close() method associated with connection object.
To ensure that a connection is closed, you could provide a finally block in your
code. A finally block always executes, regardless if an exception occurs or not.
To close above opened connection you should call close() method as follows:
conn.close();
Explicitly closing a connection conserves DBMS resources, which will make
your database administrator happy.

Learning Activity
To ensure that a connection is closed, you could provide a finally
block in your code. What is it? Discuss with example.

SUMMARY
z Swing is an advanced GUI toolkit. It has a rich set of widgets.

160
Lesson 8 - Swing and JDBC

z From basic widgets like buttons, labels, scrollbars to advanced widgets like Notes
trees and tables. Swing itself is written in Java.
z JDBC stands for Java Database Connectivity, which is a standard Java API
for database-independent connectivity between the Java programming
language and a wide range of databases.
z JDBC is a specification that provides a complete set of interfaces that
allows for portable access to an underlying database.
z The JDBC API supports both two-tier and three-tier processing models for
database access but in general JDBC Architecture consists of two layers
JDBC API and JDBC Driver API.
z The JDBC API uses a driver manager and database-specific drivers to
provide transparent connectivity to heterogeneous databases.
z The JDBC driver manager ensures that the correct driver is used to access
each data source.
z The driver manager is capable of supporting multiple concurrent drivers
connected to multiple heterogeneous databases.

KEYWORDS
Swing: It is an advanced GUI toolkit. It has a rich set of widgets.
JDBC: It is a specification that provides a complete set of interfaces that
allows for portable access to an underlying database.
JDBC API: It uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.

SELF-ASSESSMENT QUESTIONS
Short Answer Questions
1. What are the different swing API public packages?
2. List any three characteristics of swing toolkit.
3. What all types of executable can be written by Java?
4. Write a short note on JDBC Architecture.
5. List some new features of JDBC package 4.0.
Long Answer Questions
1. What do you mean by JDBC API? How it differs from JDBC driver API?
2. Explain the different components of JDBC.
3. Explain the process involved in establishing JDBC connection.

161
Web Programming

Notes 4. How can you use a database URL with a username and password to create
a connection?
5. What do you mean by swing library? Give an example also.

FURTHER READINGS

E. Balaguruswami, (2009), Programming with Java, Tata


McGraw-Hill.
Paul, Deitel and Harvey, Daitel, (2012), Java – How to program,
PHI.
Kogent Solutions (2007), Java 6 Programming Black Book,
Dreamtech Press.
Sarang, Poornachandra, (2012), Java Programming, Tata
McGraw-Hill

162
Lesson 9 - Servlets

UNIT V Notes

LESSON 9 - SERVLETS

CONTENTS
Learning Objectives
Overview
9.1 Java Servlets
9.1.1 Servlets Architecture
9.1.2 Servlets Tasks
9.1.3 Servlets Packages
9.2 Servlets API
9.3 Servlet Life Cycle
9.4 Servlet Configuration
Summary
Keywords
Self-Assessment Questions
Further Readings

LEARNING OBJECTIVES
After studying this lesson, you should be able to:
z Learn about Java Servlets
z Understand the Servlets API
z Know the Servlets Life Cycle
z Illustrate the Servlet Configuration

OVERVIEW
In the previous lesson, you have learnt about basics of swing in Java and
working with JDBC in detail.
In this lesson, you will study about Java Servlets. Java Servlets are the
programs that run on a Web or Application server. They act as a middle layer
between requests coming from a Web browser or other HTTP client and
databases or applications on the HTTP server.

163
Web Programming

Notes In this lesson, you will also learn about Servlets API, Servlets Life Cycle and
finally you will understand about Servlet Configuration.

9.1 JAVA SERVLETS


Using Servlets, you can collect input from users through web page forms,
present records from a database or another source, and create web pages
dynamically.
Java Servlets often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But Servlets offer several advantages in
comparison with the CGI.
z Performance is significantly better.
z Servlets execute within the address space of a Web server. It is not
necessary to create a separate process to handle each client request.
z Servlets are platform-independent because they are written in Java.
z Java security manager on the server enforces a set of restrictions to protect
the resources on a server machine. So servlets are trusted.
z The full functionality of the Java class libraries is available to a servlet. It
can communicate with applets, databases, or other software via the sockets
and RMI mechanisms that you have seen already.
9.1.1 Servlets Architecture
Following diagram shows the position of Servlets in a Web Application.

Figure 9.1: Servlets Architecture

9.1.2 Servlets Tasks


Servlets perform the following major tasks:
z Read the explicit data sent by the clients (browsers). This includes an
HTML form on a Web page or it could also come from an applet or a
custom HTTP client program.

164
Lesson 9 - Servlets

z Read the implicit HTTP request data sent by the clients (browsers). This Notes
includes cookies, media types and compression schemes the browser
understands, and so forth.
z Process the data and generate the results. This process may require talking
to a database, executing an RMI or CORBA call, invoking a Web service,
or computing the response directly.
z Send the explicit data (i.e., the document) to the clients (browsers). This
document can be sent in a variety of formats, including text (HTML or
XML), binary (GIF images), Excel, etc.
z Send the implicit HTTP response to the clients (browsers). This includes
telling the browsers or other clients what type of document is being
returned (e.g., HTML), setting cookies and caching parameters, and other
such tasks.
9.1.3 Servlets Packages
Java Servlets are Java classes run by a web server that has an interpreter that
supports the Java Servlet specification.

Servlets can be created using the javax.servlet and


javax.servlet.http packages, which are a standard part of the Java's
enterprise edition, an expanded version of the Java class library that
supports large-scale development projects.
These classes implement the Java Servlet and JSP specifications. At the time of
writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.
Java servlets have been created and compiled just like any other Java class.
After you install the servlet packages and add them to your computer's
Classpath, you can compile servlets with the JDK's Java compiler or any other
current compiler.

9.2 SERVLETS API


The javax.Servlet and javax.Servlet.http packages represent interfaces and
classes for servlet API. The javax.Servlet package contains many interfaces
and classes that are used by the servlet or web container. These are not specific
to any protocol. The javax.Servlet.http package contains interfaces and
classes that are responsible for http requests only.
Let's see what the interfaces of javax.Servlet package are.
Interfaces in javax.Servlet package.

165
Web Programming

Notes There are many interfaces in javax.Servlet package. They are as follows:
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
Classes in javax.Servlet Package
There are many classes in javax.Servlet package. They are as follows:
1. Generic Servlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
Interfaces in javax.Servlet.http Package
There are many interfaces in javax.Servlet.http package. They are as follows:
1. HttpServletRequest
2. HttpServletResponse

166
Lesson 9 - Servlets

3. HttpSession Notes
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
Classes in javax.Servlet.http Package
There are many classes in javax.Servlet.http package. They are as follows:
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)

Learning Activity
Servlets can be created using the javax.servlet and
javax.servlet.http packages. Can it be created using any other
package also? Find out.

9.3 SERVLET LIFE CYCLE


A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet:
init() Method
A servlet is first loaded and initialized usually when it is requested by the
corresponding clients. Some websites allow the users to load and initialize
servlets when the server is started up so that the first request will get responded
more quickly. It is called when the servlet is first created, and not called again
for each user request. So, it is used for one-time initializations, just as with the
init method of applets.

The init method is designed to be called only once.

167
Web Programming

Notes The servlet is normally created when a user first invokes a URL corresponding
to the servlet, but you can also specify that the servlet be loaded when the
server is first started.

When a user invokes a servlet, a single instance of each servlet


gets created, with each user request resulting in a new thread that is handed
off to doGet or doPost as appropriate.

The init() method simply creates or loads some data that will be
used throughout the life of the servlet.
public void init(ServletConfig config) throws ServletException
This method is called once when the servlet is loaded into the servlet engine,
before the servlet is asked to process its first request. The init method has a
ServletConfig parameter. The servlet can read its initialization arguments
through the ServletConfig object. How the initialization arguments are set is
servlet engine dependent but they are usually defined in a configuration file.
A typical example of an initialization argument is a database identifier.
A servlet can read this argument from the ServletConfig at initialization and
then use it later to open a connection to the database during processing of a
request:
private String databaseURL;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
databaseURL = config.getInitParameter("database");
}

service() Method
The service() method is the main method to perform the actual task. The
servlet container (i.e. web server) calls the service() method to handle requests
coming from the client( browsers) and to write the formatted response back to
the client.
public void service(ServletRequest request, ServletResponse
response) throws
ServletException, IOException
This method is called to process a request. It can be called zero, one or many
times until the servlet is unloaded.
Once a servlet is loaded, it remains in the server’s memory as a single object
instance. Thereafter, the server invokes the servlet to handle a request using a
simple, lightweight method invocation. Unlike with CGI, there’s no process to

168
Lesson 9 - Servlets

spawn or interpreter to invoke, so the servlet can begin handling the request Notes
almost immediately. Multiple, concurrent requests are handled by separate
threads, so servlets are highly scalable. Servlets are naturally enduring objects.
Because a servlet stays in the server’s memory as a single object instance, it
automatically maintains its state and can hold on to external resources, such as
database connections, that may otherwise take several seconds to establish. The
following servlet presents information about how many times it has been
accessed:
import java.io.*;
import javax.Servlet.*;
import javax.Servlet.http.*;
public class SimpleCounter extends HttpServlet {
int count = 0;
public void doGet(HttpServletRequest req, HttpServletResponse
res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
count++;
out.println("Since loading, this servlet has been accessed " +
count + " times.");
}
}

Each time the server receives a request for a servlet, the server
spawns a new thread and calls service.
The variable count is shared by all the threads each corresponding to a single
request. So this provides a way for the threads to communicate with each other.
Unfortunately the concurrency that multiple threads (one per request) can
execute this method in parallel also brings problems. Imagine that one thread
increments the count and just afterward, before the first thread prints the count,
the second thread also increments the count. Each thread will print the same
count value, after effectively increasing its value by 2. The order of execution
goes something like this:
count++ // Thread 1
count++ // Thread 2
out.println // Thread 1
out.println // Thread 2

169
Web Programming

Notes Now, in this case, the inconsistency is not a real problem, but many other
servlets have more serious opportunities for errors. To prevent these types of
problems and the inconsistencies that come with them, we can add one or more
synchronized blocks to the code.
Anything inside a synchronized block or a synchronized method is guaranteed
not to be executed concurrently by another thread. Before any thread begins to
execute synchronized code, it must obtain a monitor (lock) on a specified
object instance. If another thread already has that monitor – because it is
already executing the same synchronized block or some other block with the
same monitor – the first thread must wait.
For example, we may wrap the addition and print operations in a synchronized
blocks as follows:
PrintWriter out = res.getWriter();
synchronized(this) {
count++;
out.println("Since loading, this servlet has been accessed " +
count + " times.");
}
The javax.Servlet.SingleThreadModel interface provides another approach to
avoid race condition.
If a servlet implements this interface, you are guaranteed that no two threads
will execute concurrently in the servlet’s service method. The servlet container
can make this guarantee by synchronizing access to a single instance of the
servlet, or by maintaining a pool of servlet instances and dispatching each new
request to a free servlet.
If a servlet implements this interface, the servlet will be thread safe. However,
this interface does not prevent synchronization problems that result from
servlets accessing shared resources such as static class variables or classes
outside the scope of the servlet.
destroy() Method
The destroy() method is called only once at the end of the life cycle of a
servlet. 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.
After the destroy() method is called, the servlet object is marked for garbage
collection.
public void destroy()
This method is called once just before the servlet is unloaded
and taken out of service.

170
Lesson 9 - Servlets

The following gives an servlet example with both init() and Notes
destroy() methods:
3
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class InitDestroyCounter extends HttpServlet {
int count;
public void init() throws ServletException {
// Try to load the initial count from our saved persistent
state
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
fileReader = new FileReader("InitDestroyCounter.initial");
bufferedReader = new BufferedReader(fileReader);
String initial = bufferedReader.readLine();
count = Integer.parseInt(initial);
return;
}
catch (FileNotFoundException ignored) { } // no saved state
catch (IOException ignored) { } // problem during read
catch (NumberFormatException ignored) { } // corrupt saved
state
finally {
// Make sure to close the file
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException ignored) { }
}
An object of ServletConfig is created by the web container for each servlet.
This object can be used to get configuration information from web.xml file.

If the configuration information is modified from the web.xml


file, we don't need to change the servlet. So it is easier to manage the web
application if any specific content is modified from time to time.

171
Web Programming

Notes 9.4 SERVLET CONFIGURATION


Compiling a Servlet
Let us put above code if HelloWorld.java file and put this file in
C:\ServletDevel (Windows) or /usr/ServletDevel (Unix) then you would need
to add these directories as well in CLASSPATH.
Assuming your environment is setup properly, go in ServletDevel directory
and compile HelloWorld.java as follows:
$ javac HelloWorld.java
If the servlet depends on any other libraries, you have to include those JAR
files on your CLASSPATH as well. I have included only servlet-api.jar JAR
file because I'm not using any other library in Hello World program.
This command line uses the built-in javac compiler that comes with the Sun
Microsystems Java Software Development Kit (JDK). For this command to
work properly, you have to include the location of the Java SDK that you are
using in the PATH environment variable.
If everything goes fine, above compilation would produce HelloWorld.class
file in the same directory. Next section would explain how a compiled servlet
would be deployed in production.
Servlet Deployment
By default, a servlet application is located at the path <Tomcat-installation-
directory>/webapps/ROOT and the class file would reside in <Tomcat-
installation-directory>/webapps/ROOT/WEB-INF/classes.
If you have a fully qualified class name of com.myorg.MyServlet, then this
servlet class must be located in WEB-INF/classes/com/myorg/MyServlet.class.
For now, let us copy HelloWorld.class into <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/classes and create following
entries in web.xml file located in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>

172
Lesson 9 - Servlets

Above entries to be created inside <web-app>...</web-app> tags available in Notes


web.xml file. There could be various entries in this table already available, but
never mind.
You are almost done, now let us start tomcat server using <Tomcat-
installation-directory>\bin\startup.bat (on windows) or <Tomcat-installation-
directory>/bin/startup.sh (on Linux/Solaris etc.) and finally type
http://localhost:8080/HelloWorld in browser's address box.
Let us understand this with an example of ServletConfig to get all the
initialization parameters. In this example, we are getting all the initialization
parameter from the web.xml file and printing this information in the servlet.
DemoServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DemoServlet extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

ServletConfig config=getServletConfig();
Enumeration<String> e=config.getInitParameterNames();

String str="";
while(e.hasMoreElements()){
str=e.nextElement();
out.print("<br>Name: "+str);
out.print(" value: "+config.getInitParameter(str));
}

out.close();

173
Web Programming

Notes }

}
web.xml
<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>

<init-param>
<param-name>username</param-name>
<param-value>system</param-value>
</init-param>

<init-param>
<param-name>password</param-name>
<param-value>oracle</param-value>
</init-param>

</servlet>

<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

</web-app>

Advantage of ServletConfig
The core advantage of ServletConfig is that you don't need to edit the servlet
file if information is modified from the web.xml file.
Methods of ServletConfig Interface
Methods of ServletConfig Interface are as follows:
1. public String getInitParameter(String name): Returns the parameter value
for the specified parameter name.
2. public Enumeration getInitParameterNames(): Returns an enumeration of
all the initialization parameter names.
3. public String getServletName(): Returns the name of the servlet.
4. public ServletContext getServletContext(): Returns an object of
ServletContext.

174
Lesson 9 - Servlets

How to get the object of ServletConfig: Notes


getServletConfig() method of Servlet interface returns the object of
ServletConfig.
Syntax of getServletConfig() method
public ServletConfig getServletConfig();
Example of getServletConfig() method
1. ServletConfig config=getServletConfig();
2. //Now we can call the methods of ServletConfig interface
Syntax to provide the initialization parameter for a servlet
The init-param sub-element of servlet is used to specify the initialization
parameter for a servlet.
<web-app>
<servlet>
......

<init-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</init-param>
......
</servlet>
</web-app>

Learning Activity
Do research on the use of servlet configuration by taking any MNC
framework as an example and compare?

SUMMARY
z Java Servlets are programs that run on a Web or Application server and act
as a middle layer between requests coming from a Web browser or other
HTTP client and databases or applications on the HTTP server.
z Using Servlets, you can collect input from users through web page forms,
present records from a database or another source, and create web pages
dynamically.
z Java Servlets often serve the same purpose as programs implemented using
the Common Gateway Interface (CGI).
z Java Servlets are Java classes run by a web server that has an interpreter
that supports the Java Servlet specification.

175
Web Programming

Notes z Servlets can be created using the javax.servlet and javax.servlet.http


packages, which are a standard part of the Java's enterprise edition, an
expanded version of the Java class library that supports large-scale
development projects.
z The javax.Servlet and javax.servlet.http packages represent interfaces
and classes for servlet api.
z The javax.servlet package contains many interfaces and classes that are
used by the servlet or web container. These are not specific to any protocol.
z The javax.servlet.http package contains interfaces and classes that are
responsible for http requests only.
z A servlet life cycle can be defined as the entire process from its creation till
the destruction.
z The init method is designed to be called only once. It is called when the
servlet is first created, and not called again for each user request.
z A GET request results from a normal request for a URL or from an HTML
form that has no METHOD specified and it should be handled by doGet()
method.
z A POST request results from an HTML form that specifically lists POST as
the METHOD and it should be handled by doPost() method.

KEYWORDS
Java Servlets: They are programs that run on a Web or Application server and
act as a middle layer between requests coming from a Web browser or other
HTTP client and databases or applications on the HTTP server.
Servlet Life Cycle: It can be defined as the entire process from its creation till
the destruction.
init() Method: It is called when the servlet is first created, and not called again
for each user request.

SELF-ASSESSMENT QUESTIONS
Short Answer Questions
1. Write a short note on Java Servlets.
2. State the path followed by a Servlet.
3. What type of task are Servlet tasks?
4. List the different interfaces in javax.servlet package.
5. Differentiate between dopost() and doget() methods.

176
Lesson 9 - Servlets

Long Answer Questions Notes


1. Explain about Servlets API.
2. What are the advantages of Servlet over CGI?
3. Describe about Servlets Life Cycle.
4. What are the different methods of ServletConfig interface?
5. With the help of an example give syntax to provide the initialization
parameter for a servlet.

FURTHER READINGS

E. Balaguruswami, (2009), Programming with Java, Tata


McGraw-Hill.
Kogent Solutions (2007), Java 6 Programming Black Book,
Dreamtech Press.
Herbert Schildt, (2011), Java the Complete Reference, Tata
McGraw-Hill.
Sarang, Poornachandra, (2012), Java Programming, Tata
McGraw-Hill

177

You might also like