You are on page 1of 333

Advanced

JAVA
By Jitendra Patel

Copyright Reserved by the Author


All rights reserved. No part of this book shall be reproduced, stored in a retrieval
system, or transmitted by any means, electronic, mechanical, photocopying, recording, or
otherwise, without written permission from the publisher. No patent liability is assumed
with respect to the use of the information contained herein. Although every precaution has
been taken in the preparation of this book, the publisher and author assume no
responsibility for errors or omissions. Nor is any liability assumed for damages resulting
from the use of the information contained herein.

PREFACE
ADVANCED JAVA: This book is especially for those who have basic knowledge of
JAVA and want to learn some advanced features of JAVA like Applet, AWT, SWINGs,
Servlet, JDBC, JSP etc
Also every one with interest in ADVANCED JAVA can refer this book to get the
knowledge of secure Web Application Development using Swing, JDBC, Servlet and JSP.
It covers virtually most of core features and some of the advanced features of Web site
Development including more than hands on examples tested in popular Web browser like
Chrome, IE and Firefox and platforms like Apache Web Server and WampServer. Most of
code samples are presented in easy to use way through any simple text editor starting from
notepad. Throughout the book most of the programming features are explained through
syntax and examples to develop state-of-the-art Web applications.

Table of Contents
Advanced JAVA
Copyright Reserved by the Author
PREFACE
Unit I JAVA Applets
Concept of Applet Programming
Designing a Web page
Short Questions and Answers
Exercise
Unit II Introduction of Abstract Window Toolkit: (AWT)
Working with Windows and AWT
Working with frame windows
Working with graphics: AWT controls
Layout Managers
Event Handling in Java
Event Classes and Listener Interfaces
GUI with Swing
Short Questions and Answers
Exercise
Unit III Java Data Base Client/ Server
Java as a Database front end Database client/server methodology
JDBC Architecture
Common JDBC Components
JDBC Database Example
Current JDBC Drivers
Advantages Using JDBC
Limitations Using JDBC
Security Considerations
Short Questions and Answers
Exercise
Unit IV Servlets

Introduction to Web
Introduction to Servlet
The Life Cycle Of a Servlet
Servlet Container
Installing Servlets
The Servlet API
Reading Servlet Parameters
Reading Initialization Parameters
Handling HTTP Requests and responses
Session Tracking
Reading and displaying Records using servlet
Short Questions and Answers
Exercise
Unit V Java Server Pages: (JSP)
JSP technology
JSP page
Relation of Applets and Servlets with JSP
Comments in JSP
Simple JSP program
JSP Scripting Elements
JSP Expressions
JSP Scriplets
JSP Declarations
JSP Directives
Predefined Variables/implicit objects
JSP Databse Access
Short Questions and Answers
Exercise

Unit I JAVA Applets


Applets were intended to supply small functionality for activating Web pages.
However, as Java has matured, applets are now one way of delivering component-based
functionality to Web pages. The original intent is that applets would be small applications
- hence the name. Java applets take advantage of features that are built into Web browsers.
This enables developers to write applets that can contain a rich amount of functionality
with a minimal amount of code. One of the major uses of applets is to display graphics
and images. To incorporate GIF or JPEG files into a Java applet, it is not necessary to
write any special decoding methods to interpret the image files. Instead applets can use the
browsers built-in decoder to display the images.
Applets are extensible. If a new image file format becomes the hot format and is
incorporated into the browser, the Java applet will automatically be able to handle the new
format.

Concept of Applet Programming


An applet is a small Java Program. Applets are used for creating Graphical Programs.
On the Web, using Java, an applet is a small program that can be sent along with a Web
page to a user. Java applets can perform interactive animations, immediate calculations, or
other simple tasks without having to send a user request back to the server.
An Applet is a small Internet-based Java program.
Applets themselves are not written in HTML. Applets are written in Java.
Applet can be embedded in webpage. Applets are included in HTML page
using <APPLET> tag.
Applet can run in Java technology-enabled web browser or appletviewer
Applets are not executed on the server side. They are transferred to users
machine and then executed by the browsers Java Virtual Machine (JVM).
Applets are executed inside the browser via the so-called Java Plug-in, which
is a JRE capable of running Java applets in a secure manner.
An applet has no life outside an HTML page that is being processed by a browser.
Thus the browser is the container of the applet and depends on the browser to call its
methods. In a sense, a specification between the browser and the applet exists, which is
driven by both the browser and the Java language.

Local and remote applets


There are two different applet types. The applet types vary based on how the applet is
embedded into web page. Applet Types are:
Local Applets
Local applets are stored in local system.
The web page will search the local system directories, find the local
applet and execute it.
Execution of local applet does not require internet connection.
Web Browser
Applet

Local Applet
Remote Applets
The remote applets are stored in remote computer.
The web page requires internet connection to locate and load the remote
applet from the remote computer. To access a remote applet in your Web
page, you must know the applets URL and any parameters to supply in
order to display the applet correctly.
Web Browser
Remote Machine
Applet

Remote Applet
Specifying a Local Applet
The codebase attribute specifies a path name on your system for the local applet,
whereas the code attribute specifies the name of the byte-code file that contains the
applets code.
<applet

codebase=MyGame

code= MyGame.class

width=130

height=130>

</applet>
The path specified in the codebase attribute is relative to the folder containing the
HTML document that references the applet.
Specifying a Remote Applet
The codebase attribute specifies a URL on remote system for the remote applet,
whereas the code attribute specifies the name of the byte-code file that contains the
applets code.

<applet

codebase=http://www.website.com/applets/

code=MyGame.class

width=130

height=130>

</applet>
The only difference between accessing local and remote applet is the value of
the codebase attribute. In the first case, codebase specifies a local folder, and in the second
case, it specifies the URL at which the applet is located.
Difference between applet and application
The most important differences between applet and application include:
An applet is a Java class that extends the java.applet.Applet class.

Unlike Java applications, applets do not invoke a main() method.


Applets are embedded within an HTML webpage.
The applet code is automatically downloaded to the users machine when they
view an HTML webpage with an embedded applet.
A Java Virtual Machine (JVM) is required to view an applet.
The JVM creates an instance of the applet class and invokes methods defined
within the applet during the applets lifetime.
Following is the feature wise comparison between Applet and Application
Feature
Security

Applet

Application

Security Manager provided by


No default Security
browser. Remote code is untrusted Manager. All code is trusted
by default

Execution
Privileges
Container
Communication

Lifecycle
Peer

Network
Access

Invoke Native
Methods

Runs in the context of a


browser
Browser
Inter-applet communication
limited by browser
Controlled by browser

Runs standalone

None, Standalone
No restrictions

Controlled by JRE

Created and assigned by the


No default. Must be
Browser
created by the application.
May only open a socket
connection to the host it was
loaded from
No

No restrictions

Yes

Table: Summary of differences between Java applets and applications


Preparing to write applets
Lets begin with a quick introduction to some basic elements of applet programming.
Each applet starts out with a class definition, like this:
public class MyApplet extends java.applet.Applet
{
// to do
}
In this example, MyApplet is the name of the applets class.
An applet must be declared as a public class.
All applets extend the java.applet.Applet class, also referred to simply as the
Applet class.
By inheriting from java.applet.Applet the necessary structure is defined to
coordinate with a Web browser.
Another way to write the class definition is to use import to load the Applet class and
simplify the declaration:
import java.applet.Applet
public class MyApplet extends Applet
{
// to do
}
Building applet code
The superclasses of Applet give all applets a framework on which you can build user
interface. These superclasses also provide a structure for the applet that must be used
when the program is developed. Here are steps to build a simple Applet in JAVA.
1. Create SimpleApplet.java using a text editor as shown below in c:\jdk1.x\bin
directory i.e save SimpleApplet to the bin directory of the jdk you have
installed. You can actually save the file anywhere but you will have to set the

classpath variable.
// Simple Java Applet: Drawing a String. SimpleApplet.java
import java.applet.*;
import java.awt.*;

public class SimpleApplet extends Applet


{
public void paint(Graphics g)
{
g.drawString(Welcome to the applet world ,20,40);
}
}
1. Save the file, exit the editor, compile using javac and correct errors
2. Create SimpleApplet.html using a text editor in c:\jdk1.x\bin directory
<HTML>
<HEAD>
<TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>

<APPLET code=SimpleApplet.class width=350 height=200></APPLET>


</BODY>
</HTML>
1. In SimpleApplet.html add an applet tag to invoke the SimpleApplet.class
with a width of 350 and a height of 200
2. Run SimpleApplet.html using appletviewer as shown below.

3. See the output:

Instead of creating a separate html document and then including the applet in that we
can directly use the <applet> tag to embed within the applet program itself as a comment
as shown below:
// This is a simple applet with embedded applet tag. SimpleApplet2.java
/*
<applet code = SimpleApplet2 width=350 height =200>
</applet>
*/
public class SimpleApplet2 extends Applet
{
public void paint (Graphics g)
{
g.drawString(Welcome to the applet world ,20,40);
}
}

We can also use any java supported web browser to execute the applets. To do so
follow these steps:
1.

Select Open from the File menu in


internet explorer.

2.

In the dialog box that appears, click the


Browse button.

3.

In the dialog box that appears, locate the


directory containing the HTML document
(SimpleApplet.htm) for the applet you wish to
execute.

4.

Select the HTML document.

5.

Click the Open button.

6.

Click the OK button.

You will see the following output:

If your applet executes in the appletviewer, but does not execute in your Web
browser, Java may not be installed or configured for your browser. In this case, install
Java for your browser. In Internet Explorer, if this does not fix the problem, you need to
configure Internet Explorer to use J2SE 5.0. To do so, click the Tools menu and select
Internet Options, then click the Advanced tab in the window that appears. Locate the
option Use JRE v1.5.0 for <applet> (requires restart) and ensure that it is checked, and
then click OK. Close all your browser windows before attempting to execute another
applet in the browser.
Creating an Executable Applet
Executable applet is nothing but the .class file of the applet, which is obtained by
compiling the source code of the applet. Compiling an applet is exactly the same as
compiling an application. Therefore, we can use the Java compiler to compile the applet.
Assume that we have created a file called SimpleApplet.java for our applet. Here are
the steps required for compiling the SimpleApplet applet.
1. Move to the directory containing the source code and type the following command:
javac SimpleApplet.java
2. The compiled output file called SimpleApplet.class is placed in the same directory
as the source.
3. Correct errors if any and compile the applet again.

Designing a Web page


Web documents are written in Hypertext Markup Language (HTML). HTML uses
tags to describe the structure of Web documents. Tags are used to identify headings,
paragraphs, and lists, as well as other elements of Web pages such as links, images,
forms, and applets. Applets are displayed as a part of a Web page by using the HTML tag
<APPLET>.
The <APPLET> tag
Applet tag is used to add the applet into HTML page. Applet tag has following
attributes:

Example:
<applet code = SimpleApplet2 width=350 height =200>
</applet>
Simple Methods to Design Applet
Method
void

Description
setBackground

(Color colorname )

To set the background of an applet


window.

void
setForeground
To set the foreground color of an applet
(Color colorname )
window.

Color getBackground (

To obtain the current settings for the


background color

Color getForeground ( )

To obtain the current settings for the


foreground color

Applet getApplet
String name )

To obtain the applet specified by given


name from the current applet context.

Void showStatus( String


To display the status message in the
status )
status bar of applet window
URL getDocumentBase
( )

To obtain the directory of the current


browser page.

URL getCodeBase( )

To obtain the directory from which the


applets class file was loaded

Adding Applet to HTML file


An applet is like a child application of the browser. The browser launches the applet in
a predefined environment inside the browser. From within HTML, the syntax to specify
the execution of an applet is provided by the applet and parameter tags.
The applet tag provides all the information needed to launch the applet. Everything
from the base directory to command-line parameters can be specified from within this tag.
<HTML>
<HEAD>
<TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>

<APPLET code=SimpleApplet.class width=350 height=200></APPLET>

</BODY>
</HTML>
The browser is told how to launch the HelloWorld.class file as specified. Java applets
can only be displayed within a Web browser by being embedded in a standard HTML
page. This does not mean that the actual bytecode or source code of the applet is included
within the HTML file. Instead, the HTML text contains a reference to the Java applet
known as a tag.
Running the Applet
To run an Applet, you can use appletviewer utility or a Web browser.
1. Running using appletviewer utility
You can run the applet using the applet viewer utility, which can be invoked from the
DOS
prompt using the appletviewer command.
Appletviewer Utility
JDK provides a utility called appletviewer.exe for testing applet. Since web
browser is everywhere nowadays, you should use a web browser to see the actual effect
instead. You should try on all the common browsers (such as IE, firefox, chrome, safari)
if you want to put your applet in production. appletviewer processes only
the <applet> tag, and ignores all other tags in the HTML file. To use the appletviewer,
issue the following command:
> appletviewer SimpleApplet.html

Applet ran using appletviewer utility


1. Running from a Web Browser
Running an Applet from a Web browser is straightforward. We simply need to add the
following applet tag somewhere in the body of the HTML.
<applet code=AppletHelloWorld.class width=450 height=100></applet>
This tag tells the Web browser to load the Applet from AppletHelloWorld.class and to
display it in an area that is 450 pixels wide by 100 pixels high. Because the code attribute
does not indicate a path, the Web browser will search for the AppletHelloWorld.class file
in the same directory that contains the HTML file.
A minimalistic HTML file for the Applet created above is shown below. To run the
Applet, click on the file title or the Java icon.
<html>
<head>
<title>Applet Hello World</title>
</head>
<body>
<applet
code=AppletHelloWorld.class
width=450
height=100>
Your browser does not support Applets.
</applet>
</body>
</html>
A screenshot of the Applet running from Firefox on Windows 7 is shown here:

Applet ran using web browser

Applet life cycle


There are five primary methods in the Applet class. The java.applet.Applet class
defines these methods for managing the life-cycle of the applets.
Method
init()

Description
This method is invoked when the applet is first loaded. It is
called (only once) when the applet is first loaded to initialize
variables, resize the applet, setting up GUI components, and etc

start()

Invoked every time the browser displays the web page


containing the applet. The start method is automatically called once
the browser calls the init method.

stop()

Invoked when the browser is closed (and, some browsers, when


the browser is minimized or when the user leaves the web page by
going to another URL) stops or suspends anything the applet is
doing e.g. if the start method started an animation, it should be
stopped in this method

destroy()

Invoked when the browser determines that it no longer needs the


applet this is when the applet is removed from the browsers cache.
Therefore the invocation of this method is controlled by the browser
itself. Use to release resources used by the applet but should do
this in the other methods e.g in stop() as it may be a long time before
destroy() is invoked.

paint()

Called back when the applet drawing area must be refreshed,


e.g., another window partially covers the applet etc. Called
immediately after start, the paint method is what displays your
applet on a webpage. Paint is also called any time the applet needs
to repaint itself.

Applet Life Sequence


User visits page containing an applet
Browser calls init on that applet, once and then
Browser calls start on that applet
User goes away from that page
Browser calls stop on that applet
User comes back to that page
Browser calls start again on that applet
User shuts down the browser
Browser calls destroy on the applet, once
Example: Illustrating applet life cycle
import java.applet.*;
import java.awt.*;

/* <applet code=LifeCycle.class width=200 height=200>
</applet> */

public class LifeCycle extends Applet
{
String msg=The currently executing method;

public void init()


{
msg+=init();
}

public void start()
{
msg+=start();
}

public void stop()
{
msg+=stop();
}

public void paint(Graphics g)
{
g.drawString(msg,100,100);
showStatus(Test applet);
}
}
Compile and run the applet:
> javac LifeCycle.java
> appletviewer LifeCycle.java
and watch what happens as you minimize and maximize the appletviewer window.
Also, watch the event messages as they are printed to the terminal. You should end up
with something that looks like:

Passing parameter to applet


Parameters
Parameters are analogous to command-line arguments; they provide a way to pass
information to an applet. Each <param> tag contains a name and a value that are passed as
strings to the applet:
<param name = parameter_name value = parameter_value>
You can use <param> tag to pass parameters into applet.
Complete syntax for the APPLET tag including Param Tag
<APPLET
CODEBASE = codebaseURL
CODE = appletFile
ALT = alternateText
NAME = appletInstanceName
WIDTH = pixels HEIGHT = pixels
ALIGN = alignment
>
<PARAM NAME = appletAttribute1 VALUE = value>
<PARAM NAME = appletAttribute2 VALUE = value>

alternateHTML
</APPLET>
Example Applet with parameters

/*
* AppletWithPara.java
*
*/
import java.applet.*;
import java.awt.*;
/*
<applet code=AppletWithPara width=200 height =150>
<param name=author value=J.B.Patel>
<param name=age value=27>
<param name=designation value=Lecturer>
<param name=institute value=SSPC Visnagar>
</applet>
*/
public class AppletWithPara extends java.applet.Applet
{
public void paint (Graphics gp)
{
String au=getParameter(author);
String ag=getParameter(age);
String desg=getParameter(designation);
String inst=getParameter(institute);
gp.drawString(Author:+au,20,40);
gp.drawString(Age:+ag,20,70);
gp.drawString(Designation:+desg,20,100);
gp.drawString(Institute:+inst,20,130);
showStatus(Parameter methods);

}
}
Output:

Retrieving Parameters within the Applet


Java applets retrieve parameter values using the getParameter() method in the applets
init() method.
String getParameter(String name);
The applet has to call the getParameter() method supplied by the java.applet.Applet
parent class to capture the passed parameters. Calling getParameter(color) using the
previous Java applet example would return a String value containing the text blue.
Following three methods are commonly used by applets:
String getParameter(String name)
This method returns the value for the specified parameter string
URL getCodeBase()
This method returns the URL of the applet
URL getDocumentBase()
This method returns the URL of the document containing the applet
Advantages of applets
Automatically integrated with HTML; hence, resolved virtually all installation
issues.
Can be accessed from various platforms and various java-enabled web
browsers.

Can provide dynamic, graphics capabilities and visualizations


Implemented in Java, an easy-to-learn OO programming language
Alternative to HTML GUI design
Safe! Because of the security built into the core Java language and the applet
structure, you dont have to worry about bad code causing damage to
someones system
Can be launched as a standalone web application independent of the host web
server
Limitations of applet
Four major types of restrictions are imposed on applets.
1. An applet has limited access to the local and remote file systems. This is due in
part to both the security features of Java as well as the browser.
2. An applet class that was loaded from the Internet is not allowed to make any
native calls. These remote classes cannot execute any local commands. This
restriction is lifted for classes that are used by the applet but are loaded from
the local machine.
3. An applet cannot be a network socket server and may only open a socket
connection to the server machine that served the applets HTML page.
4. There are restrictions imposed on inter-applet communication that are also
driven by the browser.

Short Questions and Answers


1. What is an Applet? Should applets have constructors?
Applets are small programs transferred through Internet, automatically installed
and run as part of web-browser. Applets implements functionality of a client.
Applet is a dynamic and interactive program that runs inside a Web page
displayed by a Java-capable browser. We dont have the concept of
Constructors in Applets. Applets can be invoked either through browser or
through Appletviewer utility provided by JDK.
2. What are the Applets Life Cycle methods? Explain them?
Following are methods in the life cycle of an Applet:
init() method - called when an applet is first loaded. This method is called
only once in the entire cycle of an applet. This method usually intialize
the variables to be used in the applet.

start( ) method - called each time an applet is started.


paint() method - called when the applet is minimized or refreshed. This
method is used for drawing different strings, figures, and images on the
applet window.
stop( ) method - called when the browser moves off the applets page.
destroy( ) method - called when the browser is finished with the applet.
1. What is the sequence for calling the methods by AWT for applets? - When
an applet begins, the AWT calls the following methods, in this sequence:
init()
start()
paint()
When an applet is terminated, the following sequence of method calls takes
place :
stop()
destroy()
1. How do Applets differ from Applications?
Following are the main differences:
Feature

Applet

Application

Security

Security Manager provided by

No

browser. Remote code is untrusted

Execution
Privileges
Container
Communication

Runs in the context of a


browser
Browser
Inter-applet
communication
limited by browser

default

Security

Manager. All code is trusted


by default
Runs standalone

None, Standalone
No restrictions

Lifecycle

Controlled by browser

Peer

Controlled by JRE

Created and assigned by the


No default. Must be
Browser
created by the application.

Network
Access

May only open a socket


connection to the host it was loaded
from

Invoke Native
Methods

No

No restrictions

Yes

1. Can we pass parameters to an applet from HTML page to an applet?


How?
We can pass parameters to an applet using <param> tag in the following way:
<param name=param1 value=value1>
<param name=param2 value=value2>
Access those parameters inside the applet is done by calling getParameter()
method inside the applet. Note that getParameter() method returns String value
corresponding to the parameter name.
1. How do we read number information from my applets parameters, given
that Applets getParameter() method returns a string?
Use the parseInt() method in the Integer Class, the Float(String) constructor or
parseFloat() method in the Class Float, or the Double(String) constructor or
parseDoulbl() method in the class Double.
2. How can I arrange for different applets on a web page to communicate
with each other?
Name your applets inside the Applet tag and invoke AppletContexts
getApplet() method in your applet code to obtain references to the other applets
on the page.
3. How do I determine the width and height of my application?
Use the getSize() method, which the Applet class inherits from the Component
class in the Java.awt package. The getSize() method returns the size of the

applet as a Dimension object, from which you extract separate width, height
fields. The following code explains this:
Dimension dim = getSize();
int appletwidth = dim.width();
int appletheight = dim.height();
1. What tags are mandatory when creating HTML to display an applet?
1. name, height, width
2. code, name
3. codebase, height, width
4. code, height, width
Correct answer is d.
1. What are the steps involved in Applet development?
Following are the steps involved in Applet development:
Create/Edit a Java source file. This file must contain a class which
extends Applet class.
Compile your program using javac
Execute the appletviewer, specifying the name of your applets source
file or html file. In case the applet information is stored in html file then
Applet can be invoked using java enabled web browser.
1. Which method is used to output a string to an applet? Which function is
this method included in?
drawString( ) method is used to output a string to an applet. This method is
included in the paint method of the Applet.

Exercise
1. What is an Applet? Explain life cycle of Applet.
2. Write an applet that displays a string. Write necessary applet tag for it.
3. Write short notes: - < PARAM >tag.

Unit II Introduction of Abstract Window Toolkit: (AWT)


There are two sets of Java APIs for graphics programming: AWT
(Abstract Windowing Toolkit) and Swing.
1. AWT API was introduced in JDK 1.0. Most of the AWT components have
become obsolete and should be replaced by newer Swing components.
2. Swing API, a much more comprehensive set of graphics libraries that enhances
the AWT, was introduced as part of Java Foundation Classes (JFC) after the
release of JDK 1.1. JFC consists of Swing, Java2D, Accessibility,
Internationalization, and Pluggable Look-and-Feel Support APIs. JFC was an
add-on to JDK 1.1 but has been integrated into core Java since JDK 1.2.

Working with Windows and AWT


Java Graphics APIs - AWT provide a huge set of reusable GUI components, such as
button, text field, label, choice, panel and frame for building GUI applications. Javas
Abstract Windowing Toolkit provides many of the user interface objects we find in the
Windows environment. These are called Components of the Java AWT. There are a
wide variety of AWT components.
AWT classes
AWT is consists of 12 packages (Swing is even bigger, with 18 packages as of JDK
1.7!). Fortunately, only 2 packages - java.awt and java.awt.event - are commonly-used.
1. The java.awt package contains the core AWT graphics classes:
GUI Component classes (such as Button, TextField, and Label),
GUI Container classes (such as Frame, Panel, Dialog and ScrollPane),
Layout managers (such as FlowLayout, BorderLayout and GridLayout),
Custom graphics classes (such as Graphics, Color and Font).
1. The java.awt.event package supports event handling:
Event
classes
(such
as ActionEvent, MouseEvent, KeyEvent and WindowEvent),
Event
Listener
Interfaces
(such
as
ActionListener, MouseListener, KeyListener and
WindowListener),
Event Listener Adapter classes (such as MouseAdapter, KeyAdapter,
and WindowAdapter).

AWT provides a platform-independent and device-independent interface to develop


graphic programs that runs on all platforms, such as Windows, Mac, and Linux.
AWT Class Hierarchy
Following is the class/package hierarchy of object class in java.lang package.

Component class is at the top of AWT hierarchy. Component is an abstract class that
encapsulates all attribute of visual component. A component object is responsible for
remembering the current foreground and background colors and the currently selected text
font.

AWT classes are contained in the java.awt package. It is one of the javas largest
packages. The java.awt package contains classes, which generates GUI components. AWT
provides graphical user interface (GUI) components that are used in all java applets and
applications. AWT contains classes that can be extended and their properties can be
inherited. AWT classes can also be abstract. Every GUI component must be a subclass of
the abstract class Component or MenuComponent
Windows Fundamentals
There are two types of GUI elements:
1. Component: Components are elementary GUI entities (such as Button, Label,
andTextField.)
2. Container: Containers (such as Frame,Panel and Applet) are used to hold
components in a specific layout (such as flow or grid). A container can also hold
sub-containers.

Components
GUI components are also called controls which allow users to interact with (i.e.,
control) the application through these components (such as button-click and text-entry).
There are five components: a Label (providing description), a TextField (for users to enter
text), and three Buttons (for user to trigger certain programmed actions). In a GUI
program, a component must be kept in a container.
Useful Methods of Component class
Method

Description

public void add(Component c)

Inserts a component on this component.

public
void
width,int height)

setSize(int

Sets the size (width and height) of the


component.

public
void
Defines the layout manager for the
setLayout(LayoutManager m)
component.
public void setVisible(boolean
Changes the visibility of the component,
status)
by default false.
Containers
In the above figure, there are three containers: a Frame and two Panels.
A Frame is the top-level container of an AWT program. A Frame has a title bar
(containing an icon, a title, and the minimize/maximize/close buttons), an
optional menu bar and the content display area.
A Panel is a rectangular area used to group related GUI components in a
certain layout. In the above figure, the top-level Frame contains two Panels.

You need to identify a container to hold the components. Every container has a method
called
add(Component
c).
A
container
(say
aContainer)
can
invoke aContainer.add(aComponent) to add aComponent into itself. For example,
Panel panel = new Panel(); // Panel is a Container
Button btn = new Button(Press); // Button is a Component
panel.add(btn); // The Panel Container adds a Button Component
Hierarchy of the AWT Container Classes
The hierarchy of the AWT Container classes is as follows:

The AWT provides four container classes. They are class Window and its two subtypes
class Frame and class Dialog as well as the Panel class. In addition to the containers
provided by the AWT, the Applet class is a container it is a subtype of the Panel class
and can therefore hold components. Brief descriptions of each container class provided by
the AWT are provided below.
Panel

A generic container for holding components. A Panel is


a rectangular area used to group related GUI components in
a certain layout. An instance of the Panel class provides a
container to which to add components.

Window

A top-level display surface (a window). An instance of


the Window class is not attached to nor embedded within
another container. An instance of the Window class has no
border and no title.

Frame

A top-level display surface (a window) with a border


and title. A Frame has a title bar (containing an icon, a title,

and the minimize/maximize/close buttons), an optional


menu bar and the content display area. It is otherwise very
much like an instance of the Window class.
Dialog

A top-level display surface (a window) with a border


and title. An instance of the Dialog class cannot exist
without an associated instance of the Frame class.

Working with frame windows


Each GUI program has a top-level container. The commonly-used top-level containers
in AWT are Frame, Dialog, Scrollpane and Applet:

Working with Panel


Panel
Panel class is concrete sub class of Container. Panel does not contain title bar, menu
bar or border. It is the simplest of all the containers. It is used to layout a set of related
GUI components in pattern such as grid or flow. A Panel has no physical appearance. It is
just a rectangular display area. Its purpose is to provide a way to organize components as
theyre laid out in a window. The default LayoutManager of Panel is FlowLayout.
A Panel is the basic building block of an applet. It provides a container with no special
features. It provides a single constructor that takes no parameters. The Applet class of the
java.applet package is a subclass of the Panel class.
Example: A frame with an empty panel
import java.awt.*;
public class PanelDemo extends Panel
{

public static void main(String [] args)


{
Frame f = new Frame(PanelDemo);
PanelDemo ex = new PanelDemo ();
f.add(ex , Center);
f.pack();
f.show();
}
}
Output:

Above class extends from the Panel class. In the main() method, an instance of this
new class is created and added to the Frame object via a call to the add() method. The
result is then displayed. The results of both examples should look same.
Working with Window
A Window is a top-level display area that exists outside the browser or applet area you
are working in. It has no adornments, such as the borders, window title, or menu bar that a
typical window manager might provide. A Frame is a subclass of Window that adds these
parts (borders, window title). Normally you will work with the children of Window and
not Window directly. However, you might use a Window to create your own pop-up menu
or some other GUI component that requires its own window and isnt provided by AWT.
The default LayoutManager for Window is BorderLayout.

Constructors of Window
public Window (Frame parent)
There is one public constructor for Window. It has one parameter, which specifies the
parent of the Window. When the parent is minimized, so is the Window. In an application,
you must therefore create a Frame before you can create a Window; this isnt much of an
inconvenience since you usually need a Frame in which to build your user interface. In an
applet, you often do not have access to a Frame to use as the parent, so you can pass null
as the argument.
Working with Frame
A window that is not contained inside another window is a frame. Frames are
containers, which mean that a frame can contain other GUI components.
A Frame provides the main window for the GUI application, which has a title bar
(containing an icon, a title, minimize, maximize/restore-down and close buttons), an
optional menu bar, and the content display area. When a frame object is created, it is 0x0
pixels and invisible. You must call the show or setVisible methods to actually make the
frame appear on the screen. Then, you must set the size of the frame using setSize or
setBound() method.
Creating a Frame
There are two ways to create a Frame. They are,
1. By Instantiating Frame class
2. By extending Frame class
Creating Frame Window by Instantiating Frame class
import java.awt.*;
public class AWTDemo extends java.applet.Applet {

AWTDemo()
{
Frame fm=new Frame(); //Creating a frame.
Label lb = new Label(Welcome to Graphics); //Creating a label
fm.add(lb); //adding label to the frame.
fm.setSize(300, 300); //setting frame size.
fm.setTitle(AWT Demo);
fm.setVisible(true); //set frame visibilty true.
}
public static void main(String args[])
{
AWTDemo ta = new AWTDemo();
}
}
Output:

Creating Frame window by extending Frame class


import java.awt.*;
import java.awt.event.*;
public class AWTDemo2 extends Frame{


public AWTDemo2()
{
Button btn=new Button(Hello World);
add(btn); //adding a new Button.
setSize(250, 300); //setting size.
setTitle(Welcome to AWT); //setting title.
setLayout(new FlowLayout()); //set default layout for frame.
setVisible(true); //set frame visibilty true.
}
public static void main (String[] args)
{
AWTDemo2 test = new AWTDemo2(); //creating a frame.
}
}

Output:

Creating a frame Window in applet


By deriving the new class from class Applet instead of class Panel, this example can

now run as either a standalone application or as an applet embedded in a Web page.


Example: A frame with an empty Applet
import java.awt.*;
public class FrameAppletDemo extends java.applet.Applet
{
public static void main(String [] args)
{
Frame f = new Frame(Frame Window in Applet);
FrameAppletDemo a = new FrameAppletDemo ();
f.add(Center, a);
f.pack();
f.show();
}
}
Output

Example: An Applet embedded with HTML


<html>
<head>
<title></title>
</head>
<body>

<APPLET code=FrameAppletDemo.class width=350 height=200>


</APPLET>

</body>
</html>
Output:

Example 2: Using Frame Window with Applet


/*FrameApplet.java */
import java.awt.*;
import java.applet.*;

/* <applet code=FrameApplet.class width=200 height=150></applet> */


public class FrameApplet extends Applet


{
Frame frame;
Button button;
public void init()
{
frame = new Frame(Frame Window);
button = new Button(Show Window);

add(button);
}
public boolean action(Event evt, Object arg)
{
boolean visible = frame.isShowing();
if (visible)
{
frame.hide();
button.setLabel(Show Window);
}
else
{
frame.show();
frame.resize(200, 100);
button.setLabel(Hide Window);
}
return true;
}
}
Output:
Before

After

ScrollPane
The ScrollPane container was introduced with the 1.1 release of the Java Runtime
Environment (JRE) to provide a new Container with automatic scrolling of any ONE large
Component. That large object could be anything from an image that is too big for the
display area to a bunch of spreadsheet cells. All the event handling mechanisms for
scrolling are managed for you. Also, there is no LayoutManager for a ScrollPane since
there is only a single object within it.
The following example demonstrates the scrolling of a large image. Since an Image
object is not a Component, the image must be drawn by a component such as a Canvas .
//ScrollingImage.java
import java.awt.*;
import java.applet.*;
/* <applet code= ScrollingImage.class width=200 height=150></applet> */

class ImageCanvas extends Component {


private Image image;
public ImageCanvas(Image i) {
image = i;
}
public void paint(Graphics g) {
if (image != null)
g.drawImage(image, 0, 0, this);

}
}
public class ScrollingImage extends Applet {
public void init() {
setLayout(new BorderLayout());
ScrollPane sp =
new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS);
Image im =
getImage(getCodeBase(), ./images/Penguins.jpg); // give any local image url
sp.add(new ImageCanvas(im));
add(sp, BorderLayout.CENTER);
}
}
Output:

Canvas
The Canvas class implements a GUI object that supports drawing. Drawing is not
implemented on the canvas itself, but on the Graphics object provided by the canvas.
The Canvas is a section of a window to draw graphics or display images. In that
respect, a canvas is more similar to a container than a componenthowever, a Canvas
component cannot be used as a place to put components.
Constructors of Canvas Class

Name
Canvas()

Description
This constructor
instance of a Canvas.

creates

Canvas(GraphicsConfiguration
This constructor creates
config)
instance of a Canvas with the
given
object
of
GraphicsConfiguration.
Methods of Canvas Class
Method
getAccessibleContext()

getBufferStrategy()

Description
This method gets the accessible
context of Canvas.
This method gets the Buffer
Strategy.

paint(Graphics g)

This method paint the Canvas

update(Graphics g)

update the Canvas.

createBufferStrategy(int
numBuffers)

This
method
BufferStrategy.

creates

the

The following code creates a Canvas component, resizes it to 50x50 pixels, sets the
background of the canvas to the color black, and adds the canvas to an applet window:
Example: Using Canvas
/*
canvasDemo.java
*/

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=CanvasDemo.class height=150 width=200>
</applet>
*/

public class CanvasDemo extends Applet


{
Canvas c;
public void init( )
{
c=new Canvas( );
c.setBackground(Color.black);
c.setSize(50,90);
add(c);
}
}
Output:

You can subclass Canvas to provide a custom graphic in an applet.

import java.awt.Canvas;
import java.awt.Graphics;
class DrawingRegion extends Canvas {
public DrawingRegion() {
setSize(100, 50);
}
public void paint(Graphics g) {
g.drawRect(0, 0, 99, 49); // draw border
g.drawString(A Canvas, 20,20);
}
}
Then you use it like any other component, adding it to a parent container, for example
in an Applet subclass.
import java.applet.Applet;
/*
<applet code= CanvasPaintTest.class height=150 width=200>
</applet>
*/

public class CanvasPaintTest extends Applet {


public void init() {
DrawingRegion region = new DrawingRegion();
add(region);
}
Output:

Working with graphics: AWT controls


AWT provides many ready-made and reusable GUI components. The frequently-used
are: Button, TextField, Label, Checkbox, CheckboxGroup(radio buttons), List,
and Choice, as illustrated below.

UI Component

Full Class Name(s)

Buttons

java.awt.Button

Checkboxes

java.awt.Checkbox

Single-line text fields

java.awt.TextField

Text Area

java.awt.TextArea

Labels

java.awt.Label

Lists

java.awt.List

Pop-up lists of choices

java.awt.Choice

Sliders and scrollbars

java.awt.Scrollbar

Drawing areas

java.awt.Canvas

Menus

java.awt.Menu,

java.awt.MenuItem,

java.awt.CheckboxMenuItem
Containers

java.awt.Panel, java.awt.Window and its


subclasses

Adding components to a container


To be useful, a user interface must consist of more than just a container it must
contain components. Components are added to containers via a containers add()method.
There are three basic forms of the add() method. The method to use depends on the
containers layout manager.
Three steps are necessary to create and place a GUI component:
1. Declare the component with an identifier (name);
2. Construct the component by invoking an appropriate constructor via
the new operator;
3. Identify the container (such as Frame or Panel) designed to hold this
component. The container can then add this component onto itself
viaaContainer.add(aComponent)
method.
Every
container
has
a add(Component) method. Take note that it is the container that actively and
explicitly adds a component onto itself, instead of the other way.
Example
Label lblInput; // Declare an Label instance called lblInput
lblInput = new Label(Enter ID); // Construct by invoking a constructor via the new
operator
add(lblInput); // this.add(lblInput) - this is typically a subclass of Frame
lblInput.setText(Enter password); // Modify the Labels text string
lblInput.getText(); // Retrieve the Labels text string

An Anonymous Instance
You can create a Label without specifying an identifier, called anonymous instance. In
the case, the Java compiler will assign an anonymous identifier for the allocated object.
You will not be able to reference an anonymous instance in your program after it is
created. This is usually alright for a Label instance as there is often no need to reference
a Label after it is constructed.
Example of anonymous instance
// Allocate an anonymous Label instance. this container adds the instance into
itself.
add(new Label(Enter Name: , Label.RIGHT));

// Same as
Label lblXxx = new Label(Enter Name: , Label.RIGHT));
Example: Adding Component in a Container
import java.awt.*;
import java.applet.Applet;

public class ComponentDemo extends Applet


{
public void init()
{
add(new Button(One));
add(new Button(Two));
}
public static void main(String [] args)
{
Frame f = new Frame(Adding Components);
ComponentDemo c = new ComponentDemo ();

c.init();
f.add(Center, c);
f.pack();
f.show();
}
}
Output:

Above code adds two buttons in the init() method because it is automatically called
during applet initialization. Therefore, no matter how the program is started, the buttons
are created, because init() is called by either the browser or by the main() method. Now
Lets see how all components used to create GUI.
Labels
A Label provides a text description message. The Label component is a string
displayed in the container that cannot be modified by the user.
Constructors of Label Component
Constructor

Action

Label( )

Creates a label with its string aligned to the left.

Label(String)

Creates a label initialized with the given string, and


aligned left.

Label(String, int)

Creates a label with specified text and alignment


indicated by the int argument: Label.Right, Label.Left and
Label.Center

Methods of Label Component

Method

Action

int getAlignment()

Retrieves a labels alignment setting.

String getText()

Retrieves a labels test string.

void

Sets the alignment for this label to the specified

setAlignment(int align)

void setText(String
label)

alignment. Possible values are Label.LEFT, Label.RIGHT,


and Label.CENTER
Sets a labels text string.

Adding Label
The following code is used to create a Label component and add it to an applet
window:
Label l = new Label(Counter );
add(l);

Example: Using a Label


/* LabelTest.java */

import java.awt.*;

/*<applet code=LabelTest.class width=200 height=150></applet>*/


public class LabelTest extends java.applet.Applet


{
public void init()

{
setLayout(new GridLayout(3,1));
add(new Label(aligned left, Label.LEFT));
add(new Label(aligned center, Label.CENTER));
add(new Label(aligned right, Label.RIGHT));
}
}
Output:

TextField
Text Field is a GUI element used in applet to accept values from the user. The number
of characters visible in the text field is configurable.

Constructors of TextField Component


Constructor
TextField()

TextField(int)

Action
Creates an empty TextField that is 0 characters wide
(it will be resized by the current layout manager).
Creates an empty text field. The integer argument
indicates the minimum number of characters to display.

TextField(String)

Creates a text field initialized with the given string.


The field will be automatically resized by the current
layout manager.

TextField(String, int)

Creates a text field some number of characters wide


(the integer argument) containing the given string. If the
string is longer than the width, you can select and drag
portions of the text within the field, and the box will scroll
left or right.

Methods of TextField Component


Method
getText()

Action
Returns the text this text field contains (as
a string)

setText(String)

Puts the given text string into the field

getColumns()

Returns the width of this text field

select(int, int)

selectAll()

Selects the text between the two integer


positions (positions start from 0)
Selects all the text in the field

isEditable()

Returns true or false based on whether the


text is editable

setEditable(boolean)

true (the default) enables text to be


edited; false freezes the text

getEchoChar()

Returns the character used for masking


input

echoCharIsSet()

Returns true or false based on whether the


field has a masking character

Adding TextField
Adding a TextField component to a window is the same as adding a button or any
other component. This can be done by instantiating the class TextFiled of java.awt
package as shown below.
TextField t = new TextField(12);
add(t);
After creating the text field, we need to add it to applet using add() method. This is
done in init() method of the applet.

To retrieve value from the text field, we use getText() method. But, this can return only
string value. Depending on our requirements we might need to convert this to other data
types. The syntax to get text value is shown below.
String val = t1. getText()
Example: Using a TextField Control
/* TextFieldsDemo.java*/
import java.awt.*;

/*<applet code=TextFieldsDemo.class width=200 height=150></applet>*/


public class TextFieldsDemo extends java.applet.Applet


{
public void init()
{

add(new Label(Enter your Name));
add(new TextField(your name here, 45));

add(new Label(Enter your phone number));


add(new TextField(12));
add(new Label(Enter your password));
TextField t = new TextField(20);
t.setEchoCharacter(*);
add(t);

}
}
Output:

Example 2: Using TextField to find sum of two values


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Input extends Applet implements ActionListener
{
Button b1=new Button(ADD);
TextField t1=new TextField(10);
TextField t2=new TextField(10);
TextField t3=new TextField(10);
public void init()

{
t1.setText(0);
t2.setText(0);
t3.setText(0);
add(t1);
add(t2);
add(b1);
add(t3);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
int v1=Integer.parseInt(t1.getText());
int v2=Integer.parseInt(t2.getText());
t3.setText(String.valueOf(v1+v2));
}
}
Output:

TextArea
TextArea is the TextComponent for multiline input. Some constructors permit you to
set the rows and columns of the TextArea on the screen. However, the Layout Manager
may change your settings. As with TextField, the only way to limit the number of
characters that a user can enter is to override the keyDown() method. The text in a
TextArea appears left justified, and the justification is not customizable. Depending upon

the LayoutManager, the TextAreas could be resized automatically.


Constructors of TextArea Component
Constructor

Action

TextArea()

Creates an empty text area 0 rows long and 0


character wide (the text area will be automatically resized
based on the layout manager).

TextArea(int, int)

Creates an empty text area with the given number of


rows and columns (characters)

TextArea(String)

Creates a text area displaying the given string, which


will be sized according to the current layout manager.

TextArea(String, int,

Creates a text area displaying the given string and


with the given dimensions

int)

Methods of TextArea Component


Method

int)

Action

getColumns()

Returns the width of the text area, in characters


or columns

getRows()

Returns the number of rows in the text area


(not the number of rows of text that the text area
contains)

insertText(String,

Inserts the string at the given position in the


text (text positions start at 0)

replaceText(String,
Replaces the text between the given integer
int, int)
positions with the new string
Adding TextArea Component

The following code is used to create a TextArea component and add it to an applet
window:
TextArea t = new TextArea(5,20);
add(t);
Example: Using TextArea Component
/* TextAreaDemo.java */
import java.awt.*;

/*<applet code=TextAreaDemo.class width=200 height=150></applet>*/


import java.awt.*;
import java.applet.*;

public class TextAreaDemo extends Applet {


TextArea t1 = new TextArea(Hello, 1, 30);
TextArea t2 = new TextArea(t2, 4, 30);
public void init()
{
add(t1);
add(t2);
}
}
Output:

Push buttons
The Button component is a rectangular button that can be clicked with a mouse.

Constructors of Button Component


To create a button, use one of the following constructors:
Constructor

Action

Button()

Creates an empty button with no label.

Button(String)

Creates a button with the given string


object as a label.

Methods of Button Component


Method

Action

getLabel()

Get the label of this Button instance

setLabel(string)

Set the label of this Button instance

setEnable(boolean)

Enable or disable this Button. Disabled


Button cannot be clicked.

Events of the Button Component


Clicking a button fires a so-called ActionEvent and triggers a certain programmed
action. We will see event-handling later.
Adding the Button Component
Creating a Button component and adding it to an applet window requires two lines:
Button b = new Button(Cancel);
add(b);
Because the add(b) method does not refer to a specific container object, it defaults to
adding the button to the applet surface. You can also create a new Panel and add a new
Button component to that panel:
Panel p = new Panel();
Button b = new Button(Cancel);
p.add(b);
Example: Using a Button Control
/*ButtonsDemo.java */

import java.awt.*;

/*<applet code=ButtonsDemo.class width=200 height=150></applet>*/


import java.awt.*;
import java.applet.*;

public class ButtonsDemo extends Applet {


Button b1 = new Button(Button 1);
Button b2 = new Button(Button 2);
public void init()
{

add(b1);
add(b2);
}
public boolean action(Event evt, Object arg)
{
if(evt.target.equals(b1))
getAppletContext().showStatus(Button 1);
else if(evt.target.equals(b2))
getAppletContext().showStatus(Button 2);
// Let the base class handle it:
else
return super.action(evt, arg);
return true; // Weve handled it here
}
}
Output:
Button1 Clicked

Button2 Clicked

Check boxes
The Checkbox class is used to display checkbox controls. The checkbox has a label to
indicate its meaning. Checkbox component is toggle box that can be either selected or

deselected indicating presence or absence of choice.


If a Checkbox object is not in a CheckboxGroup object, it is implemented as a
simple checkbox.
If a Checkbox object is with a CheckboxGroup object, it is implemented as a
radio button.
Constructors of Checkbox Component
To create a checkbox, use one of the following constructors:
Constructor

Action

Checkbox()

Creates an empty checkbox, unselected.

Checkbox
(String)

Creates a checkbox with the given string as a label.

Checkbox(String,
null, boolean)

Creates a checkbox that is either selected or


unselected based on whether the boolean argument is
true or false, respectively. The null is used as a
placeholder for a group argument. Only radio buttons
have groups.

Constructors of Checkbox Component


Method

Action

getLabel()

Returns a string containing this check boxs label

setLabel(String)

Changes the text of the check boxs label

getState()

Returns true or false, based on whether the check box is


selected

setState(boolean)

Changes the check boxs state to selected (true) or


unselected (false)

Adding the Checkbox Component


The following code is used to create a Checkbox component and add it to an applet
window:
Checkbox c = new Checkbox(Listening Music);
add(c);
Example: Using Checkbox Component
/*CheckboxDemo.java */
import java.awt.*;

/*<applet code=CheckboxDemo.class width=200 height=150></applet>*/


import java.awt.*;
import java.applet.*;

public class CheckboxDemo extends Applet {


public void init()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
add(new Checkbox(Floppy));
add(new Checkbox(CD));
add(new Checkbox(DVD));
add(new Checkbox(Pen Drive, null, true));
add(new Checkbox(Zip Drive));
}
}

Output:

CheckboxGroup
To create a group of checkboxes, you use the CheckboxGroup class. The
CheckboxGroup class is used with the Checkbox class to implement radio buttons. All
Checkbox objects that are associated with a CheckboxGroup object are treated as a single
set of radio buttons. Only one button in the group may be set or on at a given point in
time.
Constructors of CheckboxGroup Component
To create a checkbox, use one of the following constructors:
Constructor

Action

CheckboxGroup()

The

CheckboxGroup

provides

single,

parameterless constructor.
Methods of CheckboxGroup Component
CheckboxGroup class also provides methods for getting and setting the Checkbox
object.
Method

Action

setCheckboxGroup()

This method associates a checkbox with a particular


group.

setCurrent()

The method of CheckboxGroup is used to make one


of the boxes the selected box.

Adding CheckboxGroup Component


The following code is used to create a CheckboxGroup component and add it to an
applet window:
CheckboxGroup cbg = new CheckboxGroup();
Checkbox c1 = new Checkbox(Hi);
c1.setCheckboxGroup(cbg);
c1.setState(false);
add(c1);
Example: Using Checkboxgroup Component
/*CheckboxgroupDemo.java */

import java.awt.*;

/*<applet code=CheckboxgroupDemo.class width=200 height=150></applet>*/


import java.awt.*;
import java.applet.Applet;

public class CheckboxgroupDemo extends Applet


{
CheckboxGroup cbg = new CheckboxGroup();
public void init()
{
Checkbox c1 = new Checkbox(Hi);
c1.setCheckboxGroup(cbg);
c1.setState(false);
add(c1);

Checkbox c2 = new Checkbox(Hello,cbg,false);

add(c2);

Checkbox c3 = new Checkbox(How r u?,cbg,true);


add(c3);
}
}
Output:

Choice lists
A choice list provides a group of options and enables selection of one at a time. The
Choice class is used to create drop-down lists. From this lists a single choice can be
selected, similar to a group of checkboxes.
Methods of ChoiceList Component
Method
addItem()

getItem(int)

Action
This method is used to build the
choice list.
Returns the string item at the given
position (items inside a choice begin at 0,
just like arrays)

countItems()

Returns the number of items in the


menu

getSelectedIndex()

Returns the index position of the item


thats selected

getSelectedItem()

Returns the currently selected item as


a string

select(int)

Selects the item at the given position

select(String)

Selects the item with the given string

Building ChoiceList Component


To create a list, you instantiate the list, add individual items to it, and then add the
loaded list to an applet window:
Choice c = new Choice();
c.addItem(Winter );
c.addItem(Summer );
c.addItem(Monsoon);
add(c);
Example: Using ChoiceList Component
/*ChoiceListDemo.java */

import java.awt.*;

/*<applet code=ChoiceListDemo.class width=200 height=150></applet>*/


import java.awt.*;
import java.applet.Applet;

public class ChoiceListDemo extends Applet


{


public void init()
{
Choice c = new Choice();

c.addItem(Apples);
c.addItem(Oranges);
c.addItem(Strawberries);
c.addItem(Blueberries);
c.addItem(Bananas);

add(c);
}

}
Output:

Lists
The List component is a scrolling list of strings from which one or more strings can be
selected. The List class is use for creating single- and multiple-selection list GUI. The List
class provides facility to set display size (number of elements) and also allow selecting
multiple items from the list.
Constructors of List Component

The List class has two constructors:


Constructor

Action

List()

Creates an empty scrolling list that enables


only one selection at a time.

List(int,
boolean)

Creates a scrolling list with the given number


of visible lines on the screen. The boolean
indicates whether this list enables multiple
selections (true) or not (false).

Methods of List Component


Method

Action

addItem()

Used to build the scrolling list

getItem(int)

Returns the string item at the given


position

countItems()

Returns the number of items in the menu

getSelectedIndex()

Returns the index position of the item


thats selected (used for lists that allow only
single selections)

getSelectedIndexes()

Returns an array of index positions


(used for lists that allow multiple selections)

getSelectedItem()

Returns the currently selected item as a


string

getSelectedItems()

Returns an array of strings containing all


the selected items

select(int)

Selects the item at the given position

select(String)

Selects the item with that string

Adding List Component


The following code is used to create a scrolling list, add items to it, and then add the
list to an applet window:
List lst = new List(4,true);
lst.addItem(CDR);
lst.addItem(CDRW);
lst.addItem(DVD);
lst.addItem(PenDrive);
add(lst);
Example: Using List Component
/*ScrollingListDemo.java */
import java.awt.*;

/*<applet code=ScrollingListDemo.class width=200 height=150></applet>*/


import java.awt.*;
import java.applet.Applet;

public class ScrollingListDemo extends Applet


{

public void init() {
List lst = new List(5, true);

lst.addItem(CDR);

lst.addItem(CDRW);
lst.addItem(DVD);
lst.addItem(PenDrive);
lst.addItem(FloppyDisk);
lst.addItem(Zipdrive);
lst.addItem(ROM);
add(lst);
}
}
Output:

Menus
A Menu is a component of AWT but it is different from other components because it
cant be added to ordinary container and laid out by layout manager. Menu can be added
only to a menu container. A top-level window can have menu bar, which displays a list of
top - level menu choices and each choice is associated with a drop-down menu.
MenuComponent hierarchy

MenuBar
A menu bar is the first building block of a menu. First create a menu bar, then position
it on a frame. The menus are added to the menu bar just like a button or any component is
added to a container. In this case, the menu bar is like the container.
E.g.,myMenuBar.add(myEditMenu); adds a menu object called myEditMenu to the
menu bar.
It can only be added to a Frame object. A frame can display only one MenuBar at a
time. The MenuBar does not support any listener.
Constructor of Menubar
Constructor
MenuBar( )

Action
To create a
default menu bar.

Menu
A Menu component provides a basic pull-down menu. A Menu object is a drop-down
menu component that is deployed from a menu bar. It can be added either to a MenuBar or
to another Menu. Menus are used to display and control menu items.
Constructor of Menu
Constructor

Action

Menu( )

To create a default menu.

Menu( String str )

Menu( String
boolean flag)

str specifies the name of the Menu


selection
str,

str specifies the name of the Menu


selection
flag represents the popup menu if
set true

MenuItem

MenuItem component are the text leaf nodes of a menu tree. MenuItems are added to a
Menu.
An ActionListener can be added to a MenuItem object.
Constructor of MenuItem
Constructor

Action

MenuItem( )

To create a default MenuItem.

MenuItem( String str )

str is the name shown in the Menu.

MenuItem(
String
MenuShortcut key)

str,

key is the short cut key for that


Menu Item

CheckboxMenuItem
CheckboxMenuItem is checkable menu item, which provides selection (on or off )
listed in menus.
CheckboxMenuItem can be controlled by the ItemListener interface. The
itemStateChanged( ) method is called, when the checkbox state is modified.
Constructor of CheckboxMenuItem
Constructor

Action

CheckboxMenuItem( )

To

create

default

CheckBoxMenuItem.
CheckboxMenuItem(
String str )
CheckboxMenuItem(
String str, boolean flag )

str is the name shown in the menu.

flag can be set on for the Item to be


checkable.

Methods of Menu
Following are some common methods, which are used while creating a menu.

Method

Action

setEnabled( boolean flag

To enable or disable menu item.

isEnabled( )

To obtain the status of the menu item.

setLabel( String str )

To change the name of the invoking


menu item.

String getLabel( )

To obtain the current name of the


menu item.

boolean getState( )

Returns true if the item is checked


otherwise false.

void setState( boolean


To check an item pass true and to
flag)
clear an item pass false.

add(MenuItem mi)

This method add menu item in Menu.

add(String label)

This method add string at menu.

addSeparator()

This method add separator between


menu items.

getItem(int index)

This method gets the item from the


given index.

getItemCount()

This method gets the number of item


inside the menu.

insert(MenuItem
item, int index)

menu

This method inserts menu item inside


menu.

insertSeparator(int index)

This method inserts separator between


menu item.

remove(MenuComponent
This method remove menu item from
item)
menu.
remove(int index)

This method remove menu item from


menu as per the index.

removeAll()

This method remove all menu item


from menu.

Example: Using MenuBar Component


/*MenuBarDemo.java*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=MenuBarDemo.class width=200 height=100></applet>*/
public class MenuBarDemo extends java.applet.Applet {
private Frame myFrame;

public void init()
{
myFrame = new Frame();
myFrame.addWindowListener(new Terminator());
myFrame.setBounds(200,200,300,300);

// place myMenuBar at top of myFrame
MenuBar myMenuBar = new MenuBar();
myFrame.setMenuBar(myMenuBar);


Menu fileMenu = new Menu(File);
myMenuBar.add(fileMenu);

Menu editMenu = new Menu(Edit);
myMenuBar.add(editMenu);

myFrame.setVisible(true);
}

public class Terminator
extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
myFrame.dispose();
// use System.exit(0) for applications
}
}
}
Output:

Example: Using Menu Component


/*MenuDemo.java*/

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class MenuDemo extends Applet implements ActionListener


{
private TextField myTextField;
private Frame myFrame;

public void init()
{
myFrame = new Frame();
myFrame.addWindowListener(new Terminator());
myTextField = new TextField(20);

add(myTextField);
myFrame.setBounds(200,200,300,300);

// place myMenuBar at top of myFrame
MenuBar myMenuBar = new MenuBar();
myFrame.setMenuBar(myMenuBar);

Menu fileMenu = new Menu(File);
myMenuBar.add(fileMenu);

Menu editMenu = new Menu(Edit);
myMenuBar.add(editMenu);
MenuItem myMenuItem;

myMenuItem = new MenuItem(Open);
myMenuItem.addActionListener(this);
fileMenu.add(myMenuItem);

myMenuItem = new MenuItem(Close);


myMenuItem.addActionListener(this);
fileMenu.add(myMenuItem);

myMenuItem = new MenuItem(Undo);
myMenuItem.addActionListener(this);
editMenu.add(myMenuItem);

myFrame.show();

}

public void actionPerformed(ActionEvent e)
{
if (e.getSource() instanceof MenuItem)
myTextField.setText(Your Choice:
+ e.getActionCommand());
}

public class Terminator
extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
myFrame.dispose();
// use System.exit(0) for applications
}
}
}

Output:

Example 2: Using Menu Component


/*MenuTest.java*/
import java.util.Vector;
import java.awt.*;

public class MenuTest extends Frame


{
MenuTest ()
{
super (MenuTest);
MenuItem mi;
Menu file = new Menu (File, true);
file.add (Open);
file.add (mi = new MenuItem (Close));
mi.disable();
Menu extras = new Menu (Extras, false);

extras.add (new CheckboxMenuItem (What));


mi = extras.add (new MenuItem (Yo));
mi = extras.add (new MenuItem (Yo));
file.add (extras);
file.addSeparator();
file.add (Quit);
Menu help = new Menu(Help);
help.add (About);
MenuBar mb = new MenuBar();
mb.add (help);
mb.add (file);
mb.setHelpMenu (help);
setMenuBar (mb);
resize (200, 200);
}

public boolean handleEvent (Event e)


{
if (e.id == Event.WINDOW_DESTROY)
{
System.exit(0);
}
return super.handleEvent (e);
}
public boolean action (Event e, Object o)
{
if (e.target instanceof MenuItem)

{
if (Quit.equals (o))
{
dispose();
System.exit(1);
}
else
{
System.out.println (User selected + o);
if (e.target instanceof CheckboxMenuItem) {
CheckboxMenuItem cb = (CheckboxMenuItem)e.target;
System.out.println (The value is: + cb.getState());
}
}
return true;
}
return false;
}
public static void main (String []args)
{
MenuTest f = new MenuTest ();
f.show();
}

Output:

Popup Menu
Example: Creating Popup Menu
/* PopupTest.java*/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

/*<applet code = PopupTest.class width=200 height=150></applet>


public class PopupTest extends Applet implements ActionListener
{
PopupMenu popup;
public void init()
{
MenuItem mi;
popup = new PopupMenu(Title Goes Here);
popup.add(mi = new MenuItem (Undo));
mi.addActionListener (this);
popup.addSeparator();
popup.add(mi = new MenuItem(Cut)).setEnabled(false);
mi.addActionListener (this);
popup.add(mi = new MenuItem(Copy)).setEnabled(false);

mi.addActionListener (this);
popup.add(mi = new MenuItem (Paste));
mi.addActionListener (this);
popup.add(mi = new MenuItem(Delete)).setEnabled(false);
mi.addActionListener (this);
popup.addSeparator();
popup.add(mi = new MenuItem (Select All));
mi.addActionListener (this);
add (popup);
resize(200, 200);
enableEvents (AWTEvent.MOUSE_EVENT_MASK);
}
protected void processMouseEvent (MouseEvent e)
{
if (e.isPopupTrigger())
popup.show(e.getComponent(), e.getX(), e.getY());
super.processMouseEvent (e);
}
public void actionPerformed(ActionEvent e) {
System.out.println (e);
}
}
Output:
Before Click

After Right Click

Layout Managers
Layout Managers apply to all AWT containers. Java uses layout managers to arrange
components inside containers.
Every container has a default layout manager that determines the sizes and
positions of components within the container.
One reason that Java uses layout managers is so that containers can be resized
gracefully.
Layout Manager Classes
Some possible Layout Managers are listed in the table below, along with the constants
defined for each one the constants are usually used to position components in the
container. The java.awt package provides five layout manager classes
Layout
Manager

Description

Constants/Methods/Constructors

BorderLayout

Arranges
NORTH,
SOUTH,
components to the top, EAST,WEST,CENTER positions in
bottom, left, right, and the container
center of a container.

FlowLayout

Arranges
components

in

LEFT, CENTER, RIGHT these


a tell it how to align the components in

directional flow, much each row


like lines of text in a
paragraph..

GridLayout

Divide the container


GridLayout(int rows, int columns)
into
equal-sized
To specify the number of rows and
rectangles and arrange columns in the grid
each component into
one of these cells.

CardLayout

Displays

one

addLayoutComponent

(String

component at a time; name, Component component)


components are added
to add a component to the layout
using
the
addLayoutComponent()
method;
each
Component can be
assigned a name; the
component displayed
can be changed in
response to an action
e.g. a button click.
Following figure demonstrates the component arrangement using different Layout
Manager
FlowLayout

GridLayout

BorderLayout

CardLayout

Flow Layout
FlowLayout arranges swing components from left to right until theres no more space
available. Then it begins a new row below it and moves from left to right again. Each
component in a FlowLayout gets as much space as it needs and no more.
setLayout() method is used to for a container to use the FlowLayout manager as
follows:
setLayout( new FlowLayout() );
When there are too many components to fit, they wrap to a new row, similar to a
word processor with word wrap enabled.
Setting FlowLayout Alignment
You can change the alignment of a FlowLayout in the constructor. To do this just pass
one of the defined constants FlowLayout.LEFT, FlowLayout.RIGHT or
FlowLayout.CENTER to the constructor, e.g.
setLayout(new FlowLayout(FlowLayout.LEFT));
setLayout(new FlowLayout(FlowLayout.RIGHT));
setLayout(new FlowLayout(FlowLayout.CENTER));
Example: Using FlowLayout
/*FlowLayoytTest.java*/

import java.awt.*;
import java.applet.*;

/*<applet code=FlowLayoutTest.class width=200 height=100></applet>*/


public class FlowLayoutTest extends Applet {

public void init()


{
setLayout(new FlowLayout());
add(new Button(One));
add(new Button(Two));
add(new Button(Three));
add(new Button(Four));
add(new Button(Five));
add(new Button(Six));
}
}
Output:
Before Resize

After Resize

In above program we can also provide the alignment of components. Default


alignment is center.
setLayout(new lowLayout());

setLayout(new
FlowLayout(FlowLayout.LEFT));

setLayout(new
FlowLayout(FlowLayout.RIGHT));

setLayout(new
FlowLayout(FlowLayout.CENTER));

Border Layout
BorderLayout places swing components in the North, South, East, West and center of a
container. All extra space is placed in the center area. You can add horizontal and vertical
gaps between the areas. The BorderLayout is the default layout manager for all Window,
Dialog, and Frame classes.
NORTH
SOUTH
WEST
WEST

CENTER

BorderLayout provides five areas to hold components. In a border layout, components


are added to the edges of the container. These areas are four borders of the screen, North,
South, East, and West, with any remaining space going into the Center area.
When you add a component to the layout, you must specify which area to place it in.
The order in which components are added to the screen is not important but you can have
only one component in each area.
The add() method takes an additional parametera string that can be North, South,

East, West, or Center. This parameter specifies the location in the border layout for the
component.
Example: Using BorderLayout without location.
/**
* BorderLayoutTest.java
*/

import java.awt.*;
import java.applet.*;

/*<applet code=BorderLayoutTest.class width=200 height=100></applet>*/


public class BorderLayoutTest extends Applet
{

public void init()


{
setLayout(new BorderLayout());
add(new Button(One));
add(new Button(Two));
add(new Button(Three));
add(new Button(Four));
add(new Button(Five));
add(new Button(Six));
}
}
Output:
Before Resize

After Resize

Example: Using BorderLayout with location


/**
* BorderLayoutTest.java
*/

import java.awt.*;
import java.applet.*;

/*<applet code=BorderLayoutTest.class width=200 height=100></applet>*/


public class BorderLayoutTest extends Applet {

public void init() {


setLayout(new BorderLayout());
add(new Button(One),BorderLayout.NORTH);
add(new Button(Two),BorderLayout.SOUTH);
add(new Button(Three),BorderLayout.CENTER);
add(new Button(Four),BorderLayout.EAST);
add(new Button(Five),BorderLayout.WEST);
add(new Button(Six),BorderLayout.WEST);

}
Output:
Before Resize

After Resize

Grid Layout
GridLayout is a layout manager arranges components in a rectangular grid inside the
container. The container is divided into equal-sized rectangles, and one component is
placed in each rectangle. The grid is given specific dimensions when created. Components
added to the container with the GridLayout manager are arranged in order from left to
right.
Component
1

Component
2

Component
4

Component
5

Component

Component

Component
6

7
This is similar to the way components are added with the FlowLayout manager, but
with GridLayout, components are given equal amounts of space in the container. The
components are resized to fill the grid cell, if possible. GridLayout can reposition or resize
objects after adding or removing components. Whenever the area is resized, the
components within it are resized.
The only parameter used with the add() method is the name of the object to add. The
GridLayout is widely used for arranging components in rows and columns. New rows are

added as neededif you create a three-by-three grid and add a tenth item, a fourth row is
added.
Example: Using GridLayout Manager
/*GridLayoutTest.java*/

import java.awt.*;
import java.applet.*;

/*<applet code=GridLayoutTest.class width=200 height=100></applet>*/


public class GridLayoutTest extends Applet {


public void init()
{
setLayout( new GridLayout(3, 2));
add(new Button(One));
add(new Button(Two));
add(new Button(Three));
add(new Button(Four));
add(new Button(Five));
add(new Button(Six));
}
}
Output:
Before Resize

After Resize

You can observe that the size of the buttons is changed to fit the area.
Card Layout
The CardLayout class is a special type of layout organizer. The CardLayout manager
treats each component in the container as a card. Only one card is visible at a time. All the
components are given the same size. Usually, the CardLayout manages a group of Panels
(or some other container), and each Panel contains several components of its own. Instead
of displaying several panels concurrently, it creates a stack of panels that can then be
displayed one at a time, much like the stack of cards in the Solitaire game. You can use the
CardLayout to create tab control for GUI.
With CardLayout we can assign names to the components and jump to a component by
name. We can also cycle through components in order.
The CardLayout class has its own group of methods that are used to control which
panel is displayed.
Following example uses a series of panels with different-colored canvases to illustrate
the CardLayout class.
Clicking on the applet area causes the layout manager to load the next panel.
If the last panel is already loaded, the CardLayout manager automatically returns to
the first panel.
Example: Using CardLayout
/*CardLayoutTest.java */

import java.awt.*;
import java.applet.*;

/*<applet code=CardLayoutTest.class width=200 height=100></applet>*/


public class CardLayoutTest extends Applet


{

public void init()


{

Panel cardPanel = new Panel();

CardLayout cards = new CardLayout(); // assume cards is declared as an instance


variable
cardPanel.setLayout(cards);

Panel panel1= new Panel();


cardPanel.add(panel1, First);

Panel panel2= new Panel();


panel2.add(hello, new Label(How r u?));
cardPanel.add(panel2, Second);

Panel panel3= new Panel();


cardPanel.add(panel3, Third);

cards.show(cardPanel, Second); //display second panel


this.add(cardPanel); //adds cardPanel to Applet
}
}

Output:
Before Resize

After Resize

Example: Using CardLayout


/*CardStack.java*/
import java.awt.*;
import java.applet.*;

/*<applet code=cardStack.class width=200 height=100></applet>*/


public class CardStack extends Applet


{
Panel canvasCards = new Panel();
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();

CardLayout cardDeck = new CardLayout();



public void init() {

canvasCards.setLayout( cardDeck );

p1.setLayout (new BorderLayout());


p2.setLayout (new BorderLayout());
p3.setLayout (new BorderLayout());

Canvas c1 = new Canvas();


Canvas c2 = new Canvas();
Canvas c3 = new Canvas();

c1.setBackground(Color.black);
c2.setBackground(Color.red);
c3.setBackground(Color.green);

p1.add(Center, c1);
p2.add(Center, c2);
p3.add(Center, c3);

canvasCards.add(p1, p1);
canvasCards.add(p2, p2);
canvasCards.add(p3, p3);

setLayout(new BorderLayout());
add(Center, canvasCards);
}

public boolean mouseDown(Event event, int x, int y)


{
cardDeck.next(canvasCards);
return true;

}
}
Output:
First Click (black)

Second Click (red)

Third Click (green)

Event Handling in Java


Fundamentals of Event Handling
Changing the state of an object is known as an event. Event describes the change of
state of any object. For example pressing a button, entering a character in Textbox. Any
GUI (graphical user interface) program is event driven. In event-driven programming, a
piece of event-handling codes is executed when an event has been fired in response to a
user input (such as clicking a mouse button or hitting the key). Events are supported by a
number of Java packages, like java.util, java.awt and java.awt.event. All events derive
from the java.util.EventObject class.
The GUI in Java processes the interactions with user via mouse; keyboard and various
user controls such buttons, checkbox, text-field etc. as the events. These events are to be
handled properly to implement Java Programming as an Event-Driven Programming.
How Events are handled?
Event handling relies on three main components,
Events Source: Event source is an object that generates an event. A source
generates an Event and sends it to one or more listeners registered with the
source.
Events: An event is any change of state of an object.
Listeners: A listener is an object that listens to the event. A listener gets
notified when an event occurs. Once event is received by the listener, they

process the event and then return.


Steps to perform EventHandling
Register Event Listners
Event listeners may register with the event sources to receive notification
about particular events. Event delivery is on registration bases. Event
listeners implement interface methods to be executed when a particular
event occurs.
Generate Events
Event sources generate events. Event sources encapsulate necessary
information in the event objects and pass them to event listeners.
Notify and handle the event
When an event is generated, the event source walks over the registered
listeners and notifies them about the event. Also implement Event Listener
by overriding its method to handle the event.
Consider ActionEvent as an example:
An ActionListener object may register with a button to be notified about action
events. Button notifies the actionListener objects by invoking its
actionPerformed() method and passing the ActionEvent reference.
When a button is clicked, it generates an ActionEvent. ActionEvent object
contains information such as the source and the action command.
Event listener can be implemented in variety of ways:
It delegates that functionality to an inner class. It is common to place the
listener class inside the class whose state would be modified by the listener
class.
It creates an anonymous inner class and delegates the event handling to that
anonymous class. Helper methods make the programs even compact.
The ButtonPanel could become the action listener by implementing the
ActionListener interface.

The user interacts with the event source object (such as Button and Textfield). Upon
triggered, it creates an event object. This event object will be messaged to all
the registered listener object(s), and an appropriate event-handler method of the listener(s)
is called-back to provide the response. In other words, triggering a source fires an event to
its entire listener, and invokes an appropriate handler of the listener(s).
To express interest for a certain sources event, the listener(s) must be registered with
the source. In other words, the listener(s) subscribes to a sources event, and the source
publishes the event to all its subscribers upon activation. This is known as subscribepublish or observable-observer design pattern.
Event loop
When you run your Java program, it cycles around in a loop waiting for an event to
occur.

In Java, we create sections of code (methods) that the Java applet will automatically
execute when an event happens. Within these event handling methods we can check
what event has occurred and ensure the required processing takes place. In this program
we will listen for a button press as the event.

Event Classes and Listener Interfaces


Javas event handling mechanism is represented by event classes. At the root of the
java event class hierarchy is EventObject in java.util, which is the super class for all
events.
Low-level Events
Low-level events represent a low-level input or window operation, like a key press,
mouse movement, or window opening. The following table displays the different lowlevel events, and the operations that generate each event (each operation corresponds to a
method of the listener interface):
ComponentEvent

Hiding, moving, resizing, showing

ContainerEvent

Adding/removing component

FocusEvent

Getting/losing focus

KeyEvent

Pressing, releasing, or typing (both) a key

MouseEvent

Clicking, dragging, entering, exiting, moving, pressing, or


releasing

WindowEvent

Iconifying, deiconifying, opening, closing, really closed,


activating, deactivating

For instance, typing the letter A on the keyboard generates three events, one for
pressing, one for releasing, and one for typing. Depending upon your interests, you can do
something for any of the three events.
Semantic Events
Semantic events represent interaction with a GUI component; for instance selecting a
button, or changing the text of a text field. Which components generate which events is
shown in the next section.
ActionEvent

Do the command

AdjustmentEvent

Value adjusted

ItemEvent

State changed

TextEvent

Text changed

Event Sources
The following table represents the different event sources. Keep in mind the object
hierarchy. For instance, when Component is an event source for something, so are all its
subclasses:

Semantic Events

Button
List
MenuItem

ActionListener

TextField

Event class hierarchy


The super class of all the events
is java.util.EventObject. This class
contains getSource() method which
returns the source of the generated
event. An immediate subclass
of EventObject is the AWTEvent class
which is the super class of all AWT
based events.

Choice
Checkbox
Checkbox
CheckboxMenuItem
List
Scrollbar

AdjustmentListener

TextArea

TextListener

TextField

Low-Level Events
Component

ItemListener

ComponentListener
FocusListener
KeyListener
MouseListener

MouseMotionListener
Container

ContainerListener

Window

WindowListener

Notice that although there is only one MouseEvent class, the listeners are spread
across two interfaces. This is for performance issues. Since motion mouse events are
generated more frequently, if you have no interest in them, you can ignore them more
easily, without the performance hit.
Event Classe

Description

Listener Interface

ActionEvent

Generated when button is

ActionListener

pressed, menu-item is selected,


list-item is double clicked
MouseEvent

Generated when mouse is


dragged, moved, clicked,
pressed or released also when
the enters or exit a component

MouseListener

KeyEvent

Generated when input is


received from keyboard

KeyListener

ItemEvent

Generated when check-box


or list item is clicked

ItemListener

TextEvent

Generated when value of


textarea or textfield is changed

TextListener

MouseWheelEvent

Generated when
wheel is moved

MouseWheelListener

WindowEvent

Generated when window is


activated,
deactivated,

mouse

WindowListener

deiconified, iconified, opened


or closed
ComponentEvent

Generated when component


is hidden, moved, resized or set
visible

ComponentEventListener

ContainerEvent

Generated when component


is added or removed from
container

ContainerListener

AdjustmentEvent

Generated when scroll bar is

AdjustmentListener

manipulated
FocusEvent

Generated when component


gains or lose keyboard focus

FocusListener

Methods of Event Class


Class
ActionEvent

Method

Descritpion

String
getActionCommand()

To obtain the command name for


the invoking ActionEvent object

int getModifiers( )

To return a value that indicates


which modifier keys were pressed

AdjustmentEvent

adjustable
getAdjustable( )

To return the object that generated


the event

ComponentEvent

int
getAdjustmentType( )

To obtain the type of the


adjustment event.

Component
getComponent()

To return the component that


generated the event.

ContainerEvent

Container
getContainer( )

To return a reference to the


component that was added to or
removed from the container.

boolean isTemporary(

To indicate if the focus change is


temporary.

boolean isAltDown( )

To identify if the Alt key is pressed


or not at the time of event generated.

)
InputEvent

boolean
isControlDown( )

To identify if the Ctrl key is pressed


or not at the time of event generated.

boolean isShiftDown(

To identify if the Shift key is


pressed or not at the time of event
generated.

object getItem( )

To obtain a reference to the Item


that generated an event.

ItemSelectable
getItemSelectable( )

To obtain a reference to the


ItemSelectable object that generated an

ItemEvent

container that generated the event.

Component getChild(
)

FocusEvent

To return a reference to the

event.
int getStateChange( )

To return the state change(select or


deselect) for the event.

KeyEvent

char getKeyChar( )

int getKeyCode( )
MouseEvent

WindowEvent

To return the character that was


entered
To return the code that was entered

int getX( ) , int getY( )

To obtain X and Y co-ordinates of


the mouse when an event occurred.

Point getPoint( )

To obtain the co-ordinates of the


mouse.

int getClickCount( )

To obtain the number of mouse


click for this event.

Window getWindow( )

To return the window object that


generated the event.

Event Source
A source is an object that generates an event
Event generation occurs when internal state of that object changes in some way

A source must register listeners in order for the listeners to receive the
notifications about a specific type of events
Event

Description

Source
Button
Checkbox

Generates ActionEvent when button is pressed


Generates ItemEvent when the checkbox is selected
or deselected

Choice

Generates ItemEvent when the choice is changed

List

Generates ActionEvent when an item is doubleclicked; generates ItemEvent when an item is selected or
deselected

Menu Item

Generates ActionEvent when a menu item is selected


and when a checkable menu item is selected or deselected

Scroll bar

Generates AdjustmentEcent when the scroll bar is


manipulated

Text

Generates TextEvent when the user enter a character

Component
Window

Generates WindowEvent when a window is activated,


closed, deactivated, deiconified, iconified, opened or quit

General form of adding such listeners:


public void addTypeListener(TypeListener obj)
Eg:
Button btnObj=new Button(Enter);
btnObj.addActionListener(el);
//el is the object of class that implements ActionListener interface

Sources of Events
Following is the list of AWT component and the events that can be generated by them

Event Listner Interfaces


The event model supports the notion of event listeners from the class
java.util.EventListener.
A listener is an object that is notified when an event occurs. An event listener is
any object that implements listener interfaces.
It has two major requirements:
It should be registered to one more source object to receive event
notification
It must implement methods to receive and process those notifications
There are listener interfaces for each of the different types of AWT event, and also for
non-graphical events. An object that implements a listener interface inherits methods that
can be used to respond to that type of event.
Java has defined a set of interfaces for receiving and processing the events under
the java.awt.event package
Event

Listener

Methods Provided

Description

Interface

(Default void return type for all


methods)

ActionListener

AdjustmentListener

actionPerformed(ActionEvent ae)

adjustmentValueChanged
(AdjustementEvent ae)

Defines one
method to receive
ActionEvent
Defines one
method to receive
AdjustementEvent

ComponentListener

componentResized(ComponentEvent

Defines four
ce)
methods
to
componentMoved(ComponentEvent ce) recognize when a
component
is
componentShown(ComponentEvent ce) hidden, moved,
componentHidden(ComponentEvent ce) resized, or shown

ContainerListener

componentAdded(ContainerEvent ce)

two

componentRemoved(ContainerEvent

methods
to
recognize when a
component
is
added to or
removed from a
container

focusGained(FocusEvent fe)

Defines two
methods
to
recognize when a
component gains

ce)

FocusListener

Defines

focusLost(FocusEvent fe)

or loses keyboard
focus
ItemListener

itemStateChanged(ItemEvent ie)

Defines
method

one
to

recognize when
the state of an
item changes
KeyListener

keyPressed(KeyEvent ke)
keyReleased(KeyEvent ke)
keyTyped(KeyEvent ke)

MouseListener

mouseClicked(MouseEvent me)
mouseEntered(MouseEvent me)
mouseExited(MouseEvent me)
mousePressed(MouseEvent me)
mouseReleased(MouseEvent me)

MouseMotionListener

mouseDragged(MouseEvent me)
mouseMoved(MouseEvent me)

Defines three
methods
to
recognize when a
key is pressed,
released or typed
Defines five
methods
to
recognize when
mouse is clicked,
enters
a
component, exits
a component, is
pressed or is
released
Defines two
methods
to
recognize when
the mouse is
dragged
or
moved.

MouseWheelListener

TextListener

mouseWheelMoved(MouseWheenEvent
Defines one
me)
method
to
recognize when
the mouse wheel
is moved
textChanged(TextEvent te)

Defines
method

one
to

recognize when a
text value changes
WindowFocusListener

windowGainedFocus(WindowEvent
we)
windowLostFocus(WindowEvent we)

Defines two
methods
to
recognize when a
window gains or
loses input focus

WindowListener

windowActivated(WindowEvent we)
windowClosed(WindowEvent we)
windowClosing(WindowEvent we)
windowDeactivated(WindowEvent we)
windowDeiconified(WindowEvent we)
windowIconified(WindowEvent we)
windowOpened(WindowEvent we)

Defines seven
methods
to
recognize when a
window
is
activated, closed,
deactivated,
deiconified,,
iconified, opened
or quit

Event types, EventSource and EventListener Interface


Event Type
ActionEvent

AdjustmentEvent
ItemEvent

Event Source
Button, List, MenuItem,
TextField
Scrollbar
Choice,
Checkbox,
CheckboxMenuItem, List

Event Listener interface


ActionListener

AdjustmentListener
ItemListener

TextEvent

TextArea, TextField

TextListener

ComponentEvent

Component

ComponentListener

ContainerEvent

Container

ContainerListener

FocusEvent

Component

FocusListener

KeyEvent

Component

KeyListener

MouseEvent

Component

WindowEvent

Window

MouseListener,
MouseMotionListener
WindowListener

Table: Event types and corresponding EventSource & EventListener


ActionEvent and ActionListener Interface
Action events are generated by specific types of action that you might want to respond
to, for example:
Clicking a button
Selecting a menu item
Hitting Enter in a text component
Methods of ActionEvent class
ActionEvent
Method
int getID()

String
getActionCommand()

Description

Returns an ID value for the action that occurred


every ActionEvent sub-class has a constant value
ACTION_PERFORMED defined in it, which is
the value returned by this method.
Returns a string that is a name for the kind of
action that occurred. Button and MenuItem
components can set this string with their
setActionCommand()
method.
If
setActionCommand() is not called to set the string,
then the label of the Button or MenuItem is
returned.

Methods of ActionListener Interface


ActionListener
Method
void
actionPerformed
(ActionEvent event)

Description

When any action event occurs in an AWT


component, this method is invoked. The event
object contains further information about the
event that occurred.

Example: Using ActionEvent and ActionListener


import java.awt.*;
import java.awt.event.*;

class ActionEventDemo extends Frame implements ActionListener


{
Button b;
public ActionEventDemo()
{
b=new Button(Maximize/Restore);
add(b);
b.addActionListener(this);

// Set the frame properties


setTitle(Button with ActionListener Demo);
setSize(300,200);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
setVisible(true);

}
@Override
public void actionPerformed(ActionEvent ae){
if(this.getExtendedState()==Frame.NORMAL)
setExtendedState(Frame.MAXIMIZED_BOTH);
else if(this.getExtendedState()==Frame.MAXIMIZED_BOTH)
setExtendedState(Frame.NORMAL);
}
public static void main(String args[])
{
new ActionEventDemo();
}
}
Output

Mouse Event and MouseListener Interface


A MouseEvent is fired to all its registered listeners, when you press, release, or click
(press followed by release) a mouse-button (left or right button) at the source object; or
position the mouse-pointer at (enter) and away (exit) from the source object.
Methods of MouseEvent Class
MouseEvent
Method

Description

getClickCount()

Returns the number of times the mouse was


clicked (use to determine if a double-click occurred
so can have different responses to single and
double clicks)

getPoint()

Returns a Point object. Point is an AWT class


that represents the x and y coordinates. The point is
where the event occurred the x and y values are
relative to the (0,0) position of the component in
which the event occurred. In this case, the
component is the applet, so x and y are relative to
the top left corner of the applet.

getX()

Returns the x coordinate of the point at which


the event occurred.

getY()

Returns the y coordinate of the point at which


the event occurred.

A MouseEvent listener must implement the MouseListener interface, which declares


the following five abstract methods:
MouseListener
Method
void

Description

Invoked when the mouse button is pressed

mousePressed
(MouseEvent
event)

down use if you want to respond before a mouse


click is completed

void
mouseReleased
(MouseEvent
event)

Invoked when the mouse button is released


(unpressed)

void

Invoked when the mouse enters the

mouseEntered
(MouseEvent
event)

component in this case, the component is the


applet itself

void
mouseExited
(MouseEvent

Invoked when the mouse exits the component

event)
void
mouseClicked
(MouseEvent
event)

Invoked when the mouse button is pressed and


then released use if it does not matter when the
button is pressed/released it only matters that a
click occurred.

Example: Using MouseEvent and MouseListener


import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MouseEventDemo extends Frame implements MouseListener {
private TextField tx; // to display mouse-click-x
private TextField ty; // to display mouse-click-y
public MouseEventDemo() {
setLayout(new FlowLayout());
add(new Label(X Co-Ordinate: ));
tx = new TextField(10);
tx.setEditable(false);
add(tx);
add(new Label(Y Co-Ordinate: ));
ty = new TextField(10);
ty.setEditable(false); // read-only

add(ty); // super frame adds component


addMouseListener(this);
// super frame fires the MouseEvent so adds this object as MouseEvent listener
setTitle(MouseEvent Demo);
setSize(350, 100);
setVisible(true);
}
public static void main(String[] args) {
new MouseEventDemo();
}
// MouseEvent handlers
@Override
public void mouseClicked(MouseEvent e) {
tx.setText(e.getX() + );
ty.setText(e.getY() + );
}
@Override
public void mousePressed(MouseEvent e) { }
@Override
public void mouseReleased(MouseEvent e) { }
@Override
public void mouseEntered(MouseEvent e) { }
@Override
public void mouseExited(MouseEvent e) { }
}
Output:

In this example, we setup a GUI with 4 components (two Labels and two noneditable TextFields), inside a top-level container Frame, arranged in FlowLayout.
To demonstrate the MouseEvent:
1. We use Frame as the source object.
2. The Frame fires a MouseEvent to its entire MouseEvent listener when you
click/press/release a mouse-button or enter/exit with the mouse-pointer.
3. We select this object as the MouseEvent listener (for simplicity).
4. We register this object as the MouseEvent listener to super Frame (source) via
the method addMouseListener(this).
5. The listener (this class) is required to implement the MouseListener interface,
which declares 5 abstract methods. We override the mouseClicked() to display
the (x, y) co-ordinates of the mouse click on the two displayed TextFields.
MouseEvent and MouseMotionListener Interface
A MouseEvent is also fired when you moved and dragged the mouse pointer at the
source object. But you need to use MouseMotionListener to handle the mouse-move and
mouse-drag. TheMouseMotionListener interface declares the following two abstract
methods:
MouseMotionListener
Method

Description

void
mouseMoved
Invoked when the mouse is moved but no
(MouseEvent event)
buttons on the mouse have been pressed
void
mouseDragged
Invoked when the mouse has been moved
(MouseEvent event)
while a button is pressed (i.e. click and drag of

the mouse)
Example: Using MouseEvent and MouseListener
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class MouseMotionDemo extends Frame
implements MouseListener, MouseMotionListener {
// This class acts as MouseListener and MouseMotionListener
// To display the (x, y) coordinates of the mouse-clicked
private TextField tx;
private TextField ty;
// To display the (x, y) coordinates of the current mouse position
private TextField xpos;
private TextField ypos;
public MouseMotionDemo() {
setLayout(new FlowLayout());
add(new Label(X Co-Ordinate: ));
tx = new TextField(10);
tx.setEditable(false);
add(tx);
add(new Label(Y Co-Ordinate: ));
ty = new TextField(10);
ty.setEditable(false);
add(ty);
add(new Label(X Position: ));

xpos = new TextField(10);


xpos.setEditable(false);
add(xpos);
add(new Label(Y Position: ));
ypos = new TextField(10);
ypos.setEditable(false);
add(ypos);
addMouseListener(this);
addMouseMotionListener(this);
// super frame fires MouseEvent to all its registered MouseListener and
MouseMotionListener
// super frame adds this object as MouseListener and MouseMotionListener
setTitle(MouseMotion Demo);
setSize(400, 120);
setVisible(true);
}

public static void main(String[] args) {
new MouseMotionDemo();
}
/** MouseListener handlers */
// Called back when a mouse-button has been clicked
@Override
public void mouseClicked(MouseEvent e) {
tx.setText(e.getX() + );
ty.setText(e.getY() + );
}

// Not Used, but need to provide an empty body for compilation


@Override
public void mousePressed(MouseEvent e) { }
@Override
public void mouseReleased(MouseEvent e) { }
@Override
public void mouseEntered(MouseEvent e) { }
@Override
public void mouseExited(MouseEvent e) { }
/** MouseMotionEvent handlers */
// Called back when the mouse-pointer has been moved
@Override
public void mouseMoved(MouseEvent e) {
xpos.setText(e.getX() + );
ypos.setText(e.getY() + );
}
// Not Used, but need to provide an empty body for compilation
@Override
public void mouseDragged(MouseEvent e) { }
}
Output:

In this example:

The MouseMotionListener (this class) needs to implement 2 abstract


methods:
mouseMoved()
and
mouseDragged()
declared
in
the MouseMotionListener interface.
We override the mouseMoved() to display the (x, y) position of the mouse pointer.
We ignore the MouseDragged() handler by providing an empty body for
compilation.
KeyEvent and KeyListener Interface
A KeyEvent is fired (to all its registered KeyListeners) when you pressed, released,
and typed (pressed followed by released) a key on the source object. A KeyEvent listener
must implement KeyListenerinterface, which declares three abstract methods:
Method
public
keyTyped(KeyEvent e)

Description
void

Invoked when a key has been typed (pressed and


released).

public
void
keyPressed(KeyEvent e)
public

void

Invoked when a key has been pressed

Invoked when a key has been released.

keyReleased(KeyEvent e)
Example: Using KeyEvent and KeyListener
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyEventDemo extends Frame implements KeyListener {
// This class acts as KeyEvent Listener
private TextField Input;
private TextArea Display;
public KeyEventDemo() {
setLayout(new FlowLayout());

add(new Label(Enter Text: ));


Input = new TextField(10);
add(Input);
Display = new TextArea(5, 40);
add(Display);
Input.addKeyListener(this);
// Input TextField fires KeyEvent to its registered KeyListeners
// Input adds this object as a KeyEvent listener
setTitle(KeyEvent Demo);
setSize(400, 200);
setVisible(true);
}
public static void main(String[] args) {
new KeyEventDemo();
}
// Called back when a key has been typed (pressed and released)
@Override
public void keyTyped(KeyEvent e) {
Display.append(You have typed + e.getKeyChar() + \n);
}
@Override
public void keyPressed(KeyEvent e) { }
@Override
public void keyReleased(KeyEvent e) { }
}
Output:

In this example:
We use the Input (TextField) as the source object.
The source fires a KeyEvent when you press/release/type a key to all
its KeyEvent listener(s).
We select this object as the KeyEvent listener.
We register this object as the KeyEvent listener to the source TextField via
method Input.addKeyListener(this).
The KeyEvent listener (this class) needs to implement
the
KeyListener
interface,
which
declares
3
abstract
methods: keyTyped(), keyPressed(), keyReleased().
We override the keyTyped() to display key typed on the display TextArea. We
ignore the keyPressed() and keyReleased().
Window Event and Window Listener Interface
This is an interface in the java.awt.event package that specify the methods for
controlling a particular window. It has the following method specifications:
Method

Purpose

windowActivated(WindowEvent

Invoked when a window is activated.

windowClosed(WindowEvent e)

Invoked when a window has been closed.

windowClosing(WindowEvent e)

Invoked when a window is in the process of


being closed.

e)

windowDeactivated(WindowEvent

Invoked when a window is de-activated.

windowDeiconified(WindowEvent

Invoked when a window is de-iconified.

windowIconified(WindowEvent e)

Invoked when a window is iconified.

windowOpened(WindowEvent e)

Invoked when a window has been opened.

e)

e)

Example: Using WindowEvent and WindowListener

import java.awt.*;
import java.awt.event.*;
class WindowEventDemo extends Frame
{
public WindowEventDemo()
{
// Set the frame properties
setTitle(Button with ActionListener Demo);
setSize(400,400);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
setVisible(true);
// Add window listener
addWindowListener(new WindowListener(){
public void windowOpened(WindowEvent we)
{
System.out.println(Window Opened);

}
public void windowClosing(WindowEvent we)
{
System.out.println(Window Closing);
System.exit(0);
}
public void windowClosed(WindowEvent we)
{
// Will not be printed
System.out.println(Window Closed);
}
public void windowIconified(WindowEvent we)
{
setTitle(Iconified);
}
public void windowDeiconified(WindowEvent we)
{
setTitle(Deiconified);
}
public void windowActivated(WindowEvent we)
{
System.out.println(Window Activated);
}
public void windowDeactivated(WindowEvent we)
{
System.out.println(Window Deactivated);
}

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

GUI with Swing


Java Foundation Classes
Java Foundation Classes (JFC), allows developers to build full-featured enterpriseready applications. So, JFC is set of APIs for building the java GUI components.
JFC is composed of five APIs: AWT, Java 2D, Accessibility, Drag and Drop, and
Swing.
Swing
Swing is a new feature provided by the JFC 1.1. Swing extends AWT by supplying
many more types of GUI components, providing 100% pure Java implementations of
these components, and gives the capability to change the appearance and behavior of these
components on different platforms. The Swing components are 100% pure Java. This
means that they dont depend on the native window implementation to support them.
Swing components are available and consistent across all platforms. Swing components
do not use AWT components. In fact, all the traditional AWT components are reimplemented as Swing components.

Swing API is set of extensible GUI Components to ease developers life to create
JAVA based Front End/ GUI Applications. It is build upon top of AWT API and acts as
replacement of AWT API as it has almost every control corresponding to AWT controls.
Swing component follows a Model-View-Controller architecture to fulfill the following
criterias.
A single API is to be sufficient to support multiple look and feels.
API is to model driven so that highest level API is not required to have the
data.
API is to use the Java Bean model so that Builder Tools and IDE can provide
better services to the developers to use it.
Swing features
Light Weight - Swing component are independent of native Operating
Systems API as Swing API controls are rendered mostly using pure JAVA code
instead of underlying operating system calls.
Rich controls - Swing provides a rich set of advanced controls like Tree,
TabbedPane, slider, colorpicker, table controls
Highly Customizable - Swing controls can be customized in very easy way as
visual apperance is independent of internal representation.
Pluggable look-and-feel- SWING based GUI Application look and feel can be
changed at run time based on available values.
Swing Package Overview
javax.swing

javax.swing.border

The border package declares the Border interface


and classes, which define specific border rendering
styles.

javax.swing.colorchooser

The high level swing package primarily consists of


components, adapters, default component models, and
interfaces for all the delegates and models.

The colorchooser package contains support classes


for the color chooser component.

javax.swing.event
.

The event package is for the Swing-specific event


types and listeners. In addition to the java.awt.event
types, Swing components can generate their own event
types.

javax.swing.filechooser

The filechooser package contains support classes for


the file chooser component

javax.swing.plaf.*

The pluggable look-and-feel (PLAF) packages


contain the User Interface (UI) classes (delegates)
which implement the different look-and-feel aspects for
Swing components. There are also PLAF packages
under the javax.swing.plaf hierarchy.

javax.swing.table

The table package contains the support interfaces


and classes the Swing table component.

javax.swing.text

The text package contains the support classes for the


Swing document framework

.
javax.swing.text.html.*

The text.html package contains the support classes


for an HTML version 3.2 renderer and parser.

javax.swing.text.rtf

The text.rtf package contains the support classes for


a basic Rich Text Format (RTF) renderer.

javax.swing.tree

The tree package contains the interfaces and classes


which support the Swing tree component.

javax.swing.undo
.
javax.accessibility

The undo package provides the support classes for


implementing undo/redo capabilities in a GUI

The JFC Accessibility package is included with the

Swing classes.
Swing Controls
Every user interface considers the following three main aspects:
UI elements: Core visual elements user interacts with.
Layouts: They define how UI elements should be organized on the screen and
provide a final look and feel to the GUI (Graphical User Interface).
Behavior: These are events which occur when the user interacts with UI
elements.
The Swing set includes
JButton

JDesktopPane

JInternalFrame

JMenuIte

JCheckbox

JDialog

JLabel

JOptionP

JCheckboxMenuItem

JDirectoryPane

JLayeredPane

JPanel

JColorChooser

JEditorPane

JList

JPasswor

JComboBox

JFileChooser

JMenu

JPopupM

JDesktopIcon

JFrame

JMenuBar

JProgress

JRadioButton

JSlider

JTextPane

JWindow

JRadioButtonMenuItem

JSplitPane

JToggleButton

JRootPane

JTabbedPane

JToolBar

JScrollBar

JTable

JToolTip

JScrollPane

JTextArea

JTree

JSeparator

JTextField

JViewport

Components Hierarchy

Jcomponent
Swing components are implemented as subclasses of the JComponent class, which
inherits from the Container class. Swing components inherit the following functionality
from JComponent:
Tool Tips -By specifying a string with the setToolTipText( ) method, you can
provide help to users of a component. When the cursor pauses over the
component, the specified string is displayed in small window that appears near
the component.
Look and Feel -Subject to the security restrictions, you can choose the look and
feel used by all Swing components by invoking the
UIManager.setLookAndFeel( ) method.
Borders -Using the setBorder() method, you can specify the border that a
component displays around its edges.
JFrame
The JFrame class is an extension to the AWT Frame class. An instance of the JFrame
class is a heavyweight component. It creates a top-level window that can be positioned
and sized independently of other windows. The JFrame instance is managed by the system
window manager.
To create an instance of a JFrame class, you can write:
JFrame frame=new JFrame (My Frame);
frame.setSize(300,300); // to give size to a frame

frame.setVisible(true); // to make frame visible


It contains the default Java icon on the far left of the titlebar, title in the center, the
minimize and maximize buttons, as well as a close button to the far right of the titlebar,
The icon can be changed to any image by using the setIconImage method. The current
image can be queried with the getIconImage method.
Using JFrame, you can to add the child to the JFrames contentPane as:
frame.getContentpane().add(child);
Note: Content Pane is a layer on some of the swing components eg. JFrame and
Japplet and acts like a container for other components, when it is necessary to have a
different look and feel for the same components.
JApplet
JApplet is a java swing public class designed for developers usually written in Java.
JApplet is generally in the form of Java bytecode that runs with the help of a Java virtual
machine (JVM) or Applet viewer from Sun Microsystems. It was first introduced in 1995.
JApplet can also be written in other programming languages and can later be compiled to
Java byte code.
Your program should import javax.applet.JApplet and java.awt.*.
Example: Using JApplet
import javax.swing.JApplet;
import java.awt.*;
/*<applet code= JAppletDemo.class width=200 height=150></applet>*/

public class JAppletDemo extends JApplet


{
final int radius = 25;

public void paint ( Graphics gr )


{

gr.setColor( Color.black );
gr.fillRect( 0, 0, 150, 150 );
}
}
Output:

JFrame
JFrame is the Swing equivalent of AWT Frame. It adds double buffering to avoid
flickering during drawing.
It has a slightly different interface to geometry management - things are added to a
contentPane. It can hold a JMenuBar.
Example: Using JFrame
import javax.swing.*;
public class JFrameDemo extends JFrame {
public static void main(String argv[])
{
new JFrameDemo();
}
JFrameDemo() {
JLabel hello = new JLabel(Hello World);
getContentPane().add(hello, Center);

setSize(200, 200);
setTitle(JFrame Demo);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setVisible(true);
}
}
Output:

JLabel
A JLabel is a single line label similar to java.awt.Label. Additional functionality that a
JLabel has the ability to:
Add an Icon
Set the vertical and horizontal position of text relative to the Icon
Set the relative position of contents within component
Constructor:
JLabel(String text, int horizontalAlignment): Creates a JLabel instance with
the specified text and horizontal alignment.
Example: Using JLabel with Frame Container
import javax.swing.*;
import java.awt.*;
public class JLabelDemo extends JFrame {
public JLabelDemo(String title ) {
super( title );

setLayout(new GridLayout(3, 1));


// Create and add a JLabel
JLabel plainLabel = new JLabel(Plain Small Label);
add(plainLabel);
// Create a 2nd JLabel
JLabel fancyLabel = new JLabel(Fancy Big Label);
// Instantiate a Font object to use for the label
Font fancyFont = new Font(Serif, Font.BOLD | Font.ITALIC, 32);
// Associate the font with the label
fancyLabel.setFont(fancyFont);
// Create an Icon
Icon tigerIcon = new ImageIcon(Plus.gif);
// Place the Icon in the label
fancyLabel.setIcon(tigerIcon);
// Align the text to the right of the Icon
fancyLabel.setHorizontalAlignment(JLabel.RIGHT);
// Add to panel
add(fancyLabel);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

public static void main ( String[] args )
{
JLabelDemo test = new JLabelDemo( JLabel Demo ) ;
test.setSize ( 300, 100 );
test.setVisible( true );
}

}
Output

Example 2: Using JLabel with Applet Container


import javax.swing.*;
import java.awt.*;
/*<applet code= JLabelDemo2.class width=200 height=150></applet>*/
public class JLabelDemo2 extends JApplet {
public JLabelDemo2( ) {
setLayout(new GridLayout(3, 1));
// Create and add a JLabel
JLabel plainLabel = new JLabel(Plain Small Label);
add(plainLabel);
// Create a 2nd JLabel
JLabel fancyLabel = new JLabel(Fancy Big Label);
// Instantiate a Font object to use for the label
Font fancyFont = new Font(Serif, Font.BOLD | Font.ITALIC, 32);
// Associate the font with the label
fancyLabel.setFont(fancyFont);
// Create an Icon
Icon tigerIcon = new ImageIcon(Plus.gif);
// Place the Icon in the label
fancyLabel.setIcon(tigerIcon);
// Align the text to the right of the Icon

fancyLabel.setHorizontalAlignment(JLabel.RIGHT);
// Add to JApplet
add(fancyLabel);
}
}
Output

JButton
A JButton can be used in a GUI just like a java.awt.Button. It behaves like an AWT
1.1 Button, notifying ActionListener list elements when pushed.
JButtons can have an image and/or text label with controllable placement
Constructor:
JButton(): creates a button with no text and icon.
JButton(String s): creates a button with the specified text.
JButton(Icon i): creates a button with the specified icon object.
Example: Using JButton

import javax.swing.*;
import java.awt.*;
public class JButtonDemo extends JFrame {
public JButtonDemo(String title) {
super(title);
setLayout(new GridLayout(3, 2));

Icon plus = new ImageIcon(plus.gif);


JButton b1 = new JButton(ADD, plus);
JButton b2 = new JButton(OK);
add(b1);
add(b2);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
public static void main ( String[] args )
{
JButtonDemo test = new JButtonDemo( JButton Demo ) ;
test.setSize ( 300, 100 );
test.setVisible( true );
}
}
Output:

JTextField
The class JTextField is a component which allows the editing of a single line of text.
JTextField(String text, int columns): Constructs a new TextField initialized
with the specified text and columns.
Example: Using JTextField
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingTextDemo extends JFrame {

public SwingTextDemo(String title){


super(title);
setSize(400,400);
setLayout(new GridLayout(3, 1));
JTextField userText = new JTextField(Hello, 6);
add(userText);
setVisible(true);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
public static void main(String[] args){
SwingTextDemo ob = new SwingTextDemo(JText Field Demo);
}
}
Output:

Example 2: Using JTextField


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextFieldExample {
public static void main(String[] args) {

JFrame f = new JFrame(Text Field Examples);

f.getContentPane().setLayout(new FlowLayout());
f.getContentPane().add(new JTextField(Hello));
f.getContentPane().add(new JTextField(How r U?, 8));
JTextField t = new JTextField(8);
t.setHorizontalAlignment(JTextField.RIGHT);
t.setText(Name Please!);
f.getContentPane().add(t);
t = new JTextField(, 15);
t.setHorizontalAlignment(JTextField.CENTER);
f.getContentPane().
add(t);
f.pack();
f.setVisible(true);
}
}
Output:

JCheckBox
A JCheckBox is similar to an AWT Checkbox that is not in a CheckboxGroup. The
class JCheckBox is an implementation of a check box - an item that can be selected or
deselected, and which displays its state to the user.
JCheckBox(String text, Icon icon, boolean selected) : Creates a check box
with text and icon, and specifies whether or not it is initially selected.
Example: Using JCheckbox
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
/*<applet code= CheckboxDemo.class width=200 height=150></applet>*/
public class CheckboxDemo extends JApplet {

Icon unchecked = new ToggleIcon (false);


Icon checked = new ToggleIcon (true);

public CheckboxDemo () {

setLayout(new GridLayout(3, 1));


// Create checkbox with its state and initialized to true
JLabel Hobby=new JLabel(Select your hobbies:);
JCheckBox cb1 = new JCheckBox(Singing, true);
cb1.setIcon(unchecked);
cb1.setSelectedIcon(checked);
// Create checkbox with its state and initialized to false
JCheckBox cb2 = new JCheckBox(Reading, false);
cb2.setIcon(unchecked);
cb2.setSelectedIcon(checked);
add(Hobby);
add(cb1);
add(cb2);
}
public static void main ( String[] args )
{
CheckboxDemo ob = new CheckboxDemo () ;
ob.setSize( 300, 100 );

ob.setVisible( true );
}
}
class ToggleIcon implements Icon {
boolean state;
public ToggleIcon (boolean s) {
state = s;
}
public void paintIcon (Component c, Graphics g, int x, int y) {
int width = getIconWidth();
int height = getIconHeight();
g.setColor (Color.black);
if (state)
g.fillRect (x, y, width, height);
else
g.drawRect (x, y, width, height);
}
public int getIconWidth() {
return 10;
}
public int getIconHeight() {
return 10;
}
}

Output:

JRadioButton class
The JRadioButton class is used to create a radio button. It is used to choose one option
from multiple options. It is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.
Constructors:
JRadioButton(): creates an unselected radio button with no text.
JRadioButton(String s): creates an unselected radio button with specified
text.
JRadioButton(String s, boolean selected): creates a radio button with the
specified text and selected status.
Example: Using JRadioButton
import javax.swing.*;
import java.awt.*;
public class RadioButtonDemo extends JFrame {

public RadioButtonDemo (String title) {


super(title);
// Set the layout to a GridLayout
setLayout(new GridLayout(4,1));

// Declare a radio button


JRadioButton radioButton;

// Instantiate a ButtonGroup
ButtonGroup rbg = new ButtonGroup();

// Create a label for the group


JLabel label = new JLabel(Select Gender: );
label.setFont(new Font(SansSerif, Font.BOLD, 14));
add(label);

// Add a new radio button to the frame


radioButton = new JRadioButton(Male);
add (radioButton);
rbg.add (radioButton);
// Set this radio button to be the default
radioButton.setSelected(true);

// Set up one more radio buttons


radioButton = new JRadioButton(Female);
add (radioButton);
rbg.add (radioButton);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main ( String[] args )
{
RadioButtonDemo ob = new RadioButtonDemo (JRadioButton Demo) ;
ob.setSize( 300, 100 );
ob.setVisible( true );
}

}
Output:

JComboBox
The JComboBox class is used to create the combobox (drop-down list). At a time only
one item can be selected from the item list. The JComboBox offers an editable option. You
can offer a JComboBox with a list of default choices, but still permit the entry of another
value. The nicest part about this control is that when the user presses the key for the first
letter of an entry, it changes the highlighted selection.
Example: Using JComboBox
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ComboBoxDemo extends JFrame {
String Seasons[] = {Winter, Summer, Monsoon};
public ComboBoxDemo(String title) {
super(title);
setLayout(new GridLayout(3, 2));
JLabel fs=new JLabel(Select your favorite season?);
JComboBox s = new JComboBox();
for (int i=0;i<Seasons.length;i++) {
s.addItem (Seasons[i]);
}
s.setEditable(false);

s.setSelectedItem(Monsoon);
s.setMaximumRowCount(4);
add(fs);
add(s);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main ( String[] args )
{
ComboBoxDemo ob = new ComboBoxDemo(JComboBox Demo) ;
ob.setSize( 300, 100 );
ob.setVisible( true );
}
}
Output:

Menus
The menuing model used in Swing is nearly identical to that used in AWT. There are
three key exceptions:
The menu classes (JMenuItem, JCheckBoxMenuItem, JMenu, and JMenuBar)
are all subclasses of JComponent. They are not off in their own independent
class hierarchy. As a result of this, you can place a JMenuBar within any
Container, including Applet. [The JApplet class has a setJMenuBar() method to
add a JMenuBar.]
There is a new menu class, JRadioButtonMenuItem, to provide a set of
mutually exclusive checkboxes on a menu, when placed within a ButtonGroup.

Also, you can associate an Icon object with any JMenuItem.


Example: Using JMenu
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JMenuDemo extends JFrame implements ActionListener {

public void actionPerformed (ActionEvent e) {


System.out.println (e.getActionCommand());
}

public JMenuDemo() {
super (JMenu Demo);

JMenuBar jmb = new JMenuBar();


JMenu file = new JMenu (File);
JMenuItem item;
file.add (item = new JMenuItem (New));
item.addActionListener (this);
file.add (item = new JMenuItem (Open));
item.addActionListener (this);
file.addSeparator();
file.add (item = new JMenuItem (Close));
item.addActionListener (this);
jmb.add (file);

JMenu edit = new JMenu (Edit);

edit.add (item = new JMenuItem (Copy));


item.addActionListener (this);
Icon plus = new ImageIcon(plus.gif);
edit.add (item = new JMenuItem (Paste, plus));
item.setHorizontalTextPosition (JMenuItem.LEFT);
item.addActionListener (this);
//edit.add (item = new JMenuItem (Woods, plus));
//item.addActionListener (this);
jmb.add (edit);

JMenu choice = new JMenu (Colors);


JCheckBoxMenuItem check = new JCheckBoxMenuItem (Toggle Screen);
check.addActionListener (this);
choice.add (check);
ButtonGroup rbg = new ButtonGroup();
JRadioButtonMenuItem rad = new JRadioButtonMenuItem (Colorful);
choice.add (rad);
rbg.add (rad);
rad.addActionListener (this);
rad = new JRadioButtonMenuItem (Black & White);
choice.add (rad);
rbg.add (rad);
rad.addActionListener (this);

jmb.add (choice);

setJMenuBar (jmb);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main ( String[] args )
{
JMenuDemo ob = new JMenuDemo() ;
ob.setSize( 300, 100 );
ob.setVisible( true );
}
}
Output:
First Menu

Second Menu

Third Menu

Short Questions and Answers


Explain the need of Layout manager.


Layout manager is used for laying the components that are added to the
container.
The sizes and the positions of the components are set by using layout managers
The rules for arranging components are different for each layout mangers.
The default layout manger is FlowLayout.
Commonly used layout mangers are BorderLayout and GridLayout.
FlowLayout manager arranges the components in rows
BorderLayout manager arranges the components by dividing the container into
3-5 strips
GridLayout manager arranges the components in rectangular grid by having the
same size for the components. A cell is used to place a component
Explain different layout manager in Java.

A layout manager organizes the objects in a container. Different layouts are used to
organize or to arrange objects
Border Layout:
It has five areas for holding components: north, east, west, south and center
When there are only 5 elements to be placed, border layout is the right choice
Flow Layout:
Default layout manager.
It lays out the components from left to right
Card Layout:
Different components at different times are laid out
Controlled by a combo box, determining which panel the Card layout displays
Grid Layout:
A group of components are laid out I equal size and displays them in certain
rows and columns
What is the difference between GridLayout & GridBagLayout manager?
GridLayout class lays all components in a rectangular grid like structure of container.
The container is divided into an equal sized rectangles and each component is placed
inside a rectangle.
The GridBagLayout class is a flexible layout manager that aligns components
vertically and horizontally, without requiring that the components be of the same size.
Each GridBagLayout object maintains a dynamic, rectangular grid of cells, with each
component occupying one or more cells, called its display area.
Each component managed by a GridBagLayout is associated with an instance of
GridBagConstraints. The constraints object specifies where a components display area
should be located on the grid and how the component should be positioned within its
display area. In addition to its constraints object, the GridBagLayout also considers each
components minimum and preferred sizes in order to determine a components size.

What is Swing? Explain the need of Swing.


Swing is a part the Java Foundation Classes

An extension library to AWT


GUI programming is simple and elegant
Describe the Need of Swing
The uniform look and feel across platforms is an advantage
Compatible for both standalone/GUI applications,Applets and Servlets
Employs model/view design pattern.
Has ability to replace the objects on-the-fly
Light weight components
Has the pluggable look and feel
Write some important features of Swing.
Platform independent : Swing is platform independent in both expression and
implementation
Extensible : Allows plugging of custom implementations of specified
framework interfaces.Users can provide custom component implementations
by overriding the default implementations
Customizable: The swing components are customizable by writing customize
code for standard swing components by assigning specific Borders, Colors etc.
Configurable: Allows changes in its settings. For example, an applications
look and feel can be changed at runtime.
Every Swing component relies on the AWT container, as JComponent extends
the AWTs Container. So that Swing can be plugged into the host OSs GUI
management framework.
Describe Java Swing class hierarchy.
The Swing class has the following hierarchy
Components The basic building blocks
Containers - All top level containers are JFrame, JDialog, Applet
JFrame A window with title, border and title
Dialog Boxes Has Modality and more limited than frames
Types of Dialog Boxes:
JOptionPane to create custom dialogs
ProgressMonitor Shows the progress of a operation
JFileChooser Allows to select a file
JDialog To make a custom dialogs

JComponent has subclasses to create Textboxes,labels,lists,menubars etc.


Window is the super class of JFrame and JDialog clases
JToggleButton has sub classes JcheckButton, JRadioButton

Exercise
1. Write short note:- Awt packge
2. Explain AWT? Write steps for creating list, checkbox, label, Text field and Text
area.
3. Lists containers and suggest where we have to use which container.
4. Explain layout manager in brief.
5. Explain panel & canvas in java.
6. Give difference: Check box & Radio
7. With respect to AWT package explain flow Layout with example.
8. Write a difference between Text field and Text area.
9. With respect to awt package explain Grid Layout with example.
10. Differentiate Between following:
Border layout & flow layout
Check box & radio button
1. Describe mouse listener and mouse events using proper example.
2. What is swing? What is difference between Swing and AWT?
3. Explain any one swing component using example.
Programming Exercise:
1. Develop an applet that receive two numeric values as input from the user and
display the addition & multiplication of these two nos.
2. Develop an applet that receives three numeric values from the user and then
displays the largest of the three on the screen. Write a HTML page and test the
applet.
3. Write a program to demonstrate background color of an applet. Take four radio
buttons of different colors to select a color.

4. Develop an applet that receives three numeric values as input from the user
And then display the largest of three on the screen.
5. Develope an applet that receive one string and display in reverse fashion (e.g.
Hellow should be display Wolleh). Write HTML page and test the applet.
6. Write an applet this display a string. Write necessary applet tag for
it.
7. Devlope an applet that receives two numbers from the user to perform +, -, *, /
operation write the HTML code and test the applet.

Unit III Java Data Base Client/ Server


Database is organized collection of data. Database Management System provides
mechanisms for storing, organizing, retrieving and modifying data. Relational DBMS is
popular standard. SQL is a language used to create, manipulate, examine, and manage
relational databases. SQL was standardized in 1992 so that a program could communicate
with most database systems without having to change the SQL commands.
Examples of RDBMS: MS SQL SERVER, ORACLE, MYSQL, MS-ACCESS etc
FIG: Database Connectivity Architecture

Java as a Database front end Database client/server


methodology
One of the most important design issues when developing a Java database application
is the overall system architecture; in particular, how many different components should be
deployed. Traditionally, this is characterized by how many tiers, or layers, the application
requires.
JDBC is a Java API for executing SQL statements. It is a considered as standard for
Java Database Connectivity. JDBC consists of a set of classes and interfaces written in
Java. Using JDBC, it is easy to send SQL statements to virtually any relational database.
The combination of Java and JDBC makes it possible for a programmer to write it once
and run it anywhere.

JDBC Architecture
The JDBC Architecture consists of two layers:
The JDBC API, which provides the application-to-JDBC Manager connection
The JDBC API uses a driver manager and database-specific drivers to
provide transparent connectivity to different databases.
The JDBC Driver API, which supports the JDBC Manager-to-Driver
Connection
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 different databases.

Two models for database access are supported by the JDBC API. They are the two-tier
model and the three-tier model. The last one is mentioned more generally as a multitier or
n-tier.
The two-tier model
In the two-tier model, a Java applet or application talks directly to the database. This
requires a JDBC driver that can communicate with the particular database management
system (DBMS) being accessed. SQL statements are delivered to the database, and the
results are sent back to the user.

This is referred to as a client/server configuration, in which the users machine is the

client and the machine housing the database is the server. The database may be located on
another machine to which the user is connected via a network.
The three-tier model
In the three-tier model, commands are sent to a middle tier of services, which then
send SQL statements to the database. The database processes the SQL statements and
sends the results back to the middle tier, which then sends them to the user.

This model makes it possible to maintain control over access and the kinds of updates
that can be made to corporate data. Another advantage of the middle tier model is that the
user can employ an easy-to-use higher-level API which is translated by the middle tier into
the appropriate low-level calls. The middle-tier architecture can provide performance
advantages.
Database vendors support JDBC through the JDBC driver interface or through the
ODBC connection. Each driver must provide implementations of java.sql.Connection,
java.sql.Statement, java.sql.PreparedStatement, java.sql.CallableStatement, and
java.sql.ResultSet. They must also implement the java.sql.Driver interface for use by the
generic java.sql.DriverManager interface.

Common JDBC Components


Java Database Connectivity (JDBC) defines how a java program can communicate
with a database. JDBC architecture consists of different layers and drivers which are
capable of working with any database. JDBC has following components:

JDBC API - The JDBC 4.0 APIs come in two packages: java.sql and javax.sql
and these packages contain all the APIs which provide programmatic access to
a relational database (like Oracle, SQL Server, MySQL, etc.) from Java.
Using JDBC API, frontend java applications can execute query and fetch data
from connected databases. JDBC API can also connect with multiple
applications with same database or same application with multiple Databases
which may be residing in different computers (distributed environment).
JDBC Driver Manager - JDBC Driver Manager Interface defines objects
which are used to connect java application with different JDBC Drivers. JDBC
Driver Manager manages the all the JDBC Drivers loaded in clients system.
JDBC Driver Manager loads the most appropriate driver among all the Drivers
for creating a connection. There are two ways of connecting to a database
One, by using the DriverManager class (the traditional way of
establishing connection to a database from Java) and
Second, by using a Data Source. This method requires javax.naming and
javax.sql packages to find a DataSource object registered with JNDI, and
to establish connection using that DataSource object. This is the
recommended approach of establishing connection to a database from
Java.
JDBC Test Suite JDBC Test Suite is used to check compatibility of a JDBC
driver with J2EE platform. It also check whether a Driver follow all the
standard and requirements of J2EE Environment. This suite do contain almost
all the standard test cases required to test the many JDBC features. You may
only need to add the application specific test cases.
JDBC-ODBC Bridge - as the name suggests this enables JDBC access via
ODBC drivers. Though this is normally used only for development and testing
purposes and not for production use. The JDBC Driver contact to the ODBC
Driver for connection to the database. The ODBC Driver is already installed or
come as default driver in windows. In Windows using this data source name
(DSN) you can connect JDBC to ODBC.
The JDBC API
JDBC API is a part of the Java platform that has included Java Standard Edition (Java
SE) and the Java Enterprise Edition (Java EE) in itself. The JDBC (Java Database

Connectivity) API defines interfaces and classes for writing database applications in Java
by making database connections. JDBC is a Java API for executing SQL statements.
Using JDBC you can send SQL, PL/SQL statements to almost any relational database.
JDBC is a Java API for executing SQL statements and supports basic SQL functionality. It
provides RDBMS access by allowing you to embed SQL inside Java code. With Java and
the JDBC API, it is possible to publish a web page containing an applet that uses
information obtained from a remote database. Applets embedded in Web pages can
contain downloadable JDBC code to enable remote database access.
The JDBC API can also interact with multiple data sources in a distributed
environment. Due to JDBC API technology, user can also access other tabular data
sources like spreadsheets or flat files even in the heterogeneous environment.
The JDBC API has four main interfaces. The latest version of JDBC 4.0 application
programming interface is divided into two packages
java.sql
javax.sql.
Java SE and Java EE platforms are included in both the packages.
java.sql package
This package includes classes and interface to perform almost all JDBC operation such
as creating and executing SQL Queries.
Important classes and interface of java.sql package
The mechanism to communicate with database servers exists as standard Java classes.
This ensures that the security features of Java remain and that JDBC code integrates
cleanly in Java code. The JDBC API is expressed through several abstract Java interf aces
that allow to link to any number of databases. The interfaces are:
java.sql.DriverManager: handles the loading and unloading of the appropriate
database drivers required to make the connection.
java.sql.Connection: exposes the database to the developer, representing the
connection as an accessible Java component.
java.sql.Statement: provides a container for executing SQL statements using a
connection.
java.sql.ResultSet: exposes the data that returns from the database server to the

Java application.
The JDBC API Components
The JDBC API provides the following interfaces and classes:
DriverManager: 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.
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
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.
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.
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.
SQLException: This class handles any errors that occur in a database
application.
The JDBC API uses a Driver Manager and database-specific drivers to provide
transparent connectivity to different databases.
The JDBC Driver Manager
The JDBC Driver Manager can connect Java applications to a JDBC driver. Driver
Manager is the backbone of the JDBC architecture. It is quite small and simple. The JDBC
driver manager is used to provide a means of managing the different types of JDBC
database driver running on an application.
The main responsibility of JDBC database driver is to load all the drivers found in
the system properly as well as to select the most appropriate driver from opening a

connection to a database. The Driver Manager also helps to select the most appropriate
driver from the previously loaded drivers when a new open database is connected.
JDBC Driver Manager functionality is available in following two Standard Extension
packages:
javax.naming and
javax.sql
The JDBC Test Suite
The function of JDBC driver test suite is to make ensure that the JDBC drivers will
run users program or not. The test suite of JDBC application program interface is very
useful for testing a driver based on JDBC technology during testing period. It ensures the
requirement of Java Platform Enterprise Edition (J2EE).
JDBC Drivers
JDBC Driver is a software component that enables java application to interact with the
database. JDBC drivers have a specific purpose and properties of its own. There are four
types of JDBC drivers available:
Once your database engine is installed and your database is all set up, you will
need a JDBC driver for that database engine.
The more commercial database engines like Oracle have commercial JDBC
drivers.
Most of them, however, allow you to have a free trial period for experimenting
with the driver.
Follow the install instructions for the driver you choose, and remember that
some JDBC drivers require to you install native code on client machines.
To help you understand what different drivers require, the following driver
categorization system id defined:
Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: All Java/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)

JDBC Drivers Overview


Tier

Two

Two

Driver
mechanism
JDBC-ODBC

Description

This driver converts JDBC calls to the


ODBC calls which actually interact with the
database. The client should have the ODBC
libraries for this driver. The JDBC-ODBC
Bridge is JDBC driver which implements
JDBC operations by translating them to ODBC
operations.

Native API This driver converts JDBC calls to database


Partly - Java driver specific calls. In order to use the driver the
client should have database libraries.

Three

JDBC - Net This driver passes the JDBC calls to proxy


Pure Java Drivers
server which communicates with the database.
This driver converts JDBC calls into DBMS
independent network protocol that is sent to the
middleware server. This will translate this
DBMS independent network protocol into

DBMS specific protocol, which is sent to a


particular database. The results are again
rooted back to middleware server and sent
back to client.
Two

Native protocol
The driver does not require anything and
- Pure Java Drivers directly calls the database. This driver is the
fastest among all the four drivers. This driver is
pure java driver. This driver is convert JDBC
commands.

Type-1 (JDBC-To-ODBC Bridge Driver)


These drivers use a bridging technology to access a database.
The JDBC-ODBC Bridge that comes with the JDK 1.1 is a good example of
this kind of driver.
It provides a gateway to the ODBC API.
Implementations of that API in turn do the actual database access.
Bridge solutions generally require software to be installed on client systems,
meaning that they are not good solutions for applications that do not allow
you to install software on the client.

Advantage
Easy to use
Allow easy connectivity to all database supported by the ODBC Driver.
Disadvantage

Slow execution time


Dependent on ODBC Driver.
Uses Java Native Interface (JNI) to make ODBC call.
Type-2 (Native API, part Java Driver)
The type 2 drivers are native API drivers.
This means that the driver contains Java code that calls native C or C++
methods provided by the individual database vendors that perform the
database access.
Again, this solution requires software on the client system.

Advantage
Faster as compared to Type-1 Driver
Contains additional features.
Disadvantage
Requires native library
Increased cost of Application
Type-3 (JDBC-Net Pure Java Drivers)
Type 3 drivers provide a client with a generic network API that is then
translated into database specific access at the server level.
In other words, the JDBC driver on the client uses sockets to call a
middleware application on the server that translates the client requests into
an API specific to the desired driver.
As it turns out, this kind of driver is extremely flexible since it requires no

code installed on the client and a single driver can actually provide access to
multiple databases.

Advantage
Does not require any native library to be installed.
Database Independency.
Provide facility to switch over from one database to another database.
Disadvantage
Slow due to increase number of network call.
Type-4 (Native Protocol Pure Java Driver)
This is Driver called Pure Java Driver because these drivers interact directly with
database. It does not require any native database library, which is why it is also known as
Thin Driver.

Advantage
Does not require any native library.
Does not require any Middleware server.
Better Performance than other driver.
Disadvantage
Slow due to increase number of network call.

JDBC Database Example


There are 5 steps to connect any java application with the database in java using
JDBC. They are as follows:
Register the driver class
Creating connection
Creating statement
Executing queries
Closing connection

1) Register the driver class


The forName() method of Class class is used to register the driver class. This method
is used to dynamically load the driver class. Syntax of forName() method
public static void forName(String className)throws ClassNotFoundException
Driver names and Database URLs for popular RDBMS are:
RDBMS

JDBC Driver Name

Database URL Format

MySQL

com.mysql.jdbc.Driver

jdbc:mysql://hostname/databasename

ORACLE

oracle.jdbc.driver.OracleDriver

jdbc:oracle:thin:@hostname:port:databa

DB2

com.ibm.db2.net.DB2Driver

jdbc:db2:hostname:portno/databasenam

Sybase

com.sybase.jdbc.SybDriver

jdbc:Sybase:Tds:hostname/databasenam

MS-

sun.jdbc.odbc.JdbcOdbcDriver

jdbc:odbc:databasename

ACCESS
Example to register the OracleDriver class
Class.forName(oracle.jdbc.driver.OracleDriver);
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection
with the database.
Syntax of getConnection() method
1) public static Connection getConnection(String url)throws SQLException

2) public static Connection getConnection(String url,String name,String password) throws SQ


Example to establish connection with the Oracle database

Connection c=DriverManager.getConnection(jdbc:oracle:thin:@localhost:1521:xe,system
3) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The
object of statement is responsible to execute queries with the database.
Syntax of createStatement() method
public Statement createStatement()throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries to the

database. This method returns the object of ResultSet that can be used to get all the
records of a table.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
ResultSet rs=stmt.executeQuery(select * from student);
while(rs.next()){
System.out.println(rs.getInt(1)+ +rs.getString(2));
}
5) Close the connection object
By closing connection object statement and ResultSet will be closed automatically.
The close() method of Connection interface is used to close the connection.
Syntax of close() method
public void close()throws SQLException
Example to close connection
con.close();
Connection Class
Methods
Statement createStatement()throws SQLException
Creates a Statement object for sending SQL statements to the
database. SQL statements without parameters are normally executed
using Statement objects.
If the same SQL statement is executed many times, it may be more
efficient to use a PreparedStatement object.
Statement createStatement(int resultSetType,int resultSetConcurrency)
throws SQLException
Creates a Statement object that will generate ResultSet objects with
the given type and concurrency.

This method is the same as the createStatement method above, but it


allows the default result set type and concurrency to be overridden.
Parameters:
resultSetType - a result set
ResultSet.TYPE_FORWARD_ONLY,

type;

one

ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.TYPE_SCROLL_SENSITIVE

of
or

resultSetConcurrency - a concurrency type; one of


ResultSet.CONCUR_READ_ONLY
or
ResultSet.CONCUR_UPDATABLE
PreparedStatement prepareStatement(String sql) throws SQLException
Creates a PreparedStatement object for sending parameterized SQL
statements to the database.
CallableStatement prepareCall(String sql)throws SQLException
Creates a CallableStatement object for calling database stored
procedures.
The CallableStatement object provides methods for setting up its IN
and OUT parameters, and methods for executing the call to a stored
procedure.
Statement Class
Methods
ResultSet executeQuery(String sql)
Executes the given SQL statement, which returns a single ResultSet
object.
int executeUpdate(String sql)
Executes the given SQL statement, which may be an INSERT,
UPDATE, or DELETE statement or an SQL statement that returns
nothing, such as an SQL DDL statement.
Creating New Database
Following steps are required to create a new Database using JDBC application:

Import the packages: Requires that you include the packages containing the
JDBC classes needed for database programming. Most often, using import
java.sql.* will suffice.
Register the JDBC driver: Requires that you initialize a driver so you can
open a communications channel with the database.
Open
a
connection:
Requires
using
the DriverManager.getConnection() method to create a Connection object,
which represents a physical connection with datbase server.
To create a new database, you need not to give any database name while preparing
database URL as mentioned in the below example.
Execute a query: Requires using an object of type Statement for building and
submitting an SQL statement to the database.
Clean up the environment: Requires explicitly closing all database resources
versus relying on the JVMs garbage collection.
Example: Creating new database in MySQL
Copy and past following example in JDBCExampleDB.java, compile and run as
follows:
//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = com.mysql.jdbc.Driver;
static final String DB_URL = jdbc:mysql://localhost/;

// Database credentials
static final String USER = root;
static final String PASS = ;

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName(com.mysql.jdbc.Driver);

//STEP 3: Open a connection


System.out.println(Connecting to database);
conn = DriverManager.getConnection(DB_URL, USER, PASS);

//STEP 4: Execute a query


System.out.println(Creating database);
stmt = conn.createStatement();

String sql = CREATE DATABASE STUDENTS;
stmt.executeUpdate(sql);
System.out.println(Database created successfully);
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{

if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println(Goodbye!);
}//end main
}//end JDBCExample
Now let us compile above example as follows:
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces following result:
C:\>java JDBCExample
Connecting to database
Creating database
Database created successfully
Goodbye!
C:\>
Connecting to MySQL Database using Thin Driver
To connect a Java application with MySQL database using Thin Driver. You need to
follow the following steps

1. Load Driver Class: The Driver Class for MySQL database is


com.mysql.jdbc.Driver and Class.forName(com.mysql.jdbc.Driver) method
is used to load the driver class for MySQL database.
2. Create Connection: For creating a connection you will need a Connection
URL. The Connection URL for MySQL is

You will also require Username and Password of your MySQL Database Server for
creating connection.
1. Loading jar file: To connect your java application with MySQL, you will also
need to load mysql-connector.jar file.
Download
the
latest
MySQL
JDBC
driver
from http://dev.mysql.com/downloads MySQL Connectors
Connector/J Connector/J 5.1.{XX} select Platform Independent
ZIP Archive (e.g., mysql-connector-java-5.1.{XX}.zip, where {XX} is the
latest release number).
UNZIP the download file into any temporary folder.
Copy the JAR file mysql-connector-java-5.1.{XX}-bin.jar to your
JDKs
Extension
Directory
at
<JAVA_HOME>\jre\lib\ext
(where <JAVA_HOME> is the JDK installed directory, e.g., c:\program
files\java\jdk1.7.0_{XX}\jre\lib\ext).
Set classpath variable to include the location of mysql-connector-java-5.1.
{XX}-bin.jar file.
Set classpath= C:\Program Files\Java\jre1.8.0_25\lib\ext\mysql-connector-java5.1.34-bin.jar;%classpath%;
Example: Using JDBC with MySQL
1) Creating a table in MySQL Using JDBC

import java.sql.*;

public class CreateTableDemo {


// JDBC driver name and database URL
static final String JDBC_DRIVER = com.mysql.jdbc.Driver;
static final String DB_URL = jdbc:mysql://localhost/students;

// Database credentials
static final String USER = root;
static final String PASS = ;

public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName(com.mysql.jdbc.Driver);

System.out.println(Connecting to database);
conn = DriverManager.getConnection(DB_URL, USER, PASS);

System.out.println(Creating table);
stmt = conn.createStatement();

String sql = CREATE TABLE STUDINFO(rollno int, name varchar(50));;

stmt.executeUpdate(sql);
System.out.println(Table created successfully);

}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2){
}// nothing we can do

try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try

System.out.println(Goodbye!);

}
}
Output
Connecting to database
Creating table
Table created successfully
Goodbye!

Process completed.
2) Inserting records into a table in MySQL Using JDBC
import java.sql.*;

public class InsertRecordDemo {


// JDBC driver name and database URL
static final String JDBC_DRIVER = com.mysql.jdbc.Driver;
static final String DB_URL = jdbc:mysql://localhost/students;

// Database credentials
static final String USER = root;
static final String PASS = ;

public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName(com.mysql.jdbc.Driver);

System.out.println(Connecting to database);
conn = DriverManager.getConnection(DB_URL, USER, PASS);

System.out.println(Inserting Records into table);


PreparedStatement pst=conn.prepareStatement(insert into studinfo values(?,?));
pst.setInt(1,101);
pst.setString(2,Jainik);
pst.executeUpdate();
pst.setInt(1,102);
pst.setString(2,Krinal);
pst.executeUpdate();

System.out.println(Records inserted successfully);


}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
finally{
//finally block used to close resources

try{
if(conn!=null)
conn.close();

}
catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try

System.out.println(Goodbye!);
}
}
Output:
Connecting to database
Inserting Records into table
Records inserted successfully
Goodbye!

Process completed.
3) Accessing record from Student table in Java application
import java.sql.*;

public class DisplayRecordDemo {


// JDBC driver name and database URL
static final String JDBC_DRIVER = com.mysql.jdbc.Driver;
static final String DB_URL = jdbc:mysql://localhost/students;

// Database credentials
static final String USER = root;
static final String PASS = ;


public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName(com.mysql.jdbc.Driver);

System.out.println(Connecting to database);
conn = DriverManager.getConnection(DB_URL, USER, PASS);

System.out.println(Displaying Records from table);


Statement s = conn.createStatement(); //creating statement

ResultSet rs = s.executeQuery(select * from studinfo); //executing statement


while(rs.next()){
System.out.println(rs.getInt(1)+ +rs.getString(2));
}

System.out.println(Records inserted successfully);


}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}

finally{
//finally block used to close resources

try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try

System.out.println(Goodbye!);
}
}
Output:
Connecting to database
Displaying Records from table
101 Jainik
102 Krinal
Goodbye!

Process completed.
Connecting to Access Database using Type-1 Driver
To connect a Java application with Access database using JDBC-ODBC Bridge(type1) Driver. You need to follow the following steps
Create DSN Name

Go to control panel

Go to Administrative tools

Select Data Source(ODBC)

Add new DSN name, select add

Select Access driver from the list, click on finish

Give a DSN name, click ok

Example: Using JDBC with MS Access


Assumed that you have created a student table with sid and name column name in
access database.
import java.sql.*;
class TestAccessDB
{
public static void main(String []args)
{
try{
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Connection con = DriverManager.getConnection(jdbc:odbc:Test, , );
Statement s=con.createStatement(); //creating statement

ResultSet rs=s.executeQuery(select * from student); //executing statement


while(rs.next()){
System.out.println(rs.getInt(1)+ +rs.getString(2));
}
con.close(); //closing connection

}catch(Exception e)
{
e.printStackTrace();
}
}
}
Connecting to Oracle Database using Thin Driver
To connect a Java application with Oracle database using Thin Driver. You need to
follow the following steps
1. Load Driver Class: The Driver Class for oracle database is
oracle.jdbc.driver.OracleDriver
and
Class.forName(oracle.jdbc.driver.OracleDriver) method is used to load the
driver class for Oracle database.
2. Create Connection: For creating a connection you will need a Connection
URL. The Connection URL for Oracle is

You will also require Username and Password of your Oracle Database Server for
creating connection.
1. Loading jar file: To connect your java application with Oracle, you will also
need to load ojdbc14.jar file. This file can be loaded into 2 ways.
1. Copy the jar file into C:\Program Files\Java\jre7\lib\ext folder.
or,
1. Set it into classpath.

NOTE: Here we are discussing about Oracle 10g as database. For other version of
Oracle you will be require to do some small changes in the Connection URL.

Current JDBC Drivers


JDBC 4.0 is new and advance specification of JDBC. It provides the following
advance features
Connection Management
Auto loading of Driver Interface.
Better exception handling
Support for large object
Annotation in SQL query.

Advantages Using JDBC


Can read any database if proper drivers are installed.
Creates XML structure of data from database automatically
No content conversion required
Query and Stored procedure supported.
Can be used for both Synchronus and Asynchronous processing.
Supports modules

Limitations Using JDBC


JDBC is not good if used in large projects. There is a big programming
overhead.
It is not at all good in the transaction management. Programmer must hardcode
the Transactions and concurrency code in the application.
JDBC needs database specifc queries.
Handling the JDBC connections and properly closing the connection is also a
big issue. Properly closing the connection is must.
JDBC cant maintain the database independent SQL statements. I.e in future if
there is needs to change the datbase because of maintainance problem then we
need to change all SQL statements according to the new database.
When multiple connections are created and closed it affects the performance.
We cant retrive each record as object. JDBC retrives it as scalar values only.
We know objects are more faster then scalar values.
ResultSet is not serializable in JDBC, but RowSet is serializable in JDBC. But
it is not supported for all drivers.

Exception Handling is one of the main drawbacks in JDBC. If exception is


raised when closing connection itself, then how many times we need to write
try-catch.

Security Considerations
There are two main JDBC scenarios to consider for security purposes:
In the case of Java applications, the Java code is trusted. We also consider
trusted applets in this category for security purposes.
In contrast, untrusted Java applets are not permitted access to local files and or
network connections to arbitrary hosts.
Securing JDBC with untrusted applets
JDBC should follow the standard applet security model. Specifically:
JDBC should assume that normal unsigned applets are untrustworthy
JDBC should not allow untrusted applets access to local database data
If a downloaded JDBC Driver registers itself with the JDBC DriverManager,
then JDBC should only use that driver to satisfy connection requests from code
which has been loaded from the same source as the driver.
An untrusted applet will normally only be allowed to open a database
connection back to the server from which it was downloaded
JDBC should avoid making any automatic or implicit use of local credentials
when making connections to remote database servers.
If the JDBC Driver level is completely confident that opening a network connection to
a database server will imply no authentication or power beyond that which would be
obtainable by any random program running on any random internet host, then it may allow
an applet to open such a connection. This will be fairly rare, and would require for
example, that the database server doesnt use IP addresses as a way of restricting access.
These restrictions for untrusted applets are fairly onerous. But they are consistent with
the general applet security model and we can see no good way of relaxing them.
Securing JDBC with Java applications
For a normal Java application (i.e. all Java code other than untrusted applets) JDBC
should happily load drivers from the local classpath and allow the application free access

to files, remote servers, etc.


However as with applets, if for some reason an untrusted sun.sql.Driver class is loaded
from a remote source, then that Driver should only be used with code loaded from that
same source.
Securing JDBC with Network Access
The security of database requests and data transmission on the network, especially in
the Internet case, is also an important consideration for the JDBC user. However, keep in
mind that we are defining programming interfaces in this specification, not a network
protocol. The network protocols used for database access have generally already been
fixed by the DBMS vendor or connectivity vendor. JDBC users should verify that the
network protocol provides adequate security for their needs before using a JDBC driver
and DBMS server.
A standard for a published protocol for a DBMS-independent JDBC-Net driver will be
an important factor in the selection of a protocol.
Security Responsibilities of Drivers
Because JDBC drivers may be used in a variety of different situations, it is important
that driver writers follow certain simple security rules to prevent applets from making
illegal database connections.
These rules are unnecessary if a driver is downloaded as an applet, because the
standard security manager will prevent an applet driver from making illegal connections.
However JDBC driver writers should bear in mind that if their driver is successful then
users may start installing it on their local disks, in which case it becomes a trusted part of
the Java environment, and must make sure it is not abused by visiting applets.
These rules all apply at connection open time. This is the point when the driver and the
virtual machine should check that the current caller is really allowed to connect to a given
database. After connection open, no additional checks are necessary.

Short Questions and Answers


Purposes of JDBC API
Following are the purposes of JDBC API:
To access tables and its data from relational databases
It is key enterprise API, as it is very rare that an enterprise does not use

database
JDBC allows operations on a database, such as creating tables, querying data,
updating data, inserting data from a Java application
The results can be obtained and modified to and from a JDBC application
The metadata of tables can be obtained
Allowing only to navigate the result set in unidirectional, avoiding updates to
the tables
What is JDBC API and when do we use it?
Java DataBase Connectivity API allows us to work with relational databases. JDBC
API interfaces and classes are part of java.sql and javax.sql package. We can use JDBC
API to get the database connection, run SQL queries and stored procedures in the database
server and process the results.
JDBC API is written in a way to allow loose coupling between our Java program and
actual JDBC drivers that makes our life easier in switching from one database to another
database servers easily.
What are different types of JDBC Drivers?
There are four types of JDBC drivers. Any java program that works with database has
two parts, first part is the JDBC API and second part is the driver that does the actual
work.
JDBC-ODBC Bridge plus ODBC Driver (Type 1): It uses ODBC driver to
connect to database. We should have ODBC drivers installed to connect to
database, thats why this driver is almost obsolete.
Native API partly Java technology-enabled driver (Type 2): This driver
converts JDBC class to the client API for the database servers. We should have
database client API installed. Because of extra dependency on database client
API drivers, this is also not preferred driver.
Pure Java Driver for Database Middleware (Type 3): This driver sends the
JDBC calls to a middleware server that can connect to different type of
databases. We should have a middleware server installed to work with this
driver. This adds to extra network calls and slow performance and thats why
not widely used JDBC driver.
Direct-to-Database Pure Java Driver (Type 4): This driver converts the JDBC
calls to the network protocol understood by the database server. This solution is

simple and suitable for database connectivity over the network. However for
this solution, we should use database specific drivers, for example OJDBC jars
by Oracle for Oracle DB and MySQL Connector/J for MySQL databases.
What is JDBC Connection? Explain steps to get Database connection in a simple
java program.
JDBC Connection is like a Session created with the database server. You can also think
Connection is like a Socket connection from the database server.
Creating a JDBC Connection is very easy and requires two steps:
Register and Load the Driver: Using Class.forName(), Driver class is registered
to the DriverManager and loaded in the memory.
Use DriverManager to get the Connection object: We get connection object
from DriverManager.getConnection() by passing Database URL String,
username and password as argument.
What is the use of JDBC DriverManager class?
JDBC DriverManager is the factory class through which we get the Database
Connection object. When we load the JDBC Driver class, it registers itself to the
DriverManager, you can look up the JDBC Driver classes source code to check this. Then
when we call DriverManager.getConnection() method by passing the database
configuration details, DriverManager uses the registered drivers to get the Connection and
return it to the caller program.
What is JDBC Statement?
JDBC API Statement is used to execute SQL queries in the database. We can create
the Statement object by calling Connection getStatement() method. We can use Statement
to execute static SQL queries by passing query through different execute methods such as
execute(), executeQuery(), executeUpdate() etc.
By default, only one ResultSet object per Statement object can be open at the same
time. Therefore, if we want to work with multiple ResultSet objects, then each must have
been generated by different Statement objects. All execute() methods in the Statement
interface implicitly close a statments current ResultSet object if an open one exists.
State the functionalities of important classes in JDBC packages.
The important interfaces in JDBC are:

java.sql.DriverManager: Used to manage JDBC drivers, thus establishes a


connection to the database server
java.sql.Connection; Used for establishing connection to a database. All SQL
statements executes within the connection context.
java.sql.Driver: Used for locating the driver to a particular DBMS.
java.sql.DatabaseMetaData: Used to return information about the tables,
attributes
java.sql.Statement: Used to execute an SQL statement
java.sql.PreparedStatement: Used to represent a precompiled SQL statements to
the database server to obtain results
java.sql.ResultSet: Used for processing the results that is returned by executing
SQL statements.
java.sql.Date: Used to handle the SQL date data type.
Explain how to use JDBC statement to execute SQL queries. Show in an example
A JDBC statement such as SELECT is executed by using a ResultSet object. The
process is as follows:
Create a Statement / PreparedStatement object.
Create a ResultSet object
Execute the Statement / PreparedStatement using executeQuery(),
executeUpdate() or execute() methods
If a SELECT statement is executed, read the results and process them
Example:
Statement stmt = conn.createStatement();
ResultSet rslSet = stmt.executeQuery(SELECT LastName FROM Employees
WHERE empId = 548521);
// Displaying the details of the result set
while (rslSet.next()) {
String lastName = rslSet.getString(LastName);
System.out.println(lastName + \n);
}
What is JDBC PreparedStatement?
JDBC PreparedStatement object represents a precompiled SQL statement. We can use

its setter method to set the variables for the query.


Since PreparedStatement is precompiled, it can then be used to efficiently execute this
statement multiple times. PreparedStatement is better choice that Statement because it
automatically escapes the special characters and avoid SQL injection attacks.
Explain how to use Prepared Statement to execute parameterized queries. Show
in an example
PreparedStatement is used to reduce the execution time
It supports sending parameters to the statement, which can be used for several
times with similar action
It has SQL statement which is precompiled. This feature facilitates the
execution of DBMS statement without compiling first.
Example:
PreparedStatement updateSales = con.prepareStatement(UPDATE BOOKS
SET SALES = ? WHERE BOOKNAME LIKE ? );
updateSales.setInt(1, 75);
updateSales.setString(2, PERFORMANCE);
updateSales.executeUpdate()
What is the difference between execute, executeQuery, executeUpdate?
Statement execute(String query) is used to execute any SQL query and it returns
TRUE if the result is an ResultSet such as running Select queries. The output is FALSE
when there is no ResultSet object such as running Insert or Update queries. We can use
getResultSet() to get the ResultSet and getUpdateCount() method to retrieve the update
count.
Statement executeQuery(String query) is used to execute Select queries and returns the
ResultSet. ResultSet returned is never null even if there are no records matching the query.
When executing select queries we should use executeQuery method so that if someone
tries to execute insert/update statement it will throw java.sql.SQLException with message
executeQuery method can not be used for update.
Statement executeUpdate(String query) is used to execute Insert/Update/Delete
(DML) statements or DDL statements that returns nothing. The output is int and equals to
the row count for SQL Data Manipulation Language (DML) statements. For DDL
statements, the output is 0.

You should use execute() method only when you are not sure about the type of
statement else use executeQuery or executeUpdate method.
What is JDBC ResultSet?
JDBC ResultSet is like a table of data representing a database result set, which is
usually generated by executing a statement that queries the database.
ResultSet object maintains a cursor pointing to its current row of data. Initially the
cursor is positioned before the first row. The next() method moves the cursor to the next
row. If there are no more rows, next() method returns false and it can be used in a while
loop to iterate through the result set.
What are different types of ResultSet?
There are different types of ResultSet objects that we can get based on the user input
while creating the Statement. If you will look into the Connection methods, you will see
that createStatement() and prepareStatement() method are overloaded to provide ResultSet
type and concurrency as input argument.
There are three types of ResultSet object.
ResultSet.TYPE_FORWARD_ONLY: This is the default type and cursor can
only move forward in the result set.
ResultSet.TYPE_SCROLL_INSENSITIVE: The cursor can move forward and
backward, and the result set is not sensitive to changes made by others to the
database after the result set was created.
ResultSet.TYPE_SCROLL_SENSITIVE: The cursor can move forward and
backward, and the result set is sensitive to changes made by others to the
database after the result set was created.
Based on the concurrency there are two types of ResultSet object.
ResultSet.CONCUR_READ_ONLY: The result set is read only, this is the
default concurrency type.
ResultSet.CONCUR_UPDATABLE: We can use ResultSet update method to
update the rows data.
What is the different between ResultSet and RowSet?
RowSet objects are derived from ResultSet, so they have all the features of ResultSet
with some additional features. One of the huge benefits of RowSet is that they can be

disconnected and that makes it lightweight and easy to transfer over a network.
Whether to use ResultSet or RowSet depends on your requirements but if you are
planning to use ResultSet for longer duration, then a disconnected RowSet is better choice
to free database resources.
What are common JDBC Exceptions?
Some of the common JDBC Exceptions are:
java.sql.SQLException This is the base exception class for JDBC exceptions.
java.sql.BatchUpdateException This exception is thrown when Batch
operation fails, but it depends on the JDBC driver whether they throw this
exception or the base SQLException.
java.sql.SQLWarning For warning messages in SQL operations.
java.sql.DataTruncation when a data values is unexpectedly truncated for
reasons other than its having exceeded MaxFieldSize.
Multiple Choice Questions

How many JDBC driver types does Sun define?

A.

One

B.

Two

C.

Three

D.

Four

Where is metadata stored in MySQL?

A.

In the MySQL database metadata

B.

In the MySQL database metasql

C.

In the MySQL database mysql

D.

None of the above is correct.

Which JDBC driver Type(s) can be used in either applet or servlet code?
A.

Both Type 1 and Type 2

B.

Both Type 1 and Type 3

C.

Both Type 3 and Type 4

D.

Type 4 only

Exercise
What is JDBC? Explain Two Tier JDBC Architecture.
What is JDBC? Explain Three Tier JDBC Architecture.
List and explain common JDBC Components.
Describe various JDBC Drivers in details.
List advantages and dis-advantages of JDBC Drivers
List advantages and dis-advantages of JDBC.
Give statement to connect Java with oracle

Unit IV Servlets
Introduction to Web
Web consist of many clients and server connected together using networks. The web
clients makes request to web server. The web server receives the request, finds the
resources and return response to the client. Server answers a request with some type of
content to the client. The client uses web browser to send request to the server. The server
sends responds to the browser with a set of instructions written in HTML (HyperText
Markup Language). All browsers know how to display HTML page to the client.

Web Application
Web applications run over the web and are consumed by end user. A web site is a
collection of static files such as HTML pages, images, graphics etc. A Web application is
a web site with dynamic functionality on the server. Google, Facebook, Twitter are
examples of web application. A typical example of Web Application would be a Shopping
Kart Application, which can be accessed over HTTP protocol from a web browser.
HTTP
HTTP is a protocol that clients and server uses on the web to communicate.
HTTP is a stateless protocol i.e HTTP supports only one request per
connection.This means that with HTTP the clients connects to the server to
send one request and then disconnects. This mechanism allows more users to
connect to a given server over a period of time.
The client sends an HTTP request and the server answer with a HTML pages to
the client, using HTTP.

Introduction to Servlet
Servlet technology is used to create web application. Servlet technology uses Java
language to create dynamic web application.

There are many (competing) server-side technologies available: Java-based (servlet,


JSP, JSF, Struts, Spring, Hibernate), ASP, PHP, CGI Script, and many others.
Java servlet is the foundation of the Java server-side technology, JSP (JavaServer
Pages), JSF (JavaServer Faces), Struts, Spring, Hibernate, and others, are extensions of the
servlet technology.
Servlets are Java programs running on a web server (hence the name Servlets,
similar to Applets on the client side) to answer client requests.
Servlets are designed to work within a request/response processing model. In a
request/response model, a client sends a request message to a server and the server
responds by sending back a reply message. A Java servlet is a Java program that executes
on the Web or HTTP server in response to requests from a Web browser. The Web server
software uses Java Virtual Machine to run the servlet and generate an HTML page. The
servlet takes input from a HTML page containing HTML input tags, processes it, and
returns a HTML page with the results.

Servlets are a powerful addition to the Java environment. They are fast, safe, reliable,
and 100% pure Java. Because servlets plug into an existing server, they leverage a lot of
existing code and technology. The server handles the network connections, protocol
negotiation, class loading, and more; all of this work does not need to be replicated! And,
because servlets are located at the middle tier, they are positioned to add a lot of value and
flexibility to a system.
Servlets are not tied to a specific client-server protocol but they are most commonly
used with HTTP and the word Servlet is often used in the meaning of HTTP Servlet.
A servlet can be plugged into a Java-enabled web server to provide custom services.
These services can include:
New features
Runtime changes to content
Runtime changes to presentation
New standard protocols (such as FTP)
New custom protocols
Features of servlet
Servlets execute as a thread within the Web server. Threaded execution avoids
the overhead of creating separate processes for each call.
Servlets may retain data between executions using session tracking mechanism.
For example, a servlet could retain a network connection or access counter
between executions.
A servlet may connect to any computer on the network or write files on the
server. Java servlets allow a platform independent implementation.
A Servlet is a Java program that runs on a Web Container. The Web Container
is capable of handling HTTP requests and responses. A Servlet can run on any
web container as it is developed using a common Servlet-API.
Servlets act as an inter-mediatory interface between HTTP requests originated
from Web Browsers (IE, Chrome etc) and Java Applications hosted on
Application Servers
Servlet runs as a light-weight thread instead of a separate OS process.
Servlets can be used to collect form inputs from a page.
Servlet specification is released by Oracle, which vendors implement to create

their own Web Containers.


Most popular Open Source Web Containers are: Apache Tomcat, Jetty and
Glassfish.
We must import javax.servlet.*; javax.servlet.http.*; packages in order to create
a servlet.
Functions of Servlets
Read any data sent by the user.
This data may be in a form on a Web page, from a Java applet or a custom HTTP
client program.
Look up any other information about the request that is embedded in the
HTTP request.
This information includes details about browser capabilities, cookies, the host
name of the requesting client etc
Generate the results.
This process may require database operations, executing an RMI or CORBA call
or direct response.
Format the results inside a document.
In most cases, this involves embedding the information inside an HTML page.
Set the appropriate HTTP response parameters.
This means informing the browser about the type of document being returned
(e.g., HTML), setting cookies and caching parameters, and other such tasks.
Send the document back to the client.
This document may be sent in text format (HTML), binary format (GIF images),
or even in a compressed format like gzip that is layered on top of some other
underlying format.
Uses for HTTP Servlets
Processing and/or storing data submitted by an HTML form.
Providing dynamic content, e.g. returning the results of a database query to the
client.

Managing state information on top of the stateless HTTP, e.g. for an online
shopping cart system which manages shopping carts for many concurrent
customers and maps every request to the right customer.
As Servlet Technology uses Java, web application made using Servlet
are secured, scalable and robust.
Advantage of Servlet
Portability
Servlets are written in java and follow well known standardized APIs so they
are highly portable across operating systems and server implementations. We
can develop a servlet on Windows machine running the tomcat server or any
other server and later we can deploy that servlet effortlessly on any other
operating system like UNIX server running on the iPlanet/Netscape
Application server. So servlets are write once, run anywhere (WORA) program.
Powerful
We can do several things with the servlets which were difficult or even
impossible to do with CGI, for example the servlets can talk directly to the web
server while the CGI programs cant do. Servlets can share data among each
other, they even make the database connection pools easy to implement. They
can maintain the session by using the session tracking mechanism which helps
them to maintain information from request to request. It can do many other
things which are difficult to implement in the CGI programs.
Efficiency
As compared to CGI the servlets invocation is highly efficient. When the
servlet get loaded in the server, it remains in the servers memory as a single
object instance. However with servlets there are N threads but only a single
copy of the servlet class. Multiple concurrent requests are handled by separate
threads so we can say that the servlets are highly scalable.
Safety
As servlets are written in java, servlets inherit the strong type safety of java
language. Javas automatic garbage collection and a lack of pointers mean that
servlets are generally safe from memory management problems. In servlets we
can easily handle the errors due to Javas exception handling mechanism. If any

exception occurs then it will throw an exception.


Integration
Servlets are tightly integrated with the server. Servlet can use the server to
translate the file paths, perform logging, check authorization, and MIME type
mapping etc.
Extensibility
The servlet API is designed in such a way that it can be easily extensible. As it
stands today, the servlet API support Http Servlets, but in later date it can be
extended for another type of servlets.
Inexpensive
There are number of free web servers available for personal use or for
commercial purpose. Web servers are relatively expensive. So by using the free
available web servers you can add servlet support to it.
Servlet Vs Applet
Servlet

Applet

A Java servlet executes on the Web


A Java Applet executes on the Web
server in response to requests from a Web browser.
browser.
Servlets have no GUI

Applets are rich in GUI

Servlet requires a Java-enabled Web

Java applet requires a Java-enabled

server
Servlet are more powerful than Applet

Web browser
Java Applets are limited to certain
operations on the browser.

Complex interface is difficult to build


Applet allows more complex user
using HTML with Servlets
interface options than HTML with servlets
Servlets can be used for server side

Applets can be used for client side

data validation.

data validation.

The Life Cycle Of a Servlet


The life cycle contains the following steps:
Load Servlet Class.
Create Instance of Servlet.
Call the servlets init() method.
Call the servlets service() method.
Call the servlets destroy() method.

1. Loading Servlet Class: A Servlet class is loaded when first request for the
servlet is recieved by the Web Container.
2. Create Servlet instance: After the Servlet class is loaded, Web Container
creates the instance of it. Servlet instance is created only once in the life cycle.
3. Call the init() method: init() is called by the Web Container on servlet
instance to initialize the servlet.
4. Call the service() method: The container calls the service() method each time
the request for servlet is received.
5. Call destroy() method: The Web container calls the destroy() method before
removing servlet instance giving a chance for cleanup activity.
Usefule Servlet methods

init() method
The servlet is initialized by calling the init () method.
The init method is called only one time, when servlet is first created, never called
again for each user request.
The init() method simply create or load some data that will be used overall life of the
servlet.
public void init() throws ServletException {
//initialize code.
}
This method allows the servlet to per form any setup processing such as opening files
or establishing connections to their servers. If a servlet has been permanently installed in a
server, it loads when the server starts to run.
The init() method takes one argument, a reference to a ServletConfig object which
provides initialization arguments for the servlet.
service()method
The service() method is the heart of the servlet. Each request message from a client
results in a single call to the servlets service() method. The service() method reads the
request and produces the response message from its two parameters:
A ServletRequest object with data from the client.
A ServletResponse represents the servlets reply back to the client.
The service() methods job is conceptually simpleit creates a response for each
client request sent to it from the host server. The servlet container calls the service()
method to handle requests coming from the client or browsers and to write the formatted
response back to the client.
The service() method checks the HTTP request type such as GET, POST etc and calls
doGet, doPost etc.
public void service (ServletRequest request, ServletResponse response)
throws ServletException, IOException
{
}
doGet() Method

GET is HTTP method. It works to tell server to get a resource and send it.
It should be handled by doGet() method.
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Servlet code
}
The doPost() Method
With POST, you can request something and at same time send form data to server.
It should be handled by doPost() method.
public void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Servlet code
}
destroy() method
The destroy() method is called to allow your servlet to clean up any resources (such as
open files or database connections) before the servlet is unloaded. If you do not require
any clean-up operations, this can be an empty method.
The server waits to call the destroy() method until either all service calls are complete,
or a certain amount of time has passed. The destroy() method is called only one time at the
end of the life cycle of a servlet.
public void destroy()
{
// Finalization code
}

Servlet Container
The most popular Servlet Container today is Tomcat. It is very light-weight and easy
to develop and deploy applications on Tomcat. Originally Tomcat was built by Sun
MicroSystems, and later was handed over to the Apache Software Foundation in October
1999. It can be easily integrated with all popular IDEs (like Eclipse, NetBeans etc) and

promotes ease of development.

How a servlet application works?


Web container is responsible for managing execution of servlet. The life cycle of
event is controlled by the web container in which the servlet has been deployed. When a
request is mapped to a servlet, the container performs the following steps:
1. If an instance of the servlet does not exist, the web container loads the servlet
class, creates an instance of the servlet class and initializes the servlet instance
by calling the init method.
2. Invokes the service method, passing request and response objects.
3. If the container needs to remove the servlet, it finalizes the servlet by calling
the servlets destroy method.
The container creates multiple threads to process multiple requests to a single servlet.
Servlet dont have a main() method. Web Container manages the life cycle of a servlet
instance.
Quick Review on how a servlet work
1. User sends request for a servlet by clicking a link that has URL to a servlet.

1. The container finds the servlet using deployment descriptor and creates two
objects
a. HttpServletRequest
b. HttpServletResponse

1. The container creates or allocates a thread for that request and calls the
servlets service() method and passes the request, response objects as
argument

1. The service method decide which servlet method doGet() or doPost() to call
based on HTTP Request Method(Get,Post) sent by the client. Suppose the
client sent an HTTP GET request, so the service() method calls
servlets doGet() method

1. The servlet uses response object to write the response back to the client

1. After the service() method is completed the thread dies. The request and
response object are ready for garbage collection

Installing Servlets
Servlets are not run in the same sense as applets and applications. Servlets provide
functionality that extends a server. In order to test a servlet, two steps are required:
1. Install the servlet in a hosting server
2. Request a servlets service via a client request
There are many web servers that support servlets. It is beyond the scope of this course
to cover different ways to install servlets in each server. This course examines the JSDKs
servletrunner utility and the Apache Web Server.
The Java Servlet Development Kit
For both JDK 1.1 and the Java 2 platform, you need to install the Java Servlet

Development Kit (JSDK) to run servlet. JSDK (Java Servlet Development Kit) is a
package containing all the classes and interfaces needed to develop servlets. JSDK also
contains a web server and servlet engine to test your creations. The servlet engine
provided in JSDK is a basic one (but free). There are many other servlet engines much
more robust and can be interfaced with most major web servers of the market.
This is an Add-on to the regular JDK (Java Developers Kit). The JSDK has the
additional files needed in order to compile Java servlets.
Included in the JSDK is a Java Servlet Runner program. The Servlet Runner is a
program that runs on your workstation, and allows you to test servlets you have written
without running a web server. Other files included are the several Java Servlet examples.
Included are the .java and .class files for testing purposes and to help you understand how
the Java code is implemented. Another important file that is included is the jsdk.jar file.
This file includes the class information necessary to compile the servlets.
Installing JSDK
To install JSDK simply doublie-click on the executable under Windows:
Install JSDK 2.0 to C:\JSDK20 to make it easier when searching for the
directory.
In order to use both the JDK and JSDK together, the java compiler (javac.exe)
needs to know where the class files are located.
First put the bin directory for the JDK in the path. This will make it easy to find
the javac.exe program when compiling code.
Second, add the jsdk.jar file to the classpath. This can be done by adding a SET
statement. The SET statement should read SET CLASSPATH = C:\JSDK
install path\lib\jsdk.jar (ex. SET CLASSPATH = C:\jsdk20\lib\jsdk.jar). Once
this is done, you will have no problem compiling your java servlets. You can
observe following screenshot:

Using sevletrunner utility


Once you have written your servlet, you can run it in many web servers, or in
the servletrunner.
The servletrunner is a small, multithreaded process that handles requests for servlets.
Because servletrunner is multi-threaded, it can be used to run multiple servlets
simultaneously, or to test one servlet that calls other servlets to satisfy client requests.
Unlike some web servers, servletrunner does not automatically reload updated
servlets. However you can stop and restart servletrunner with very little overhead to run a
new version of a servlet.
Properties
Properties are key-value pairs, used for the configuration, creation, and initialization of
a servlet.
There are two properties for servlets.
One is servlet.name.code, whose value is the servlets class name.
The other property is servlet.name.initargs, whose value holds the initialization
parameters for the servlet.
Using the code Property
The servlet.name.code property names your servlet by associating its name with its
class. If your servlet uses initialization parameters, this property is required. It allows the

server to associate the servlet object with its initialization arguments: they both have the
same name. Even if your servlet does not use initialization parameters, it is recommended
that it have this property, so that clients can access the servlet using its name.
Using the Initargs Property
The value of the servlet.name.initArgs property holds the servlets initialization
parameters.
The syntax of a single parameter is
parameterName=parameterValue.
The entire property (the entire key-value pair) must be a single logical line.
Starting servletrunner
To use servletrunner, make sure your PATH environment variable points to its
directory. For the JSDK 2.0 installed with all default options, that location is:
c:\jsdk2.0\bin on a Windows platform.
To make sure that servletrunner has access to the Java servlet packages, check that
your CLASSPATH environment variable is pointing to the correct JAR file,
c:\jsdk2.0\lib\jsdk.jar on a Windows platform. With the Java 2 platform, instead of
modifying the CLASSPATH, it is easier to just copy the JAR file to the ext directory under
the Java runtine environment. This treats the servlet packages as standard extensions.
To verify that the installation was performed correctly, simply start the servletrunner
utility, the servlet engine included in the JSDK, that is to say, a basic server running on
port 8080. If JSDK utility is correctly installed servletrunner should return the following
lines (available at C:\jsdk20\bin\servletrunner.exe from command prompt) :
servletrunner
servletrunner starting with settings :
port = 8080
backlog = 50
max handlers = 100
timeout = 5000
servletdir = ./examples
document dir = ./examples

servlet propfile = ./examples/servlet.properties


Note: JSDK 2.0 require JDK 1.7 or earlier version.
Invoking servletrunner with the -help flag shows a usage message without running it:
>servletrunner -help
Syntax:
servletrunner [options]
Options:
-p port the port number to listen on
-b backlog the listen backlog
-m max maximum number of connection handlers
-t timeout connection timeout in milliseconds
-d dir servlet directory
-r root document root directory
-s filename servlet property file name
-v verbose output
To see the default values of these options, call servletrunner with the -v option:
>servletrunner -v
Server settings:
port = 8080
backlog = 50
max handlers = 100
timeout = 5000
servlet dir = ./examples
document dir = ./examples
servlet propfile = ./examples/servlet.properties
How to use servletrunner to run a Servlet
Once you have written your servlet, you can test it in the servletrunner utility. For

example, to run the HelloServlet Servlet create


C:\JSDK20\examples\HelloServlet.java directory as follows:
//HelloServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet
{
public void doGet (
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException
{
String title = Simple Servlet Output;
response.setContentType(text/html);
PrintWriter out = response.getWriter();
try
{
out.println(<HTML><HEAD><TITLE>);
out.println(title);
out.println(</TITLE></HEAD><BODY>);
out.println(<H1> Hello, world! </H1>);
out.println(</BODY></HTML>);
}
finally
{
out.close();

HelloServlet.java

in

}
}
}
After creating above .java Servlet file compile it as follows:

Note: We have included jsdk.jar file in the classpath it is necessary to compile the
servlet.
Before running any newly created servlet using servletrunner utility we need to create
its entry in the servlet.propertis file.
The Property File
Properties are stored in a file that is, by default, called servlet.properties, though you
can specify another name when servletrunner is started. The file should hold the properties
for all the servlets that servletrunner will run. It should be plain text. You can create it in
any editor. It is located under <Drive>:\JSDK20\examples directory.

For example, to run the HelloServlet Servlet modify servlet.properties file as follows:

Now start servletrunner as follows.

Start a web browser and request the servlet


There are are three ways to invoke servlets:
Typing a servlet URL into a browser window
Calling a servlet from within an HTML page
From another servlet
Typing a servlet URL into a browser window
Servlets can be called directly by typing their URL into a browsers location
window. This is how you access the main page of example.
Once the servletrunner is executing, you run servlets by calling them directly in your
browser, or by using a form that calls a servlet to process its data. The URL for a servlet
has the following general form:
http://machine-name:port/servlet/servlet-name
where servlet-name corresponds to the name you have given your servlet.
Use the following URL. (It assumes that servletrunner is running on machine
(localhost), at port 8080, and that the HelloServlet servlet is located in the servlet
directory provided to servletrunner at startup:
http://localhost: 8080/servlet/HelloServlet
Output:

Creating Servlet using Apache


Creating a servlet
There are three different ways to create a servlet:
By implementing Servlet interface
By extending GenericServlet class
By extending HttpServlet class
But mostly a servlet is created by extending HttpServlet abstract class. As discuss
earlier HttpServlet gives the definition of service() method of the Servlet interface. The
servlet class that we will create should not override service() method. Our servlet class
will override only doGet() or doPost() method.
When a request comes in for the servlet, the Web Container calls the
servlets service() method and depending on the type of request the service() method calls
either the doGet() or doPost() method.
Steps to create servlet using tomcat server
To create a servlet application you need to follow some steps. These steps are common
for the entire Web server. In our example we are using Apache Tomcat server. Apache
Tomcat is an open source web server for testing servlets and JSP technology. Download
latest version of Tomcat Server and install it on your machine.
After installing Tomcat Server on your machine follow the following steps.
Configure the Tomcat Server
Create directory structure for your application.
Create a servlet
Compile the servlet

Create Deployement Descriptor


Start the server and deploy the application
Lets start stepwise process for this:
1. Install jdk1.7 or above for Tomcat 8.x
2. Download and Extract Tomcat 8.x to D:\
3. Create an environment variable JAVA_HOME to point to jdk1.8
a. using CMD i.e. set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25

a. using Windows Settings


Files\Java\jdk1.8.0_25

i.e.

set

JAVA_HOME=C:\Program

Goto Start->Computer-> Right Click-> Properties->Advanced System Settings>Advanced Tab

Click on Environment Variables->New System Variables


Click Add New
Type

JAVA_HOME

in

variable

Files\Java\jdk1.8.0_25 as shown below

Click OK->OK->OK

name

and

value=

C:\Program

1. Configure Tomcat Server


a. Set the TCP Port Number
Open D:\apache-tomcat-8.0.15\conf\server.xml file
Locate the following lines that define the HTTP connector, and change
port=8080 to port=9999.
<Connector port=9999 protocol=HTTP/1.1
connectionTimeout=20000
redirectPort=8443 />

a. Enable Directory Listing


Open D:\apache-tomcat-8.0.15\conf\web.xml file
Locate the following lines that define the default servlet; and change
the listings from false to true.

a. Enable Automatic Reload


Open D:\apache-tomcat-8.0.15\conf\context.xml file
Locate the <Context> start element, and change it to <Context
reloadable=true>.

a. Enable the Tomcats manager (Optional)


Open D:\apache-tomcat-8.0.15\conf\tomcat-users.xml file
Add following user and role inside the <tomcat-users> elements

1. Starting Tomcat Server


a. Launch a CMD shell.
<TOMCAT_HOME>\bin,

Set

the

current

directory

to

a. run startup.bat. A new Tomcat console window appears. Study the


messages on the console.

1. Start a Client to connect to Server


a. Start a browser
b. Open URL http://localhost:9999 to access the Tomcat servers
welcome page.

1. Shutdown Server. You can shutdown the tomcat server by either:


a. Press ctrl-c on the Tomcat console; or
b. Run D:\apache-tomcat-8.0.15\bin\shutdown.bat script:

1. Develop and Deploy a Web Application


a. Create the Directory Structure for your WebApp
The Java defines a unique directory structure that must be followed to create
a servlet application.

i. Create root directory hello inside Tomcats webapps directory.

i. Create a sub-directory WEB-INF inside hello directory.

i. Create a sub-sub-directory classes inside WEB-INF directory.

a. Restart your Tomcat server to pick up the hello webapp. Check the
Tomcats console to confirm that hello application has been properly
deployed.

a. You can issue the following URL to access the web application hello

a. Write an HTML Page. Create the HelloHome.html in root directory


hello.

a. Access
this
page
in
browser
http://localhost:9999/hello/HelloHome.html

by

URL:

a. Rename HelloHome.html to index.html, and issue a directory listing


again. Now, the server will redirect the directory request to index.html,
if the root directory contains an index.html

1. Create and Compile a Java Servlet


a. Write a Hello-world Java Servlet. HelloServlet.java and save it under
your application classes directory.

a. Compile the Servlet. We need the Servlet API to compile the servlet.
Servlet API is NOT part of JDK. Tomcat provides in lib
directory:/lib/servlet-api.jar. We need to include this JAR file in the
compilation via the -cp (classpath) option.

i. Change directory to the source file (i.e. HelloServlet.java)


ii. Check and Set path environment variable to point to JDKs bin
directory
iii. Check and Set classpath environment variable to point to Webapps
classes directory
iv. Compile using the javac command.
v. The output of the compilation is HelloServlet.class created in
classes directory.

a. Configure Servlets Request URL


i. Create the following configuration file called web.xml, and save
it under D:\apache-tomcat-8.0.15\webapps\hello\WEB-INF.

This web.xml configuration file is applicable only to this particular


webapp hello

In the above web.xml configuration file, a servlet having a class


file HelloServlet.class is mapped to request URL /sayhello (via
an arbitrary servlet-name HelloWorld), under this web
application hello. In other words, the complete request URL for
this servlet is http://hostname:port/hello/sayhello. For EACH
servlet, you need to write a pair of <servlet> and <servletmapping> elements with a common but arbitrary <servlet-name>
a. Restart your Tomcat server to refresh the web.xml file.
b. Invoke
the
Servlet
by
issuing
http://localhost:9999/hello/sayhello

the

request

URL:

1. This is the end of the demo of running Servlet on Apache Tomcat 8.x.
Example 2: To create a Servlet that output HTML not just plain text
//HelloWWW.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWWW extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(text/html);
PrintWriter out = response.getWriter();
String docType =
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.0 +
Transitional//EN>\n;
out.println(docType +
<HTML>\n +
<HEAD><TITLE>Hello World in HTML</TITLE></HEAD>\n +

<BODY>\n +
<H1>Hello, World!</H1>\n +
</BODY></HTML>);
}
}

The Servlet API


The central abstraction in the Servlet API is the Servlet interface. All servlets
implement this interface, either directly or, more commonly, by extending a class that
implements it such as HttpServlet. The inheritance hierarchy looks as follows.

Servlet API consists of two important packages that encapsulate all the important
classes and interface.
javax.servlet
javax.servlet.http
It defines Life Cycle methods that all Servlets must implement.
Method

Description

void

Called the when Servlet is initialized or created. Web

init(ServletConfig
config)
throws ServletException
public ServletConfig
getServletConfig()

Container calls the init method exactly once after


instantiating the Servlet. An UnavailableException is thrown
if the servlet cannot be intialized.
Returns ServletConfig object.

public
void
Called by the Web Container to allow the servlet to
service(ServletRequest
respond to a request. Parameters: Object of
req,
ServletRequest(req) that contains the clients request and
ServletResponse res)
Object of ServletResponse(res)that contains the servlets
throws ServletException, response. An IOException is thrown if IO problem occurs.
IOException
String
getServletInfo()

Returns a String containing information about Servlet.

public void destroy()

Called when the servlet is unloaded (being taken out of


service method). Happens during web-container shut down.

The javax.servlet Package


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. All servlets must
implement the Servlet interface, which defines life-cycle methods.
Classes in javax.servlet package
There are many classes in javax.servlet package. They are as follows:
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
The javax.servlet.Http Package

The javax.servlet.http package contains a number of interfaces and


classes
that
are
commonly
used
by servlet developers. You will see that its functionality makes it easy to build servlets
that work with HTTP requests and responses. The following table summarizes the core
interfaces that are provided in this package:
Interface

Description/Use

HttpServletRequest

Enables ser vlets to read data from an


HTTP request.

HttpServletResponse

Enables ser vlets to write data to an


HTTP response.

HttpSession

Allows session data to be read


and written.

HttpSessionBindingListener

Informs an object that it is bound to or


unbound from a session.

The following table summarizes the core classes that are provided in this package. The
most important of these is HttpServlet. Servlet developers typically extend this class in
order to process HTTP requests.
Class

Description/Use

Cookie

Allows state information to be stored on


a client machine.

HttpSer vlet

Provides
methods
to handle HTTP requests and responses.

HttpSessionEvent
HttpSessionBindingEvent

Encapsulates a session-changed event.


Indicates when a listener is bound to or
unbound
from
a
session

value, or that a session attribute changed.


HttpServlet Class
The javax.servlet.http.HttpServlet class is a slightly more advanced base class than
theGenericServlet. The HttpServlet class has methods you can override for each HTTP
method (GET, POST etc.). Here is a list of the methods you can override:
doGet()
doPost()
doHead()
doPut()
doDelete()
doOptions()
doTrace()
HttpServlet is easier to work with, and has more convenience methods
thanGenericServlet. Most often you just want to respond to either HTTP GET or POST
requests, so you just override these two methods.
The HttpServlet class reads the HTTP request, and determines if the request is an
HTTP GET, POST, PUT, DELETE, HEAD etc. and calls one of the corresponding
method. To respond to e.g. HTTP GET requests only, you will extend
the HttpServlet class, and override the doGet() method only. Here is an example:
public class SimpleHttpServlet extends HttpServlet {
protected void doGet( HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().write(<html><body>GET response</body></html>);
}
}
If you want to handle both GET and POST request from a given servlet, you can
override both methods, and have one call the other. Here is how:
public class SimpleHttpServlet extends HttpServlet {
protected void doGet( HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doPost(request, response);
}
protected void doPost( HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().write(GET/POST response);
}
}

Reading Servlet Parameters


Parameters between web pages can be passed either using GET or POST method. If
we use GET method then parameters in the form of key+value pair are appended at the
end of a URL when you submit a form on a web page. For example, if an HTML form was
defined as follows with a username field:
<form action=http://www.testsite.com/login method=GET>
<input type=text name=username>
<input type=submit>
</form>
Then
submitting
the
form
will
make
the
browser
request http://www.testsite.com/login, but with theusername parameter appended on to the
end:
http://www.testsite.com/login?username=jbpatel
Instead of adding request parameters to the end of the URL, it is also possible
to POST them as actual data.
Reading parameters from the Servlet
When creating an application with Java servlet most of the time we will work with the
request and response object. From the request object we can read the parameter submitted
by the users browser either through an HTTP GET or POST method.
To the Servlet, it makes no difference which request method (GET or POST) was used

to send the parameters. In either case, we read the parameter using


the getParameter() method of HttpServletRequest:
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String userName = req.getParameter(username);
}
If the given parameter was not set, then null was returned.
In this example Ill show you how to read the parameter to process user action in a
very simple login servlet.
Directory Structure:

In this example well create a login form, an html page(LoginDemo.html inside


LoginDemo Directory) that accept user input for username and password.
LoginDemo.html (Later rename to index.html as explained in Creating and
Compiling Servlet section)
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>

<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>Login Page</title>
</head>
<body>
<form id=loginForm action=/login method=post>
<label>Username</label>
<input type=text name=username />
<label>Password</label>
<input type=password name=password />
<input type=submit value=Login />
</form>
</body>
</html>
In this form youll have to input box for username and password. You also have a
submit button for executing the login procces. Now we have the form, lets create the
login servlet(LoginServlet.java inside /LoginDemo/WEB-INF/classes).
//LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;

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

public class LoginServlet extends HttpServlet implements Servlet {


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

doLogin(request, response);
}

protected void doPost(HttpServletRequest request,


HttpServletResponse response) throws ServletException, IOException {

doLogin(request, response);
}
protected void doLogin(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

// Reading the parameters from servlet request
String username = request.getParameter(username);
String password = request.getParameter(password);
PrintWriter pw = response.getWriter();
if (username != null && username.equals(administrator)
&& password != null && password.equals(secret)) {
// authentication accepted!
pw.println(Success!);
} else {
// authentication denied!
pw.println(Denied!);

}
pw.close();
}
}
For our servlet to work you must register the servlet in the web.xml file under the
WEB-INF folder. You can find the configuration below (web.xml inside
/LoginDemo/WEB-INF/).
Content of Web.xml file
<?xml version=1.0 encoding=UTF-8?>
<web-app
id=WebApp_ID
xmlns=http://java.sun.com/xml/ns/j2ee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee

version=2.4

http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
<display-name>java-web-examples</display-name>
<servlet>
<description>
</description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.javacoderanch.example.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
Now you have everything, you can deploy the application on your servlet container,

for example Apache Tomcat. Access you login page in the following address:
http://localhost:9999/LoginDemo/LoginDemo.html
You can also access the servlet directly from the following URL:
http://localhost:9999/LoginDemo/index.html
To pass the username and password information you can append the parameter like:
http://localhost:9999/LoginDemo/login?username=administrator&password=secret
This will call the servlet and validate your login information as follows:

Or you can also pass parameters through form like following:

After inputing username and password correctly as shown above when you press the
login button:

If you enter invalid information you get following output:

In order to get all Request Parameters in Servlet, one should take the following steps:
Create a handleRequest
in doGet and doPostmethods.

method

so

you

can

use

it

both

Use HttpServletRequest.getParameterNames to get an Enumeration of


parameter names.
Use HttpServletRequest.getParameterValues(paramName)
parameters values.
Example: To get all Request Parameters in Servlet
//GetAllParams.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.http.HttpServlet;

to

get

the

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetAllParams extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
IOException {
handleRequest(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
IOException {
handleRequest(req, res);
}
public void handleRequest(HttpServletRequest req, HttpServletResponse res)
throws IOException {
PrintWriter out = res.getWriter();
res.setContentType(text/plain);
Enumeration<String> parameterNames = req.getParameterNames();
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
out.write(paramName);
out.write(n);
String[] paramValues = req.getParameterValues(paramName);
for (int i = 0; i < paramValues.length; i++) {
String paramValue = paramValues[i];
out.write(\t + paramValue);
out.write(\n);
}
}

out.close();
}
}
Now lets create servlet web deployment descriptor in web.xml file
<?xml version=1.0 encoding=UTF-8?>
<web-app

id=WebApp_ID

xmlns=http://java.sun.com/xml/ns/j2ee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
<display-name>Reading Parameters</display-name>
<servlet>
<servlet-name>GetAllParams</servlet-name>
<servlet-class>GetAllParams</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetAllParams</servlet-name>
<url-pattern>/getall</url-pattern>
</servlet-mapping>

</web-app>
URL:

version=2.4

After submitting username and password when you press login button you are
redirected to servlet processing:

Parameters vs request headers


HTTP parameters are generally used to pass user-supplied data. They should not be
confused with HTTP request headers, which are generally used to carry meta
information, such as the character encoding, referring page, type of browser etc.

Reading Initialization Parameters


You can pass parameters to a servlet from the web.xml file too. They are called
initialization parameters.
The ServletConfig interface is implemented by the server. It allows a servlet to get
information about Configuration during its initialization.
Method
String
name)

Description
getInitParameter(String

Enumeration

Returns Enumeration of String objects

getInitParameterNames()

public
getServletContext()

Returns a String which contains the value


of the initialization parameter and name
which defines names of initialization
parameter.

containing the names of all initialization


parameters.
ServletContext

Returns the reference of ServletContext.

There are two types of init parameters available. They are both referred to as init
parameters, although defined in defferent elements.
servlet init parameters (defined in <init-param> element).
Servlet init parameters are available to only the servlet for which
the <init-param> was confgured.
Servlet init parameters are defined within the <servlet> element for each
specific servlet.
context init parameters (defined in <context-param> element)
Context init parameters are available to any servlet or JSP that are part
of the current web app.
Context init parameters are defined within the <web-app> element.
Servlet init parameters
Initialization information is passed to the servlet via the ServletConfig parameter of
the init() method. The initialization parameters of a servlet can only be accessed by that
servlet. Accessing servlet init parameter in a servlet for which it was defined in DD:
getServletConfig().getInitParameter(username);
An alternative way of getting servlet init parameter is using method defined in the
class GenericServlet:
getInitParameter(username);
This method is supplied for convenience. It gets the value of the named parameter
from the servletsServletConfig object.
Here is how you configure them in the web.xml file:
<?xml version=1.0 encoding=UTF-8?>
<web-app
id=WebApp_ID
xmlns=http://java.sun.com/xml/ns/j2ee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
<servlet>

version=2.4

<servlet-name>InitParamServlet</servlet-name>
<servlet-class>InitParamServlet</servlet-class>
<display-name>InitParamServlet</display-name>
<init-param>
<param-name>username</param-name>
<param-value>Jbpatel</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>InitParamServlet</servlet-name>
<url-pattern>/InitParam</url-pattern>
</servlet-mapping>
</web-app>
Here is how you read the init parameters from inside your servlet
(InitParamServlet.java) - in the servlets init() method:
//GetAllParams.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletConfig;
public class InitParamServlet extends GenericServlet{
protected String myParam = null;
public void init(ServletConfig servletConfig) throws ServletException{

this.myParam = servletConfig.getInitParameter(username);
}
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.getWriter().write(<html><body>username = +
this.myParam + </body></html>);
}
}
A servlets init() method is called when the servlet container loads the servlet for the
first time. No one can access the servlet until the servlet has been loaded, and
the init() method has been called successfully.
index.htm
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>Servlet Initialization Paramaters</title>
</head>
<body>
<form id=GetAllParams action=/InitParams/InitParam method=post>
<label>Press to Login</label>
<input type=submit value=Login />
</form>
</body>
</html>
Output:

After pressing login button initialization parameters are read from web.xml file and
used by servlet:

Context init parameters


You can also set some context parameters which can be read from all servlets in your
application.
Servlet Context
A servlet lives and dies within the bounds of the server process. To understand its
operating environment, a servlet can get information about its environment at different
times. Servlet initialization information is available during servlet start-up; information
about the hosting server is available at any time; and each service request can contain
specific contextual information.
Example: Servlet Context Parameters Demonstration
ContextParam.html (or index.html)
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>

<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>Servlet Context Initialization Paramaters</title>
</head>
<body>
<form id=ContextParam action=/ServletParam/ContextParam method=GET>
<label>Press to Login</label>
<input type=submit value=Login />
</form>
</body>
</html>
ContextParam.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;

public class ContextParam extends HttpServlet {


ServletConfig config ;

public void init(ServletConfig config)throws ServletException {
this.config = config;
super.init(config);
}

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException , IOException {


try {
response.setContentType(text/plain);
PrintWriter out = response.getWriter();
ServletContext application = config.getServletContext();
String email = application.getInitParameter(email);
out.println(Welcome:+email );
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
web.xml
<?xml version=1.0 encoding=ISO-8859-1?>
<web-app version=3.0
xmlns=http://java.sun.com/xml/ns/javaee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd>

<servlet>
<servlet-name>ContextParam</servlet-name>
<servlet-class>ContextParam</servlet-class>
</servlet>

<servlet-mapping>

<servlet-name>ContextParam</servlet-name>
<url-pattern>/ContextParam</url-pattern>
</servlet-mapping>
<context-param>
<param-name>email</param-name>
<param-value>admin@example.com</param-value>
</context-param>
</web-app>
Output:

When you press login button:

Difference between ServletConfig and ServletContext


The ServletContext object is contained within the ServletConfig object. That is, the
ServletContext can be accessed using the ServletConfig object within a servlet. You can
specify param-value pairs for ServletContext object in <context-param> tags in web.xml
file.
ServletConfig is implemented by the servlet container to initialize a single
servlet using init(). That is, you can pass initialization parameters to the servlet
using the web.xml deployment descriptor. For understanding, this is similar to a

constructor in a java class.


ServletContext is implemented by the servlet container for all servlet to
communicate with its servlet container, for example, to get the MIME type of a
file, to get dispatch requests, or to write to a log file. That is to get detail about
its execution environment. It is applicable only within a single Java Virtual
Machine. If a web applicationa is distributed between multiple JVM this will
not work. For understanding, this is like an application global variable
mechanism for a single web application deployed in only one JVM.

Handling HTTP Requests and responses


True job of a servlet is to handle client request. Requests can come in the form of an
HTTP, URL, FTP or a custom protocol. The request and the corresponding response
reflect the state of the client and the server at the time of the request.
Servlet Request and Response Model

Figure: Request and Response Model of HttpServlets


Servlet
API
provides
two
important
interface
javax.servlet.ServletRequest and javax.servlet.http.HttpServletRequest to encapsulate
client request.
The HttpServlet class provides specialized methods that handle the various types of
HTTP requests.
Using the HTTP support classes
When using the HTTP support classes, you generally create a new servlet that extends
HttpServlet and overrides either doGet() or doPost(), or possibly both. Other methods can
be overridden to get more fine-grained control.
HTTP method

HTTP request can be made using a variety of methods, but the ones you will use most
often are Get andPost. The method name tells the server the kind of request that is being
made, and how the rest of the message will be formated.
HTTP Method and Descriptions
Method

Description

OPTIONS

Request for communication options available


on the request/response chain.

GET

Request to retrieve information from server

HEAD

Identical to GET except that it does not return


a message-body, only the headers

POST

Request for server to accept the entity


enclosed in the body of HTTP method.

DELETE
CONNECT

Request for the Server to delete the resource.


Reserved for use with a proxy that can switch
to being a tunnel.

The GET and POST requests are commonly used when handling form input.
Difference between GET and POST request
GET Request
Data is sent in header to the
server

POST Request
Data is sent in request body

Get request can send only


Large amount of data can be
limited amount of data
sent.
Get request is not secured

Post request is secured

because data is exposed in URL

Get
request
bookmarked.

can

because data is not exposed in


URL.
be

Post request cannot be


bookmarked.

Get request is more efficient

Post request is less efficient.

The HTTP processing methods are passed two parameters, an HttpServletRequest


object and an HttpServletResponse object. The HttpServletRequest class has several
convenience methods to help parse the request, or you can parse it yourself by simply
reading the text of the request. A servlet developer typically overrides one of
these methods:
doDelete()
doGet()
doHead()
doOptions()
doPost()
doPut()
doTrace()
A servlets doGet() method should
Read request data, such as input parameters
Set response headers (length, type, and encoding)
Write the response data
We should select one of doGet or doPost methods for overriding. This choice depends
on what type of http request (GET request or POST request) we are expecting. GET
request is generally only used to retrieve data from the web server, however POST request
are used for more complex requests like storing data.
Some important methods of ServletRequest:
Methods
Object
getAttribute(String name)

Description
return attribute set on request object by name

Enumeration
getAttributeName()

return an Enumeration containing the names of the


attributes available inthis request

int getContentLength()

return size of request body

int getContentType()

return media type of request content

ServletInputStream
getInputStream()

returns a input stream for reading binary data

String
getParameter(String
name)

returns value of parameter by name

String getLocalAddr()

Enumeration
getParameterNames()

returns the Internet Protocol(IP) address of the


interface on which the request was received
returns an enumeration of all parameter names

String[]
returns an array of String objects containing all of
getParameterValues(String the values the given request parameter has, or null if
name)
the parameter does not exist
ServletContext
getServletContext()
String
getServerName()

return the servlet context of current request.

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
HttpServletRequest interface adds the methods that relates to the HTTP protocol.

Some important methods of HttpServletRequest:


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


client sent with this request

String
returns the query string that is contained in the request URL
getQueryString() after the path

HttpSession
getSession()

returns the current HttpSession associated with this 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 requests URL that calls the servlet

Servlet Response
Servlet
API
provides
two
important
interfaces ServletResponse and HttpServletResponse to assist in sending response to
client.
HttpResponse class
The purpose of the HttpResponse object is to represent the HTTP response your web
application sends back to the browser, in response to the HTTP request the browser send
to your web application.
The HttpResponse object has a lot of methods, so I will just cover the most commonly
used here. The rest you can read about in the JavaDoc, if you are interested.
Some important methods of ServletResponse
Methods
PrintWriter
getWriter()

Description
returns a PrintWriter object that can send character
text to the client.

void
Sets the preferred buffer size for the body of the
setBufferSize(int size) response
void
setContentLength(int
len)

Sets the length of the content body in the response In


HTTP servlets, this method sets the HTTP ContentLength header

void
sets the content type of the response being sent to the
setContentType(String client before sending the respond.
type)
void
sets the preferred buffer size for the body of the
setBufferSize(int size) 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.

HttpServletResponse interface
HttpServletResponse interface adds the methods that relates to the HTTP response.

Some important methods of HttpServletResponse

Methods

Description

void

adds the specified cookie to the response.

addCookie(Cookie
cookie)
void
sendRedirect(String
location)

Sends a temporary redirect response to the client


using the specified redirect location URL and clears the
buffer

int getStatus()

gets the current status code of this response

String

gets the value of the response header with the given

getHeader(String
name)
void
setHeader(String
name, String value)
void setStatus(int

name.

sets a response header with the given name and value

sets the status code for this response

sc)
void sendError(int
sends an error response to the client using the
sc, String msg)
specified status and clears the buffer
Handling HTTP GET Requests
Here we will develop a servlet that handles an HTTP GET request. The servlet is
invoked when a form on a web page is submitted. The example contains two files. A web
page is defined in ColorGet.htm, and a servlet is defined in ColorGetServlet.java. The
HTML page ColorGet.htm defines a form that contains a select element and a submit
button. Notice that the action parameter of the form tag specifies a URL. The URL
invokes a servlet to process the HTTP GET request.
ColorGet.html

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN


http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>Handling HTTP Request using GET Method</title>
</head>
<body>
<form id=ContextParam action=/GetDemo/ColorGetServlet method=GET>
<B>Color:</B>
<select name=color size=1>
<option value=Red>Red</option>
<option value=Green>Green</option>
<option value=Blue>Blue</option>
</select>
<br><br>
<input type=submit value=Submit>
</form>

</body>
</html>
ColorGetServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {


String color = request.getParameter(color);
response.setContentType(text/html);
PrintWriter pw = response.getWriter();
pw.println(<B>The selected color is: );
pw.println(color);
pw.close();
}
}
The doGet( )method is overridden to process any HTTP GET requests that are sent
to
this
servlet.
It
uses
the
getParameter(
) method of HttpServletRequest to obtain the selection that was made by the user. A
response is then formulated.
web.xml
<?xml version=1.0 encoding=UTF-8?>
<web-app

id=WebApp_ID

xmlns=http://java.sun.com/xml/ns/j2ee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
<display-name>Reading Parameters</display-name>
<servlet>
<display-name>ColorGetServlet</display-name>
<servlet-name>ColorGetServlet</servlet-name>
<servlet-class>ColorGetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ColorGetServlet</servlet-name>

version=2.4

<url-pattern>/ColorGetServlet</url-pattern>
</servlet-mapping>
</web-app>
Steps for Executing above example:
Compile the servlet.
Copy it to the appropriate directory
Update the web.xml file to include ColorGet servlet.
Start Tomcat, if it is not already running.
Display the web page in a browser.
Select a color.
Submit the web page.
After completing these steps, the browser will display the response that is dynamically
generated by the servlet.
Output:

When you press submit:

Parameters for an HTTP GET request are included as part of the URL that is sent to

the web server. Assume that the user selects the blue option and submits the form. The
URL sent from the browser to the server is
http://localhost:8080/ColorGetServlet?color=Blue
The characters to the right of the question mark are known as the query string.
Handling HTTP POST Requests
Now we will develop a servlet that handles an HTTP POST request.
The servlet is invoked when a form on a web page is submitted. This example also
contains two files. A web page is defined in ColorPost.htm, and
a servlet is defined in ColorPostServlet.java. The method parameter for the form tag is set
to POST.
ColorPOST.html
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>Handling HTTP Request using POST Method</title>
</head>
<body>
<form id=ContextParam action=/PostDemo/ColorPostServlet method=POST>
<B>Color:</B>
<select name=color size=1>
<option value=Red>Red</option>
<option value=Green>Green</option>
<option value=Blue>Blue</option>
</select>
<br><br>
<input type=submit value=Submit>

</form>
</body>
</html>
The
source
code
for
ColorPostServlet.java
is
shown
in
the following listing. The doPost( ) method is overridden to process any HTTP POST
requests that are sent to this servlet. It uses the getParameter(
) method of HttpServletRequest to obtain the selection that was made by the user. A
response is then formulated.
ColorPostServlet .html
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter(color);
response.setContentType(text/html);
PrintWriter pw = response.getWriter();
pw.println(<B>The selected color is: );
pw.println(color);
pw.close();
}
}
web.xml
<?xml version=1.0 encoding=UTF-8?>
<web-app

id=WebApp_ID

xmlns=http://java.sun.com/xml/ns/j2ee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance

version=2.4

xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
<display-name>Reading Parameters</display-name>
<servlet>
<display-name>ColorPostServlet</display-name>
<servlet-name>ColorPostServlet</servlet-name>
<servlet-class>ColorPostServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ColorPostServlet</servlet-name>
<url-pattern>/ColorPostServlet</url-pattern>
</servlet-mapping>
</web-app>
Compile and Test the Servlet.
Output

When you click submit button:

Handling HTTP HEAD Requests


There is no doHead() method to write. Any servlet that subclasses HttpServlet and
implements the doGet() method automatically supports HEAD requests.
The service() method of the HttpServlet identifies HEAD requests and treats them
specially. It constructs a modified HttpServletResponse object and passes it, along with an
unchanged request, to the doGet()method. The doGet() method proceeds as normal, but
only the headers it sets are returned to the client. The special response object effectively
suppresses all body output.
Although this strategy is convenient, you can sometimes improve performance by
detecting HEAD requests in the doGet() method, so that it can return early, before wasting
cycles writing output that no one will see.
Example: Demonstration of handling HEAD requests
Index.htm
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>Handling HTTP Head Request </title>
</head>
<body>
<form
id=HeadDemo
method=HEAD>

action=/HeadDemo/HeadRequestServlet

<label>Username</label>
<input type=text name=name />
<br><br>
<input type=submit value=Submit>
</form>
</body>
</html>
HeadRequestServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HeadRequestServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
// Set the Content-Type header
res.setContentType(text/html);
// Return early if this is a HEAD
if (req.getMethod().equals(HEAD))
return;
// Proceed otherwise
PrintWriter out = res.getWriter();
String name = req.getParameter(name);
out.println(<HTML>);
out.println(<HEAD><TITLE>Hello, + name + </TITLE></HEAD>);
out.println(<BODY>);
out.println(Hello, + name);
out.println(</BODY></HTML>);

}
}
web.xml
<?xml version=1.0 encoding=UTF-8?>
<web-app

id=WebApp_ID

xmlns=http://java.sun.com/xml/ns/j2ee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
<display-name>Reading Parameters</display-name>
<servlet>
<display-name>HeadRequestServlet</display-name>
<servlet-name>HeadRequestServlet</servlet-name>
<servlet-class>HeadRequestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HeadRequestServlet</servlet-name>
<url-pattern>/HeadRequestServlet</url-pattern>
</servlet-mapping>
</web-app>
Output:

version=2.4

When you press submit button:

Notice that we set the Content-Type header, even if we are dealing with a HEAD
request. Headers such as these are returned to the client. Some header values, such
as Content-Length, may not be available until the response has already been calculated. If
you want to be accurate in returning these header values, the effectiveness of this shortcut
is limited.
Make sure that you end the request handling with a return statement. Do not
call System.exit(). If you do, you risk exiting the web server.

Session Tracking
Session
A session can be defined as a series of related interactions between a single client and
the Web server over a period of time. HTTP is a stateless protocol, where each request
is independent of the previous one. However, in some applications, it is necessary to save
state information so that information can be collected from several interactions between a
browser and a server. Sessions provide such a mechanism. Sessions provide such a
mechanism.
A new session is created if one does not already exist.
It is required to implement session management capabilities that link both the
authentication and access control modules commonly available in web
applications.
Session Tracking
To track data among requests in a session is known as session tracking.
Approaches to Session-Tracking:-

1. Using Session Tracking API


2. Cookies
3. Hidden Form Field
4. Using URL -rewriting
Using Session Tracking API
Java Servlet API provides an interface called HttpSession that can be used to keep
track of sessions in the Current servlet context.
Method
HttpSession
s=request.getSession()

boolean b=s.IsNew();

Description
This method is use to reterive the current HttpSession
that is associated with user. if session does not exist,then
a session can be created by using getSession(true)
Returns the Value true If the new Session ID has been
created and has not been sent the client.

s.invalidate()

Returns nothing and it is used to destroy the existing


session.

long
l=s.getCreationTime();

This function returns the time when the session was


created in miliseconds.

long
l=s.getLastAccessedTime();

This function returns the previous time a request was


made with same sessionId.

s.setAttribute(userid,a)
Object
o=s.getAtribute(userid);

Used to set session attribute in session Object.


Used to reterive the set Attribute value.

A session can be created using the getSession() method of HttpServletRequest. An


HttpSession object is returned.
Creating Session

HttpSession s=request.getSession()
Setting Session timeout
You dont have to use them to get rid of stale (inactive) sessions. The container can do
it for you.
Three ways a session can die(timeout)
1. It times out.
2. You call invalidate () on the session object.
3. The application goes down (Crashes or is undeployed).
Configure Session Time out in Deployment Descriptor (i.e. web.xml file)
<session-config>
<session-timeout>15</session-timeout> //15 min
</session-config>
Or
session.setMaxInactiveInterval (20*60); //20 minute
It is important to note that session state is shared among all the servlets that are
associated with a particular client. The following servlet illustrates how to use session
state. The getSession( ) method gets the current session. A new session is created if one
does not already exist. The getAttribute( ) method is called to obtain the
object that is bound to the name date. That object is a Date object that encapsulates the
date and time when this page was last accessed. (Of course, there is no
such binding when the page is first accessed.) A Date object encapsulating the current date
and time is then created. The setAttribute( ) method is called to bind the name date
to this object.
Example: Handling Sessions
Index.html
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>

<meta http-equiv=Content-Type content=text/html; charset=UTF-8>


<title>Handling Session</title>
</head>
<body>
<form id=SessionDemo action=/SessionDemo/SessionServlet method=GET>

<label>Username</label>
<input type=text name=name />
<br><br>
<input type=submit value=Submit>
</form>
</body>
</html>
SessionServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SessionServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType(text/html);
PrintWriter out = response.getWriter();

String n=request.getParameter(name);
out.print(Welcome: +n);

HttpSession session=request.getSession();
session.setAttribute(uname,n);

out.print(<a href=SessionTrack> Check Session Tracking</a>);
out.close();
}catch(Exception e){System.out.println(e);}
}

}
SessionTrack.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionTrack extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try{

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

HttpSession session=request.getSession(false);
String n=(String)session.getAttribute(uname);
out.print(Hello +n);
out.close();
}
catch(Exception e){System.out.println(e);}

}

}
web.xml
<?xml version=1.0 encoding=UTF-8?>
<web-app

id=WebApp_ID

xmlns=http://java.sun.com/xml/ns/j2ee
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation=http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd>
<display-name>Reading Parameters</display-name>
<servlet>
<servlet-name>SessionServlet</servlet-name>
<servlet-class>SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionServlet</servlet-name>
<url-pattern>/SessionServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SessionTrack</servlet-name>
<servlet-class>SessionTrack</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionTrack</servlet-name>
<url-pattern>/SessionTrack</url-pattern>
</servlet-mapping>
</web-app>

version=2.4

Output:

When you click submit button:

When you click link:

Observe that the name of user is made available to second servlet through use of
session.
Using Cookies
Cookies
HTTP Cookies are little pieces of data that a web application can store on the client

machine of users visiting the web application. Typically up to 4 kilo bytes of data.
Cookies are small text files that are used by a Web server to keep track of users.
A cookie has value in the form of key-value pairs.
They are created by the server and sent to the client with the HTTP response
headers.
javax.servlet.http.Cookie class is used to represent a cookie.
A server can send one or more cookies to the client.
A web-browser, which is the client software, is expected to support 20 cookies
per host and the size of each cookie can be a maximum of 4 bytes each.
Important Methods of Cookie class
Cookie Method
Cookie

Description
c=new

Creating a cookie Object.

Cookie(theme,decent);
c.setMaxAge(int);

This method is used to specify the


maximum amount of time for which the
client browser retains the cookie value.

HttpServletResponse.addCookie(c);
Cookie
c[]=HttpServletResponse.getCookies.
c.getName()

To send cookie client.


Reterive all cookies.

To reterive cookie name.

Writing cookie
You can write cookies using the HttpServletResponse object like this:
Cookie cookie = new Cookie(myCookie, myCookieValue);
response.addCookie(cookie);
Whenever the browser accesses the web application it submits the cookies stored on

the client machine to the web application. Only cookies stored by the accessed web
application are submitted. Cookies from other web applications are not submitted.
Reading Cookies Sent From the Browser
A web-browser, which is the client software, is expected to support 20 cookies per host
and the size of each cookie can be a maximum of 4 bytes each. You can read the cookies
via the HttpServletRequest like this:
Cookie c[]=request.getCookies();
Now, lets develop a servlet that illustrates how to use cookies.
The servlet is invoked when a form on a web page is submitted. The example contains
three files as summarized here:
AddCookie.htm
Allows a user to specify a value for the cookie named MyCookie.
AddCookieServlet.java
Processes the submission of AddCookie.htm.
GetCookiesServlet.java
Displays cookie values.
The HTML source code for AddCookie.htm is shown in the following listing. This
page contains a text field in which a value can be entered. There is also a submit button on
the page. When this button is pressed, the value in the text field is sent
to AddCookieServlet via an HTTP POST request.
AddCookie.html
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>Handling Session using Cookie</title>
</head>
<body>

<form
id=CookieDemo
method=POST>

action=/CookieDemo/AddCookieServlet

<B>Enter a value for MyCookie:</B>


<input type=textbox name=data size=25 value=></br>
<input type=submit value=Submit>
</form>
</body>
</html>
AddCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get parameter from HTTP request.
String data = request.getParameter(data);
// Create cookie.
Cookie cookie = new Cookie(MyCookie, data);
// Add cookie to HTTP response.
response.addCookie(cookie);
// Write output to browser.
response.setContentType(text/html);
PrintWriter pw = response.getWriter();
pw.println(<B>Cookie Created: MyCookie=);
pw.println(data);

pw.println(<a href=GetCookieServlet> Click to access</a>);


pw.close();
}
}
Above code gets the value of the parameter named data. It then creates
a Cookie object that has the name MyCookie and contains the value of
the data parameter. The cookie is then added to the header of the HTTP
response via the addCookie( ) method. A feedback message is then written to the browser.
GetCookiesServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookieServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
// Display these cookies.
response.setContentType(text/html);
PrintWriter pw = response.getWriter();
pw.println(<B>);
for(int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println(name = + name +; value = + value);
}
pw.close();

}
}
The code for GetCookiesServlet.java is shown above. It invokes
the getCookies() method to read any cookies that are included in the HTTP GET request.
The names and values of these cookies are then written to the HTTP response.
Observe that the getName( ) and getValue( ) methods are called to obtain this information.
Executing the Cookie example:
Compile the servlets.
Copy to the appropriate directory
Update the web.xml file to include the servlets.
Start Tomcat, if it is not already running.
Display AddCookie.htm in a browser.
Enter a value for MyCookie.
Submit the web page.
After completing these steps, you will observe that a feedback message is displayed by
the browser.
Next, request the following URL via the browser:
http://localhost:9999/GetCookiesServlet
Observe that the name and value of the cookie are displayed in the browser.
Output:

When you press submit button:

When you click link to access the cookie:

Cookie Expiration
One important Cookie setting is the cookie expiration time. This time tells the browser
receiving the cookie how long time it should keep the cookie before deleting it.
You can set the cookie expiration time using the setMaxAge() method. This method
takes the number of seconds the cookie is to live as parameter. Here is an example:
Cookie cookie = new Cookie(username, Jbpatel);
cookie.setMaxAge(24 * 60 * 60); // 24 hours.
response.addCookie(cookie);
This example first creates a Cookie instance with the name username and the value
Jbpatel. Second, it sets the expiration to 24 hours using the setMaxAge() method. 24
hours is 60 seconds x 60 minutes x 24 hours (24 x 60 x 60). Finally the example sets the
cookie on the HttpServletResponse object, so the cookie is included in the response sent to
the browser.
Removing Cookies

You can remove a cookie from the browser by setting the cookie expiration time
0 or -1. If you set the expiration time to 0 the cookie will be removed immediately from
the browser. If you set the expiration time to -1 the cookie will be deleted when the
browser shuts down. Here is an example:
Cookie cookie = new Cookie(username, );
cookie.setMaxAge(0);
response.addCookie(cookie);
If the browser already has a cookie stored with the name username, it will be deleted
after receiving the cookie with the same name (username) with an expiration time of 0.
If the browser did not already have the cookie stored, this new cookie is just thrown out
immediately since its expiration time is 0.
Using Hidden Form Fields
A hidden form field is simplest session tracking techniques. It can be used to keep
track of users by placing hidden fields in a form. The values that have been entered in
these fields are sent to the server when the user submits the form.
For Example:
<input type=hidden name=text1 value=20>
URL-Rewritting
If web browser at Client side has disabled Cookie then Session API fails. If client
wont take cookies, you can use URL rewriting as a back up. URL rewriting is a better
way to maintain sessions when the browsers dont support cookie. So URL rewriting is a
better way to maintain sessions.

Reading and displaying Records using servlet


I will be using MySQL as databse to work with servlet.
Create databse
Create databse in MySQL as:
CREATE DATABASE STUDENTS
Create Table
Now create table inside the databse in MySQL as:

CREATE TABLE STUDENTS.`studentinfo` (


`RollNo` INT NOT NULL ,
`Name` VARCHAR( 50 ) NOT NULL
);
Insert Records in the table
Create few records in Student table as follows:
INSERT INTO `Students`.`studentinfo` (`RollNo`, `Name`) VALUES (1, Jainik),
(2, Krinal);
Accessing a Database Using Servlet
Here is an example which shows how to access Students database using Servlet.
DatabaseAccess.java
// Loading required libraries
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class DatabaseAccess extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// JDBC driver name and database URL
final String JDBC_DRIVER = com.mysql.jdbc.Driver;
final String DB_URL = jdbc:mysql://localhost/students;

// Database credentials
final String USER = root;

final String PASS = ;



Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

// Set response content type


response.setContentType(text/html);
PrintWriter out = response.getWriter();
String title = Database Records from StudentInfo Table;
String docType =
<!doctype html public -//w3c//dtd html 4.0 +
transitional//en>\n;
out.println(docType +
<html>\n +
<head><title> + title + </title></head>\n +
<body bgcolor=#f0f0f0>\n +
<h1 align=center> + title + </h1>\n);
try{
// Register JDBC driver
Class.forName(JDBC_DRIVER);
System.out.println(Connecting to database);
// Open a connection
try{
conn = DriverManager.getConnection(DB_URL,USER,PASS);
out.println(Connected Successfully Please Wait!<br>);
}

catch(SQLException se){
se.printStackTrace();
}

// Execute SQL query


System.out.println(Displaying Records from table);
stmt = conn.createStatement();
String sql;
sql = SELECT * FROM studentinfo;
rs = stmt.executeQuery(sql);

// Extract data from result set


while(rs.next()){
//Retrieve by column name
int rno = rs.getInt(rollno);
String sname = rs.getString(name);

//Display values
out.println(Students Roll No: + rno + );
out.println(, Name: + sname + <br>);
}
out.println(</body></html>);

// Clean-up environment
rs.close();
stmt.close();
conn.close();

}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
} //end try
}
}
index.html
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>

<meta http-equiv=Content-Type content=text/html; charset=UTF-8>


<title>Accessing Database Using JDBC and Servlet</title>
</head>
<body>
<form

id=ContextParam

action=/DatabaseServlet/LoadRecords

method=GET>
<label>Press to Display Student Records</label>
<input type=submit value=Display />
</form>
</body>
</html>
web.xml
<servlet>
<servlet-name>LoadRecords</servlet-name>
<servlet-class>LoadRecords</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoadRecords</servlet-name>
<url-pattern>/LoadRecords</url-pattern>
</servlet-mapping>
Output:
Before running this servlet care following:
Copy
mysql-connector-java-5.1.34-bin.jar
file
to
C:\Program
Files\Java\jdk1.8.0_25\jre\lib\ext folder
Set classpath to include servlet-api.jar file and mysql-connector-java-5.1.34bin.jar file.

When you press display button:

Short Questions and Answers


What is different between web server and application server?
A web server responsibility is to handle HTTP requests from client browsers and
respond with HTML response. A web server understands HTTP language and runs on
HTTP protocol. Apache Web Server is kind of a web server and then we have specific
containers that can execute servlets and JSPs known as servlet container, for example
Tomcat.
Application Servers provide additional features such as Enterprise JavaBeans support,
JMS Messaging support, Transaction Management etc. So we can say that Application
server is a web server with additional functionalities to help developers with enterprise
applications.

What is a servlet?
Java Servlet is server side technologies to extend the capability of web servers by
providing support for dynamic response and data persistence.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for
writing our own servlets.
All servlets must implement the javax.servlet.Servlet interface, which defines servlet
lifecycle methods. When implementing a generic service, we can extend the
GenericServlet class provided with the Java Servlet API. The HttpServlet class provides
methods, such as doGet() and doPost(), for handling HTTP-specific services.
Most of the times, web applications are accessed using HTTP protocol and thats why
we mostly extend HttpServlet class. Servlet API hierarchy is shown in below image.
What are the uses of Servlet?
The important used of HTTP Servlets are:
Storage and processing of data submitted by an HTML form.
Providing dynamic content to the client for example outputting the result of
a query.
Improving the system performance by handling multiple requests at a time.
Managing state information on top of the stateless HTTP.

What is an Applet container?



It is a container to manage the execution of applets.


It consists of a web browser and a Java plug-in running together on the
client.

What are common tasks performed by Servlet Container?


Servlet containers are also known as web container, for example Tomcat. Some of the
important tasks of servlet container are:
Lifecycle management - Managing the lifecycle events of a servlet lik class
loading, instantiation, initialization, service, and making servlet instances
eligible for garbage collection.
Communication support: Handling the communication between servlet and

Web server.
Multithreading support: Automatically creating a new thread for every

servlet request and finishing it when the Servlet service() method is over.
Declarative security: Managing the security inside the XML deployment
descriptor file.
JSP support: Converting JSPs to servlets and maintaining them.
What is the difference between GET and POST method?
GET Request

POST Request

Data is sent in header to the


server
Get request can send only
limited amount of data.

Data is sent in request body

Large amount of data can be


sent.

Get request is not secured


Post request is secured
because data is exposed in URL
because data is not exposed in
URL.
Get
request
bookmarked.

can

be

Get request is more efficient

Post request cannot be


bookmarked.
Post request is less efficient.

What is MIME Type?


The Content-Type response header is known as MIME Type. Server sends MIME
type to client to let them know the kind of data its sending. It helps client in rendering the
data for user. Some of the mostly used mime types are text/html, text/xml, application/xml
etc.
We can use ServletContext getMimeType() method to get the correct MIME type of
the file and use it to set the response content type. Its very useful in downloading file
through servlet from server.
What is a web application and what is its directory structure?
Web Applications are modules that run on server to provide both static and dynamic
content to the client browser. Apache web server supports PHP and we can create web

application using PHP. Java provides web application support through Servlets and JSPs
that can run in a servlet container and provide dynamic content to client browser.
When using servlets to build the HTML, you build a DOCTYPE line, why do you
do that?
Building a DOCTYPE line informs the HTML validators about the version of HTML
you are using. This tells them the specification against which your document should be
checked.
These validators work as valuable debuggers which help you catch the HTML syntax
errors.
What is ServletConfig object?
javax.servlet.ServletConfig is used to pass configuration information to Servlet. Every
servlet has its own ServletConfig object and servlet container is responsible for
instantiating this object. We can provide servlet init parameters in web.xml file or through
use of WebInitParam annotation. We can use getServletConfig() method to get the
ServletConfig object of the servlet.
What is ServletContext object?
javax.servlet.ServletContext interface provides access to web application parameters
to the servlet. The ServletContext is unique object and available to all the servlets in the
web application. When we want some init parameters to be available to multiple or all of
the servlets in the web application, we can use ServletContext object and define
parameters in web.xml using <context-param> element. We can get the ServletContext
object via the getServletContext() method of ServletConfig. Servlet containers may also
provide context objects that are unique to a group of servlets and which is tied to a specific
portion of the URL path namespace of the host.
ServletContext is enhanced in Servlet Specs 3 to introduce methods through which we
can programmatically add Listeners and Filters and Servlet to the application. It also
provides some utility methods such as getMimeType(), getResourceAsStream() etc.
What is difference between ServletConfig and ServletContext?
Some of the differences between ServletConfig and ServletContext are:
ServletConfig is a unique object per servlet whereas ServletContext is a
unique object for complete application.
ServletConfig is used to provide init parameters to the servlet whereas

ServletContext is used to provide application level init parameters that all other
servlets can use.
We cant set attributes in ServletConfig object whereas we can set attributes
in ServletContext that other servlets can use in their implementation.
Why is a constructor needed in a servlet even if we use the init method?
Although the init method of the servlet initializes it, a constructor instantiates it. A
developer might never explicitly call the servlets constructor but a container uses it to
create an instance of the servlet.
What is difference between PrintWriter and ServletOutputStream?
PrintWriter is a character-stream class whereas ServletOutputStream is a byte-stream
class. We can use PrintWriter to write character based information such as character array
and String to the response whereas we can use ServletOutputStream to write byte array
data to the response.
We can use ServletResponse getWriter() to get the PrintWriter instance whereas we
can use ServletResponse getOutputStream() method to get the ServletOutputStream object
reference.
Can we get PrintWriter and ServletOutputStream both in a servlet?
We cant get instances of both PrintWriter and ServletOutputStream in a single servlet
method, if we invoke both the methods; getWriter() and getOutputStream() on response;
we will get java.lang.IllegalStateException at runtime with message as other method has
already been called for this response.
When should you prefer to use doGet() over doPost()?
GET is preferred over POST in most of the situations except for the following:

When the data is sensitive.


When the data is greater than 1024 characters

Do we need to override service() method?


When servlet container receives client request, it invokes the service() method which
in turn invokes the doGet(), doPost() methods based on the HTTP method of request. I
dont see any use case where we would like to override service() method. The whole
purpose of service() method is to forward to request to corresponding HTTP method
implementations. If we have to do some pre-processing of request, we can always use

servlet filters and listeners.


What is GenericServlet class?
GenericServlet is an abstract class which implements the Servlet interface and the
ServletConfig interface. Other than the methods included in above two interfaces, it also
provides simple versions of the lifecycle methods init and destroy, and implements the log
method declared in the ServletContext interface. Since this class is not specific to any
protocol, it is known as generic servlet.
What is difference between GenericServlet and HttpServlet?
GenericServlet is protocol independent implementation of Servlet interface whereas
HttpServlet is HTTP protocol specific implementation. Most of the times we use servlet
for creating web application and thats why we extend HttpServlet class. HttpServlet class
extends GenericServlet and also provide some other methods specific to HTTP protocol.
What are the types of Session Tracking ?
Following are the popular ways of session tracking:
URL rewriting: In this method of session tracking, some extra data is appended
at the end of the URL, which identifies the session. This method is used for
those browsers which do not support cookies or when the cookies are disabled
by the user.
Hidden Form Fields: This method is similar to URL rewriting. New hidden
fields are embedded by the server in every dynamically generated form page
for the client. When the form is submitted to the server the hidden fields
identify the client.
Cookies: Cookie refers to the small amount of information sent by a servlet to a
Web browser. Browser saves this information and sends it back to the server
when requested next. Its value helps in uniquely identifying a client.
Using session Tracking API
What are the disadvantages of storing session state in cookies?
Using a cookie, all the session data is stored with the client. If the cookies at client side
get corrupt, purged or expired, the information received wont be complete. Some user
may disable the cookies or their browser might not support them. Some users might have a
firewall filtering out the cookies. So, you may either not receive the information or trying
to switch to an alternate means may cause complexity. Cookie based solutions work only

for HTTP clients. A low-level API controls the cookies. It is quite difficult to implement
them.
How can the session in Servlet be destroyed?
There are two ways to destroy a session:
Programatically: By using session.invalidate() method. It makes the container
abandon the session on which the method is called.
When the server shuts down.

Exercise
What is servlet?
What is difference between Applet and Servlet?
Explain the life cycle of Servlet.
What are the uses of Servlets?
Whats the Servlet Interface?
What is web container? Explain its working.
Explain following methodsof using Servlet in JAVA
Using Servletrunner utility
Using WebServer
List interfaces and class available in Servlet API.
How HTTP Servlet handles client requests?
When a servlet accepts a call from a client, it receives two objects. What are
they?
What information that the ServletRequest interface allows the servlet access
to?
What information that the ServletResponse interface gives the servlet
methods for replying to the client?
If you want a servlet to take the same action for both GET and POST
request, what you should do?
Write Servlet to read parameters using GET method.
Write Servlet to read parameters using POST method.
Write Servlet to read servlet initialization parameters.
Write Servlet to read context initialization parameters.
Write Servlet to provide session management using session tracking API.
Write Servlet to provide session management using Cookie.

Which code line must be set before any of the lines that use the PrintWriter?
When using servlets to build the HTML, you build a DOCTYPE line, why
do you do that?

Unit V Java Server Pages: (JSP)


JSP technology
JavaServer Pages is server side component in a web application, used to dynamically
generate HTML / XML documents. JSP allows the java code dynamically embedded
within a web page like HTML and gets executed when the page is served by the server.
After the page is served, the dynamic content is sent to the client. With the script, the page
is run on the server before it reaches to the client. JSP are used to invoke the built-in
functionalities. In addition to the HTML, the JSP technology adds a tag library which
provides a platform independent extending capabilities of a web server.
Java Server Page is a standard Java extension that is defined on top of the servlet
Extensions. The goal of JSP is the simplified creation and management of dynamic Web
pages. JSPs are secure, platform-independent, and best of all; make use of Java as a
server-side scripting language.

JSP page
A JSP page is a text-based document that contains two types of text: static template
data, which can be expressed in any text-based format such as HTML, SVG, WML, and
XML, and JSP elements, which construct dynamic content.
Life cycle of JSP Page
The generated servlet class for a JSP page implements the HttpJspPage interface of the
javax.servlet.jsp package. The HttpJspPage interface extends the JspPage interface which
inturn extends the Servlet interface of the javax.servlet package. The generated servlet
class thus implements all the methods of these three interfaces. The JspPage interface
declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all
JSP pages regardless of the client-server protocol. However the JSP specification has
provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests.
This interface declares one method _jspService().
JSP page looks like a HTML page but is a servlet. When presented with JSP page the
JSP engine does the following 7 phases.
1. Translation JSP container checks the JSP page code and parses it to generate
the servlet source code. For example in Tomcat you will find generated servlet
class files at <tomcat>/WEBAPP/org/apache/jsp directory. If the JSP page
name is home.jsp, usually the generated servlet class name is home_jsp and file

name is home_jsp.java
2. Compilation JSP container compiles the jsp class source code and produce
class file in this phase.
3. Class Loading Container loads the class into memory in this phase.
4. Instantiation Container invokes the no-args constructor of generated class to
load it into memory and instantiate it.
5. Initialization Container invokes the init method of JSP class object and
initializes the servlet config with init params configured in deployment
descriptor. After this phase, JSP is ready to handle client requests. Usually from
translation to initialization of JSP happens when first request for JSP comes but
we can configure it to be loaded and initialized at the time of deployment like
servlets using load-on-startup element.
6. Request Processing This is the longest lifecycle of JSP page and JSP page
processes the client requests. The processing is multi-threaded and similar to
servlets and for every request a new thread is spawned and ServletRequest and
ServletResponse object is created and JSP service method is invoked.
7. Destroy This is the last phase of JSP lifecycle where JSP class is unloaded
from memory. Usually it happens when application is undeployed or the server
is shut down.
JSP lifecycle methods
JSP lifecycle methods are:
1. jspInit(): This method is declared in JspPage and its implemented by JSP
container implementations. This method is called once in the JSP lifecycle to
initialize it with config params configured in deployment descriptor. We can
override this method using JSP declaration scripting element to initialize any
resources that we want to use in JSP page.
2. _jspService(): This is the JSP method that gets invoked by JSP container for
each client request by passing request and response object. Notice that method
name starts with underscore to distinguish it from other lifecycle methods
because we cant override this method. All the JSP code goes inside this
method and its overridden by default. We should not try to override it using
JSP declaration scripting element. This method is defined in HttpJspPage

interface.
3. jspDestroy(): This method is called by container when JSP is unloaded from
memory such as shutting down application or container. This method is called
only once in JSP lifecycle and we should override this method to release any
resources created in JSP init method.

Relation of Applets and Servlets with JSP


There are three primary ways to create client interfaces to Java programs that are
delivered over the Internet: applets, servlets, and Java Server Pages (JSP). Applets run
within a client browser, while servlets and JSPs run on the Web server machine.
They have certain advantages and disadvantages in relation to the others. Applets are
better suited for high functionality applications, where download times are not a
factor. Servlets and JSP pages are more appropriate for applications where the users may
access a host site through a slow Internet connection.
Applets
Applets are small programs that are downloaded into a Java Enabled Web
Browser. The browser will execute the applet on the clients machine. The downloaded
applet has very limited access to the client machines file system and network capabilities.
These limitations ensure that the applet cant perform any malicious activity on the clients
machine, such as deleting files or installing viruses. By default, a downloaded applet
cannot read or write files from the file system, and may use the network only to
communicate back to the server of origin.
Enhanced User Interface
Applets greatly enhance the user interface available through a
browser. Applets can be created to act exactly like any other client-server GUI
application including menus, popup dialog windows, and many other userfriendly features not otherwise available in a web browser environment.
Long Setup Time over slow internet
On the downside, applets need to be downloaded over the Internet. Instead of
just downloading the information to be displayed, a browser must download the
whole application to execute it. The more functionality the applet provides, the
longer it will take to download. Applets are best suited for applications that

either run on an Intranet, or are small enough to download quickly or dont


require special security access.
Servlets
A servlet is a Java program that runs in conjunction with a Web Server. A servlet is
executed in response to an HTTP request from a client browser. The servlet executes and
then returns an HTML page back to the browser.
Servlets Handle Multiple Request
Servlets once started it remains in memory and can handle multiple HTTP
requests.
Server Side Execution
Servlets do not run on the client, all execution takes place on the server. While,
they provide the advantages of generating dynamic content, they do not levy
the same download time requirement as applets.
Limited GUI Functionality
Since they deliver HTML pages to their clients, the user interface available
through a servlet is limited by what the HTML specification supports.
JSP (Java Server Pages)
JSPs are text documents that describe how a server should handle specific requests. A
JSP is run by a JSP Server, which interprets the JSP and performs the actions the page
describes. The JSP server compiles the JSP into a servlet to enhance performance. The
server would then periodically check the JSP for changes. If the JSP changes the server
will recompile it into a servlet.
Extension of the Servlet API
The JSP specification is an extension of the servlet specification. JSPs have the
same advantages and disadvantages as servlets when compared to applets.
Easier to Develop and Maintain than Servlets
To the developer, JSPs look very similar to static HTML pages, except that they
contain special tags are used to identify and define areas that contain Java
functionality. Because of the close relationship between JSPs and the resulting
HTML page, JSPs are easier to develop than a servlet that performs similar

operations. Because they do not need to be compiled, JSPs are easier to


maintain and enhance than servlets.
Initial Access Slower than Servlets
However, because they need to be interpreted or compiled by the server,
response time for initial accesses may be slower than is experienced with
servlets as the JSP is compiled.
JSP versus Servlet
JSP

Servlet

JSP can be compiled into Servlet


Servlets are Java programs that
when accessed
are already compiled
Its easier to code in JSP than in
Application coding is difficult
Java Servlets
compared to JSP
JSP are generally not preferred
Servlet are preferred when there is
when there is much processing of much processing of data required.
data required.
We can achieve functionality of
There are no such methods for
JSP at client side by running servlets.
JavaScript at client side.
We can build custom tags using
We can not build custom tags
JSP.
using JSP.

Comments in JSP
Following syntax is sued to put comment in JSP Page.
<% JSP Comment %>
<! HTML Comment >

Simple JSP program


Java Server Pages or JSP is used for developing dynamic web sites. JSP provide

excellent server side scripting support for creating database driven web applications. JSP
enable the developers to directly insert java code into jsp file, this makes the development
process very simple and its maintenance also becomes very easy. JSP pages are efficient,
it loads into the web servers memory on receiving the request very first time and the
subsequent calls are served within a very short period of time.
In todays environment most web sites servers dynamic pages based on user request.
Database is very convenient way to store the data of users and other things. JDBC provide
excellent database connectivity in heterogeneous database environment. Using JSP and
JDBC its very easy to develop database driven web application.
Java is known for its characteristic of write once, run anywhere. JSP pages are
platform independent. Your port your .jsp pages to any platform.
Java Server Pages are saved with .jsp extension.
Installation and execution of JSP
Follow these steps to run JSP Page:
Step 1: Download and install latest Apache Tomcat and JAVA.
Step 2: Create directory JSPDemo and JSPDemo\WEB-INF directories under
the webapps as shown here:

Step 3: Create simple HelloWorld.jsp program using any editor like notepad:
<%
Document : HelloJSP.jsp

Author : J.B.Patel
%>
<%@page contentType=text/html pageEncoding=UTF-8%>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>First JSP Page</title>
</head>
<body>
<p> Hi, <h3><%=Hello! %></h3></p>
</body>
</html>

Step 4: Save this file as HelloWorld.jsp in JSPApp directory:

Step 5: Before run this code, start apache tomcat as you have learned in Servlet
Section.

Step 6: Set path, java_home, and classpath variable as required from command line.
For example:
set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25\
set PATH=%JAVA_HOME%;%PATH%
set
CLASSPATH=.;D:\apache-tomcat-8.0.15\lib\servlet-api.jar;D:\apache-tomcat8.0.15\lib\jsp-api.jar;D:\apache-tomcat-8.0.15\lib\el-api.jar;
D:\apache-tomcat8.0.15\webapps\JSPDemo; %classpath%
Step 7:Start or Restart (if already running) Apache Tomcat Server

Stpe 8: Run HelloWorld.jsp program in browser using following link:


http://localhost:9999/JSPDemo/HelloWorld.jsp
Or (if you have renamed HelloWorld.jsp to index.jsp)
http://localhost:9999/JSPDemo/
Stpe 9: Observe the output:

How JSP and JSP Container functions?


A JSP page is executed in a JSP container or a JSP engine, which is installed in a web
server or in a application server. When a client asks for a JSP page the engine wraps up the
request and delivers it to the JSP page along with a response object. The JSP page
processes the request and modifies the response object to incorporate the communication
with the client. The container or the engine, on getting the response, wraps up the
responses from the JSP page and delivers it to the client. The underlying layer for a JSP is
actually a servlet implementation. The abstractions of the request and response are the
same as the ServletRequest and ServletResponse respectively. If the protocol used is
HTTP, then the corresponding objects are HttpServletRequest and HttpServletResponse.
The first time the engine intercepts a request for a JSP, it compiles this translation unit
(the JSP page and other dependent files) into a class file that implements the servlet
protocol. If the dependent files are other JSPs they are compiled into their own classes.
The servlet class generated at the end of the translation process must extend a superclass
that is either
Specified by the JSP author through the use of the extends attribute in the
page directive or
Is a JSP container specific implementation class that implements
javax.servlet.jsp.JspPage interface and provides some basic page specific
behavior.
Since most JSP pages use HTTP, their implementation classes must actually
implement the javax.servlet.jsp.HttpJspPage interface, which is a sub interface of
javax.servlet.jsp.JspPage.

The javax.servlet.jsp.JspPage interface contains two methods:


public void jspInit() - This method is invoked when the JSP is initialized
and the page authors are free to provide initialization of the JSP by
implementing this method in their JSPs.
public void jspDestroy() - This method is invoked when the JSP is about
to be destroyed by the container. Similar to above, page authors can
provide their own implementation.
The javax.servlet.jsp.HttpJspPage interface contains one method:
public
void
_jspService(HttpServletRequest
request,
HttpServletResponse response) throws ServletException, IOException
This method generated by the JSP container is invoked, every time a request comes to
the JSP. The request is processed and the JSP generates appropriate response. This
response is taken by the container and passed back to the client.

JSP Scripting Elements


JSP scripting elements let you insert Java code into the servlet that will be generated
from the current JSP page. There are three forms:
1. Expressions of the form <%= expression %> that are evaluated and inserted
into the output,
2. Scriptlets of the form <% code %> that are inserted into the servlets service
method, and
3. Declarations of the form <%! code %> that are inserted into the body of the
servlet class, outside of any existing methods.
When Are the Scripting Elements Executed?
A JSP source file is processed in two stages-HTTP TRANSLATION
TIME and REQUEST PROCESSING TIME.
At HTTP translation time, which occurs when a user first loads a JSP page, the JSP
source file is compiled to a Java class, usually a Java servlet. The HTML tags and as many
JSP tags as possible are processed at this stage, before the user makes a request.
Request processing time occurs when your user clicks in the JSP page to make a
request. The request is sent from the client to the server by way of the request object. The

JSP engine then executes the compiled JSP file, or servlet, using the request values the
user submitted.
When you use scripting elements in a JSP file, you should know when they are
evaluated. Declarations are processed at HTTP translation time and are available to other
declarations, expressions, and scriptlets in the compiled JSP file. Expressions are also
evaluated at HTTP translation time. The value of each expression is converted to a String
and inserted in place in the compiled JSP file. Scriptlets, however, are evaluated at request
processing time, using the values of any declarations and expressions that are made
available to them.

JSP Expressions
A JSP expression is used to insert Java values directly into the output. It has the
following syntax:
<%= Java Expression %>
The Java expression is evaluated, converted to a string, and inserted in the page. This
evaluation is performed at run-time (when the page is requested), and thus has full access
to information about the request.
For example, the following shows the date/time that the page was requested:
Current time: <%= new java.util.Date() %>
To simplify these expressions, there are a number of predefined variables that you can
use. The most important ones are:
request, the HttpServletRequest;
response, the HttpServletResponse;
session, the HttpSession associated with the request (if any); and
out, the PrintWriter (a buffered version of type JspWriter) used to send output
to the client.
Heres an example:
<%
Document : ExpressionDemo.jsp
Author : J.B.Patel
%>

<%@page contentType=text/html pageEncoding=UTF-8%>


<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>JSP Expression Demo</title>
</head>
<body>
<p> Addition of three nos (1,2,3): <%= 1+2+3 %> </p>
</body>
</html>
Output:

The XML syntax of JSP expression is:


<jsp:expression>
Java Expression
</jsp:expression>
Remember that XML elements are case sensitive. So be sure to use lowercase.

JSP Scriplets
A scriptlet tag is used to execute java source code in JSP. If you want to do something
more complex than insert a simple expression, JSP scriptlets let you insert arbitrary code
into the servlet method that will be built to generate the page. Scriptlets have the following

syntax:
<% Java Code %>
Scriptlets have access to the same automatically defined variables as expressions. So,
for example, if you want output to appear in the resultant page, you would use the out
variable.
Example: Using scriplet tag
<%
Document : ScripletDemo.jsp
Author : J.B.Patel
%>
<%@page contentType=text/html pageEncoding=UTF-8%>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>JSP Scriplet Demo</title>
</head>
<body>
<p> <% out.print(This is Java Code inside JSP Page); %> </p>
</body>
</html>
Output:

Note that code inside a scriptlet gets inserted exactly as written and any static HTML
(template text) before or after a scriptlet gets converted to print statements. This means
that scriptlets need not contain complete Java statements, and blocks left open can affect
the static HTML outside of the scriptlets.
Example: JSP containing mixed HTML and scriptlets
<%
Document : ScripletDemo2.jsp
Author : J.B.Patel
%>
<%@page contentType=text/html pageEncoding=UTF-8 language=java%>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>JSP Scriplet Demo2</title>
</head>
<body>
<p> <%!int age=23;%>
<% if (age < 18) { %>
You can not <B>Vote</B> baby!
<% } else { %>
Welcome to <B>voting club</B> Dear!
<% } %>
</p>
</body>
</html>

Output:

The XML equivalent of <% Code %> is:


<jsp:scriptlet>
Code
</jsp:scriptlet>

JSP Declarations
A JSP declaration lets you define methods or fields that get inserted into the main body
of the servlet class (outside of the service method processing the request). It has the
following synntax:
<%! Java Code %>
Since declarations do not generate any output, they are normally used in conjunction
with JSP expressions or scriptlets.
Example: Using declaration tag in JSP
<%
Document : DeclarationDemo.jsp
Author : J.B.Patel
%>
<%@page contentType=text/html pageEncoding=UTF-8%>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>

<title>JSP Declaration Demo</title>


</head>
<body>
<%! int a=1;int b=2;int c=3; %>
<p> Multiplication of three nos (1,2,3): <%= a*b*c %> </p>
</body>
</html>
Output:

The XML equivalent of <%! Code %> is:


<jsp:declaration>
Code
</jsp:declaration>

JSP Directives
A JSP directive affects the overall structure of the servlet class. It usually has the
following syntax:
<%@ directive attribute=value %>
You can also combine multiple attribute settings for a single directive, as follows:
<%@ directive attribute1=value1 attribute2=value2 attributeN=valueN %>
The XML equivalent of defining directives is:
<jsp:directive.directiveType attribute=value />
For example, the XML equivalent of
<%@ page import=java.util.* %>

is
<jsp: directive.page import=java.util.* />
There are two main types of JSP directive:
Page Directove
Used to ets you do things like import classes, customize the servlet
superclass, and the like.
Include Directive
Used to insert a file into the servlet class at the time the JSP file is
translated into a servlet.
JSP page Directive
The page directive lets you define one or more of the following case-sensitive
attributes:
Attribute
Import
To
specify
what
packages
should be
imported.
The
import
attribute
is
the
only one
that is

Syntax

Example

import=package.class
<%@ page import=java.util.*
or import=package.class1, %>
,package.classN.

allowed
to appear
multiple
times.
contentType

contentType=MIME-

<%@

page

To
specify
the
MIME

Type or
contentType=text/plain %>
contentType=MIME-Type; Same effect as the scriptlet
charset=Character-Set
<%
response.setContentType(text/plain);

type of
the
output.

%>

The
default is
text/html.
isThreadSafe=true|false
A value of false indicates that the servlet should implement
SingleThreadModel, with requests either delivered serially or with simultaneous
requests being given separate servlet instances.
session=true|false
A value of true (the default) indicates that the predefined variable session (of
type HttpSession) should be bound to the existing session if one exists;
otherwise a new session should be created and bound to it.
A value of false indicates that no sessions will be used, and attempts to access
the variable session will result in errors at the time the JSP page is translated
into a servlet.
buffer=sizekb|none
This specifies the buffer size for the JspWriter out. The default is serverspecific, but must be at least 8kb.
autoflush=true|false
A value of true, the default, indicates that the buffer should be flushed when it is
full.
A value of false, indicates that an exception should be thrown when the buffer
overflows. A value of false is illegal when also using buffer=none.
extends=package.class

This indicates the superclass of servlet that will be generated.


info=message.
*

This defines a string that can be retrieved via the getServletInfo method.

errorPage=url.
*

This specifies a JSP page that should process any Throwables thrown but not
caught in the current page.

isErrorPage=true|false.
*

This indicates whether or not the current page can act as the error page for
another JSP page. The default is false.

language=java.
*

To specify the underlying language being used.

Predefined Variables/implicit objects


Implicit objects are created by the web container and contain information related to a
particular request, page, or application. To simplify code in JSP expressions and scriptlets,
you are supplied with eight automatically defined variables, sometimes called implicit
objects. The available variables are request, response, out, session, application, config,
pageContext, and page.
Variable

Description

request

This is the HttpServletRequest object associated with the request


and lets you access request parameters (via getParameter() method),
the request type (GET, POST, HEAD, etc.), and the incoming HTTP
headers (cookies, Referer, etc.).

response

This is the HttpServletResponse associated with the response to


the client. Note that, since the output stream is buffered, it is legal to
set HTTP status codes and response headers, even though this is not
permitted in regular servlets once any output has been sent to the

client.
out

This is the PrintWriter object used to send output to the client.


You can adjust the buffer size through use of the buffer attribute of the
page directive. Also note that out is used almost exclusively in
scriptlets, since JSP expressions automatically get placed in the output
stream, and thus rarely need to refer to out explicitly.

session

This is the HttpSession object associated with the request.


Sessions are created automatically, so this variable is bound even if
there was no incoming session reference except you turn off in page
directive. In this case attempts to reference the session variable cause
errors at the time the JSP page is translated into a servlet.

application

This
is
the
ServletContext
getServletConfig().getContext().

config

as

obtained

via

This is the ServletConfig object for this page.

pageContext

To encapsulate use of server-specific features like higher


performance JspWriters. The idea is that, if you access them through
this class rather than directly, your code will still run on regular
servlet/JSP engines

page

This is simply a synonym for this, and is not very useful in Java. It
was created as a placeholder for the time when the scripting language
could be something other than Java.

Example: Using predefined request variable


HTMLForm.html
<html>
<body>
<form action=ImplicitObjectDemo.jsp>
<P> Enter Your Name: <input type=text name=uid> </p>

<p> Enter email: <input type=text name=email> </p>


<input type=submit value=Ok><br/>
</form>
</body>
</html>
</html>
ImplicitObjectDemo.jsp
<%
Document : ImplicitObjectDemo.jsp
Author : J.B.Patel
%>
<%@page contentType=text/html pageEncoding=UTF-8 language=java%>
<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
<title>JSP Implicit Object</title>
</head>
<body>
<%
String name=request.getParameter(username);
String email=request.getParameter(email);
out.print(Welcome +username);
out.print(<br/>Your email is: +email);
%>
</body>

</html>
Output:

After submitting user information:

JSP Databse Access


I will be using MySQL as databse to work with JSP.
Create databse
Create databse in MySQL as:
CREATE DATABASE STUDENTS
Create Table
Now create table inside the databse in MySQL as:
CREATE TABLE STUDENTS.`studentinfo` (
`RollNo` INT NOT NULL ,
`Name` VARCHAR( 50 ) NOT NULL
);
Insert Records in the table

Create few records in Student table as follows:


INSERT INTO `Students`.`studentinfo` (`RollNo`, `Name`) VALUES (1, Jainik),
(2, Krinal);
Displaying Database Records Using JSP
Here is an example which shows how to access Students database using JSP.
DatabaseAccess.jsp
<%@ page language=java import=java.sql.*%>
<html>
<head> <title>Displaying Records from MYSQL Database </title> </head>
<body>

<p align=center><b>Records from the studentinfo table.</b><br> </p>

<div align=center width=85%>
<center>
<table border=1 borderColor=#ffe9bf cellPadding=0 cellSpacing=0
width=658 height=63>

<% String DRIVER = com.mysql.jdbc.Driver;
Class.forName(DRIVER).newInstance();
Connection con=null;
ResultSet rst=null;
Statement stmt=null;
try{
String url=jdbc:mysql://localhost/students;

int i=1;

con=DriverManager.getConnection(url,root,);
stmt=con.createStatement();
rst=stmt.executeQuery(SELECT * FROM studentinfo);
if (rst.next()) {
%>
<TABLE BORDER=1 BGCOLOR=C0C0C0>
<TH WIDTH=200 BGCOLOR=white> <I>Roll No</I> </TH>
<TH WIDTH=100 BGCOLOR=white> <I>Name</I> </TH>
<TR> <TD ALIGN=CENTER> <%= rst.getInt(1) %> </TD>
<TD ALIGN=CENTER> <%= rst.getString(2) %> </TD>
</TR>
<% while (rst.next()) {
%>
<TR> <TD ALIGN=CENTER> <%= rst.getInt(1) %> </TD>
<TD ALIGN=CENTER> <%= rst.getString(2) %> </TD>
</TR>

<% }
%>
</TABLE>
<% }
else {
%>
<P> Sorry, the query returned no rows! </P>

<%
}

rst.close();
stmt.close();
} catch (SQLException e) {
out.println(<P> + There was an error doing the query:);
out.println (<PRE> + e + </PRE> \n <P>);
}
%>

</table>
</center>

</body>
Output:
Before running this servlet care following:
Copy
mysql-connector-java-5.1.34-bin.jar
file
to
C:\Program
Files\Java\jdk1.8.0_25\jre\lib\ext folder
Set classpath to include servlet-api.jar file and mysql-connector-java-5.1.34bin.jar file.
set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25\
set PATH=%JAVA_HOME%;%PATH%
set
CLASSPATH=.;D:\apache-tomcat-8.0.15\lib\servlet-api.jar;
C:\Program
Files\Java\jdk1.8.0_25\jre\lib\ext\ mysql-connector-java-5.1.34-bin;D:\apache-tomcat8.0.15\lib\jsp-api.jar;D:\apache-tomcat-8.0.15\lib\el-api.jar;
D:\apache-tomcat8.0.15\webapps\JSPDemo; %classpath%

Syntax Summary
JSP
Element
JSP
Expression

Syntax

<%=
expression
%>

Interpretation

Notes

Expression
is
XML equivalent is
evaluated and placed <jsp:expression>
in output.
expression
</jsp:expression>.
Predefined

variables

are

request, response, out, session,


application,
config,
and
pageContext
(available
in
scriptlets also).
JSP
Scriptlet

<%
code %>

JSP
<%!
Declaration code %>

JSP

<%@

Code is inserted in
service method.

XML equivalent is
<jsp:scriptlet>
code
</jsp:scriptlet>.

Code is inserted in
XML equivalent is
body of servlet class, <jsp:declaration>
outside of service code
method.
</jsp:declaration>.
Directions to the

XML equivalent is

page
Directive

page
att=val
%>

servlet engine about <jsp:directive.page att=val\>.


general setup.
Legal attributes, with default
values in bold, are:
import=package.class
contentType=MIME-Type
isThreadSafe=true|false
session=true|false
buffer=sizekb|none
autoflush=true|false
extends=package.class
info=message
errorPage=url
isErrorPage=true|false
language=java

JSP
include
Directive

<%@
include
file=url
%>

A file on the local


system to be included
when the JSP page is
translated into a
servlet.

XML equivalent is
<jsp:directive.include
file=url\>.
The URL must be a relative one.
Use the jsp:include action to
include a file at request time
instead of translation time.

<%

Comment; ignored

If you want a comment in the

JSP
Comment

comment when JSP page is resultant HTML, use regular


%>
translated into servlet. HTML comment syntax of <
comment >.

Short Questions and Answers


What is JSP?
JavaServer Pages is server side component in a web application, used to dynamically

generate HTML / XML documents. JSP allows the java code dynamically embedded
within a web page like HTML and gets executed when the page is served by the server.
After the page is served, the dynamic content is sent to the client. With the script, the page
is run on the server before it reaches to the client. JSP are used to invoke the built-in
functionalities. In addition to the HTML, the JSP technology adds a tag library which
provides a platform independent extending capabilities of a web server.
What is JSP and why do we need it?
JSP stands for JavaServer Pages. JSP is java server side technology to create dynamic
web pages. JSP is extension of Servlet technology to help developers create dynamic
pages with HTML like syntax.
We can create user views in servlet also but the code will become very ugly and error
prone. Also most of the elements in web page are static, so JSP page is more suitable for
web pages. We should avoid business logic in JSP pages and try to use it only for view
purpose. JSP scripting elements can be used for writing java code in JSP pages but its best
to avoid them and use JSP action elements, JSTL tags or custom tags to achieve the same
functionalities.
One more benefit of JSP is that most of the containers support hot deployment of JSP
pages. Just make the required changes in the JSP page and replace the old page with the
updated jsp page in deployment directory and container will load the new JSP page. We
dont need to compile our project code or restart server whereas if we make change in
servlet code, we need to build the complete project again and deploy it. Although most of
the containers now provide hot deployment support for applications but still its more
work that JSP pages.
What are the JSP lifecycle phases?
If you will look into JSP page code, it looks like HTML and doesnt look anything like
java classes. Actually JSP container takes care of translating the JSP pages and creates the
servlet class that is used in web application. JSP lifecycle phases are:
1. Translation JSP container checks the JSP page code and parses it to generate
the servlet source code. For example in Tomcat you will find generated servlet
class files at <tomcat>/WEBAPP/org/apache/jsp directory. If the JSP page
name is home.jsp, usually the generated servlet class name is home_jsp and file
name is home_jsp.java
2. Compilation JSP container compiles the jsp class source code and produce

class file in this phase.


3. Class Loading Container loads the class into memory in this phase.
4. Instantiation Container invokes the no-args constructor of generated class to
load it into memory and instantiate it.
5. Initialization Container invokes the init method of JSP class object and
initializes the servlet config with init params configured in deployment
descriptor. After this phase, JSP is ready to handle client requests. Usually from
translation to initialization of JSP happens when first request for JSP comes but
we can configure it to be loaded and initialized at the time of deployment like
servlets using load-on-startup element.
6. Request Processing This is the longest lifecycle of JSP page and JSP page
processes the client requests. The processing is multi-threaded and similar to
servlets and for every request a new thread is spawned and ServletRequest and
ServletResponse object is created and JSP service method is invoked.
7. Destroy This is the last phase of JSP lifecycle where JSP class is unloaded
from memory. Usually it happens when application is undeployed or the server
is shut down.
What are JSP lifecycle methods?
JSP lifecycle methods are:
1. jspInit(): This method is declared in JspPage and its implemented by JSP
container implementations. This method is called once in the JSP lifecycle to
initialize it with config params configured in deployment descriptor. We can
override this method using JSP declaration scripting element to initialize any
resources that we want to use in JSP page.
2. _jspService(): This is the JSP method that gets invoked by JSP container for
each client request by passing request and response object. Notice that method
name starts with underscore to distinguish it from other lifecycle methods
because we cant override this method. All the JSP code goes inside this
method and its overridden by default. We should not try to override it using
JSP declaration scripting element. This method is defined in HttpJspPage
interface.
3. jspDestroy(): This method is called by container when JSP is unloaded from

memory such as shutting down application or container. This method is called


only once in JSP lifecycle and we should override this method to release any
resources created in JSP init method.
Which JSP lifecycle methods can be overridden?
We can override jspInit() and jspDestroy() methods using JSP declaration scripting
element. We should override jspInit() methods to create common resources that we would
like to use in JSP service method and override jspDestroy() method to release the common
resources.
Explain how a JSP is compiled into servlets by the container.
JSPs are compiled into JavaServlets by the JSP container. A JSP compiler may
generate a servlet in java code that is compiled by the java compiler or the bytecode may
be generated directly for the servlet. JSP directives control the compilation process of a
JSP that generates a servlet. Tomcat web server provides the JSP compilation as a task of
ANT tool. The JSP compiled servlets are stored by ANT in work folder of
CATALINA_HOME
Explain the categories of JSP tags - Directives, Scripting elements, Actions
Directives
The directive tags are used for simple java programming calls like importing
packages, specifying the error handling pages or to handle session in a JSP
page.
The directive tags are:
Page: To provide information about the type of page.
Include: To include another JSP.
Taglib: To specify / utilizes the custom tags [user defined tags] in the JSP.
Scripting Elements:
A scriplet tag is used to place a valid java code. This code is placed in the
jspService() method by the JSP engine.
Actions:
Actions are the core part of a JSP. An action can be printing an expression from
the scriplet or even creating and persisting a bean. Scriplets, declarations,
expressions, forwarding a page, handling bean properties, creating a bean for

the page comprises all the actions that are part of the JSP.
What are different types of comments in JSP?
JSP pages provide two types of comments that we can use:
HTML Comments: Since JSP pages are like HTML, we can use HTML
comments like < HTML Comment >. These comments are sent to client
also and we can see it in HTML source. So we should avoid any code level
comments or debugging comments using HTML comments.
JSP Comments: JSP Comments are written using scriptlets like <% JSP
Comment %>. These comments are present in the generated servlet source
code and doesnt sent to client. For any code level or debugging information
comments we should use JSP comments.
What are Scriptlet, Expression and Declaration in JSP?
Scriptlets, Expression and Declaration are scripting elements in JSP page using which
we can add java code in the JSP pages.
A scriptlet tag starts with <% and ends with %>. Any code written inside the scriptlet
tags go into the _jspService() method. For example;
<%
Date d = new Date();
System.out.println(Current Date=+d);
%>
Since most of the times we print dynamic data in JSP page using out.print() method,
there is a shortcut to do this through JSP Expressions. JSP Expression starts with <%= and
ends with %>.
<% out.print(Jitendra); %> can be written using JSP Expression as <%= Jitendra
%>
Notice that anything between <%= %> is sent as parameter to out.print() method. Also
notice that scriptlets can contain multiple java statements and always ends with semicolon
(;) but expression doesnt end with semicolon.
JSP Declarations are used to declare member methods and variables of servlet class.
JSP Declarations starts with <%! and ends with %>.

For example we can create an int variable in JSP at class level as <%! public static int
count=0; %>.
What is JSP Expression Language and what are its benefits?
Most of the times we use JSP for view purposes and all the business logic is present in
servlet code or model classes. When we receive client request in servlet, we process it and
then add attributes in request/session/context scope to be retrieved in JSP code. We also
use request params, headers, cookies and init params in JSP to create response views.
We can use scriptlets and JSP expressions to retrieve attributes and parameters in JSP
with java code and use it for view purpose.
What are JSP implicit objects?
JSP implicit objects are created by container while translating JSP page to Servlet
source to help developers. We can use these objects directly in scriptlets that goes in
service method; however we cant use them in JSP Declaration because that code will go
at class level.
We have 8 implicit objects that we can directly use in JSP page. Seven of them are
declared as local variable at the start of _jspService() method whereas one of them are part
of _jspService() method argument that we can use.
1. out Object
2. request Object
3. response Object
4. config Object
5. application Object
6. session Object
7. pageContext Object
8. page Object
Can we use JSP implicit objects in a method defined in JSP Declaration?
No we cant because JSP implicit objects are local to service method and added by JSP
Container while translating JSP page to servlet source code. JSP Declarations code goes
outside the service method and used to create class level variables and methods and hence
cant use JSP implicit objects.

Which implicit object is not available in normal JSP pages?


JSP exception implicit object is not available in normal JSP pages and its used in JSP
error pages only to catch the exception thrown by the JSP pages and provide useful
message to the client.
How do we configure init params for JSP?
We can configure init params for JSP similar to servlet in web.xml file, we need to
configure JSP init params with servlet and servlet-mapping element. The only thing differs
from servlet is jsp-file element where we need to provide the JSP page location.
Why use of scripting elements in JSP is discouraged?
JSP pages are mostly used for view purposes and all the business logic should be in the
servlet or model classes. We should pass parameters to JSP page through attributes and
then use them to create the HTML response in JSP page.
Most part of the JSP page contains HTML code and to help web designers to easily
understand JSP page and develop them, JSP technology provides action elements, JSP EL,
JSP Standard Tag Library and custom tags that we should use rather than scripting
elements to bridge the gap between JSP HTML part and JSP java part.

Exercise
1. What is JSP technology?
2. What is JSP page?
3. What are the implicit objects?
4. How many JSP scripting elements and what are they?

Table of Contents
Advanced JAVA
Copyright Reserved by the Author
PREFACE
Unit I JAVA Applets
Concept of Applet Programming
Designing a Web page
Short Questions and Answers
Exercise
Unit II Introduction of Abstract Window Toolkit: (AWT)
Working with Windows and AWT
Working with frame windows
Working with graphics: AWT controls
Layout Managers
Event Handling in Java
Event Classes and Listener Interfaces
GUI with Swing
Short Questions and Answers
Exercise
Unit III Java Data Base Client/ Server
Java as a Database front end Database client/server methodology
JDBC Architecture
Common JDBC Components
JDBC Database Example
Current JDBC Drivers
Advantages Using JDBC
Limitations Using JDBC
Security Considerations
Short Questions and Answers
Exercise
Unit IV Servlets
Introduction to Web
Introduction to Servlet
The Life Cycle Of a Servlet
Servlet Container
Installing Servlets
The Servlet API
Reading Servlet Parameters
Reading Initialization Parameters
Handling HTTP Requests and responses
Session Tracking
Reading and displaying Records using servlet
Short Questions and Answers
Exercise
Unit V Java Server Pages: (JSP)

JSP technology
JSP page
Relation of Applets and Servlets with JSP
Comments in JSP
Simple JSP program
JSP Scripting Elements
JSP Expressions
JSP Scriplets
JSP Declarations
JSP Directives
Predefined Variables/implicit objects
JSP Databse Access
Short Questions and Answers
Exercise

You might also like