0% found this document useful (0 votes)
26 views139 pages

Advanced Java Programming: Chapter 1 - Abstract Windowing Toolkit (AWT)

The document provides an overview of the Abstract Windowing Toolkit (AWT) in Java, detailing its role in developing GUI applications with platform-dependent components. It covers key AWT classes, including Component, Container, Window, Frame, and Panel, along with their methods and functionalities. Additionally, it discusses creating windowed programs and applets, as well as various AWT controls like labels, buttons, and checkboxes.

Uploaded by

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

Advanced Java Programming: Chapter 1 - Abstract Windowing Toolkit (AWT)

The document provides an overview of the Abstract Windowing Toolkit (AWT) in Java, detailing its role in developing GUI applications with platform-dependent components. It covers key AWT classes, including Component, Container, Window, Frame, and Panel, along with their methods and functionalities. Additionally, it discusses creating windowed programs and applets, as well as various AWT controls like labels, buttons, and checkboxes.

Uploaded by

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

Advanced Java Programming

Chapter 1 - Abstract Windowing Toolkit (AWT)


Introduction

Java AWT (Abstract Windowing Toolkit) is an API for developing GUI or window-based
applications in Java.

AWT components in Java are platform-dependent, meaning the components are displayed
according to the view of the operating system.

AWT is considered "heavyweight" because its components utilize system resources.

Java's AWT provides a broad set of reusable GUI components, such as buttons,
textfields, labels, panels, and frames, for building GUI applications.

AWT consists of twelve packages, but typically only two are commonly used: java.awt

and java.awt.event .

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.

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

The AWT classes are contained in the java.awt package. It is one of Java's largest
packages.

The commonly used of Java AWT classes are given below:

Class Description

AWTEvent Encapsulates AWT events.

Manages border layout with five areas:


BorderLayout
North, South, East, West, and Center.

Button Creates a push button control.

Manages card layout, displaying only one


CardLayout
component (like an index card) at a time

Checkbox Creates a checkbox control.

CheckboxGroup Creates a group of check box controls.

Choice Creates a pop-up list.

A subclass of Component that can hold


Container
other components.

Dialog Creates a dialog window.

Event Encapsulates events.

Advanced Java Programming 1


Class Description

FileDialog Creates a window for file selection.

Positions components in a left-to-right,


FlowLayout
top-to-bottom flow layout.

Creates a standard window with a title


Frame
bar, resize corners, and a menu bar.

TextArea Creates a multiline edit control.

TextField Creates a single-line edit control.

Creates a window with no frame and no


Window
menu bar.

Component, Container, Window, Frame, and Panel

The Java AWT (Abstract Windowing Toolkit) contains fundamental classes used for
constructing GUIs.

Component , Container , Window , Frame , and Panel are the fundamental elements in AWT.

Hierarchy of Java AWT classes:

Commonly used elements in AWT Hierarchy class are explained as follows:

1. Object:

The Object class is the topmost class in Java and the parent of all other
classes by default.

Every Java class is directly or indirectly derived from the Object class.

The widely used methods of Object class are:

Method Description

Returns the string


String toString() representation of this
object.

Called by the garbage


void finalize() throws Throwable collector before an object is
garbage collected.

2. Component:

The Component class is at the top of the AWT hierarchy. It is an abstract class
that encapsulates the attributes of a visual component.

All UI elements displayed on the screen and interacting with the user are
subclasses of Component .

It is responsible for remembering foreground and background colors and the


selected text font.

The widely used methods of Component class are:

Advanced Java Programming 2


Method Description
void add(Component c) Adds a component to another component.
void setSize(int width, int
Sets the size of the component.
height)

void setLayout(LayoutManager m) Sets the layout manager for the component.

Sets the visibility of the component (default is


void setVisible(boolean b)
false ).

void remove(Component c) Removes a component.

void setBounds(int x, int y, int Sets the location and size of a component (useful when
width, int height) no layout manager is applied).

3. Container:

The Container class, a subclass of Component , has additional methods that allow
nesting of Component objects.

It organizes its contained components using layout managers.

This class inherits methods from the java.awt.Component and java.lang.Object .

Method Description
void setFont(Font f) Sets the font of this container.

Sets the layout manager for this


void setLayout(LayoutManager mgr)
container.

4. Panel:

The Panel class is a concrete subclass of Container . It doesn’t add any new
methods; it simply implements Container .

It represents a simple screen component without a title bar, menu bar, or


border. Other components can be added to a Panel using the add() method
(inherited from Container ).

5. Window:

The Window class creates a top-level window that is not contained within any
other object.

Typically, Window objects are not created directly; instead, a subclass called
Frame is commonly used.

6. Frame:

The Frame class represents a top-level window with a title bar, menu bar,
borders, and resizing corners.

The widely used methods of Frame class are:

Method Description
void setTitle(String title) Sets the title of the frame.
void setBackground(Color bgColor) Sets the background color of the frame.

Frame Class

In Java, we can create standalone AWT-based applications by creating instances of


windows within the main() method.

A Frame is a top-level window with a title bar, which includes an icon, title text,
and buttons for minimizing, maximizing/restoring, and closing the window.

It can optionally contain a menu bar and a content display area.

There are two commonly used constructors for creating Frame objects:

1. Frame() : This constructor creates a standard frame window without a title.

Frame frame = new Frame();

Advanced Java Programming 3


2. Frame(String title) : This constructor creates a frame window with a specified title.

Frame frame = new Frame("My Application Window");

The Frame class inherits methods and properties from several classes in the AWT
class hierarchy:

1. java.awt.Window

2. java.awt.Container

3. java.awt.Component

4. java.lang.Object

There are two ways to create a Frame through program. They are:

1. By Instantiating Frame class:

import java.awt.*;

public class Main {


Main() {
Frame fm = new Frame();
Label lb = new Label("Hare Krishna!!");
lb.setBounds(10, 10, 50, 50);
fm.add(lb);
fm.setSize(300, 300);
fm.setVisible(true);
}

public static void main(String args[]) {


new Main();
}
}

2. By extending Frame class:

import java.awt.*;

public class Main extends Frame{


Main() {
Label lb = new Label("Hare Krishna!!");
lb.setBounds(10, 10, 50, 50);
add(lb);
setSize(300, 300);
setVisible(true);
}

public static void main(String args[]) {


Main main = new Main();
}
}

Panel Class

The Panel class is the simplest container in Java AWT.

It provides a space where an application can add other components, including


additional panels.

By default, Panel uses FlowLayout as its layout manager, which arranges components in
a left-to-right flow.

Advanced Java Programming 4


Example:

import java.awt.*;

public class Main {


Main() {
Frame f = new Frame("Panel Example");
Panel panel = new Panel();

panel.setBounds(50, 100, 200, 200);


panel.setBackground(Color.RED);

f.add(panel);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}

public static void main(String args[]) {


new Main();
}
}

Creating Windowed programs and Applets

In the previous section, we covered creating a Frame and a Panel . A frame window
created by the programmer has a title bar that includes three buttons: Minimize,
Maximize, and Close. While the Minimize and Maximize buttons work automatically,
the Close button requires additional code to function properly.

One way to address this is by creating a frame window inside an applet. To use
applet programming, we need to extend the Applet class.

An applet is a small program that runs within a larger environment, such as an


applet viewer or a Java-enabled web browser. It depends on this environment to
provide the context in which it runs.

Below are the main methods of the Applet class, each contributing to the applet's
lifecycle:

1. init() : This method initializes the applet. The browser calls this method before
any other method. It’s used to set up objects, initialize variables, and set
background and foreground colors for the applet GUI.

2. : After init() , this method makes the applet active, allowing it to use
start()

processor time. This method is called whenever the applet needs to start or
resume running.

3. paint(Graphics g) : This method is where drawing operations are done. It takes a


Graphics object as a parameter, enabling the programmer to include graphics,
animations, and other visual content.

4. : This method is called when the applet becomes inactive, for example, if
stop()

the user navigates away. An applet can repeatedly enter and leave this state.
This method is ideal for code that pauses or cleans up resources temporarily.

5. : Called just before the applet is garbage collected, this method marks
destroy()

the end of the applet’s lifecycle. It is best suited for final cleanup code,
similar to the "dead" state of a thread.

Example:

The following program demonstrates creating an applet with two classes, SampleFrame

and AppletFrame . Here:

SampleFrame extends the Frame class.

Advanced Java Programming 5


AppletFrame extends the Applet class and creates an instance of SampleFrame within its
init() method.

The start() and stop() methods of AppletFrame control the visibility of SampleFrame ,
showing it when the applet becomes active and hiding it when inactive. This setup
ensures the window appears when the browser returns to the applet.

import java.applet.Applet;
import java.awt.Frame;
import java.awt.Graphics;

public class AppletFrame extends Applet {


SampleFrame f;

public void init() {


f = new SampleFrame("A Frame Window");
f.setSize(250, 250);
f.setVisible(true);
}

public void start() {


f.setVisible(true);
}

public void stop() {


f.setVisible(false);
}

public void paint(Graphics g) {


g.drawString("This is in the applet window", 10, 20);
}
}

class SampleFrame extends Frame {


SampleFrame(String title) {
super(title);
}

public void paint(Graphics g) {


g.drawString("This is in the frame window", 10, 40);
}
}

AWT Controls

In Java, controls are components that allow users to interact with the application
in various ways.

These controls provide the most common ways for users to give instructions to a
program.

AWT (Abstract Window Toolkit) supports various types of controls:

1. Labels

2. Buttons

3. CheckBox

4. CheckBoxGroup (Radio Button)

5. Choice Controls

6. Lists

Advanced Java Programming 6


7. Scroll Bars

8. Text Field

9. Text Area

Labels

A label is the simplest control in Java, used to display a single line of read-only
text.

It is an object of the Label class, which contains the string to be displayed.

Labels are passive controls, meaning they do not interact with the user.

Constructors of the Label Class:

1. Label() : Creates an initially empty label.

2. : Creates a label that contains the specified string. The string


Label(String strLabel)

is left-justified.

3. Label(String strLabel, int alignment) : Creates a label with the given text string and
alignment. The possible alignments are:

Label.LEFT

Label.CENTER

Label.RIGHT

Methods of the Label Class:

1. String getText() : Returns the text displayed by the label.

2. void setText(String strLabel) : Sets the text of the label to the specified string.

3. int getAlignment() : Returns the alignment of the text (left, center, or right).

4. void setAlignment(int alignment) : Sets the alignment of the text (left, center, or
right).

Example:

import java.awt.*;

class Main extends Frame {


Main() {
setLayout(null);
setVisible(true);
setSize(500, 300);
setTitle("Label Example");

Label one = new Label("Label One");


Label two = new Label("Label Two");
Label three = new Label("Label Three");

one.setBounds(50, 50, 100, 100);


two.setBounds(150, 50, 100, 100);
three.setBounds(250, 50, 100, 100);

add(one);
add(two);
add(three);
}

public static void main(String[] args) {


new Main();

Advanced Java Programming 7


}
}

Buttons

The Button class is used to create a push button control that generates an ActionEvent

when it is clicked or pressed.

A push button is a component containing a label, and it can generate an event when
pressed.

Constructors of Button Class:

1. Button() : Constructs a button with an empty label.

2. Button(String buttonLabel) : Constructs a button with the given label.

Methods of Button Class:

1. String getLabel() : Returns the label of this button instance.

2. void setLabel(String buttonLabel) : Sets the label of this button instance.

3. void setEnabled(boolean enable) : Enables or disables the button. A disabled button cannot
be clicked.

4. : Adds the specified action listener to receive


void addActionListener(ActionListener l)

action events from this button.

5. : Removes the specified action listener so it no


void removeActionListener(ActionListener l)

longer receives action events from this button.

6. void setActionCommand(String command) : Sets the command name for the action event fired by
this button.

7. String getActionCommand() : Returns the command name of the action event fired by this
button.

Example:

import java.awt.*;

class Main extends Frame {


Button ok, cancel;

Main() {
setLayout(null);
setVisible(true);
setSize(500, 300);
setTitle("Button Example");

ok = new Button("OK");
cancel = new Button("Cancel");

ok.setBounds(50, 50, 50, 50);


cancel.setBounds(120, 50, 100, 50);

add(ok);
add(cancel);
}

public static void main(String[] args) {


new Main();
}
}

CheckBox

Advanced Java Programming 8


A checkbox is a control that allows the user to toggle between two options: on
(true) or off (false).

It consists of a small box that can contain a checkmark or be empty, and it is


typically used with a label that describes the option it represents.

The state of the checkbox can be changed by clicking on it.

Checkboxes can be used individually or in groups. In Java, checkboxes are


represented by the Checkbox class.

Constructors of Checkbox Class:

1. Checkbox() : Creates a checkbox with an empty string as its label.

2. Checkbox(String label) : Creates a checkbox with the specified label.

3. : Creates a checkbox with the specified label and sets


Checkbox(String label, boolean state)

its state (checked or unchecked).

4. Checkbox(String label, boolean state, CheckboxGroup group) : Creates a checkbox with the specified
label, sets its state, and adds it to a specified checkbox group.

5. : Creates a checkbox with the specified


Checkbox(String label, CheckboxGroup group, boolean state)

label, adds it to a specified checkbox group, and sets its state.

Methods of Checkbox Class:

1. String getLabel() : Returns the label of this checkbox.

2. boolean getState() : Returns the state of the checkbox (true for checked, false for
unchecked).

3. void setLabel(String label) : Sets the label of this checkbox to the specified string.

4. void setState(boolean state) : Sets the state of the checkbox to the specified value
(true or false).

5. : Adds the specified item listener to receive item


void addItemListener(ItemListener l)

events from this checkbox.

6. : Removes the specified item listener so it no longer


void removeItemListener(ItemListener l)

receives item events from this checkbox.

Example:

import java.awt.*;

public class Main extends Frame {


Checkbox cb1, cb2, cb3, cb4, cb5;

Main() {
setLayout(null);
setVisible(true);
setSize(300, 300);
setTitle("Checkbox Example");

cb1 = new Checkbox("C", false);


cb1.setBounds(50, 50, 150, 30);
add(cb1);

cb2 = new Checkbox("C++", false);


cb2.setBounds(50, 80, 150, 30);
add(cb2);

cb3 = new Checkbox("Java", false);


cb3.setBounds(50, 110, 150, 30);
add(cb3);

Advanced Java Programming 9


cb4 = new Checkbox("JavaScript", false);
cb4.setBounds(50, 140, 150, 30);
add(cb4);

cb5 = new Checkbox("Python", false);


cb5.setBounds(50, 170, 150, 30);
add(cb5);
}

public static void main(String args[]) {


new Main();
}
}

CheckBoxGroup (Radio Button)

The CheckboxGroup class in Java is used to group checkboxes together in such a way that
only one checkbox from the group can be selected at any given time.

This behavior is similar to radio buttons, where selecting one automatically


deselects the others in the group.

Constructors of CheckboxGroup Class:

1. CheckboxGroup() : Creates a new instance of CheckboxGroup .

Methods of CheckboxGroup Class:

1. Checkbox getSelectedCheckbox() : This method returns the checkbox currently selected in


the group.

2. void setSelectedCheckbox(Checkbox checkbox) : This method sets the specified checkbox as the
selected one in the group.

Example:

import java.awt.*;

public class Main extends Frame {


Checkbox cb1, cb2, cb3;
CheckboxGroup group;

Main() {
setLayout(null);
setVisible(true);
setSize(300, 300);
setTitle("Radio Buttons Example");

group = new CheckboxGroup();

cb1 = new Checkbox("Male", false, group);


cb1.setBounds(50, 50, 150, 30);
add(cb1);

cb2 = new Checkbox("Female", false, group);


cb2.setBounds(50, 80, 150, 30);
add(cb2);

cb3 = new Checkbox("Other", false, group);


cb3.setBounds(50, 110, 150, 30);
add(cb3);
}

Advanced Java Programming 10


public static void main(String args[]) {
new Main();
}
}

Choice Controls

The Choice class in Java is used to create a pop-up menu or a drop-down list from
which the user can select an item.

This component is often used when you want to display multiple options but want to
conserve space on the screen when the menu is not being interacted with.

Constructors of Choice Class:

1. Choice() : Creates an empty choice box (drop-down menu).

Methods of Choice Class:

1. void addItem(String item) : Adds a new item to the drop-down list.

2. int countItems() : Returns the number of items in the choice list.

3. String getItem(int index) : Retrieves the item at the specified index in the list.

4. int getSelectedIndex() : Returns the index of the currently selected item in the list.

5. String getSelectedItem() : Returns the text of the currently selected item in the list.

6. : Selects the item at the specified position (index) in the list


void select(int pos)

as the default or currently selected item.

7. : Highlights and selects the first item in the list that matches
void select(String str)

the provided string ( str ).

Example:

import java.awt.*;

public class Main extends Frame {


Choice choice;

Main() {
setLayout(null);
setVisible(true);
setSize(300, 200);
setTitle("Choice Example");

choice = new Choice();


choice.setBounds(50, 50, 150, 30);
choice.addItem("Vrindavan");
choice.addItem("Mayapur");
choice.addItem("Jangannath Puri");
choice.addItem("Dwarka");
add(choice);
}

public static void main(String args[]) {


new Main();
}
}

Lists

The List class in Java provides a scrollable list for selecting one or more items.

Advanced Java Programming 11


It allows for displaying multiple items in a list, and users can either select one
or multiple items based on the configuration.

It is more flexible than the Choice class, which only displays a single selected
item.

Constructors of List Class:

1. List() : Creates a new scrolling list with a default number of visible lines.

2. : Creates a new scrolling list with the specified number of visible


List(int rows)

lines ( rows ).

3. : Creates a new scrolling list with a specified number


List(int rows, boolean multipleMode)

of visible lines ( rows ) and enables multiple selection mode if multipleMode is


true .

Methods of List Class:

1. void add(String item) : Adds the specified item to the end of the list.

2. void add(String item, int index) : Adds the specified item at the given index in the list.

3. : Adds the specified ActionListener to receive action


void addActionListener(ActionListener l)

events when an item is selected or an action occurs on the list.

4. : Adds the specified ItemListener to receive item events


void addItemListener(ItemListener l)

(like selection or deselection) from this list.

5. : Returns an array of indexes of the selected items in the


int[] getSelectedIndexes()

list (useful in multiple selection mode).

6. : Returns the index of the currently selected item in the list


int getSelectedIndex()

(only applicable in single selection mode).

7. String getSelectedItem() : Returns the text of the currently selected item in the list.

8. : Returns an array of selected items in the list (useful in


String[] getSelectedItems()

multiple selection mode).

9. void clear() : Clears the list, removing all items.

Example:

import java.awt.*;

public class Main extends Frame {


List list;

Main() {
setLayout(null);
setVisible(true);
setSize(300, 200);
setTitle("List Example");

list = new List(4, true);


list.setBounds(50, 50, 100, 100);
list.add("Java");
list.add("C++");
list.add("Python");
list.add("JavaScript");
list.add("Ruby");
add(list);
}

public static void main(String args[]) {


new Main();

Advanced Java Programming 12


}
}

Scroll Bars

The Scrollbar class in Java is used to create a scrollbar that allows users to select
a value from a range.

Scrollbars can be either horizontal or vertical and are often used to scroll
through a large set of items or adjust a value within a specified range.

The thumb or slider of the scrollbar indicates the current value relative to the
minimum and maximum values.

Constructors of Scrollbar Class:

1. Scrollbar() : Creates a new scrollbar (horizontal orientation by default).

2. Scrollbar(int style) : Creates a scrollbar with the specified orientation. You can set
the orientation to either Scrollbar.HORIZONTAL or Scrollbar.VERTICAL .

3. : Creates a scrollbar with the


Scrollbar(int style, int initialValue, int thumbSize, int min, int max)

specified orientation, initial value, thumb size, and range. This constructor
allows you to set:

style : Orientation ( Scrollbar.HORIZONTAL or Scrollbar.VERTICAL ).

initialValue : The starting value of the scrollbar.

thumbSize : The size of the thumb (slider).

min : The minimum value of the scrollbar.

max : The maximum value of the scrollbar.

Methods of Scrollbar Class:

1. int getMaximum() : Returns the maximum value that the scrollbar can report.

2. int getMinimum() : Returns the minimum value that the scrollbar can report.

3. : Sets the current position of the scrollbar (the value of the


void setValue(int value)

thumb) to the specified value.

4. : Resets the scrollbar by adjusting


void setValues(int value, int visible, int minimum, int maximum)

its current value, the visible size of the scrollbar, and the minimum and
maximum values.

5. int getValue() : Returns the current value of the scrollbar.

Example:

import java.awt.*;

class Main extends Frame {


Scrollbar sb;

Main() {
setLayout(null);
setVisible(true);
setSize(400, 400);
setTitle("Scrollbar Example");

sb = new Scrollbar(Scrollbar.VERTICAL, 0, 2, 0, 100);


sb.setBounds(100, 100, 20, 250);
add(sb);
}

public static void main(String[] args) {


new Main();

Advanced Java Programming 13


}
}

When you click on the arrow buttons (at the top or bottom of the scrollbar), the
scrollbar moves by one unit at a time.

When you click inside the scrollbar (the track area between the arrows), the
scrollbar thumb (slider) moves one "page" at a time. This is known as the block
increment. (In this example, it is 10)

Text Field

The TextField class is used in Java for creating a single-line text entry field,
usually called as an edit control.

It is part of the java.awt package and is a subclass of TextComponent .

This class is used for allowing users to input and edit text in graphical user
interfaces (GUIs).

Constructors of TextField Class:

1. : Constructs a TextField instance with no initial text but with


TextField(int columns)

the specified number of columns, which determines its width.

2. : Constructs a TextField instance with the specified initial


TextField(String initialText)

text but without defining the width.

3. : Constructs a TextField instance with the specified


TextField(String initialText, int columns)

initial text and a set number of columns to define the width of the text field.

Methods of TextField Class:

1. String getText() : Retrieves the current text content of the TextField .

2. void setText(String text) : Sets the text content displayed on the TextField to the
specified string.

3. void setEditable(boolean editable) :


Allows you to set whether the TextField should be editable or not.

true : Makes the TextField editable (default).

false : Makes the TextField read-only (non-editable).

4. : Adds an action listener to the


void addActionListener(ActionListener listener) TextField that
listens for action events (such as pressing the "Enter" key).

5. void removeActionListener(ActionListener listener) : Removes a previously added action listener,


so it no longer listens for events from the TextField .

Example:

import java.awt.*;

public class Main extends Frame {


TextField tf;

Main() {
setLayout(null);
setSize(300, 200);
setVisible(true);
setTitle("TextField Example");

tf = new TextField("Hare Krishna!");


tf.setBounds(50, 20, 200, 50);
add(tf);
}

Advanced Java Programming 14


public static void main(String[] args) {
new Main();
}
}

Text Area

The TextArea class is part of AWT and provides a multi-line area for text input,
which can be used for handling large amounts of text that may exceed the visible
area.

The TextArea control can automatically display scrollbars when the content exceeds
the viewable space.

Constructors of TextArea Class:

1. TextArea() : Constructs a new text area with an empty string as text.

2. : Constructs a new text area with the specified number of


TextArea(int rows, int columns)

rows and columns, and an empty string as text.

3. TextArea(String text) : Constructs a new text area with the specified text.

4. TextArea(String text, int rows, int columns) : Constructs a new text area with the specified
text, rows, and columns.

5. : Constructs a new text area with the


TextArea(String text, int rows, int columns, int scrollbars)

specified text, rows, columns, and scrollbar visibility. The scrollbars parameter
can be:

SCROLLBARS_BOTH : Display both vertical and horizontal scrollbars.

SCROLLBARS_HORIZONTAL_ONLY : Display only the horizontal scrollbar.

SCROLLBARS_NONE : Do not display any scrollbars.

SCROLLBARS_VERTICAL_ONLY : Display only the vertical scrollbar.

Methods of TextArea Class:

1. void setColumns(int columns) : Sets the number of columns for this text area.

2. int getColumns() : Returns the number of columns in the text area.

3. void setRows(int rows) : Sets the number of rows for this text area.

4. int getRows() : Returns the number of rows in the text area.

5. void insert(String str, int pos) : Inserts the specified text at the specified position in
this text area.

6. void append(String str) : Appends the given text to the text area's current text.

7. : Replaces the text between the specified


void replaceRange(String str, int start, int end)

start and end positions with the provided replacement text.

Example:

import java.awt.*;

public class Main extends Frame {


TextArea ta;

Main() {
setLayout(null);
setSize(400, 300);
setVisible(true);

ta = new TextArea("Hare Krishna!", 5, 30, TextArea.SCROLLBARS_BOTH);


ta.setBounds(50, 50, 300, 150);
add(ta);

Advanced Java Programming 15


}

public static void main(String[] args) {


new Main();
}
}

Use of Layout Managers

Layout refers to how components are arranged within a container. The Layout Manager
automatically handles this task.

The layout manager is set using the setLayout() method. If not set, the default layout
manager is used.

When a container is resized, the layout manager positions components inside it.

Syntax of setLayout() :

void setLayout(LayoutManager lm)

Java provides five predefined layout managers in the java.awt package:

1. FlowLayout: Arranges components in rows of variable length.

2. BorderLayout: Places components on the sides and in the center.

3. CardLayout: Displays components as cards, showing one at a time.

4. GridBagLayout: Aligns components in a flexible grid with varying sizes.

5. GridLayout: Arranges components in fixed rows and columns.

FlowLayout

FlowLayout is the default layout manager, arranging components from left to right, top
to bottom, similar to how text flows in a text editor.

When there is no space for a component on the current line, it moves to the next
line.

A small gap is maintained between components, both horizontally and vertically.

Constructors of FlowLayout Class:

1. FlowLayout() – Creates a new FlowLayout with centered alignment and a default 5-


unit gap.

2. FlowLayout(int align) – Creates a new FlowLayout with the specified alignment and a
default 5-unit gap. Alignments: FlowLayout.LEFT , FlowLayout.RIGHT , or FlowLayout.CENTER .

3. – Creates a new FlowLayout with the specified


FlowLayout(int align, int hgap, int vgap)

alignment and horizontal and vertical gaps.

Methods of FlowLayout Class:

1. int getAlignment() – Gets the alignment of the layout.

2. int getHgap() – Gets the horizontal spacing.

3. int getVgap() – Gets the vertical spacing.

4. int setAlignment(int) – Sets the alignment of the layout.

5. int setHgap(int) – Sets the horizontal spacing.

6. int setVgap(int) – Sets the vertical spacing.

Example:

import java.awt.*;

public class Main extends Frame {

Advanced Java Programming 16


Button btn1, btn2, btn3, btn4, btn5, btn6;

public Main() {
setLayout(new FlowLayout());

btn1 = new Button("Button 1");


add(btn1);

btn2 = new Button("Button 2");


add(btn2);

btn3 = new Button("Button 3");


add(btn3);

btn4 = new Button("Button 4");


add(btn4);

btn5 = new Button("Button 5");


add(btn5);

btn6 = new Button("Button 6");


add(btn6);

setTitle("FlowLayout Demo");
setSize(200, 150);
setVisible(true);
}

public static void main(String[] args) {


new Main();
}
}

BorderLayout

The BorderLayout class provides a layout manager that arranges components in five
regions: North, South, East, West, and Center.

The four edges have fixed-width components, and the center region takes up the
remaining space.

Constructors of BorderLayout Class:

1. BorderLayout() : Creates a new layout manager without spacing between the regions.

2. BorderLayout(int hgap, int vgap) : Creates a new layout manager with the specified
horizontal ( hgap ) and vertical ( vgap ) spacing. By default, vgap and hgap are set
to 0.

Methods of BorderLayout Class:

1. int getHgap() : Gets the horizontal spacing between regions.

2. int getVgap() : Gets the vertical spacing between regions.

3. void setHgap(int hgap) : Sets the horizontal spacing between regions.

Advanced Java Programming 17


4. void setVgap(int vgap) : Sets the vertical spacing between regions.

Example:

import java.awt.*;

public class Main extends Frame {


Button btnNorth, btnSouth, btnCenter, btnEast, btnWest;

public Main() {
setLayout(new BorderLayout(3, 3));

btnNorth = new Button("NORTH");


add(btnNorth, BorderLayout.NORTH);

btnSouth = new Button("SOUTH");


add(btnSouth, BorderLayout.SOUTH);

btnCenter = new Button("CENTER");


add(btnCenter, BorderLayout.CENTER);

btnEast = new Button("EAST");


add(btnEast, BorderLayout.EAST);

btnWest = new Button("WEST");


add(btnWest, BorderLayout.WEST);

setTitle("Border Layout Demo");


setSize(400, 250);
setVisible(true);
}

public static void main(String[] args) {


new Main();
}
}

GridLayout

GridLayout arranges components in a two-dimensional grid.

The number of rows and columns is defined when the GridLayout manager is created.

Components are placed from left to right in each row and top to bottom in each
column.

Constructors of GridLayout Class:

1. GridLayout() : Creates a GridLayout manager with the default number of rows and
columns.

Advanced Java Programming 18


2. GridLayout(int rows, int cols) : Creates a GridLayout manager with the specified number of
rows and columns.

3. : Creates a GridLayout manager with the


GridLayout(int rows, int cols, int hgap, int vgap)

specified number of rows and columns, along with horizontal and vertical
spacing. By default, rows=1, cols=0, hgap=0, vgap=0.

Methods of GridLayout Class:

1. int getColumns() : Gets the number of columns in the layout.

2. int getHgap() : Gets the horizontal spacing between components.

3. int getRows() : Gets the number of rows in the layout.

4. int getVgap() : Gets the vertical spacing between components.

5. int setColumns(int cols) : Specifies the number of columns in the layout.

6. int setHgap(int hgap) : Specifies the horizontal spacing between components.

7. int setRows(int rows) : Specifies the number of rows in the layout.

8. int setVgap(int vgap) : Specifies the vertical spacing between components.

Example:

import java.awt.*;

public class Main extends Frame {


Button btn1, btn2, btn3, btn4, btn5, btn6;

public Main() {
setLayout(new GridLayout(2, 3, 3, 3));

btn1 = new Button("Button 1");


add(btn1);

btn2 = new Button("Button 2");


add(btn2);

btn3 = new Button("Button 3");


add(btn3);

btn4 = new Button("Button 4");


add(btn4);

btn5 = new Button("Button 5");


add(btn5);

btn6 = new Button("Button 6");


add(btn6);

setTitle("GridLayout Demo");
setSize(300, 200);
setVisible(true);
}

public static void main(String[] args) {


new Main();
}
}

Advanced Java Programming 19


CardLayout

The CardLayout manager arranges components as cards, displaying one card at a time.

Components are shown in the order they are added.

Only one card is visible at a time, and the container acts as a stack of cards.

Constructors of CardLayout Class:

1. CardLayout() : Creates a new layout manager with no spacing between components.

2. : Creates a new layout manager with the specified


CardLayout(int hgap, int vgap)

horizontal ( hgap ) and vertical ( vgap ) spacing.

Methods of CardLayout Class:

1. void first(Container container) : Displays the first component in the specified container.

2. int getHgap() : Gets the horizontal spacing between components.

3. int getVgap() : Gets the vertical spacing between components.

4. void last(Container container) : Displays the last component in the specified container.

5. void next(Container container) : Displays the next component in the specified container.

6. void previous(Container container) : Displays the previous component in the specified


container.

7. void setHgap(int hgap) : Specifies the horizontal spacing between components.

8. void setVgap(int vgap) : Specifies the vertical spacing between components.

Example:

import java.awt.*;

class Main extends Frame {


CardLayout card = new CardLayout(20, 20);

Main() {
setTitle("CardLayout Example");
setSize(300, 200);
setVisible(true);
setLayout(card);

Button first = new Button("First");


Button second = new Button("Second");
Button third = new Button("Third");

add(first, "Card1");
add(second, "Card2");
add(third, "Card3");
}

public static void main(String args[]) {


new Main();

Advanced Java Programming 20


}
}

GridBagLayout

The GridBagLayout layout manager is powerful and flexible, but it is more complicated
to use than other layout managers.

GridBagLayout arranges components in a rectangular grid, similar to GridLayout .

Unlike GridLayout , components in GridBagLayout can have different sizes and can span
multiple rows or columns.

It requires a lot of information to position components. This is provided by the


GridBagConstraints class.

GridBagConstraints specifies how to:

Position components

Distribute space among components

Resize and align components

Each component in a GridBagLayout has its own GridBagConstraints object associated with it.

Instance Variables of GridBagConstraints :

Variable Role

Coordinates of the component's position in the grid


gridx, gridy
(default: RELATIVE ).

Define how many cells the component will occupy


gridwidth, gridheight (default: 1). REMAINDER specifies that the component
will be the last in a row or column.

Defines how to resize a component if it is smaller


fill than the grid cell. Possible values: NONE ,
HORIZONTAL , VERTICAL , BOTH .

Used to define horizontal and vertical padding


ipadx, ipady
(default: (0, 0) ).

Defines how the component should be aligned within


the cell when it is smaller than the cell. Possible
anchor
values: NORTH , NORTHWEST , NORTHEAST , SOUTH ,
SOUTHWEST , SOUTHEAST , WEST , EAST .

Defines how space is distributed if the container


weightx, weighty
size changes.

Example:

import java.awt.*;

class Main extends Frame {


Main() {
Label lb1 = new Label("Name");
TextField tf = new TextField(10);
Label lb2 = new Label("Comments");
TextArea ta = new TextArea(6, 15);

Advanced Java Programming 21


Button bt = new Button("Submit");

setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();

add(lb1, gc, 0, 0, 1, 1, 0, 0);


add(tf, gc, 1, 0, 1, 1, 0, 20);
add(lb2, gc, 0, 1, 1, 1, 0, 0);
add(ta, gc, 1, 1, 1, 1, 0, 60);
add(bt, gc, 0, 2, 2, 1, 0, 20);

setTitle("GridBagLayout Example");
setSize(400, 300);
setVisible(true);
}

void add(Component comp, GridBagConstraints gc, int x, int y, int w, int h, in


t wx, int wy) {
gc.gridx = x;
gc.gridy = y;
gc.gridwidth = w;
gc.gridheight = h;
gc.weightx = wx;
gc.weighty = wy;
add(comp, gc);
}

public static void main(String args[]) {


new Main();
}
}

Menu Bars and Menus

A top-level window can have a menuBar associated with it.

A menuBar displays a list of top-level menu choices. Each choice is associated with a
dropdown menu.

Hierarchy of Menu:

Menu Controls:

Advanced Java Programming 22


Control Description

It is the top-level class for all menu-related


MenuComponent
controls.

The MenuBar object is associated with the top-


MenuBar
level window.

The items in the menu must belong to the


MenuItem
MenuItem class or any of its subclasses.

The Menu object is a pull-down menu component,


Menu
which is displayed from the menu bar.

CheckboxMenuItemis a subclass of MenuItem and is


CheckboxMenuItem
used for items that can be toggled on or off.

A PopupMenu can be dynamically popped up at a


PopupMenu
specified position within a component.

Steps for Creating Menus:


- Step 1: Create the menu bar.
- Step 2: Add the menu bar to the frame.
- Step 3: Create menus.
- Step 4: Add menus to the menu bar.

- Step 5: Create menu items.


- Step 6: Add menu items to menus.
- Step 7: Event handling.

Menu Bar

In general, a menuBar contains one or more Menu objects. Each Menu object contains a
list of MenuItem objects, where each MenuItem represents an option that the user can
select.

Since Menu is a subclass of MenuItem , a hierarchy of nested submenus can be created.

It is also possible to include checkable menu items, which are menu options of type
CheckboxMenuItem . These options will have a checkmark next to them when selected.

Steps to Create a MenuBar :

1. Create an instance of the MenuBar class.

2. Create instances of the Menu class that define the selections displayed on the
bar.

Constructors of MenuBar Class and Menu Class:

Constructor Description

MenuBar() Creates a menu bar.

Menu() Creates a default menu.

Creates a menu with the


Menu(String name)
specified name.

If tearOff is true, the menu


Menu(String name, Boolean tearOff) can be torn off as a separate
window.

Example:

import java.awt.*;

public class Main extends Frame {


Main() {
MenuBar mBar = new MenuBar();
setMenuBar(mBar);

Advanced Java Programming 23


Menu colors = new Menu("Colors");
Menu exit = new Menu("Exit");

mBar.add(colors);
mBar.add(exit);

setTitle("Menu Demo");
setSize(400, 400);
setVisible(true);
}

public static void main(String args[]) {


new Main();
}
}

Menu

The Menu class represents a pull-down menu component, which is displayed from a menu
bar.

Each Menu object contains a list of MenuItem objects, and each MenuItem represents an
option that can be selected by the user.

Constructors of MenuItem Class:

Constructor Description

MenuItem() Creates a default menu item.

Creates a menu item using the


MenuItem(String itemName)
specified name.

Creates a menu item with a


MenuItem(String itemName, MenuShortcut shortcut)
specified name and shortcut.

Methods of MenuItem Class:

Method Description

Adds the specified menu item to this


MenuItem add(MenuItem mi)
menu.

Adds an item with the specified label


void add(String label)
to this menu.

Adds a separator line or a hyphen to


void addSeparator()
the menu at the current position.

Gets the item located at the specified


MenuItem getItem(int index)
index of this menu.

Returns the number of items in this


int getItemCount()
menu.

void insert(MenuItem menuItem, Inserts a menu item into this menu at


int index) the specified position.

Inserts a menu item with the specified


void insert(String label, int
label into this menu at the specified
index)
position.

Inserts a separator at the specified


void insertSeparator(int index)
position.

Indicates whether this menu is a tear-


boolean isTearOff()
off menu.

Removes the menu item at the specified


void remove(int index)
index from this menu.

Removes the specified menu item from


void remove(MenuComponent item)
this menu.
void removeAll() Removes all items from this menu.

Advanced Java Programming 24


CheckboxMenuItem Class

You can create a checkable menu item by using the CheckboxMenuItem class, which is a
subclass of MenuItem .

Constructors of CheckboxMenuItem Class:

1. CheckboxMenuItem()

2. CheckboxMenuItem(String itemName)

3. CheckboxMenuItem(String itemName, boolean on)

Example:

import java.awt.*;

public class Main extends Frame {


Main() {
MenuBar mb = new MenuBar();
setMenuBar(mb);

Menu files = new Menu("Colors");


Menu exit = new Menu("Exit");
mb.add(files);
mb.add(exit);

files.add(new MenuItem("RED"));
files.add(new MenuItem("GREEN"));
files.addSeparator();
files.add(new MenuItem("BLUE"));

exit.add(new MenuItem("Close"));

setTitle("Menu Demo");
setSize(400, 400);
setVisible(true);
}

public static void main(String args[]) {


new Main();
}
}

Dialog Boxes

A dialog box is a GUI object used to display messages or obtain user input.

It is commonly used to hold a set of related controls.

Dialog boxes differ from frame windows in the following ways:

Child Window: Dialog boxes are always child windows of a top-level window.

No Menu Bars: They do not have menu bars.

Types: Dialog boxes can be either modal or modeless.

1. Modal Dialog Box: When active, it restricts access to other parts of the program
until it is closed.

2. Modeless Dialog Box: When active, other parts of the program remain accessible,
allowing input focus to be directed to other windows.

Constructors of Dialog Box Class:

Advanced Java Programming 25


Constructor Description

Creates a dialog with no title and with parent


Dialog(Frame parent) as the owning Frame . It is not modal and is
initially resizable.

Creates a dialog with no title and with parent


as the owning Frame . If modal is true , it grabs
Dialog(Frame parent, boolean modal)
all user input until it is closed. Otherwise, no
special behavior is associated.

Creates a dialog with the specified title and


Dialog(Frame parent, String title) with parent as the owning Frame . It is not modal
and is initially resizable.

Creates a dialog with the specified title and


with parent as the owning Frame . If modal is
Dialog(Frame parent, String title,
true , it grabs all user input until it is
boolean modal)
closed. Otherwise, no special behavior is
associated.

Example:

import java.awt.*;

public class Main extends Dialog {


Main(Frame parent, String title) {
super(parent, title, false);

setLayout(new FlowLayout());
setSize(300, 200);
setBackground(Color.YELLOW);

Button b = new Button("Cancel");


add(b);
}

public static void main(String args[]) {


Frame fl = new Frame();
Main dd = new Main(fl, "Dialog Example");
dd.setVisible(true);
}
}

File Dialog

Java provides a built-in dialog box that allows the user to select or specify a
file.

To create a file dialog box, you can use the FileDialog class. This will show the
standard file dialog box provided by the operating system.

Constructors of FileDialog Class:

1. FileDialog(Frame parent) : This constructor creates a file dialog box for loading a
file.

2. : This constructor creates a file dialog box with


FileDialog(Frame parent, String boxName)

the specified parent frame and a title bar with the given name ( boxName ).

3. FileDialog(Frame parent, String boxName, int how)

This constructor creates a file dialog box with the specified parent frame
and title ( boxName ).

The how parameter determines the behavior of the dialog:

If how is FileDialog.LOAD , the dialog allows selecting a file for reading.

Advanced Java Programming 26


If how is FileDialog.SAVE , the dialog allows selecting a file for writing.

This allows you to easily implement file selection dialogs for both opening
and saving files in Java applications.

Example:

import java.awt.*;

class SampleFrame extends Frame {


SampleFrame(String title) {
super(title);
}
}

class Main {
public static void main(String args[]) {
Frame f = new SampleFrame("File Dialog Demo");

f.setVisible(true);
f.setSize(100, 100);

FileDialog fd = new FileDialog(f, "File Dialog");


fd.setVisible(true);
}
}

Chapter 2 - Swing
Introduction to Swing

Swing is a Java foundation classes library and an extension to Abstract Windowing


Toolkit (AWT).

Swing is part of Java Foundation Classes (JFC).

Swing provides a pluggable look and feel for components.

It offers lightweight components for designing user interfaces.

Swing supplies several additional components like tabbed panes, scroll panes,
trees, and tables.

Swing buttons can have both an image and a text string associated with them.

Swing components are platform-independent, as they are written entirely in Java.

Swing components are considered "lightweight" because they are not implemented with
platform-specific code.

Class Hierarchy of the Swing GUI classes:

A component represents an object with a graphical representation.

Advanced Java Programming 27


A container is a component that can hold other Swing components.

JComponent is the base class for all Swing UI components.

To use a Swing component that inherits from JComponent, it must be part of a


containment hierarchy, with a top-level Swing container as the root.

Swing Features

Lightweight: Swing components are independent of the native Operating System's API.
They are mostly rendered using pure Java code instead of OS-specific calls.

Rich Controls: Swing provides advanced controls like trees, tabbed panes, sliders,
color pickers, and tables.

Borders: You can add different styles of borders around components using the
setBorder() method.

Easy Mouseless Operation: It's simple to connect keystrokes (keyboard shortcuts) to


components.

Tooltips: You can use the setToolTipText() method to add tooltips to components, which
are small windows that show explanatory text when the mouse hovers over a
component.

Easy Scrolling: Swing allows easy scrolling for components, which was not possible
in AWT.

Pluggable Look and Feel: You can change the appearance of your app to match one of
three standard looks: Windows, Motif (Unix), or Metal (the default Swing look).

MVC Architecture

Swing uses the Model-View-Controller (MVC) paradigm, making it possible to create


more flexible user interfaces.

MVC architecture is the design foundation for all Swing components, separating
common features of GUI applications:

Data access (usually through a database)

Business logic (how data is used)

User interaction (how data and actions are presented visually)

MVC Architecture:

Components in MVC architecture:

1. Model: Manages the data, retrieving and manipulating it.

2. View: Represents the visual interface components of the GUI that interact with
the user. It reacts to user events such as mouse clicks and key presses.

3. Controller: Connects the Model and View. It controls the logic of the
application by associating user events with data actions.

Interactions in MVC:

1. User events start in the View, and the Controller listens for these events. The
Controller can update the View in response.

2. The Controller interacts with the Model to either request data or update it
based on user events.

3. The Model provides an interface for the Controller to interact with the database
or data source. The Controller doesn't interact directly with the database.

Advanced Java Programming 28


4. The View communicates with the Model only for type information or data
abstractions, with minimal interaction because data manipulation occurs within
the Controller's event handlers.

Difference between AWT and Swing

AWT Swing

AWT stands for Abstract Windowing Swing is also called Java Foundation
Toolkit. Classes (JFC).

Swing components require javax.swing


AWT components require java.awt package.
package.

AWT components are platform-dependent. Swing components are platform-independent.

AWT components are heavyweight. Swing components are lightweight.

AWT does not support pluggable look and


Swing supports pluggable look and feel.
feel.

Swing provides more powerful components


AWT provides fewer components. such as tables, scroll panes, color
chooser, tabbed panes, etc.

Swing follows the MVC architecture, where


AWT does not follow MVC (Model-View- Model represents data, View represents
Controller). presentation, and Controller acts as an
interface between Model and View.

Working with Swing

The main window in Swing is known as the top-level container.

The top-level container is the root of a hierarchy, containing all other Swing
components in the window.

Every Swing application must have at least one top-level container.

Every top-level container has an intermediate container called the content pane.

The content pane holds all visible components in the GUI window.

The content pane is the base pane upon which all other components or container
objects are placed.

Exception: If there is a menu bar in the top-level container, it will be placed


outside the content pane.

All Swing component names start with the letter "J".

Example: The Swing button class is named JButton.

Top-Level Containers in Swing:

1. JFrame: Used for the application's main window, including:

An icon, title, minimize/maximize/close buttons, optional menu-bar, and


content-pane.

2. JDialog: Used for secondary pop-up windows, including:

A title, close button, and content-pane.

Advanced Java Programming 29


3. JApplet: Used for displaying applets inside a browser window, including a
content-pane.

Secondary Containers:

Similar to AWT, Swing has secondary containers such as JPanel.

Panels are used to group and layout relevant components and are considered
intermediate containers.

Advantages and Disadvantages of Swing

Advantages:

Swing offers paint debugging support to help when creating your own components.

Swing components are lighter than AWT components.

Swing follows the Model-View-Controller (MVC) design, making the UI more flexible.

Swing provides additional components like JTable and JTree, along with improved
functionality compared to AWT.

Swing includes built-in double buffering, improving performance.

Disadvantages:

Swing can be slower than AWT if not programmed carefully because all components are
drawn.

Swing components may not behave exactly like native components, even though they
look similar.

Swing requires Java 2 or a separate JAR file to run.

Swing Components

Swing components are written entirely in Java and do not rely on platform-specific
code, making them platform-independent.

All Swing components start with the letter J (e.g., JButton , JLabel ).

Swing components are called lightweight because they do not depend on any non-Java
system classes.

Swing components have their own view and are supported by Java's look and feel
classes.

Swing supports pluggable look and feel, allowing the same set of components to have
a consistent appearance across different operating systems.

JFrame

A JFrame is a top-level container or window in a Swing application, where other


components are placed.

JFrame extends the java.awt.Frame class.

Every JFrame object has a root pane.

Constructors of JFrame Class:

1. JFrame() : Creates a new frame without a title.

2. JFrame(String title) : Constructs a new frame with a specified title.

Methods of JFrame Class:

1. getContentPane() : Returns the content pane for the JFrame.

2. setLayout(LayoutManager) : Sets the LayoutManager for the JFrame.

3. setJMenuBar(JMenuBar) : Sets the JMenuBar for the JFrame.

4. setIconImage(Image image) : Sets an icon image for the JFrame.

There are two way to create a JFrame Window:

Advanced Java Programming 30


1. By instantiating JFrame class:

import javax.swing.*;
import java.awt.*;

public class Main {


JFrame jf;

Main() {
jf = new JFrame("JFrame Ex");

JButton btn = new JButton("Say Hello");


jf.add(btn);

jf.setLayout(new FlowLayout());
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(400, 400);
jf.setVisible(true);
}

public static void main(String[] args) {


new Main();
}
}

2. By extending JFrame class:

import javax.swing.*;
import java.awt.*;

public class Main extends JFrame{


Main() {
JButton btn = new JButton("Say Hello");
add(btn);

setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("JFrame Ex");
setSize(400, 400);
setVisible(true);
}

public static void main(String[] args) {


new Main();
}
}

JApplet

JApplet is a Swing class that represents applets.

It is a subclass of the Applet class and extends its functionality.

Swing applets add support for features like menu bars and layering of components,
making them more versatile than regular AWT applets.

Advanced Java Programming 31


JApplet supports various panes such as:

1. Root Pane

Swing containers like JApplet , JFrame , and JDialog rely on a JRootPane for their
structure.

The root pane includes the following:

Content Pane: Used for adding GUI components.

Layered Pane: Manages multiple layers for components.

Glass Pane: Allows drawing over existing components.

Menu Bar: Optional feature for top-level containers.

Components are added to these areas instead of directly to the root pane.

2. Content Pane

The content pane is part of the layered pane.

It is the area where most components are placed.

The content pane and menu bar are located in the Frame-Content-Layer.

3. Glass Pane

The glass pane is part of the multi-layered root pane.

It is used to draw on top of an area that already contains components,


enabling overlays or special effects.

Differences between Swing applets and Regular applets:

Components are added to the content pane of Swing applets, not directly to the
applet.

Layout managers are applied to the content pane of Swing applets.

Swing applets use BorderLayout by default, unlike regular applets that use
FlowLayout .

JLabel

JLabel is a simple Swing component used for displaying text or images.

It is commonly used to provide descriptive text for other components.

JLabel is read-only, meaning users cannot edit its content.

Constructors of JLabel Class:

Constructor Description

Creates an empty label with no text


JLabel()
or icon.

Creates a label with the specified


JLabel(String str)
text.

Creates a label with the specified


JLabel(ImageIcon i)
icon image.

Methods of JLabel Class

Method Description
void setHorizontalAlignment(int Sets the horizontal alignment of
alignment)

Advanced Java Programming 32


Method Description
the label text or image.

Returns the text associated with


String getText()
the label.
void setText(String s) Sets new text for the label.

Sets an icon (image) for the


void setIcon(Icon i)
label.

Example:

import javax.swing.*;

public class Main extends JFrame {


Main() {
setTitle("JLabel Example");
setSize(400, 300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel jl = new JLabel("Hare Krishna!");


jl.setBounds(50, 50, 100, 30);

add(jl);
}

public static void main(String[] args) {


new Main();
}
}

Icons

In Swing, many components like labels, buttons, and tabbed panes can display an
icon, which is a fixed-size picture.

An icon is an object that follows the Icon interface.

Swing provides the ImageIcon class, which implements the Icon interface.

The ImageIcon class is used to display images in formats like GIF, JPEG, or PNG.

Constructors of ImageIcon Class:

Constructor Description
ImageIcon(String filename) Creates an icon from the image file specified by the filename.
ImageIcon(URL url) Creates an icon from the image resource identified by the URL.

Methods of Icon Interface:

Method Description

Returns the height of the icon


int getIconHeight()
in pixels.

Returns the width of the icon


int getIconWidth()
in pixels.

Example:

import javax.swing.*;

public class Main {


public static void main(String[] args) {

Advanced Java Programming 33


JFrame frame = new JFrame("Icon Example");

ImageIcon icon = new ImageIcon("src/main/java/img.jpg");

JLabel label = new JLabel("This is an icon label", icon, JLabel.CENTER);

frame.add(label);
frame.setSize(250, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

JTextField

The JTextField component allows us to enter or edit a single line of text.

There are 3 constructors of the JTextField class:

1. JTextField() : Creates a new, empty text field.

2. JTextField(int columns) : Creates a new, empty text field with the specified number of
columns (width).

3. JTextField(String text) : Creates a new text field with the specified initial text.

Example:

import javax.swing.*;

public class Main extends JFrame {


Main() {
JLabel jl = new JLabel("TextField");
jl.setBounds(30, 30, 80, 30);
add(jl);

JTextField tfl = new JTextField(30);


tfl.setBounds(100, 30, 100, 30);
add(tfl);

setLayout(null);
setSize(300, 300);
setTitle("JTextField Example");
setVisible(true);
}

public static void main(String[] args) {


new Main();
}
}

JTextArea

The JTextArea component allows users to enter and edit multiple lines of text.

It has advanced features compared to the AWT text area.

JTextArea does not handle scrolling directly. Instead, it can be placed inside a
JScrollPane for scrolling functionality.

Constructors of JTextArea class:

1. JTextArea() : Creates an empty text area.

Advanced Java Programming 34


2. JTextArea(int rows, int columns) : Creates an empty text area with the given rows and
columns.

3. JTextArea(String text) : Creates a text area initialized with the given text.

4. JTextArea(String text, int rows, int columns) : Creates a text area with the given text, rows,
and columns.

Example:

import javax.swing.*;

public class Main extends JFrame {


Main() {
JLabel jl = new JLabel("TextArea");
jl.setBounds(30, 30, 80, 30);
add(jl);

JTextArea ta = new JTextArea();


ta.setBounds(100, 30, 100, 100);
add(ta);

setLayout(null);
setSize(300, 300);
setTitle("JTextField Example");
setVisible(true);
}

public static void main(String[] args) {


new Main();
}
}

Combo Boxes

A JComboBox is a Swing component that combines a text field and a dropdown list.

It allows users to:

Select an item from the dropdown list.

Type their selection directly into the text field.

JComboBox is similar to the Choice component in AWT but offers more flexibility.

Constructors of JComboBox class:

1. JComboBox() : Creates an empty combo box.

2. JComboBox(Object[] items) : Creates a combo box with items from the given array.

Example:

import javax.swing.*;

public class Main extends JFrame {


Main() {
String[] country = {"India", "Aus", "U.S.A", "England", "Australia"};

JComboBox<String> cb = new JComboBox<>(country);


cb.setBounds(50, 50, 90, 20);
add(cb);

setLayout(null);
setSize(300, 300);
setTitle("Checkbox example");

Advanced Java Programming 35


setVisible(true);
}

public static void main(String[] args) {


new Main();
}
}

JButton

The JButton class is used to create push buttons in Swing.

It is a subclass of the AbstractButton class.

Constructors of JButton Class:

1. JButton() : Creates an empty button without a label or icon.

2. JButton(String str) : Creates a button with the specified text label.

3. JButton(Icon i) : Creates a button with an image as an icon.

4. JButton(String str, Icon i) : Creates a button with both text and an icon.

Methods of JButton class:

1. void addActionListener(ActionListener obj) : Registers the button to perform an action when


clicked.

2. String getText() : Returns the text (label) on the button.

3. void setText(String s) : Sets or changes the label text of the button.

4. void setHorizontalTextPosition(int pos) : Adjusts the position of the text horizontally


relative to the icon.

5. void setVerticalTextPosition(int pos) : Adjusts the position of the text vertically relative
to the icon.

6. void setIcon(Icon i) : Sets an icon (image) for the button.

7. void setMnemonic(char c) : Sets a shortcut key (mnemonic) for the button.

Example:

import javax.swing.*;

public class Main extends JFrame {


Main() {
JButton b = new JButton("Click");
b.setBounds(100, 100, 100, 40);
add(b);

setLayout(null);
setSize(300, 300);
setTitle("JButton Example");
setVisible(true);
}

public static void main(String[] args) {


new Main();
}
}

JRadioButton

The JRadioButton class is used to create radio buttons in Swing.

These buttons allow users to select one option at a time within a group.

Advanced Java Programming 36


The buttons must be placed in a group created using the ButtonGroup class to ensure
only one is selected at any time.

Constructors of JRadioButton class:

1. JRadioButton() : Creates an empty radio button without any label or icon.

2. JRadioButton(String text) : Creates a radio button with the specified text label.

3. JRadioButton(Icon icon) : Creates a radio button with an icon image.

4. JRadioButton(String text, Icon icon) : Creates a radio button with both a text label and an
icon image.

5. JRadioButton(String text, Icon icon, boolean selected) : Creates a radio button with a text
label, an icon image, and sets the button as selected if true is passed.

6. JRadioButton(String text, boolean selected) : Creates a radio button with a text label and
specifies whether it should be selected by default.

Example:

import javax.swing.*;

public class Main extends JFrame {


Main() {
JRadioButton b1 = new JRadioButton("Male");
b1.setBounds(100, 100, 100, 40);

JRadioButton b2 = new JRadioButton("Female");


b2.setBounds(100, 130, 100, 40);

JRadioButton b3 = new JRadioButton("Other");


b3.setBounds(100, 160, 100, 40);

ButtonGroup group = new ButtonGroup();


group.add(b1);
group.add(b2);
group.add(b3);

add(b1);
add(b2);
add(b3);

setLayout(null);
setSize(300, 300);
setTitle("JRadioButton Example");
setVisible(true);
}

public static void main(String[] args) {


new Main();
}
}

JCheckBox

A checkbox is a control that allows users to turn an option ON or OFF.

The JCheckBox class in Swing is used to create and manage checkboxes.

A checkbox can display its state (selected or deselected) to the user.

Constructors of JCheckBox class:

1. JCheckBox() : Creates an empty, unselected checkbox with no text or icon.

Advanced Java Programming 37


2. JCheckBox(Icon icon) : Creates an unselected checkbox with the specified icon.

3. JCheckBox(Icon icon, boolean selected) : Creates a checkbox with the specified icon and
initial selected state.

4. JCheckBox(String text) : Creates an unselected checkbox with the specified text label.

5. JCheckBox(String text, boolean selected) : Creates a checkbox with the specified text and
initial selected state.

6. JCheckBox(String text, Icon icon) : Creates an unselected checkbox with the specified text
and icon.

7. JCheckBox(String text, Icon icon, boolean selected) : Creates a checkbox with the specified
text, icon, and initial selected state.

Example:

import javax.swing.*;

public class Main extends JFrame {


Main() {
JCheckBox b1 = new JCheckBox("Gulab Jamun");
b1.setBounds(100, 100, 150, 40);

JCheckBox b2 = new JCheckBox("Rasgulla");


b2.setBounds(100, 130, 100, 40);

JCheckBox b3 = new JCheckBox("Jalebi");


b3.setBounds(100, 160, 100, 40);

JCheckBox b4 = new JCheckBox("Kaju Katli");


b4.setBounds(100, 190, 100, 40);

add(b1);
add(b2);
add(b3);
add(b4);

setLayout(null);
setSize(300, 300);
setTitle("JCheckBox Example");
setVisible(true);
}

public static void main(String[] args) {


new Main();
}
}

Tabbed Panes (JTabbedPane)

A tabbed pane is a component that displays multiple "tabs" (like folders).

Each tab has a title, and when a user clicks on a tab, its contents are displayed.
Only one tab is visible at a time.

Tabbed panes are commonly used for configuration settings.

The JTabbedPane class is used to create tabbed panes, and it extends JComponent .

Constructors of JTabbedPane :

1. JTabbedPane()

Creates a tabbed pane with no tabs.

Advanced Java Programming 38


Tabs are placed at the top by default ( JTabbedPane.TOP ).

2. JTabbedPane(int tabPlacement)

Creates a tabbed pane with no tabs.

You can specify where the tabs are placed:

JTabbedPane.TOP : Tabs at the top (default).

JTabbedPane.BOTTOM : Tabs at the bottom.

JTabbedPane.LEFT : Tabs on the left side.

JTabbedPane.RIGHT : Tabs on the right side.

3. JTabbedPane(int tabPlacement, int tabLayoutPolicy)

Creates a tabbed pane with no tabs.

You can specify both tab placement (as above) and the layout policy:

JTabbedPane.WRAP_TAB_LAYOUT : Tabs wrap to a new row/column if there isn’t enough


space.

JTabbedPane.SCROLL_TAB_LAYOUT : Tabs can be scrolled horizontally or vertically if


there isn’t enough space.

Adding Tabs:
Tabs are added to a JTabbedPane using the method:

void addTab(String title, Component component)

title : The text label for the tab.

component : The content to display in the tab (usually a JPanel ).

Steps to Use a Tabbed Pane:

1. Create a JTabbedPane object.

2. Add tabs using addTab() for each tab.

Pass the title and the component to display in the tab.

3. Add the tabbed pane to a JFrame or another container.

Example:

import javax.swing.*;

public class Main extends JFrame {


Main() {
setSize(400, 300);
setTitle("JTabbedPane Example");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JTabbedPane tabbedPane = new JTabbedPane();

JPanel panel1 = new JPanel();


panel1.add(new JLabel("This is Whatsapp"));

JPanel panel2 = new JPanel();


panel2.add(new JLabel("This is Instagram"));

JPanel panel3 = new JPanel();


panel3.add(new JLabel("This is Linkedin"));

JPanel panel4 = new JPanel();


panel4.add(new JLabel("This is Twitter"));

Advanced Java Programming 39


tabbedPane.addTab("Whatsapp", panel1);
tabbedPane.addTab("Instagram", panel2);
tabbedPane.addTab("Linkedin", panel3);
tabbedPane.addTab("Twitter", panel4);

add(tabbedPane);
}

public static void main(String[] args) {


new Main();
}
}

JScrollPane

A scroll pane is a component that lets you display a rectangular area in which
another component can be viewed.

If the content inside the area is too large, scroll bars (horizontal and/or
vertical) will appear to help you view the hidden part.

In Swing, the JScrollPane class is used to create scroll panes.

Constructors of JScrollPane class:

1. JScrollPane(Component comp) : Creates a scroll pane with the specified component inside
it.

2. JScrollPane(int vsb, int hsb) : Creates a scroll pane where vsb and hsb are constants that
control when vertical and horizontal scroll bars should appear.

3. JScrollPane(Component comp, int vsb, int hsb) : A combination of the previous two constructors,
where both the component and the scroll bar policies are specified.

Constants in JScrollPane :

1. HORIZONTAL_SCROLLBAR_ALWAYS : Always show the horizontal scroll bar.

2. HORIZONTAL_SCROLLBAR_AS_NEEDED : Show the horizontal scroll bar only when necessary.

3. VERTICAL_SCROLLBAR_ALWAYS : Always show the vertical scroll bar.

4. VERTICAL_SCROLLBAR_AS_NEEDED : Show the vertical scroll bar only when necessary.

Steps to Use a JScrollPane :

1. Create a JComponent that you want to display inside the scroll pane.

2. Create a JScrollPane object, specifying the component and the scroll bar
policies (whether to show them always or only when needed).

3. Add the scroll pane to your applet or frame.

Example:

import javax.swing.*;
import java.awt.*;

public class Main extends JFrame {


Main() {
setLayout(new BorderLayout());

JPanel jp = new JPanel();


jp.setLayout(new GridLayout(10, 10));

int b = 1;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {

Advanced Java Programming 40


jp.add(new JButton("Button " + b));
++b;
}
}

int v = JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(jp, v, h);

add(jsp, BorderLayout.CENTER);

setSize(400, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {


new Main();
}
}

JTree

A tree is a component used to display data in a hierarchical structure, where each


item (or node) can have sub-items (or child nodes). The user can expand or collapse
these sub-items.

A good example of this is how files and folders are displayed in Windows Explorer
or File Manager. Folders are shown as branches, and subfolders are displayed below
them.

In Java, this tree-like structure can be created using the JTree class, which is a
part of the Swing library. This class allows you to display hierarchical data.

Constructors of JTree Class:

1. JTree(Hashtable ht) : Creates a tree using a hash table where each element in the
table is a node in the tree.

2. JTree(Object[] ob) : Creates a tree using an array of objects as nodes.

3. JTree(TreeNode tn) : Creates a tree with a specific root node, which is a TreeNode .

4. JTree(Vector v) : Creates a tree using a vector where each element in the vector is a
node.

Methods of JTree Class:


getPathForLocation(int x, int y) :
This method helps translate a mouse click on a specific point in the tree (given by
the x and y coordinates) into a tree path, pointing to the exact node that was
clicked.

DefaultMutableTreeNode Class:
This class is used to represent a node in the tree. By using DefaultMutableTreeNode , you
can create nodes for the root and any other data that needs to be represented in
the tree.

Constructors of DefaultMutableTreeNode Class:

1. DefaultMutableTreeNode() : Creates a node with no associated data.

2. DefaultMutableTreeNode(Object ob) : Creates a node with a specific object as its data.

3. DefaultMutableTreeNode(Object ob, boolean allowsChildren) : Creates a node that either allows or


disallows child nodes.

Methods of DefaultMutableTreeNode Class:

Advanced Java Programming 41


add(MutableTreeNode child) : Adds a child node to the tree.

Steps to Create a JTree :

1. Create a JTree object

2. Create a JScrollPane object

3. Add the tree to the scroll pane

4. Add the scroll pane to the frame

Example:

import java.awt.*;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;

public class Main {


JTree tree;
JFrame f;

Main() {
f = new JFrame();
f.setLayout(new BorderLayout());
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");

DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");


top.add(a);
DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
top.add(b);

DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");


a.add(a1);
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
a.add(a2);

DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");


b.add(b1);
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
b.add(b2);
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
b.add(b3);

tree = new JTree(top);


JScrollPane jsp = new JScrollPane(tree);
f.add(jsp, BorderLayout.CENTER);
f.setSize(500, 500);
f.setVisible(true);
}

public static void main(String[] args) {


new Main();
}
}

JTable

A JTable is a component used to display rows and columns of data in a table format.

You can resize columns by dragging their boundaries and move columns to different
positions.

Constructors of JTable class:

Advanced Java Programming 42


1. JTable(Object[][] data, Object[] columnHeads) : Creates a table with the specified data and
column headers.

2. JTable(int numRows, int numColumns) : Creates an empty table with the specified number of
rows and columns.

3. JTable(Vector rowData, Vector columnData) : Creates a table using vectors for row and column
data.

Steps to use a table in an applet:

1. Create a JTable object with your data.

2. Create a JScrollPane to make the table scrollable (define the scroll bar policies).

3. Add the table to the scroll pane.

4. Add the scroll pane to the container (applet/frame).

Example:

import javax.swing.*;

public class Main extends JFrame {


public Main() {
String[] columnNames = {"ID", "Name", "Age"};

Object[][] data = {
{1, "Jay", 25},
{2, "Rushikesh", 33},
{3, "Sanket", 36},
};

JTable table = new JTable(data, columnNames);

JScrollPane scrollPane = new JScrollPane(table);

add(scrollPane);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("JTable Example");
setSize(400, 300);
setVisible(true);
}

public static void main(String[] args) {


new Main();
}
}

JToolTip

A tooltip is a small pop-up text that appears when the mouse cursor hovers over a
component in a GUI.

It provides additional information or a brief description about that component's


functionality.

In Java Swing, tooltips can be added to almost any component using the
setToolTipText(String s) method.

Example:

import javax.swing.*;

public class Main extends JFrame {


public Main() {

Advanced Java Programming 43


JButton button = new JButton("Click Me");
button.setToolTipText("This button will print a message when clicked.");

add(button);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args) {


new Main();
}
}

JProgressBar

The JProgressBar class in Java is used to display the progress of a task visually.

It provides a graphical representation of the completion percentage of a task, and


the progress bar fills up as the task progresses.

Additionally, the progress bar can display a string or text showing the task's
current state or percentage.

Constructors of JProgressBar class:

1. JProgressBar() : Creates a horizontal progress bar without any text.

2. JProgressBar(int min, int max) : Creates a horizontal progress bar with the specified
minimum and maximum values.

3. JProgressBar(int orient) : Creates a progress bar with a specified orientation. The


orientation can either be vertical or horizontal by using the constants
SwingConstants.VERTICAL or SwingConstants.HORIZONTAL .

4. : Creates a progress bar with specified


JProgressBar(int orient, int min, int max)

orientation, minimum, and maximum values.

Methods of JProgressBar Class:

1. : This method determines whether the progress bar should


void setStringPainted(boolean b)

display a string (the task's progress). If b is true , the string will be


displayed.

2. void setString(String s) : This method is used to set the string value that will be
displayed on the progress bar (e.g., "50% complete").

3. void setOrientation(int orientation) : This method sets the orientation of the progress bar.

4. void setValue(int value) : This method sets the current value of the progress bar.

Example:

import javax.swing.*;

public class Main extends JFrame {

JProgressBar progressBar;

public Main() {
progressBar = new JProgressBar(0, 100);
progressBar.setBounds(50, 50, 300, 30);
progressBar.setStringPainted(true);

JButton button = new JButton("Start Task");


button.setBounds(150, 100, 120, 30);
button.addActionListener(e -> startTask());

Advanced Java Programming 44


setLayout(null);
add(progressBar);
add(button);
setSize(400, 200);
setTitle("JProgressBar Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

private void startTask() {


new Thread(() -> {
for (int i = 0; i <= 100; i++) {
progressBar.setValue(i);
progressBar.setString(i + "%");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}

public static void main(String[] args) {


new Main();
}
}

Chapter 3 - Event Handling


Introduction

Events represent interactions between a user and an application.

When a user interacts with the program (e.g., clicking a button), the system
generates an event.

This event is passed to the event handling code, which processes it and provides an
appropriate response.

A change in the state of an object is referred to as an event.

In Java, events are represented by Objects.

Event Classes:

Event Handling is the process of controlling events and deciding how to respond
when they occur.

Advanced Java Programming 45


It involves the use of an event handler, which is a block of code that executes
when an event happens.

For example: Clicking a button, Moving the mouse, Typing characters on the
keyboard, Selecting an item from a list, Scrolling a page.

Types of Events:

1. Foreground Events:

Require direct user interaction.

Examples:

Clicking a button.

Typing on the keyboard.

Scrolling a page.

2. Background Events:

Do not involve direct user interaction.

Examples:

Timer expiration.

System interrupts.

Hardware or software failure.

Delegation Event Model

Commonly handled events include those generated by:

Mouse actions.

Keyboard inputs.

Controls like push buttons.

Events in Java are supported by the java.awt.event package.

Both AWT and Swing components in Java use the Event Delegation Model.

In this model:

An event source generates an event.

The event is sent to one or more listeners.

The listener waits for the event, processes it when received, and then returns.

A user interface element delegates the event processing to a specific handler in


the code.

Listeners must register with the source to receive notifications about the event.

Event delegation model consists of three parts:

1. Event: Represents the action or interaction (e.g., clicking a button).

2. Source: The object that generates the event.

3. Listener: The object that processes the event after receiving it.

Events

Advanced Java Programming 46


An event is an object that describes a change in the state of a source.

It is generated when a user interacts with graphical user interface (GUI) elements.

Examples of events:

1. Pressing a button.

2. Entering a character using the keyboard.

3. Selecting an item in a list.

4. Clicking the mouse.

Source

A source is an object that generates an event (e.g., Button, Checkbox).

Event sources are subclasses of java.awt.Component , capable of producing events.

A source must register listeners to notify them about specific events.

Notifications are sent only to registered listeners.

Each type of event has its own registration method:

Syntax: public void addTypeListener(TypeListener el)

Example: addMouseMotionListener() .

When an event occurs:

All listeners are notified and receive a copy of the event (called
multicasting).

If only one listener can register, it is called unicasting.

Syntax for Unicasting: public void addTypeListener(TypeListener el) throws

TooManyListenersException

A source also allows unregistering a listener:

Syntax: public void removeTypeListener(TypeListener el)

Description of Event Sources:

Source Event Generated

Generates Action events when the button is


Button
pressed.

Generates Item events when selected or


Checkbox
deselected.

Choice Generates Item events when a choice is changed.

Generates Action events when an item is double-


List clicked; item events when an item is
selected/deselected.

Generates Action events when selected; item


Menu Item events when a checkable menu item is selected
or deselected.

Generates Adjustment events when the scrollbar


Scrollbar
is manipulated.

Generates Text events when the user enters


Text
characters.

Generates Window events for actions like


Window activation, deactivation, opening, closing,
minimizing, or quitting.

Event Listener

A listener is an object that gets notified when an event occurs.

Advanced Java Programming 47


Listeners are part of the java.awt.event package and are used to handle events from GUI
components.

Requirements of a listener:

1. Registration with a Source: A listener must register with a source to receive


notifications for specific events.

2. Implementation of Methods: It must implement methods to handle and process the


events it receives.

How it works:

A listener listens for events from a source.

When an event occurs, the source invokes the appropriate method in the listener
to handle the event.

Event Classes

Event classes in Java encapsulate events and provide a standardized way to handle
them.

Each event source generates a specific event, represented by a Java class. For
example:

A button generates an ActionEvent .

A checkbox generates an ItemEvent .

The AWTEvent class is defined in the java.awt package.

It is a subclass of EventObject .

It serves as the superclass for all AWT-based events in the delegation event model.

Types of Events:

Event Class Description

Occurs when a button is pressed, a list


ActionEvent item is double-clicked, or a menu item is
selected.

AdjustmentEvent Occurs when a scroll bar is manipulated.

Occurs when a component is hidden, moved,


ComponentEvent
resized, or becomes visible.

Advanced Java Programming 48


Event Class Description

Occurs when a component is added to or


ContainerEvent
removed from a container.

Occurs when a component gains or loses


FocusEvent
keyboard focus.

Abstract superclass for all input-related


InputEvent
event classes.

Occurs when a checkbox or list item is


ItemEvent clicked, a choice is made, or a menu item
is selected/deselected.

Occurs when a keyboard key is pressed,


KeyEvent
released, or typed.

Occurs when the mouse is dragged, moved,


MouseEvent clicked, pressed, released, or enters/exits
a component.

MouseWheelEvent Occurs when the mouse wheel is moved.

Occurs when the value in a text field or


TextEvent
text area is changed.

Occurs when a window is opened, closed,


WindowEvent activated, deactivated, minimized,
maximized, or quit.

These events are defined in the java.awt.event package and are widely used in GUI-based
applications.

ActionEvent Class

The ActionEvent class is part of the java.awt.event package.

It is used to handle actions like button presses, double-clicking a list item, or


selecting a menu item.

The ActionEvent class defines constants to identify specific modifiers during an


action event:

ALT_MASK

CTRL_MASK

META_MASK

SHIFT_MASK

Additionally, there is the constant ACTION_PERFORMED to identify the occurrence of an


action event.

Constructors of ActionEvent class:

1. ActionEvent(Object source, int id, String command)

This constructor creates an ActionEvent object with the given source, event ID,
and command.

2. ActionEvent(Object source, int id, String command, int modifiers)

This constructor creates an ActionEvent object with modifiers (e.g., ALT, CTRL).

You can obtain the command name (e.g., the label of a button) by using the
getActionCommand() method.

Syntax: String getActionCommand()

For example, when a button is pressed, the action event will have the button’s
label as its command name.

ItemEvent Class

An ItemEvent is generated when a checkbox or a list item is clicked.

The ItemEvent class defines two constants to represent the state of an item:

Advanced Java Programming 49


1. DESELECTED : The user deselected an item.

2. SELECTED : The user selected an item.

Additionally, the constant ITEM_STATE_CHANGED is used to signify that the item's state
has changed.

Methods of ItemEvent class:

1. getItem()

This method returns a reference to the item that generated the event.

Syntax: Object getItem()

2. getItemSelectable()

This method returns a reference to the ItemSelectable object (like a list or


choice) that generated the event.

Syntax: ItemSelectable getItemSelectable()

3. getStateChange()

This method returns the state change of the item (either SELECTED or DESELECTED ).

Syntax: int getStateChange()

User interface elements like lists and choices implement the ItemSelectable interface,
which allows them to generate ItemEvent objects.

KeyEvent Class

A KeyEvent is generated when there is keyboard input. It captures key actions such as
pressing, releasing, or typing a key.

There are three types of key events:

1. KEY_PRESSED : Generated when a key is pressed.

2. KEY_RELEASED : Generated when a key is released.

3. KEY_TYPED : Generated when a character is typed (this only happens when the key
press produces a character, like pressing 'A' or '1').

Not all key presses generate characters. For example, pressing the SHIFT key does
not produce a character.

The KeyEvent class defines several constants for key codes, such as:

VK_0 to VK_9 : Represents number keys 0-9.

VK_A to VK_Z : Represents letter keys A-Z.

VK_ENTER , VK_ESCAPE , VK_SHIFT , VK_CONTROL , VK_UP , VK_DOWN , VK_LEFT , VK_RIGHT , VK_PAGE_UP ,


VK_PAGE_DOWN , VK_ALT , VK_CANCEL : These represent various other special keys.

The KeyEvent class has two constructors:

1. KeyEvent(Component src, int type, long when, int modifiers, int code) - Creates a KeyEvent with the
specified parameters.

2. KeyEvent(Component src, int type, long when, int modifiers, int code, char ch) - Creates a KeyEvent with
the specified parameters and a character for the typed key.

MouseEvent Class

A MouseEvent indicates that a mouse action occurred in a component.

There are eight types of mouse events, which are identified by the following
constants:

1. MOUSE_CLICKED : The user clicked the mouse.

2. MOUSE_DRAGGED : The user dragged the mouse.

3. MOUSE_ENTERED : The mouse entered a component.

4. MOUSE_EXITED : The mouse exited a component.

Advanced Java Programming 50


5. MOUSE_MOVED : The mouse was moved.

6. MOUSE_PRESSED : The mouse button was pressed.

7. MOUSE_RELEASED : The mouse button was released.

8. MOUSE_WHEEL : The mouse wheel was moved.

Methods of MouseEvent class:

1. getX() : Returns the X coordinate of the mouse when the event occurred.

int getX()

2. getY() : Returns the Y coordinate of the mouse when the event occurred.

int getY()

3. getPoint() : Returns a Point object containing the X and Y coordinates.

Point getPoint()

TextEvent Class

The TextEvent class represents text-related events, such as when a user types or
modifies text in a text field or text area.

These events are triggered by user input or programmatic changes.

Constant: TEXT_VALUE_CHANGED indicates the text value has changed.

Constructor:

TextEvent(Object source, int type)

source : The object that triggered the event.

type : The type of the event.

The TextEvent does not directly provide the changed text. You must use methods from
the text component (like getText() ) to retrieve the updated content.

WindowEvent Class

A WindowEvent represents a change in the state of a window. It is a low-level event


generated by a Window object when certain actions occur, such as opening, closing,
or losing focus.

A WindowEvent is generated when:

A window is opened, closed, iconified, deiconified, activated, or deactivated.

Focus is transferred to or from the window.

The WindowEvent class defines the following constants to identify event types:

1. WINDOW_ACTIVATED : The window was activated.

2. WINDOW_CLOSED : The window was closed.

3. WINDOW_CLOSING : The user requested to close the window.

4. WINDOW_DEACTIVATED : The window was deactivated.

5. WINDOW_DEICONIFIED : The window was restored (deiconified).

6. WINDOW_GAINED_FOCUS : The window gained input focus.

7. WINDOW_ICONIFIED : The window was minimized (iconified).

8. WINDOW_LOST_FOCUS : The window lost input focus.

9. WINDOW_OPENED : The window was opened.

Advanced Java Programming 51


10. WINDOW_STATE_CHANGED : The window's state changed.

The most commonly used method in this class is:

getWindow() : Returns the Window object that generated the event.

Syntax:
Window getWindow()

Adapter Classes

Java provides adapter classes to simplify the creation of event handlers.

These classes offer default (empty) implementations of all methods in an event


listener interface.

Why use Adapter Classes ?

Adapter classes are helpful when you need to handle only specific events from an
event listener interface.

Instead of implementing all the methods in the listener interface, you can
extend an adapter class and override only the methods you need.

How it Works ?

1. An adapter class is a predefined class in java.awt.event that implements a listener


interface with empty method bodies.

2. You can create a new class that extends the adapter class and override only the
required methods.

3. For example, the MouseMotionAdapter class implements the MouseMotionListener interface


and provides empty definitions for:

mouseDragged()

mouseMoved()

If you are interested only in the mouseDragged() event, you can override it, while the
empty mouseMoved() method will handle other events.

Commonly Used Adapter Classes:

Adapter Class Implements Listener Interface

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

Window Adapter WindowListener

Inner Classes

An inner class is a class defined within another class.

It has a special relationship with its outer class, allowing it to access the outer
class's members (both static and non-static) as if they were its own.

Types of Inner Classes:


There are four types of inner classes in Java:

1. Member Inner Class -

Defined at the top level inside an outer class.

Can use access modifiers like public, protected, or private.

Can access all members (including private ones) of the outer class.

Example:

class OuterClass {
private String message = "Hare Krishna!!";

Advanced Java Programming 52


class MemberInner {
void display() {
System.out.println(message); // Accessing outer class member
}
}
}

public class Main {


public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.MemberInner inner = outer.new MemberInner();
inner.display();
}
}

2. Static Member Inner Class

Defined like a member inner class but marked with the static keyword.

Acts as an outer class itself, so it cannot access non-static members of the


outer class.

Accessed using the syntax: OuterClass.InnerClass

Example:

class OuterClass {
static String staticMessage = "Static Hare Krishna!!";

static class StaticInner {


void display() {
System.out.println(staticMessage); // Accessing static member
}
}
}

public class Main {


public static void main(String[] args) {
OuterClass.StaticInner inner = new OuterClass.StaticInner();
inner.display();
}
}

3. Local Inner Class

Defined within a method of the outer class.

Scope is limited to the method in which it is defined.

Can only access final or effectively final local variables of the method.

Example:

class OuterClass {
void displayMessage() {
final String localMessage = "Hare Krishna from Local Inner Class!";

class LocalInner {
void display() {
System.out.println(localMessage);
}
}

Advanced Java Programming 53


LocalInner inner = new LocalInner();
inner.display();
}
}

public class Main {


public static void main(String[] args) {
OuterClass outer = new OuterClass();
outer.displayMessage();
}
}

4. Anonymous Inner Class

An inner class without a name, created during the creation of an object.

Used once, typically for event handling or when implementing an interface.

Can extend a class or implement an interface.

Example (Extending a Class):

abstract class Greeting {


abstract void sayHello();
}

public class Main {


public static void main(String[] args) {
Greeting greeting = new Greeting() { // Anonymous inner class
@Override
void sayHello() {
System.out.println("Hare Krishna from Anonymous Inner Class!");
}
};

greeting.sayHello();
}
}

Event Listener Interfaces

The delegation event model in Java is used to handle events like mouse clicks, key
presses, etc.

It consists of two main components:

1. Event Source

The object where the event occurs (e.g., a button, text field).

It generates events and sends them to listeners.

2. Event Listener

Also called the event handler.

Responsible for responding to an event.

Created by implementing one or more interfaces from the java.awt.event package.

Event Listeners in Java:

Advanced Java Programming 54


Event Listener Interface

The listener is defined as an interface to handle specific events.

Example: MouseListener , KeyListener , ActionListener , etc.

These interfaces are part of the java.awt.event package.

Declaration of Event Listener Interface

public interface EventListener

This is the base interface for all event listener interfaces.

How It Works ?

When an event occurs, the event source invokes the corresponding method in the
listener.

The event object is passed as an argument to the method.

ActionListener Interface

The ActionListener interface is used to handle action events in Java.

It is part of the java.awt.event package.

This interface is implemented to handle events like button clicks or menu


selections.

Method of ActionListener Interface:

actionPerformed(ActionEvent ae) - This method is invoked automatically when an action event


occurs.

Example:

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

public class Main extends Frame implements ActionListener {


Button button;

public Main() {
button = new Button("Click Me");
button.setBounds(50, 100, 80, 30);

add(button);

button.addActionListener(this);

setSize(200, 200);

Advanced Java Programming 55


setLayout(null);
setVisible(true);
}

public void actionPerformed(ActionEvent ae) {


System.out.println("Button clicked!");
}

public static void main(String[] args) {


new Main();
}
}

ItemListener Interface

The ItemListener interface is used to handle item events in Java.

It is part of the java.awt.event package.

This interface is implemented to respond when the state of an item changes, such as
selecting or deselecting a checkbox or list item.

Method of ItemListener Interface:


itemStateChanged(ItemEvent ie) - This method is automatically called when the state of an
item changes.

Example:

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

public class Main extends Frame implements ItemListener {


Checkbox checkbox;

public Main() {
checkbox = new Checkbox("Accept Terms", false);
checkbox.setBounds(50, 100, 150, 30);

add(checkbox);

checkbox.addItemListener(this);

setSize(300, 200);
setLayout(null);
setVisible(true);
}

public void itemStateChanged(ItemEvent ie) {


if (ie.getStateChange() == ItemEvent.SELECTED) {
System.out.println("Checkbox selected.");
} else {
System.out.println("Checkbox deselected.");
}
}

public static void main(String[] args) {


new Main();
}
}

KeyListener Interface

Advanced Java Programming 56


The KeyListener interface is used to handle keyboard events in Java.

It is part of the java.awt.event package.

A class that processes keyboard events must implement this interface.

Methods of KeyListener interface:

1. void keyPressed(KeyEvent e) - Invoked when a key is pressed down.

2. void keyReleased(KeyEvent e) - Invoked when a key is released after being pressed.

3. void keyTyped(KeyEvent e) - Invoked when a key is typed (pressed and released)

Example:

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

public class Main extends Frame implements KeyListener {


TextField textField;
Label label;

public Main() {
textField = new TextField();
textField.setBounds(50, 100, 200, 30);
label = new Label();
label.setBounds(50, 150, 300, 20);

textField.addKeyListener(this);

add(textField);
add(label);

setSize(400, 300);
setLayout(null);
setVisible(true);
}

public void keyPressed(KeyEvent e) {


label.setText("Key Pressed: " + e.getKeyChar());
}

public void keyReleased(KeyEvent e) {


label.setText("Key Released: " + e.getKeyChar());
}

public void keyTyped(KeyEvent e) {


System.out.println("Key Typed: " + e.getKeyChar());
}

public static void main(String[] args) {


new Main();
}
}

MouseListener Interface

The MouseListener interface is used to handle mouse events in Java.

It is part of the java.awt.event package.

A class implementing this interface can respond to mouse actions like clicks,
movements, and when the mouse enters or exits a component.

Advanced Java Programming 57


Methods of MouseListener Interface:

1. void mouseClicked(MouseEvent me) - Invoked when the mouse is clicked (pressed and
released at the same point).

2. void mouseEntered(MouseEvent me) - Invoked when the mouse enters a component's boundary.

3. void mouseExited(MouseEvent me) - Invoked when the mouse exits a component's boundary.

4. void mousePressed(MouseEvent me) - Invoked when a mouse button is pressed down.

5. void mouseReleased(MouseEvent me) - Invoked when a mouse button is released.

Example:

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

public class Main extends Frame implements MouseListener {


Label label;

public Main() {
label = new Label();
label.setBounds(50, 100, 200, 30);
add(label);
setSize(400, 300);
setLayout(null);
setVisible(true);

addMouseListener(this);
}

public void mouseClicked(MouseEvent me) {


label.setText("Mouse Clicked");
}

public void mouseEntered(MouseEvent me) {


label.setText("Mouse Entered");
}

public void mouseExited(MouseEvent me) {


label.setText("Mouse Exited");
}

public void mousePressed(MouseEvent me) {


label.setText("Mouse Pressed");
}

public void mouseReleased(MouseEvent me) {


label.setText("Mouse Released");
}

public static void main(String[] args) {


new Main();
}
}

MouseMotionListener Interface

The MouseMotionListener interface is used to handle mouse motion events in Java.

It defines two methods that respond to mouse dragging and movement actions.

Methods of MouseMotionListener Interface:

Advanced Java Programming 58


1. void mouseDragged(MouseEvent me) - This method is called multiple times as the mouse is
dragged over a component.

2. void mouseMoved(MouseEvent me) - This method is called multiple times as the mouse is
moved over a component.

Example:

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

public class Main extends Frame implements MouseMotionListener {


Label label;

public Main() {
label = new Label();
label.setBounds(50, 100, 200, 30);
add(label);
setSize(400, 300);
setLayout(null);
setVisible(true);

addMouseMotionListener(this);
}

public void mouseDragged(MouseEvent me) {


label.setText("Mouse Dragged at: " + me.getX() + ", " + me.getY());
}

public void mouseMoved(MouseEvent me) {


label.setText("Mouse Moved at: " + me.getX() + ", " + me.getY());
}

public static void main(String[] args) {


new Main();
}
}

TextListener Interface

The TextListener interface is used to handle text events in Java.

It allows you to react to changes in the text contained in components such as


TextField and TextArea .

Method of TextListener Inteface:

void textValueChanged(TextEvent e) - This method is invoked whenever the text in a TextField or


TextArea is entered or edited by the user.

Example:

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

public class Main extends Frame implements TextListener {


TextField textField;
Label label;

public Main() {
textField = new TextField();
textField.setBounds(50, 100, 200, 30);
textField.addTextListener(this);

Advanced Java Programming 59


label = new Label();
label.setBounds(50, 150, 200, 30);

add(textField);
add(label);
setSize(400, 300);
setLayout(null);
setVisible(true);
}

public void textValueChanged(TextEvent e) {


label.setText("Text: " + textField.getText());
}

public static void main(String[] args) {


new Main();
}
}

WindowListener Interface

The WindowListener interface is used to receive events related to window actions, like
opening, closing, activating, or deactivating a window.

It defines seven methods, which are invoked when the corresponding event occurs.

Method of WindowListener Inteface:

1. void windowActivated(WindowEvent we) - This method is called when a window is activated


(brought to the front).

2. void windowClosed(WindowEvent we) - This method is called when a window is closed.

3. void windowClosing(WindowEvent we) - This method is called when a window is being closed,
but before it's actually closed. It allows you to handle any actions (like
prompting the user to save changes) before closing the window.

4. void windowDeactivated(WindowEvent we) - This method is called when a window is deactivated


(when it loses focus).

5. void windowDeiconified(WindowEvent we) - This method is called when a window is restored


(after being minimized or iconified).

6. void windowIconified(WindowEvent we) - This method is called when a window is minimized


(iconified).

7. void windowOpened(WindowEvent we) - This method is called when a window is opened (made
visible).

Example:

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

public class WindowEventDemo extends Frame implements WindowListener {

public WindowEventDemo() {
setSize(400, 300);
setTitle("Window Listener Example");

addWindowListener(this);

setVisible(true);
}

Advanced Java Programming 60


public void windowActivated(WindowEvent we) {
System.out.println("Window Activated");
}

public void windowClosed(WindowEvent we) {


System.out.println("Window Closed");
}

public void windowClosing(WindowEvent we) {


System.out.println("Window Closing");
System.exit(0);
}

public void windowDeactivated(WindowEvent we) {


System.out.println("Window Deactivated");
}

public void windowDeiconified(WindowEvent we) {


System.out.println("Window Restored");
}

public void windowIconified(WindowEvent we) {


System.out.println("Window Minimized");
}

public void windowOpened(WindowEvent we) {


System.out.println("Window Opened");
}

public static void main(String[] args) {


new WindowEventDemo();
}
}

Chapter 4 - Networking Basics


Introduction

Java is a programming language designed with networking in mind, making it ideal


for building network applications as the Internet grows.

Java provides solutions to problems like platform independence, security, and


international character sets, which are essential for Internet applications and
challenging for other programming languages.

Communication is a vital part of modern existence, with many resources like


printers and fax machines that need to be shared over networks.

Networks enable the sharing of expensive resources and consist of computers and
other devices that can send and receive data.

Java offers robust and simple techniques for applications to communicate across
networks and share resources.

Java communication is based on a standard client/server architecture, where a


server listens for client requests on a specific port.

Advanced Java Programming 61


Both client and server on the network need to be uniquely identified, which is
achieved using TCP/IP.

TCP/IP allows every computer, whether a client or server, to be uniquely identified


on the network.

These network features make Java well-suited for writing networked programs, as the
Internet is all about connecting machines together.

Socket Overview

Sockets provide the communication mechanism between two computers using TCP.

A client program creates a socket on its side of the communication and attempts to
connect that socket to a server.

When the connection is established, the server creates a socket object on its side
of the communication.

Once the connection is made, the client and server can communicate by reading from
and writing to the socket.

Concept of Socket

Network programming revolves around the concept of sockets, which serve as


endpoints for two-way communication between programs running on a network.

In Java, programs communicate through a programming abstraction called a socket.

A socket is a bi-directional communication channel between hosts (computers on a


network).

In Java, sockets are created using specific classes found in the java.net package.

Separate classes in the java.net package are used for creating TCP sockets and UDP
sockets.

The client socket is created using the Socket class, while the server socket is
created using the ServerSocket class.

Client/Server Networking

In client/server networking, communication between the client and server occurs


through well-established protocols.

The client makes a service request to the server, and the server responds to the
client's request.

A server provides resources that can be shared, such as computing power, printers
(print servers), disk space (disk servers), and web pages (web servers).

Advanced Java Programming 62


A client is any entity that seeks access to a specific server.

A server can accept multiple clients connected to the same port, but each session
remains unique.

To manage multiple client connections, a server process must be multithreaded or


use some other method for multiplexing simultaneous input/output.

Reserved Ports/Sockets

Once connected, a higher-level protocol is used, which depends on the port being
used.

A port serves as an endpoint for a logical connection and acts as a medium through
which an application establishes a connection with another application.

A port number identifies a specific application running on a machine. It is a 16-


bit unsigned integer ranging from 1 to 65535.

Ports are transport layer addresses used by TCP (Transmission Control Protocol) and
UDP (User Datagram Protocol) to manage communication between applications.

Port numbers are divided into three ranges:

1. Well-known ports: Reserved for specific protocols (e.g., FTP on port 21, Telnet
on port 23, HTTP on port 80).

2. Registered ports: Used by specific applications.

3. Dynamic or private ports: Used for ephemeral connections, typically assigned


dynamically.

TCP/IP reserves the lower 1,024 ports for well-known protocols, such as:

Port 21: FTP

Port 23: Telnet

Port 25: Email

Port 80: HTTP

Port 119: Net-news

Protocols like HTTP define how clients interact with these ports. For example, when
a client requests a file from an HTTP server:

It sends the file name in a predefined format to port 80.

The server responds with the contents of the file and a status code indicating
the request's success or failure.

Communication Protocols

When computers communicate over the Internet, they use either Transmission Control
Protocol (TCP) or User Datagram Protocol (UDP).

Advanced Java Programming 63


These protocols manage how data is transferred between computers.

1. Network Layer Protocols:


(i) Internet Protocol (IP):

Internet Protocol (IP) is a Layer 3 (network layer) protocol used for


transmitting data packets over the Internet.

Each computer, also known as a host, on the Internet has a unique IP address
that distinguishes it from other computers.

IP acts as a bridge, connecting networks of different types and forming a global


network of computers and subnetworks.

IP is a packet-switching network protocol, meaning data is exchanged between


hosts in the form of IP packets (or IP datagrams).

Each datagram is treated as an independent unit, not linked to any other


previously sent packet. There are no "connections" between machines at the
network layer.

During transmission, a message is divided into multiple packets, and each packet
may take a different route across the Internet.

Packets can arrive out of order, and it is the responsibility of another


protocol, Transmission Control Protocol (TCP), to reassemble the packets into
the correct order.

2. Transport Layer Protocols:


(i) TCP (Transmission Control Protocol):

TCP is a connection-based protocol that ensures a reliable flow of data between


two computers.

It provides reliable communication between applications, typically used over the


Internet Protocol (TCP/IP).

As shown in the figure, Socket is the communication interface between the


application process and TCP. The application developer controls the application
layer on the socket side.

Client-Server Interaction:

The client initiates contact with the server.

Advanced Java Programming 64


The server must be running as a process and have a socket to receive the
client’s connection request.

TCP provides a point-to-point channel for reliable communication, commonly used


by applications like HTTP, FTP, and Telnet.

(ii) UDP (User Datagram Protocol):

UDP is a connectionless protocol that sends independent packets of data


(datagrams) with no guarantees about arrival or order.

It is faster than TCP but unreliable, meaning there's no way to verify if the
data arrived or if it arrived in the correct order.

UDP is encapsulated in IP datagrams, which are sent to the destination.

In UDP, each datagram contains the destination port number, which routes the
packet to the correct application.

UDP is used for applications that prioritize speed over reliability, where
occasional data loss is acceptable.

Comparison between TCP and UDP:

TCP UDP

Reliable Unreliable

Connection-oriented Connectionless

Uses retransmission and flow control through windowing No retransmission or flow control

Segments are sequenced No sequencing

Acknowledges each segment No acknowledgment

3. Application Layer Protocols:


(i) Domain Name System (DNS):

DNS helps convert human-friendly domain names (like www.yahoo.com ) into IP


addresses.

Every device on the Internet has an IP address (e.g., 137.170.4.124 ), but it's
easier for people to remember names like www.niralibooks.org .

DNS is like a huge database that stores these name-to-IP mappings. When you need
to find the IP address of a website, your computer asks a DNS server to resolve
it.

DNS uses the UDP protocol and works on port 53.

(ii) Simple Mail Transfer Protocol (SMTP):

SMTP is used to send and receive emails on the Internet.

It defines how email servers communicate to forward messages from the sender to
the receiver.

SMTP is a text-based protocol and works over TCP on ports 25 or 587.

Advanced Java Programming 65


In this system, the server sends and receives emails, and the client sends
emails to the server using SMTP.

(iii) File Transfer Protocol (FTP):

FTP is a protocol for transferring files between computers.

It is widely used to upload files to websites or share files on the Internet.

FTP follows the client-server model: a client accesses files stored on a remote
server.

FTP uses TCP port 20 for control messages and port 21 for transferring the
actual data.

(iv) Post Office Protocol (POP3):

POP3 is used to retrieve emails from a mail server.

The client connects to the server on TCP port 110 and downloads the emails to
the local computer.

POP3 has two modes:

Delete mode: Emails are deleted from the server after being downloaded.

Keep mode: Emails stay on the server, so you can access them later.

(v) HyperText Transfer Protocol (HTTP):

HTTP is the protocol that browsers use to communicate with web servers.

It is the core protocol of the World Wide Web (WWW), governing how websites are
transferred between servers and browsers.

When you use a browser to visit a website, your browser sends an HTTP request to
the web server, which responds by sending the website’s data back.

HTTP works over TCP.

Proxy Servers

A proxy server is software running on a server that acts as a middleman between


clients (e.g., browsers) and the actual server.

It hides the actual server from the clients and communicates on their behalf.

Why is it used?

Clients might have restrictions on which servers they can connect to. A proxy
server bypasses these restrictions by communicating with the actual server for
the client.

Proxy Document Retrieval:

Additional Features:

Filters Requests: Can block certain types of requests.

Caching: Stores frequently requested data so it can be reused.

Benefits of Caching Proxy Servers:

1. Reduced Bandwidth Usage:

Advanced Java Programming 66


Instead of multiple users downloading the same content from the Internet, the
proxy server fetches it once and shares it locally.

2. Faster Response Times:

Cached data is served to users quickly, avoiding the need to repeatedly


access remote servers.

3. Reduced Network Traffic:

Fewer requests are sent to the Internet, easing the load on the network.

Example:

If many users frequently visit a popular website, the proxy server stores the
website’s data locally. When users request it, the proxy server provides the data
directly, saving time and Internet usage.

Internet Addressing

The Internet is the largest network in the world, connecting millions of smaller
networks globally.

Each computer on the Internet has a unique IP address for identification.

IP Address:

A unique number (e.g., 172.17.167.4) identifying a computer on a network.

Assigned by Internet Corporation for Assigned Names and Numbers (ICANN).

Consists of 4 octets (in IPv4) separated by dots.

Number of Networks = 2 ^ network bits − 2

Number of Hosts per Network = 2 ^ host bits − 2

Subtract 2 because:

The first IP is reserved as the network address.

The last IP is reserved for broadcasting.

IP Classes:

1. Class A:

Used for large networks.

Range: 1.x.x.x to 126.x.x.x.

Reserved: 127.x.x.x for loopback testing.

Subnet Mask: 255.0.0.0.

2. Class B:

Used for medium-sized networks.

Range: 128.0.x.x to 191.255.x.x.

Subnet Mask: 255.255.0.0.

3. Class C:

Used for small networks.

Range: 192.0.0.x to 223.255.255.x.

Subnet Mask: 255.255.255.0.

4. Class D:

Reserved for multicasting (no host assignment).

Range: 224.0.0.0 to 239.255.255.255.

No subnet mask.

5. Class E:

Reserved for research and experimentation.

Advanced Java Programming 67


Range: 240.0.0.0 to 255.255.255.254.

No subnet mask.

IP Class Summary:

Java and The Net (Networking Classes and Interfaces)

Java provides built-in support for TCP/IP networking through the java.net package.

It supports both TCP and UDP protocols for communication over a network:

1. TCP (Transmission Control Protocol):

Used for reliable, stream-based data transfer.

Ensures the delivery of data in the correct order.

2. UDP (User Datagram Protocol):

Provides a faster, simpler, and connectionless way of transferring data using


datagrams.

Does not guarantee reliability or order.

Java is widely used for network programming due to its extensive support for
handling network resources through the java.net package.

Important Classes in java.net

Class Purpose
CacheRequest Used for representing requests stored in cache.
CookieManager Manages cookies in HTTP communication.
CookieHandler Handles cookies for HTTP requests.
DatagramPacket Represents data packets sent via UDP.

A connection-less socket for sending/receiving


DatagramSocket
datagrams.
InetAddress Represents an IP address.
Proxy Represents proxy settings.
Socket Used for client-server communication via TCP.
ServerSocket Used by servers to listen for client requests.
URL Represents a Uniform Resource Locator (URL).

Manages communication with a resource identified


URLConnection
by a URL.

Important Interfaces in java.net

Interface Purpose
CookiePolicy Defines policies for cookie acceptance.
CookieStore Stores cookies.
FileNameMap Maps file names to MIME types.
SocketImplFactory Creates socket implementations.

Advanced Java Programming 68


Interface Purpose
SocketOption Defines socket configuration options.

Represents a protocol family (like TCP or


ProtocolFamily
UDP).

Classes that we’ll study about in this chapter:

1. InetAddress :

Represents an IP address in Java.

Can be used to identify computers on a network.

2. URL and URLConnection :

: Represents a Uniform Resource Locator that uniquely identifies resources


URL

on the internet.

URLConnection : Handles communication with the resource identified by a URL.

3. Socket :

Represents a socket connection for communication between a client and a


server.

Uses TCP protocol.

4. ServerSocket :

Used by a server application to listen for client requests on a specific


port.

5. DatagramPacket :

Represents data packets sent using the UDP protocol.

6. DatagramSocket :

Provides a connectionless way to send and receive datagrams over UDP.

InetAddress

Addresses are essential in communication, whether making a phone call, sending


mail, or connecting over the Internet.

In Java, the InetAddress class represents both:

The numerical IP address.

The domain name for that IP address.

The InetAddress class is part of the java.net package, which provides tools for handling
network addresses.

This class allows interaction with IP addresses and domain names in an easy-to-
understand way.

It hides the IP address's numerical representation behind a more readable host


name.

Using host names is more convenient and understandable than raw IP addresses.

The InetAddress class does not have constructors.

Instead, it uses factory methods to create objects.

class is used to make network programming simpler by providing easy-to-use


InetAddress

methods for:

Resolving host names into IP addresses.

Converting IP addresses back into host names.

Factory Methods

The InetAddress class doesn't have visible constructors, so we need to use factory
methods to create an InetAddress object.

Advanced Java Programming 69


Factory methods are static methods in a class that return an instance of that
class.

Most commonly used InetAddress factory methods:

1. static InetAddress getByName(String host) throws UnknownHostException

This method returns an InetAddress object containing the IP address and host
name of the given host.

2. static InetAddress getLocalHost() throws UnknownHostException

This method returns an InetAddress object containing the local host's name and
IP address.

3. static InetAddress getByAddress(byte[] addr) throws UnknownHostException

This method creates an InetAddress object using a specified IP address (without


a host name).

4. static InetAddress getByAddress(String hostname, byte[] addr) throws UnknownHostException

This method creates an InetAddress object using both an IP address and a host
name.

5. static InetAddress[] getAllByName(String hostname) throws UnknownHostException

This method determines all the IP addresses associated with a given host name
and returns them in an array.

Example:

import java.net.*;

public class NetDemo {


public static void main(String[] args) {
try {
InetAddress ip = InetAddress.getByName("www.google.com");
System.out.println("Host Name: " + ip.getHostName());
System.out.println("IP Address: " + ip.getHostAddress());
} catch (Exception e) {
System.out.println(e);
}
}
}

Instance Methods

The InetAddress class has several useful methods that can be used on the objects
returned by the methods mentioned earlier.

Some commonly used InetAddress instance methods are:

1. boolean equals(Object obj)

Compares the current object with the specified object and returns true if both
have the same Internet address, otherwise false .

2. byte[] getAddress()

Returns the IP address associated with the object as an array of bytes in


network order.

3. String getHostAddress()

Returns the string representation of the IP address associated with the


object. For example, it could return "206.175.64.78".

4. String getHostName()

Returns the hostname associated with the object.

5. int hashCode()

Advanced Java Programming 70


Returns the hash code based on the IP address of the object.

6. boolean isMulticastAddress()

Returns true if the object represents a multicast address, otherwise returns


false .

7. String toString()

Returns a string that contains both the hostname and IP address of the
object.

Example:

import java.net.*;

public class Main {


public static void main(String[] args) {
try {
InetAddress local = InetAddress.getLocalHost();
String address = local.getHostAddress();
String hostName = local.getHostName();

System.out.println("Local Host IP Address: " + address);


System.out.println("Local Host Name: " + hostName);
} catch (Exception e) {
System.out.println(e);
}
}
}

TCP/IP Sockets

A socket is one endpoint in a two-way communication link between two programs


running on a computer network. It allows data to flow between these programs.

A socket is bound to a port number, which helps the TCP layer identify which
application the data should be sent to.

Java provides excellent support for TCP sockets through two main classes:

1. : This class represents a TCP client socket. It allows the client to


java.net.Socket

connect to a server socket and exchange data using protocols.

2. : This class is used to create a server. The server listens for


java.net.ServerSocket

incoming connections from one or more clients.

Socket Class

TCP/IP sockets are used to establish reliable, bi-directional, point-to-point, and


stream-based connections between hosts on the Internet.

They enable communication between Java's I/O system and other programs that may be
on the same machine or a remote machine across the Internet.

Socket and ServerSocket Connectivity:

Advanced Java Programming 71


There are two kinds of TCP sockets in Java:

Server Socket: Used by server applications to listen for incoming client


connections.

Client Socket: Used by client applications to connect to a server.

: A class that listens for client connections. It waits for clients to


ServerSocket

connect before performing any further actions.

Socket : A class that is used by clients to connect to the server and begin protocol
exchanges.

Constructors of Socket class:

1. Socket() :

Creates an unconnected socket. You need to use the connect() method to connect
it to a server.

2. Socket(String host, int port) :

Attempts to connect to the specified server at the given port.

If no exception is thrown, the connection is successful.

3. Socket(InetAddress host, int port) :

Similar to the previous constructor but takes an InetAddress object for the
host.

4. Socket(String host, int port, InetAddress localAddress, int localPort) :

Connects to the specified host and port and creates a socket on the local
machine at the specified address and port.

5. Socket(InetAddress host, int port, InetAddress localAddress, int localPort) :

Similar to the previous constructor, but the host is specified by an


InetAddress object instead of a string.

Methods of Socket class:

1. void connect(SocketAddress host, int timeout) throws IOException :

Connects the socket to a specified host and port.

This method is needed only when you create the socket using the no-argument
constructor.

2. InetAddress getInetAddress() :

Returns the IP address of the machine that this socket is connected to.

3. int getPort() :

Returns the port number that the socket is connected to on the remote
machine.

4. int getLocalPort() :

Returns the port number that the socket is bound to on the local machine.

5. SocketAddress getRemoteSocketAddress() :

Returns the address of the remote socket (the machine you are connected to).

6. InputStream getInputStream() throws IOException :

Returns the input stream of the socket, which is connected to the output
stream of the remote socket.

7. OutputStream getOutputStream() throws IOException :

Returns the output stream of the socket, which is connected to the input
stream of the remote socket.

8. void close() throws IOException :

Closes the socket, making it no longer capable of connecting to any server.

Advanced Java Programming 72


Example:

import java.net.*;
import java.io.*;

public class Main {


public static void main(String[] args) {
try {
Socket socket = new Socket("www.google.com", 80);
System.out.println("Connected to "
+ socket.getInetAddress()
+ " on port " + socket.getPort()
+ " from port " + socket.getLocalPort()
+ " of " + socket.getLocalAddress());
} catch (UnknownHostException e) {
System.err.println("I can't find https://www.google.com");
} catch (SocketException e) {
System.err.println("Could not connect to https://www.google.com");
} catch (IOException e) {
System.err.println(e);
}
}
}

ServerSocket Class

The ServerSocket class is used to create servers that listen for incoming connections
from clients, either local or remote, on specific ports.

How it works:

1. A ServerSocket is created on a specific port using the ServerSocket constructor.

2. The server listens for client connection attempts using the accept() method. The
server runs in a loop, continuously accepting incoming connections.

3. Once a client connects, the accept() method returns a Socket object representing
the connection.

4. The server communicates with the client through the input and output streams
provided by the Socket object ( getInputStream() and getOutputStream() methods).

5. After the communication is complete, either the server or the client can close
the connection. If the server doesn't close the connection, it will wait for new
connections by going back to step 2.

Constructors of ServerSocket Class:

1. ServerSocket(int port)

Binds the server socket to the specified port.

Throws an exception if the port is already in use.

2. ServerSocket(int port, int backlog)

Similar to the previous constructor, but the backlog parameter specifies how
many incoming client connections can be queued up before the server starts
accepting them.

3. ServerSocket(int port, int backlog, InetAddress address)

Similar to the previous constructor, but the InetAddress parameter specifies the
local IP address to bind to.

This is useful if the server has multiple IP addresses and needs to choose
which one to use for client connections.

4. ServerSocket()

Advanced Java Programming 73


Creates an unbound server socket.

Use the bind() method to bind it to a specific address and port later.

Methods of ServerSocket Class:

1. int getLocalPort()

Returns the port number that the server socket is listening on.

Useful when you pass 0 as the port number in the constructor and let the
server choose an available port.

2. Socket accept()

Waits for an incoming client connection.

Blocks until a client connects or the socket times out (if a timeout is set
using setSoTimeout() ).

3. void setSoTimeout(int timeout)

Sets the timeout value for how long the server socket waits for a client
during the accept() method.

If the timeout is reached, the server socket stops waiting.

4. void bind(SocketAddress host, int backlog)

Binds the server socket to the specified address and port.

Used when the ServerSocket is created without any address or port and needs to
be bound later.

Example:

import java.net.*;
import java.io.*;

class Main {
public static void main(String[] args) {
for (int port = 1; port <= 65535; port++) {
try {
ServerSocket server = new ServerSocket(port);
} catch (IOException ex) {
System.out.println("There is a server on port " + port + ",");
}
}
}
}

If you try to connect server socket on a particular port which is already occupied
by other applications then code will throw the exception and you will get the
message that "There is a server ... "

Sending a single message from Server to Client

SimpleServer.java

import java.net.*;
import java.io.*;

public class SimpleServer {


public static void main(String args[]) throws IOException {
ServerSocket s = new ServerSocket(1254); // Service on port 1254
System.out.println("Server Started, waiting for client connection ...");

Socket sl = s.accept(); // Wait and accept a connection


OutputStream out = sl.getOutputStream(); // Get output stream
DataOutputStream dos = new DataOutputStream(out);

Advanced Java Programming 74


dos.writeUTF("Hi there"); // Send a string!

// Close the connection, but not the server socket


dos.close();
out.close();
sl.close();
}
}

SimpleClient.java

import java.net.*;
import java.io.*;

public class SimpleClient {


public static void main(String args[]) throws IOException {
// Open your connection to the server at port 1254
Socket sl = new Socket("localhost", 1254);

// Get an input file handle from the socket and read the input
InputStream in = sl.getInputStream();
DataInputStream dis = new DataInputStream(in);
String st = new String(dis.readUTF());

System.out.println(st); // Output: Hi there

dis.close();
in.close();
sl.close();
}
}

Program to send number of client and server will reply number as even or odd.

OddEvenServer.java

import java.net.*;
import java.io.*;

public class OddEvenServer {


public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(1000);
System.out.println("Searching...");

Socket s = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream
()));

// Reading the number from the client


int n = Integer.parseInt(br.readLine());

OutputStream o = s.getOutputStream();
PrintStream ps = new PrintStream(o);
System.out.println("Checking...");

// Check if the number is even or odd


if (n % 2 == 0)
ps.println("No is Even");
else

Advanced Java Programming 75


ps.println("No is Odd");

// Close the resources


ps.close();
br.close();
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

OddEvenClient.java

import java.net.*;
import java.io.*;

public class OddEvenClient {


public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 1000);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

// Prompt the user to enter a number


System.out.println("Enter no:");
int n = Integer.parseInt(br.readLine());

OutputStream o = s.getOutputStream();
PrintStream ps = new PrintStream(o);
ps.println(n); // Send the number to the server

// Read the response from the server


BufferedReader br1 = new BufferedReader(new InputStreamReader(s.getInputStrea
m()));
String response = br1.readLine();
System.out.println(response); // Display the result (Even/Odd)

// Close the resources


ps.close();
br.close();
br1.close();
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Whois

The WHOIS protocol is a simple directory service that provides information about
Internet resources such as domain names, IP addresses, or autonomous systems.

It was originally designed to track administrators responsible for Internet hosts


and domains.

A WHOIS client typically connects to a WHOIS server to query for data like contact
information of the domain owner (e.g., phone numbers, email addresses, and physical
addresses). The process involves:

1. Opening a TCP connection to port 43 of a WHOIS server (commonly whois.internic.net ).

Advanced Java Programming 76


2. Sending a search string (e.g., a domain name) followed by a carriage
return/linefeed ( \\r\\n ).

3. Receiving human-readable information from the server.

4. Displaying the result to the user.

Using Apache Commons Net Library to Access WHOIS Data:

Java does not include built-in support for WHOIS queries. Therefore, we use an
external library, Apache Commons Net, to query WHOIS servers.

This library is not bundled with the JDK, so you must download and include it in
your project.

Steps:

1. Download the Apache Commons Net 3.6 library from Apache Commons Net Download.

2. Extract the downloaded zip file.

3. Add the jar file to your project:

Right-click on the project → Properties → Libraries → Add JAR → Select the


downloaded JAR file.

Once the JAR file is added to your project, you can use it to query WHOIS servers.

Example:

import org.apache.commons.net.whois.*;
import java.io.IOException;

public class WhoisClientExample {


public static void main(String[] args) {
// Define the domain you want to query
String domain = "example.com";

// Create an instance of WhoisClient


WhoisClient whois = new WhoisClient();

try {
// Connect to the WHOIS server (internic.net is commonly used)
whois.connect(WhoisClient.DEFAULT_HOST);

// Send the domain to the WHOIS server and get the response
String whoisData = whois.query(domain);

// Display the WHOIS data (contact information for the domain)


System.out.println("WHOIS Information for " + domain + ":");
System.out.println(whoisData);

// Disconnect from the WHOIS server


whois.disconnect();
} catch (IOException e) {
System.err.println("Error occurred: " + e.getMessage());
}
}
}

URL

A URL (Uniform Resource Locator) provides a way to uniquely identify or address


information on the Internet.

Advanced Java Programming 77


In essence, the Web is simply the same Internet, but with all its resources
addressed as URLs, along with HTML.

In Java’s network class library, the URL class offers a simple and concise API to
access information on the Internet using URLs.

Format of URL

Two examples of URLs are http://www.rediff.com/ and http://www.rediff.com:80/index.htm/ .

A URL is made up of four main components:

1. Protocol:

This specifies the method to access the resource and is separated from the
rest of the URL by a colon ( : ).

Common protocols include http , ftp , gopher , and file , with HTTP being the most
widely used today.

2. Host Name or IP Address:

This identifies the host where the resource is located.

It is separated from the protocol by double slashes ( // ) and may end with a
slash ( / ) or optionally a colon ( : ).

3. Port Number:

This is an optional component, separated from the host name by a colon ( : )


and from the file path by a slash ( / ).

If not specified, it defaults to port 80, which is used for HTTP.

4. File Path:

This specifies the exact resource on the server.

If a directory is specified, most HTTP servers will automatically look for a


file named index.html .

For example, http://www.rediff.com/ is equivalent to http://www.rediff.com/index.html .

The Java URL class in the java.net package is used to work with URLs, which uniquely
identify or locate resources on the Internet.

URL Class

A URL (Uniform Resource Locator) is a reference or address used to locate a


resource on the Internet.

In Java, the simplest way to locate and retrieve data from the network is by using
the java.net.URL class.

The URL class provides methods to manipulate and interact with URLs, making it
easier for Java programs to handle resources on the Internet.

Constructors of the URL Class:

1. URL(String spec) : Creates a URL object from the string representation.

2. URL(String protocol, String host, int port, String file) : Creates a URL object from the specified
protocol, host, port number, and file.

3. : Creates a URL object


URL(String protocol, String host, int port, String file, URLStreamHandler handler)

from the specified protocol, host, port number, file, and handler.

4. URL(String protocol, String host, String file) : Creates a URL from the specified protocol,
host name, and file name.

5. URL(URL context, String spec) : Creates a URL by parsing the given spec within a specified
context.

6. : Creates a URL by parsing the given spec


URL(URL context, String spec, URLStreamHandler handler)

with the specified handler within a specified context.

Advanced Java Programming 78


Methods of the URL Class:

The URL class also provides methods for retrieving individual components of the URL
and interacting with the resource.

Some of the key methods include:

1. void set(String protocol, String host, int port, String file, String ref) : Sets the fields of the URL.
This is a non-public method used by URLStreamHandlers to modify URL fields.

2. int getPort() : Returns the port number of the URL, or -1 if the port is not set.

3. String getProtocol() : Returns the protocol name used in the URL.

4. String getHost() : Returns the host name of the URL.

5. String getFile() : Returns the file name specified in the URL.

6. String getPath() : Returns the path part of the URL.

7. String getQuery() : Returns the query part of the URL.

8. boolean equals(Object obj) : Compares the URL with another object and returns true if
they are equal, otherwise false.

9. URLConnection openConnection() : Creates a connection to the remote object referred to by


the URL.

10. final InputStream openStream() : Opens an input stream for reading data from the resource.

11. final Object getContent() : Retrieves the content from the opened connection.

Example of URL Structure:

Example:

import java.net.*;

class Main {
public static void main(String[] args) {
try {
URL hp = new URL("http://www.yahoo.com:80/index");

System.out.println(hp.getProtocol());
System.out.println(hp.getPath());
System.out.println(hp.getHost());
System.out.println(hp.getFile());
System.out.println(hp.getPort());
} catch (MalformedURLException e) {}
}
}

URLConnection Class

URLConnection is an abstract class in Java that represents an active connection to a


resource specified by a URL.

It provides more control over the interaction with a server compared to the URL

class.

Purposes of URLConnection :

1. Control over server interaction:

Advanced Java Programming 79


With URLConnection , you have more control than with the URL class.

You can inspect the headers sent by the server and respond accordingly.

You can also set the headers for the client request.

Additionally, URLConnection allows downloading binary files.

2. Sending data to the server:

can send data back to the server using methods like POST or PUT,
URLConnection

and it supports other HTTP request methods.

Differences Between URL and URLConnection :

1. URLConnection gives access to the HTTP header.

2. URLConnection allows you to configure request parameters sent to the server.

3. URLConnection can write data to the server as well as read data from it.

Constructors of URLConnection Class:


URLConnection(URL url)

This constructor creates a URLConnection object for the specified URL.

However, the actual connection to the resource is not created until you call the
connect() method.

Methods of URLConnection Class:

1. abstract void connect() - Opens a communication link to the resource referred to by the
URL.

2. URL getURL() - Returns the URL associated with the connection.

3. int getContentLength() - Returns the content length (size) of the resource.

4. String getContentType() - Returns the content type (e.g., text, image) of the resource.

5. long getDate() - Returns the date header field (in milliseconds since Jan 1, 1970,
GMT).

6. - Returns the last modified date of the resource in


long getLastModified()

milliseconds since Jan 1, 1970 GMT.

7. Object getContent() - Retrieves the content of the URL connection.

8. - Retrieves the content of the URL connection and tries


Object getContent(Class[] classes)

to convert it to the specified class type.

9. Permission getPermission() - Returns the permission object necessary to make the


connection.

10. InputStream getInputStream() - Returns the input stream of the connection to read data
from the resource.

11. OutputStream getOutputStream() - Returns the output stream of the connection to write
data to the resource.

Basic Steps in Using URLConnection :


Step 1: Create a URL object for the resource you want to connect to.

Step 2: Call the openConnection() method on the URL object to get a URLConnection object.
Step 3: Use the input stream to read data from the connection.

Step 4: If you need to send data, use the output stream to write to the server.
Step 5: Close the connection once you're done.

Example:

import java.net.*;
import java.io.*;

public class Main {

Advanced Java Programming 80


public static void main(String[] args) {
try {
URL url = new URL("http://www.google.com");
URLConnection con = url.openConnection();

InputStream stream = con.getInputStream();


int i;

while ((i = stream.read()) != -1) {


System.out.print((char) i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

TCP/IP Server Sockets

In Java, there is a special class called ServerSocket used for creating server
applications.

The ServerSocket class helps servers listen for incoming connections from client
programs, either locally (on the same machine) or remotely (over a network).

These connections happen through specific ports, which the server "publishes" or
makes available for clients to connect to.

Datagrams (Datagram Packet, Datagram Server and Client)

In TCP/IP communication, a reliable and predictable stream of packet data is


established.

Clients and servers communicate through a reliable channel, such as a TCP socket.

In this communication, all data sent over the channel arrives in the same order it
was sent.

On the other hand, UDP communication provides an unreliable stream of packets


called datagrams.

Unlike TCP, UDP does not require a dedicated point-to-point connection between the
client and server, meaning the delivery and order of datagrams are not guaranteed.

A datagram is a self-contained, independent message sent over the network, but


there is no guarantee about its arrival, arrival time, or content.

Java supports datagram communication through the following classes:

1. DatagramPacket : Represents the packet of data being sent or received.

2. DatagramSocket : Represents the socket used for sending and receiving datagrams.

DatagramPacket Class

Datagram packets are used for connectionless packet delivery, which is supported by
the UDP protocol.

Each message is sent from the source machine to the destination machine based on
the information in the packet.

These packets are independent of each other, meaning each packet has its own
destination address, and they may be routed differently or arrive in any order.

The delivery of the packets is not guaranteed, and they may not reach their
destination.

The format of a datagram packet includes:

Advanced Java Programming 81


Message

Length

Host

Server Port

Java provides the DatagramPacket class to facilitate the connectionless transfer of


messages from one system to another.

Constructors of DatagramPacket Class:

1. DatagramPacket(byte[] buf, int len)

Constructs a DatagramPacket for receiving packets of length len .

2. DatagramPacket(byte[] buf, int off, int len)

Constructs a DatagramPacket for receiving packets of length len , with an


offset of off bytes into the buffer.

3. DatagramPacket(byte[] buf, int len, InetAddress addr, int port)

Constructs a DatagramPacket for sending packets of length len to the specified


port number on the specified host (address).

4. DatagramPacket(byte[] buf, int off, int len, InetAddress addr, int port)

Constructs a DatagramPacket for sending packets of length len , with an offset


of off , to the specified port number on the specified host .

5. DatagramPacket(byte[] buf, int off, int len, SocketAddress addr)

Constructs a DatagramPacket for sending packets of length len , with an offset


of off , to the specified address and port.

Methods of DatagramPacket Class:

1. InetAddress getAddress()

Returns the address of the source (for received datagrams) or destination


(for sent datagrams).

2. byte[] getData()

Returns the byte array of data contained in the datagram. This is used to
retrieve data after it has been received.

3. int getLength()

Returns the length of the valid data contained in the byte array returned
from getData() . It may not equal the total length of the byte array.

4. int getPort()

Returns the port number for the datagram.

5. void setData(byte[] data)

Sets the data in the datagram. The offset is set to zero, and the length is
set to the number of bytes in data .

6. void setLength(int size)

Sets the length of the packet to the specified size.

DatagramSocket Class

In addition to the DatagramPacket class, Java also supports the DatagramSocket class for
sending and receiving datagram packets.

Constructors of DatagramSocket Class:

1. DatagramSocket()

Constructs a datagram socket and binds it to any available port on the local
host.

2. DatagramSocket(int port)

Advanced Java Programming 82


Constructs a datagram socket and binds it to the specified port on the local
host.

3. DatagramSocket(int port, InetAddress iaddr)

Creates a datagram socket, bound to the specified local address ( iaddr ).

4. DatagramSocket(DatagramSocketImpl impl)

Creates an unbound datagram socket with the specified DatagramSocketImpl .

5. DatagramSocket(SocketAddress bindaddr)

Creates a datagram socket, bound to the specified local socket address


( bindaddr ).

Methods of DatagramSocket Class:

1. void close()

Closes the datagram socket.

2. InetAddress getLocalAddress()

Returns the local address to which the socket is bound.

3. int getLocalPort()

Returns the port number on the local host to which this socket is bound.

4. void receive(DatagramPacket p)

Receives a datagram packet from this socket.

5. void send(DatagramPacket p)

Sends a datagram packet from this socket.

This class helps manage the communication channels between different networked
devices using UDP (connectionless communication).

Datagrams Server and Client

A datagram is an independent, self-contained message sent over the network.

Unlike TCP communication, the delivery, arrival time, and content of a datagram are
not guaranteed.

The DatagramPacket and DatagramSocket classes in Java implement system-independent


datagram communication using the UDP protocol.

The example below demonstrates how a client and server can exchange messages using
UDP. The server listens for messages from the client, and when the client sends a
message, it is displayed on the server side. The server then responds back to the
client, and the process repeats.

UDPClient.java (Client-Side Code)

import java.io.*;
import java.net.*;

public class UDPClient {


public static void main(String[] args) throws IOException {
String message = null;
DatagramSocket clientSocket = null;

// Create the DatagramSocket


clientSocket = new DatagramSocket();
byte[] receiveData = new byte[512];
byte[] sendData = new byte[512];

BufferedReader reader = new BufferedReader(new InputStreamReader(System.i


n));
System.out.println("UDP Client socket is created and waiting for server.");

Advanced Java Programming 83


// Get the server's IP address and port number
InetAddress serverAddress = InetAddress.getLocalHost();
int serverPort = 9000;

while (true) {
// Get message input from the user
System.out.println("Client Says:");
message = reader.readLine();

// Convert the message to bytes and send it to the server


sendData = message.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
serverAddress, serverPort);
clientSocket.send(sendPacket);

// Receive the response from the server


DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveDat
a.length);
clientSocket.receive(receivePacket);
message = new String(receivePacket.getData(), 0, receivePacket.getLength
());
System.out.println("Server Says: " + message);
}
}
}

UDPServer.java (Server-Side Code)

import java.io.*;
import java.net.*;

public class UDPServer {


public static void main(String[] args) throws IOException {
DatagramSocket serverSocket = null;

// Create the DatagramSocket on port 9000


serverSocket = new DatagramSocket(9000);

byte[] receiveData = new byte[512];


byte[] sendData = new byte[512];

BufferedReader reader = new BufferedReader(new InputStreamReader(System.i


n));
System.out.println("UDP Server socket is created and waiting for client.");

while (true) {
// Receive message from the client
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveDat
a.length);
serverSocket.receive(receivePacket);

String message = new String(receivePacket.getData(), 0, receivePacket.getL


ength());
System.out.println("Client Says: " + message);

// Check if the client wants to end the communication


if (message.equals("end")) {
break;

Advanced Java Programming 84


}

// Get the server's response message


System.out.println("Enter Server Message:");
message = reader.readLine();

// Send the server's response back to the client


InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
sendData = message.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
clientAddress, clientPort);
serverSocket.send(sendPacket);
}

// Close the server socket


serverSocket.close();
System.out.println("Server Stopped by User.");
}
}

Program to check a number is even or odd using UDP connectivity.

OddEvenServer.java :

import java.io.*;
import java.net.*;

public class OddEvenServer {

public static void main(String[] args) {


try {
// Create a DatagramSocket on port 2000
DatagramSocket ds = new DatagramSocket(2000);
System.out.println("Searching for client...");

byte[] data = new byte[1024];


DatagramPacket receivePacket = new DatagramPacket(data, data.length);

// Receive data from the client


ds.receive(receivePacket);

String str = new String(receivePacket.getData(), 0, receivePacket.getLength


());
System.out.println("Client sent: " + str);

int number;
try {
number = Integer.parseInt(str);
} catch (NumberFormatException e) {
System.out.println("Error: Received data is not a valid number.");
return;
}

String response;
if (number % 2 == 0) {
response = "Number is even";
} else {
response = "Number is odd";
}

Advanced Java Programming 85


byte[] responseBytes = response.getBytes();
DatagramPacket sendPacket = new DatagramPacket(responseBytes, responseBytes.l
ength,
receivePacket.getAddress(), 1000);

// Send the response back to the client


ds.send(sendPacket);

} catch (Exception e) {
e.printStackTrace();
}
}
}

OddEvenClient.java :

import java.io.*;
import java.net.*;

public class OddEvenClient {


public static void main(String args[]) {
try {
// Create a DatagramSocket bound to port 1000
DatagramSocket ds = new DatagramSocket(1000);

// Create a BufferedReader to read input from the user


BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number: ");
String num = br.readLine();

// Convert the number to a byte array


byte[] data = new byte[1024];
data = num.getBytes();

// Create a DatagramPacket to send the number


DatagramPacket sendPacket = new DatagramPacket(data, data.length, InetAddres
s.getLocalHost(), 2000);
ds.send(sendPacket);

// Create a byte array to receive the server's response


byte[] response = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(response, response.length);

// Receive the response from the server


ds.receive(receivePacket);

// Convert the received data to a string and display it


String str = new String(receivePacket.getData(), 0, receivePacket.getLength
());
System.out.println(str);

} catch (Exception e) {
// Print any exception that occurs
e.printStackTrace();
}
}
}

Advanced Java Programming 86


Chapter 5 - Interacting with Database
Introduction

Java offers several benefits for software developers creating front-end


applications for a database server.

Java is known for its "Write Once, Run Everywhere" philosophy, meaning it can run
on any platform that supports Java.

Java interacts with databases using a common database application programming


interface called JDBC (Java Database Connectivity).

The JDBC specification required a JDBC driver to act as a translator, converting


low-level DBMS (Database Management System) messages into messages understood by
the JDBC API, and vice versa. This enables Java programmers to use high-level Java
data objects defined in the JDBC API to interact with the DBMS.

These Java data objects convert the routine into low-level messages that conform to
the JDBC driver specification and send them to the JDBC driver. The JDBC driver
then translates these messages into a form that can be understood and processed by
the DBMS.

Additionally, Open Database Connectivity (ODBC) is an open standard API that


allows access to databases. By using ODBC statements, programs can access a variety
of databases, including Access, dBase, DB2, Excel, and others.

JDBC

JDBC (Java DataBase Connectivity) is a technology that enables Java applications to


interact with databases. It can refer to:

1. A specification for using data sources in Java applications and applets.

2. An API for using low-level JDBC drivers.

3. An API for creating low-level JDBC drivers, which handle the actual connection
and transactions with databases.

JDBC defines the process for making Java applications and applets that can work
with data.

The low-level JDBC drivers perform the necessary database-specific translations to


the high-level JDBC interface, allowing developers to use a consistent API without
worrying about the unique syntax of different databases.

JDBC is part of the Java package, similar to other Java packages like java.awt .

The key benefit of JDBC is that the required drivers for connecting to databases do
not need to be pre-installed on the client system.

JDBC API

JDBC (Java Database Connectivity) is an API provided by Sun Microsystems as part of


Java Enterprise APIs.

It defines a set of interfaces and classes that allow Java applications to interact
with databases.

The JDBC API is contained in two packages:

java.sql : This package contains core Java objects of the JDBC API.

: This package contains additional interfaces for working with more


javax.sql

advanced database operations.

JDBC Architecture:
JDBC follows a layered architecture with two main layers:

Application Layer: This is where database application developers interact with


the database.

Advanced Java Programming 87


Driver Layer: This is where the JDBC driver vendors implement the actual
communication with the database.

These layers are connected as shown in the diagram below:

The Driver interface implementation is where the connection to the database is


made. In most applications, the Driver is accessed through the DriverManager class.

There are four main interfaces that every driver layer must implement, along with
one class that bridges the application and driver layers:

1. Driver: Establishes the connection to the database.

2. Connection: Manages the connection between the application and the database.

3. Statement: Allows execution of SQL queries.

4. ResultSet: Holds the result of the executed query.

JDBC Objects:

1. Date Object: Inherited from the Java Date object, it provides methods for
accessing date values.

2. DriverManager Object: Manages JDBC Driver objects and establishes a connection


to the database.

3. Time Object: Inherited from the Java Date object, it provides methods for getting
and setting time values.

4. Timestamp Object: Used for handling timestamp data types in databases, with
methods for comparing timestamp values.

5. Types Object: Contains predefined integer values that identify various JDBC data
types.

Main Functions of JDBC:

1. Establishing a Connection: Connect to a database or other tabular data sources.

2. Sending SQL Commands: Send SQL queries and commands to the database.

3. Processing Results: Process and manipulate the results from SQL queries.

The Java JDBC API enables Java applications to interact with relational databases
using a standard API, making applications independent of the underlying database
they use.

Advanced Java Programming 88


This flexibility is illustrated in the diagram showing a Java application
connecting to a database via JDBC.

ODBC

ODBC is a standard API (Application Programming Interface) designed for accessing


Database Management Systems (DBMS).

It acts as middleware, allowing applications to interact with various databases


without being dependent on specific database systems or operating systems.

Features of ODBC:

Platform Independence: Applications written using ODBC can run on different


platforms with minimal changes to the data access code.

DBMS Independence: ODBC achieves this by using an ODBC driver, which acts as a
translator between the application and the DBMS.

How ODBC Works:

1. The application uses ODBC functions through an ODBC driver manager.

2. The driver manager, in turn, links the application with the ODBC driver.

3. The ODBC driver translates the application's SQL queries into commands that the
DBMS understands and then passes them to the database.

ODBC Architecture:

Components of ODBC Architecture:

1. Application:

Performs the main processing tasks.

Calls ODBC functions to send SQL queries and retrieve results.

2. Driver Manager:

A DLL (Dynamic Link Library) provided as part of ODBC on platforms like


Windows.

Manages communication between the application and the driver.

3. Driver:

Processes the ODBC function calls.

Sends SQL queries to the specific database and returns the results to the
application.

4. Data Source:

Contains the data to be accessed.

Includes the associated operating system, DBMS, and network platform (if
applicable) used to access the database.

Advanced Java Programming 89


ODBC API

The ODBC API (Open Database Connectivity) uses SQL (Structured Query Language) as
the primary language for interacting with databases.

It provides functions to:

Insert, modify, and delete data.

Retrieve and manage database information.

ODBC Connection:

How ODBC Connection Works:

The application can be written in any programming language, such as Java, C++,
or others.

The application uses ODBC to interact with the database.

A driver manager (part of Microsoft ODBC) manages the various database drivers
installed on the system. It handles tasks such as loading the appropriate
driver.

Role of Driver Manager:


If an application accesses multiple databases, the driver manager ensures that
function calls are routed to the correct database management system (DBMS).

Difference between JDBC and ODBC

ODBC JDBC

Stands for Open Database Connectivity. Stands for Java Database Connectivity.

Introduced by Microsoft in 1992. Introduced by Sun Microsystems in 1997.

Can be used with any language like C, C++,


Can be used only with Java.
Java, etc.

Limited to the Windows platform. Works on any platform.

Drivers are mostly developed in native


Drivers are written in Java.
languages like C, C++.

Not recommended for Java applications due to Highly recommended for Java applications as there
performance issues and platform dependency. are no performance or platform dependency issues.

Procedural approach. Object-oriented approach.

JDBC Architecture

JDBC supports two-tier and three-tier processing models for accessing a database.

The implementation of the actual connection to the data source or database is


handled by the JDBC driver.

Goals of JDBC:

1. Provides a DBMS-independent interface for accessing databases.

2. Allows the programmer to write a single database interface, enabling access to


any data source without requiring recoding.

JDBC Architecture:

Advanced Java Programming 90


JDBC Components:

1. Application:

The JDBC API enables applications to manage database connections.

SQL statements are executed, and results are retrieved using JDBC methods in
the application.

2. JDBC Driver API:

Provides the connection between the JDBC manager and the specific driver.

3. Driver Manager:

Responsible for loading the appropriate driver for the user application.

Acts as a mediator between the application and the drivers.

4. Driver:

Facilitates communication between the application and the database.

5. Data Source:

Refers to the database or the data repository that the application interacts
with to fetch or store data.

Two Tier Model

The first generation of client-server architectures is called two-tiered.

It consists of two active components:

1. Client – Requests data.

2. Server – Delivers data.

The network usually connects the back end (server) to the front end (client),
although both can exist on the same hardware.

Example: Airline seat reservation systems where numerous client applications


connect to a central DBMS to request, insert, or modify data.

Two Tier Client/Server Architecture:

Characteristics:

Clients handle tasks like graphics rendering and data entry validation.

Advanced Java Programming 91


The DBMS focuses on data processing, but some processing might occur on the
client side to reduce server load.

Preferred design involves:

Separating database queries and updates from user interface presentation


tasks.

Advantages:

1. Simple Design – Easy to implement and manage.

2. Client-Side Processing – Reduces server load by delegating some tasks to the


client.

Disadvantages:

1. Limited Scalability – Each client requires a separate session with the database.

2. Inflexibility – Changes to the system may be difficult to implement.

Three Tier Model

In contrast to the two-tier architecture, the three-tiered architecture introduces


a middle tier to avoid embedding application logic both on the client and database
sides.

The middle tier handles the business logic, so if business rules change, only the
middle tier needs to be modified.

Three-Tier Architecture:

Components of Three-Tier Architecture

1. Client Tier:

Typically a thin presentation layer, often implemented with a Web browser.

2. Middle Tier:

Manages business or application logic.

Can be implemented using a servlet engine (e.g., Tomcat) or an application


server (e.g., JBOSS).

This layer also contains the JDBC driver for database connections.

3. Data Source Layer:

This layer is where the RDBMS (Relational Database Management System)


resides.

Advantages

1. Flexibility – Changes can be made to one layer without affecting the others.

2. Database Independence – Can connect to different databases without altering


code.

3. Clear Separation – Business logic is separated from the database, making the
system more organized.

4. Improved Performance – Performance can be enhanced by separating the application


server and database server.

Disadvantages

1. Higher Complexity – More components make the system more complicated.

Advanced Java Programming 92


2. Increased Maintenance – More layers and components require more effort to
maintain.

3. Lower Network Efficiency – Communication between multiple layers can lead to


slower network performance.

4. Higher Costs and Time – More parts to configure and purchase, making it costly
and time-consuming.

Types of JDBC Drivers

Sun Microsystems has defined four types of JDBC drivers, which differ in their
architecture and how they handle database connections. A key difference is whether
the driver is written in native code or Java code.

Native code refers to machine code that is specific to a hardware platform. For
example, a driver written in C and compiled to run on a specific system.

Java code means the driver is written entirely in Java and can be used across
different platforms.

1. Type 1:

Relies on additional software, like ODBC drivers (C or C++ DLLs), installed


on the client computer to provide database connectivity.

2. Type 2:

Also depends on native software (like C or C++ DLLs) to interact with the
database.

3. Type 3:

A pure Java driver, but requires a network protocol to connect to the


database. It does not need any additional software installed on the client
except for the JDBC driver.

4. Type 4:

A 100% pure Java driver. It connects directly to the database over a network
without requiring any additional software on the client side.

Type 1 Driver: JDBC/ODBC Bridge

The Type 1 JDBC driver uses bridge technology to connect a Java client to a third-
party API, such as Open Database Connectivity (ODBC).

An example of this type is the JDBC-ODBC bridge, which connects Java to an ODBC
data source, often used with Microsoft databases.

Advanced Java Programming 93


The driver is implemented using native code and requires the ODBC driver to be
installed on the client computer.

The ODBC data source typically needs to be configured for this driver to work.

This driver was created to help Java developers work with data-driven applications
before Type 3 and Type 4 drivers were available.

Java 8 removed the JDBC ODBC bridge driver class "sun.jdbc.odbc.jdbcodbcdriver" from JDK and
JRE, which is necessary to connect to databases using ODBC drivers (e.g., Microsoft
Access).

Advantages:

1. Easy to use: Simple to implement for connecting to databases supported by ODBC


drivers.

2. Broad database support: Allows connectivity to any database that has an ODBC
driver.

3. Free: No extra cost for using this driver.

Disadvantages:

1. Slow execution time: Performance is often slower due to the additional layers
involved.

2. Dependency on ODBC Driver: It requires the ODBC driver to be installed and


configured on the client machine.

3. Java Native Interface (JNI): Uses JNI to make ODBC calls, which can add
complexity.

4. Platform dependent: It’s not fully platform-independent as it depends on the


ODBC driver being present on the target machine.

5. Performance impact: The translation between JDBC and ODBC can slow down
execution time and increase overhead.

6. Time-consuming: The configuration and setup process can be slow and cumbersome.

Type 2 Driver: Native API Driver

The Type 2 JDBC driver wraps a native API with Java classes.

An example of this driver is the Oracle Call Interface (OCI) driver.

Since it uses local native code, a Type 2 driver is expected to have better
performance than a Type 1 driver.

Advanced Java Programming 94


The driver uses native code (like C or C++) to access the database. It translates
JDBC calls into database-specific code.

This driver connects Java programs to a database by using database-specific APIs,


which are typically written in languages like C or C++.

Advantages:

1. Faster: Type 2 drivers generally perform better than Type 1 drivers.

2. Extra features: They offer additional features compared to Type 1 drivers.

Disadvantages:

1. Requires native library: The driver depends on native libraries, which must be
installed on the client machine.

2. Increased cost: The application might have additional costs due to the need for
native code and libraries.

Type 3 Driver: Network Protocol, Pure Java Driver

The Type 3 JDBC driver translates JDBC requests into a network protocol that is not
specific to any database.

These requests are then sent to a server, which translates them into a database-
specific protocol.

The driver communicates with a middle-tier server using a network protocol. The
middle tier then communicates with the database.

Type 3 drivers do not require native libraries to be installed on the client.

The requests can be sent to any database, making this driver database-independent.

Advantages:

1. No native library: It does not require any native libraries to be installed on


the client.

2. Database independence: It works with any database, offering flexibility.

Advanced Java Programming 95


3. Easy database switching: Allows easy switching from one database to another.

4. No client installation: The client doesn’t need to install the driver.

5. Supports multiple networking options: Can use networking options like HTTP
tunneling.

Disadvantages:

1. Slower: Performance may be slower due to the increased number of network calls.

2. Complex setup: The architecture is complicated, and it can be difficult to set


up because of the network interface.

3. Costly: Type 3 drivers are usually more expensive compared to other types of
JDBC drivers.

Type 4 Driver: Native Protocol, Pure Java Driver

The Type 4 JDBC driver directly converts JDBC requests into database-specific
network protocols, allowing Java programs to connect directly to a database.

This type of driver is written entirely in Java, with no need for native code.

It connects directly to the database without needing any additional middleware or


translation layers.

Oracle’s Thin Driver is an example of a Type 4 driver.

Advantages:

1. Platform independence: Being fully written in Java, Type 4 drivers achieve


platform independence, making them ideal for web applications. There are no
deployment issues related to platform compatibility.

2. Better performance: Fewer translation layers lead to better performance because


the driver doesn’t need to translate requests into ODBC or other protocols.

3. No additional installation: No need for special software on the client or


server, and these drivers can be downloaded dynamically.

Disadvantage:
Database-specific: A separate driver is required for each type of database, which
could be a limitation if you work with multiple databases.

Java Interfaces and Driver Manager Class

Java provides various interfaces for connecting to the database and executing SQL
statements through the JDBC API.

These interfaces allow you to execute both normal and dynamic SQL statements.

The table below lists the main interfaces provided by JDBC:

Interface Description

This interface connects your Java application to the


Connection
database.

Advanced Java Programming 96


Interface Description

This interface provides vendor-specific implementations


Driver
of the abstract classes provided by JDBC.
Statement This interface is used to execute normal SQL statements.

This interface is used to execute dynamic SQL


PreparedStatement
statements.

This interface accepts the results from a SQL SELECT


ResultSet
statement.

1. Connection Interface:

The Connection interface provides your Java application with a connection to the
database.

It allows you to create various Statement objects for executing SQL statements.

2. Driver Interface:

The Driver interface is a database-specific object provided by the JDBC


vendor.

It contains specific information about connecting your Java application to


the database.

3. Statement Interface:

The Statement interface is created from the Connection object.

It is used to execute standard SQL statements.

It provides three main methods:

execute()

executeQuery()

executeUpdate()

4. PreparedStatement Interface:

The PreparedStatement interface enables the execution of dynamic SQL statements.

It is typically used when you need to execute the same SQL query multiple
times with different values.

5. ResultSet Interface:

The ResultSet interface is created to get the results from a SQL SELECT

statement.

A SELECT statement returns a cursor, which the ResultSet interface uses to


navigate through the result set.

It provides methods to get information from different columns in the result


set.

Driver Interface

A JDBC driver is a software component that enables a Java application to interact


with a database.

To connect to different databases, JDBC requires specific drivers for each one.

The JDBC driver establishes a connection to the database.

It implements the protocol for transferring SQL queries and results between the
client (Java application) and the database.

JDBC Driver Example:

oracle.jdbc.driver.OracleDriver for Oracle database connections.

com.mysql.jdbc.Driver for MySQL database connections.

sun.jdbc.odbc.JdbcOdbcDriver for MS Access database connections.

Advanced Java Programming 97


The Driver interface is crucial and must be implemented by every driver class.

This interface provides vendor-specific implementations for connecting Java


applications to databases.

Loading a JDBC Driver:

When a driver class is loaded, it registers itself with the DriverManager .

To manually load and register a driver, you use the Class.forName() method:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

In JDK 6 or higher, the Class.forName() method is no longer required for loading the
driver.

The driver is automatically loaded when your application requests its first
database connection.

DriverManager Class

The JDBC DriverManager is a crucial class that connects Java applications to a JDBC
driver.

It is the backbone of the JDBC architecture and plays a key role in loading the
appropriate driver and establishing a connection to the database.

Responsibilities of DriverManager

Load Drivers: The DriverManager loads all the available JDBC drivers in the system.

Select Driver: It selects the most suitable driver to establish a connection to


a database.

Act as an Interface: It acts as an interface between the user and the drivers,
keeping track of registered drivers and managing connections.

Registering and Deregistering Drivers:

registerDriver() : Registers a JDBC driver.

deregisterDriver() : Deregisters a JDBC driver from the DriverManager .

Methods of DriverManager Class:

Method Description

Registers the given driver with the


void registerDriver(Driver driver)
DriverManager .

Deregisters the given driver (removes it from


void deregisterDriver(Driver driver)
the list).

Establishes a connection using the provided


Connection getConnection(String url)
URL.

Connection getConnection(String url, Establishes a connection using the provided


String username, String password) URL, username, and password.

Example for Connecting to MS Access Database:

Since Java 8 removed the JDBC ODBC bridge driver ( sun.jdbc.odbc.JdbcOdbcDriver ), to connect
to a MS Access database, you need to use a third-party driver like UCanAccess.

1. Download UCanAccess: Download the latest version from UCanAccess Website.

2. Extract Files: Extract the ZIP folder, and you will find the following JAR
files:

hsqldb.jar

jackcess 2.0.4.jar

commons-lang-2.6.jar

commons-logging-1.1.1.jar

ucanaccess-2.0.8.jar

Advanced Java Programming 98


3. Add JARs to Project:

Right-click on the project → Properties → Libraries → Add JARs.

4. Connect to Database:
Below is an example code to check if the connection to an MS Access database (
Database2.accdb ) is successful:

import java.sql.*;

public class Main {


public static void main(String[] args) {
ResultSet rs;
try {
// Database URL for MS Access using UCanAccess
String url = "jdbc:ucanaccess://C:\\Users\\Jay\\Documents\\Database2.a
ccdb";

Connection con = DriverManager.getConnection(url);

System.out.println("Connection to database created");

con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Output:

Connection to database created

This code will connect to the Database2.accdb file and print a success message if
the connection is established successfully.

Connection Interface

A Connection represents the session between a Java application and the database.

It is an essential part of JDBC, as it allows your application to interact with the


database, execute queries, and manage transactions.

Since the Connection interface is just an interface, it cannot be instantiated


directly. Instead, it is created using the DriverManager.getConnection() method, which
establishes a connection to the database.

Advanced Java Programming 99


Connection con = DriverManager.getConnection(URL);

When you call this method, a Connection object is created, establishing a permanent
connection between the Java application and the database.

Methods of the Connection Interface:

Method Description

Creates a Statement object used to execute SQL


createStatement()
queries.

createStatement(int Creates a Statement object that will generate


resultSetType, int ResultSet objects with the specified type and
resultSetConcurrency) concurrency.

Enables or disables automatic transaction commit. If


true , every SQL statement is automatically
setAutoCommit(boolean status)
committed. If false , you control when to commit or
roll back.

Commits the current transaction, making changes


commit()
permanent in the database.

Rolls back the current transaction, discarding any


rollback()
changes made since the last commit or rollback.

Closes the connection and releases JDBC resources


close()
immediately.

Creates a PreparedStatement object for executing


prepareStatement(String sql) dynamic SQL queries, where some parameters may not
be known at the time of creating the statement.

Example:

import java.sql.*;

public class Main {


public static void main(String[] args) {
ResultSet rs;
try {
String url = "jdbc:ucanaccess://C:\\Users\\Jay\\Documents\\Database2.accd
b";
Connection con = DriverManager.getConnection(url);
System.out.println("Connection to database created");

Statement st = con.createStatement();
System.out.println("Statement object created");

con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Statement Interface

The Connection object connects you to the database, but to execute SQL statements and
retrieve results, you need a Statement object.

The Statement object cannot be created directly. You must first create a Connection
object and then use its createStatement() method to create a Statement object.

The createStatement() method returns a Statement object that you can use to execute SQL
queries or updates.

Steps to create a Statement object:

Advanced Java Programming 100


1. Establish a connection to the database:

Connection con = DriverManager.getConnection(URL);

2. Create the Statement object by calling createStatement() on the Connection object:

Statement st = con.createStatement();

Methods of the Statement Interface:

1. executeQuery(String sql)

Used to execute SQL SELECT queries.

It returns a ResultSet object that contains all the records that match the
SELECT query's criteria.

2. executeUpdate(String sql)

Used to execute SQL update statements like DELETE , INSERT , and UPDATE .

It returns an integer indicating how many records were affected by the SQL
statement.

3. execute(String sql)

Executes a SQL statement that may return true or false (used primarily for
SQL statements that do not return data, like CREATE or DROP ).

4. executeBatch()

Executes a batch of SQL commands that you have added to the batch.

5. close()

Closes the Statement object and releases any resources it holds.

Example:

import java.sql.*;

public class Main {


public static void main(String[] args) {
ResultSet rs;
try {
String url = "jdbc:ucanaccess://C:\\Users\\Jay\\Documents\\Database2.accd
b";
Connection con = DriverManager.getConnection(url);
System.out.println("Connection to database created");

Statement st = con.createStatement();
System.out.println("Statement object created");

st.executeUpdate("INSERT INTO Student(Rollno, Name) VALUES(333, 'Sanke


t')");
System.out.println("One record inserted successfully");

st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

ResultSet Interface

Advanced Java Programming 101


A ResultSet in JDBC represents the result of a database query and provides access to
the data in a tabular format (rows and columns).

It acts as an iterator, allowing you to traverse through the rows in a result set,
typically returned by a Statement or PreparedStatement .

The cursor in a ResultSet object initially points before the first row, and you move
it to the next row using methods like next() .

Once the cursor reaches the end, the next() method returns false , indicating no more
rows are available.

Methods of ResultSet Interface:

Method Description

Moves the cursor to the next row. Returns


boolean next() true if the cursor is moved, false if no
more rows.

Moves the cursor to the previous row.


boolean previous() Returns true if successful, false if no
previous row exists.

Moves the cursor to the first row. Returns


boolean first() true if the cursor is successfully
positioned at the first row.

Moves the cursor to the last row. Returns


boolean last() true if successful, false if the result set
is empty.

Moves the cursor to the specified row


boolean absolute(int row) number. Returns true if the row exists,
false otherwise.

Moves the cursor to a row that is a


boolean relative(int rows) specified number of rows ahead or behind the
current position.

Retrieves the integer value of the specified


int getInt(int columnIndex)
column index in the current row.

Retrieves the integer value of the specified


int getInt(String columnName)
column name in the current row.

Retrieves the string value of the specified


String getString(int columnIndex)
column index in the current row.

Retrieves the string value of the specified


String getString(String columnName)
column name in the current row.

Example:

import java.sql.*;

public class ResultSetExample {


public static void main(String[] args) {
try {
String url = "jdbc:ucanaccess://C:\\Users\\Jay\\Documents\\Database2.accd
b";
Connection con = DriverManager.getConnection(url);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT Rollno, Name FROM Student");

while (rs.next()) {
int rollNo = rs.getInt("Rollno");
String name = rs.getString("Name");
System.out.println("Rollno: " + rollNo + ", Name: " + name);
}

rs.close();
st.close();

Advanced Java Programming 102


con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

PreparedStatement Interface

The PreparedStatement interface in JDBC allows you to execute SQL statements with
dynamic parameters, making it safer and more efficient than using Statement objects,
especially when dealing with user inputs.

It also helps prevent SQL injection attacks because it ensures that parameters are
automatically escaped by the database.

Creating a PreparedStatement :

To create a PreparedStatement object, you must first establish a Connection to the


database and then call the prepareStatement() method on the Connection object.

The SQL statement in the PreparedStatement can contain placeholders ( ? ) for


parameters that will be set later.

Example:

String sql = "SELECT * FROM Studentinfo WHERE college = ?";


PreparedStatement stmt = connection.prepareStatement(sql);

In this example, the ? acts as a placeholder, and you will specify the actual value
to be used in the query later.

Methods of PreparedStatement Interface:

1. void setInt(int parameterIndex, int value)

Sets an integer value for the specified parameter at the given index.

2. void setString(int parameterIndex, String value)

Sets a string value for the specified parameter at the given index.

3. void setDouble(int parameterIndex, double value)

Sets a double value for the specified parameter at the given index.

4. void setDate(int parameterIndex, Date value)

Sets a Date value for the specified parameter at the given index.

5. void setBoolean(int parameterIndex, boolean value)

Sets a boolean value for the specified parameter at the given index.

6. ResultSet executeQuery()

Executes the SQL query and returns a ResultSet containing the results.

7. int executeUpdate()

Executes an update operation such as INSERT , UPDATE , or DELETE , and returns the
number of rows affected.

8. void execute()

Executes the SQL statement, which can be used for statements that may or may
not return a result.

9. void close()

Closes the PreparedStatement object and releases any associated resources.

10. void setNull(int parameterIndex, int sqlType)

Sets a NULL value for the specified parameter at the given index.

Advanced Java Programming 103


Example:

import java.sql.*;

public class PreparedStatementExample {


public static void main(String[] args) {
try {
String url = "jdbc:ucanaccess://C:\\Users\\Jay\\Documents\\Database2.accd
b";
Connection con = DriverManager.getConnection(url);

// SQL query with dynamic parameter


String sql = "SELECT * FROM Studentinfo WHERE college = ?";
PreparedStatement stmt = con.prepareStatement(sql);

// Set the dynamic parameter (college name)


stmt.setString(1, "Engineering College");

// Execute the query


ResultSet rs = stmt.executeQuery();

// Process the result set


while (rs.next()) {
System.out.println("Student Name: " + rs.getString("Name"));
System.out.println("Roll No: " + rs.getInt("RollNo"));
System.out.println("College: " + rs.getString("College"));
}

// Close resources
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

The Essential JDBC Program

The following program demonstrates the creation of Connection and Statement objects and
performs multiple operations on a database:

import java.sql.*;

public class DatabaseOperations {


public static void main(String[] args) {
try {
// Database URL
String url = "jdbc:ucanaccess://C:\\Users\\Jay\\Documents\\Database2.accdb";

// Establishing Connection
Connection con = DriverManager.getConnection(url);
System.out.println("Connection to database established.");

// Creating Statement object


Statement st = con.createStatement();
System.out.println("Statement object created.");

Advanced Java Programming 104


// 1. Insertion of a record
String insertQuery = "INSERT INTO Student (Rollno, Name) VALUES (147, 'Jay Ka
dlag')";
st.executeUpdate(insertQuery);
System.out.println("Record inserted successfully.");

// 2. Deletion of a record
String deleteQuery = "DELETE FROM Student WHERE Rollno = 147";
st.executeUpdate(deleteQuery);
System.out.println("Record deleted successfully.");

// 3. Updation of a record
String updateQuery = "UPDATE Student SET Name = 'Nikhil Dabhade' WHERE Rollno
= 126";
st.executeUpdate(updateQuery);
System.out.println("Record updated successfully.");

// 4. Retrieval of all records


String selectQuery = "SELECT * FROM Student";
ResultSet rs = st.executeQuery(selectQuery);
System.out.println("Records retrieved:");
while (rs.next()) {
System.out.println("Rollno: " + rs.getInt("Rollno") + ", Name: " + rs.getSt
ring("Name"));
}

rs.close();
st.close();
con.close();
System.out.println("All operations completed and resources closed.");

} catch (Exception e) {
e.printStackTrace();
}
}
}

Chapter 6 - Servlets
Introduction

With the emergence of the Internet, web technologies have become more important,
and web applications have become more common.

Initially, web pages were static, where a user requested a resource, and the server
returned it.

With the growth of commercial activities on the web, companies wanted to deliver
dynamic content such as online banking transactions, ticket bookings, news, and
marketing.

To deliver dynamic content, servlet technology was introduced.

Java Servlets are programs that run on a web or application server and act as a
middle layer between a web browser's request and databases or applications on the
HTTP server.

Advanced Java Programming 105


Servlets can:

Collect input from users via web page forms.

Present records from a database or another source.

Create web pages dynamically.

Web applications are helper applications that reside on a web server and build
dynamic web pages.

A dynamic page can be anything from randomly chosen images to a page displaying the
current time.

As servlet technology uses Java, web applications made with servlets are secure,
scalable, and robust.

Servlet

Servlets are Java programs that run on a Java-enabled web server or application
server.

They handle requests from the web server, process the requests, generate responses,
and send the response back to the web server.

Servlets provide a component-based, platform-independent method for building web-


based applications without the performance limitations of CGI programs.

Servlets have access to the entire family of Java APIs, including the JDBC API to
access enterprise databases.

Java Servlet Technology

Java Servlet technology is used to create web applications that reside on the
server side and generate dynamic web pages.

A Java servlet is a server-side program that services HTTP requests and returns the
result as HTTP responses.

A servlet:

Is a Java program that runs on a server to handle client requests.

Is supported by virtually all web and application servers.

Solves performance issues by executing requests as threads in one process.

Is used for creating dynamic web applications.

When a user requests a URL corresponding to a servlet, the server forwards the
request to the servlet for processing.

The servlet dynamically generates a response (usually an HTML web page) and sends
it back to the client’s web browser.

A Java Servlet:

Advanced Java Programming 106


Web servers use servlets to access databases, extract data, and convert it into a
format (e.g., HTML) that can be sent to the client’s browser over the internet.

Common interfaces and classes in the servlet API include:

Servlet

GenericServlet

HttpServlet

ServletRequest

ServletResponse

Position of Servlet in Web Application:

Tasks of Servlets:

1. Read explicit data sent by clients (e.g., HTML form data or custom HTTP client
programs).

2. Read implicit HTTP request data sent by clients (e.g., cookies, media types,
compression schemes).

3. Process the data and generate results (which may involve database interaction).

4. Send the explicit data (e.g., document, HTML, XML, images, etc.) to the client.

5. Send the implicit HTTP response (e.g., document type, cookies, caching settings)
to the client.

Servlet vs. CGI

CGI (Common Gateway Interface) was the first method to provide dynamic content to
users.

It allows users to execute programs residing on the server to process data and
access databases to generate relevant content.

CGI Processing:

Advanced Java Programming 107


These programs were written in the native operating system language and stored in a
specific directory.

Servlets are a Java-based implementation that aims to provide the same


functionality as CGI.

Instead of being written in native operating system languages, servlets are


compiled into Java bytecode.

The bytecode is then executed in the Java Virtual Machine (JVM).

Servlet Processing:

Differences between CGI and Servlet:

CGI Servlet

CGI creates a new process for each Servlet creates a thread for each request and
request. services it in that thread.

Servlets operate in the same parent process


Each process created by CGI is assigned a
address space, with no separate address space
separate address space.
for each thread.

CGI cannot directly link to the web


Servlets can link directly to the web server.
server.

CGI does not provide a sharing property


Servlets can share data among each other.
between processes.

CGI cannot perform session tracking or Servlets can perform session tracking and
caching of previous computations. cache previous computations.

CGI programs are platform dependent and Servlets are platform independent and
not portable. portable.

In Servlets, the Java Virtual Machine (JVM)


In CGI, each request is handled by a
stays up, and each request is handled by a
heavyweight operating system process.
lightweight Java thread.

CGI cannot automatically parse and decode Servlets automatically parse and decode HTML
HTML form data. form data.

CGI cannot read or set HTTP headers, Servlets can read and set HTTP headers,
handle cookies, or track sessions. handle cookies, and track sessions.

CGI is more expensive in terms of Servlets are less expensive and more
resources and execution time. efficient than CGI.

Advantages of Servlets

1. Performance: Servlets are handled by the servlet container process. Once a servlet
completes a request, it stays in memory, ready to handle the next one.

2. Portability: Like other Java technologies, servlet applications are portable,


meaning they can run on different platforms without changes.

3. Rapid Development: Servlets benefit from the extensive Java library, making it
easier and faster to develop applications.

4. Robustness: Servlets run under the Java Virtual Machine (JVM), which manages memory
and handles garbage collection, ensuring that applications are stable and reliable.

Advanced Java Programming 108


5. Widespread Acceptance: Java is widely used, meaning many vendors support Java-based
technologies, making it easier to find solutions and support.

6. Security: Servlet technology is secure because it is based on the Java programming


language, which is known for its strong security features.

Servlet Application Architecture

A servlet is a Java class that is dynamically loaded and executed by a special web
server when it receives a request from the client.

This web server, known as the servlet container (or servlet engine in the earlier
days of servlet technology), is responsible for running servlets.

Servlets communicate with clients using a request-response model based on the HTTP
protocol.

Servlet Application Architecture:

A typical servlet application architecture can include both dynamic content


generated by servlets and static content like HTML pages and image files.

However, it is not ideal for the servlet container to serve static content because
this is more efficiently handled by a robust HTTP server (e.g., Apache Web Server
or Microsoft Internet Information Server).

Therefore, it is common practice to place a web server in front to handle all


client requests.

Servlet Application Architecture with an HTTP Server:

The web server serves static content and forwards requests for servlets to the
servlet container for processing.

Types of Servlets

There are two types of servlets: GenericServlet and HttpServlet .

GenericServlet : Defines a generic servlet that is protocol-independent.

: A subclass of GenericServlet that provides HTTP-specific functionality,


HttpServlet

such as the doGet and doPost methods.

Generic Servlets

The GenericServlet class extends javax.servlet.GenericServlet .

For example:

public class NewServlet1 extends GenericServlet {


// Servlet implementation here

Advanced Java Programming 109


}

is protocol-independent, meaning it does not have built-in support for


GenericServlet

HTTP or any other specific protocol.

It provides a foundation for creating servlets that can handle different types of
protocols.

HTTP Servlets

The HTTPServlet class extends javax.servlet.HttpServlet .

Example:

public class Main extends HttpServlet {


// Servlet implementation here
}

HTTP servlets have built-in support for the HTTP protocol and are particularly
useful in a Sun Java System Web Server environment.

Common Methods:

init() : Initializes the servlet (used for resource allocation).

destroy() : Deallocates resources when the servlet is destroyed.

: Handles all incoming servlet requests. It is implemented for both


service()

servlet types, but HTTP servlets have additional handling to route requests
based on the HTTP transfer method.

HTTP-specific Methods:

doPost() : Used to handle POST requests.

doGet() : Used to handle GET requests.

For HTTP servlets, overriding these methods (like doGet() or doPost() ) allows for
handling different types of HTTP requests.

Life Cycle of a Servlet

A Java program becomes a Servlet by implementing the javax.servlet.Servlet interface.

This interface is the foundation of all servlet programming. Every servlet must
implement this interface, either directly or indirectly.

The lifecycle of a servlet refers to the process from its creation to its
destruction.

The key steps in the lifecycle are:

1. Initialization:

The servlet is initialized using the init() method.

2. Request Handling:

The servlet processes client requests by calling the service() method.

3. Termination:

The servlet is terminated with the destroy() method.

4. Garbage Collection:

Finally, the servlet is garbage-collected by the JVM when no longer needed.

Steps in Servlet Processing:

The HTTP request from the client is sent to the web server.

The web server passes this request to the servlet container.

The servlet container:

Advanced Java Programming 110


Loads the servlet if it’s not already loaded.

Calls the service() method to process the request.

For multiple requests, the servlet container creates threads, each executing the
service() method.

Servlet Methods:

1. init() Method:

Called once when the servlet is initialized.

Prepares the servlet for service by allocating necessary resources.

Syntax:

public void init(ServletConfig config) throws ServletException

The ServletConfig object contains configuration details specified in the


web.xml file.

2. service() Method:

Called for each request to handle the logic of processing client data.

For generic servlets, this method can be overridden directly.

For HTTP servlets, it automatically dispatches requests to other methods like


doGet() or doPost() based on the HTTP request type.

Syntax for a generic servlet:

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException {
// Servlet logic
}

Syntax for an HTTP servlet:

public void service(HttpServletRequest request, HttpServletResponse respon


se)
throws ServletException, IOException {
// Servlet logic
}

Roles of service() :

ServletRequest carries client information.

ServletResponse sends the server’s response back to the client.

For HTTP requests:

Routes GET requests to doGet() method.

Routes POST requests to doPost() method.

Can also handle other HTTP methods like doPut() and doDelete() .

HTTP-Specific Methods:

1. doGet() Method:

Handles HTTP GET requests.

Used when:

A form is submitted with the GET method.

A form does not specify any method (defaults to GET).

Syntax:

Advanced Java Programming 111


public void doGet(HttpServletRequest request, HttpServletResponse respons
e)
throws ServletException, IOException {
// Logic for handling GET requests
}

2. doPost() Method:

Handles HTTP POST requests.

Used when a form is submitted with the POST method.

Syntax:

public void doPost(HttpServletRequest request, HttpServletResponse respons


e)
throws ServletException, IOException {
// Logic for handling POST requests
}

3. destroy() Method:

Called when the servlet is about to be removed from service.

Releases resources held by the servlet (e.g., closing database connections).

Usually called when:

The servlet container shuts down.

The servlet is no longer needed.

Syntax:

public void destroy() {


// Cleanup code
}

Creating Simple Servlet

There are three ways to create a servlet in Java:

1. By implementing the Servlet interface.

2. By extending the GenericServlet class.

3. By extending the HttpServlet class.

Steps to Create a Servlet Application in NetBeans IDE:


Step 1 : Create a New Project

Open NetBeans.

Go to File > New Project .

In the dialog, select Java Web > Web Application , and click Next .

Advanced Java Programming 112


Step 2 : Name Your Project

Enter a name for your project and click Next .

Step 3 : Create a Servlet Class

Once the project is created, locate the project directory in the Projects tab.

Right-click on Source Packages > New > Servlet .

Step 4 : Configure the Servlet

Enter a name for your servlet class and click Next .

Advanced Java Programming 113


On the next screen, check the box "Add information to deployment descriptor (web.xml)" .

Click Finish .

Step 5 : web.xml File

A web.xml file is automatically created in the WEB-INF folder. Below is the structure
of the file:

<?xml version="1.0" encoding="UTF-8"?>


<web-app version="3.1" xmlns="<http://xmlns.jcp.org/xml/ns/javaee>"
xmlns:xsi="<http://www.w3.org/2001/XMLSchema-instance>"
xsi:schemaLocation="<http://xmlns.jcp.org/xml/ns/javaee>
<http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd>">

<servlet>
<servlet-name>SimpleServlet</servlet-name>
<servlet-class>SimpleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SimpleServlet</servlet-name>
<url-pattern>/SimpleServlet</url-pattern>
</servlet-mapping>

<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>

Step 6 : Write Servlet Code

In the generated SimpleServlet.java file, write the following code:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class SimpleServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();

out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Servlet Testing</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<p>Welcome to the Servlet Programming</p>");
out.println("</BODY>");

Advanced Java Programming 114


out.println("</HTML>");
}
}

Step 7 : Run the Servlet

In the Projects tab, select the file SimpleServlet.java .

Right-click and select Run File .

The output will display in your browser, showing a simple HTML page with the
message:

Welcome to the Servlet Programming

Servlet API

The Servlet API is divided into two Java packages:

1. javax.servlet Package

This package is used for handling requests that are not specific to any
protocol.

It contains interfaces and classes that all servlets need to implement or


extend.

Every servlet must implement the Servlet interface in some way.

The abstract class GenericServlet provides a basic framework for creating simple
servlets.

2. javax.servlet.http Package

This package is designed for creating servlets that use the HTTP protocol.

It includes the abstract class HttpServlet , which extends GenericServlet and serves as
the base class for HTTP-based servlets.

The interfaces HttpServletRequest and HttpServletResponse allow servlets to interact with


clients more effectively.

This package also provides HttpSession and related classes to enable session
tracking.

javax.servlet Package

The javax.servlet package is the core of the Servlet API.

It provides the basic building blocks required for creating and managing servlets.

The package includes the Servlet interface, which every servlet must implement in
some way.

It also contains an abstract class, GenericServlet , which provides a foundation for


creating basic servlets.

Advanced Java Programming 115


This package enables communication between the servlet, the host server, and the
client.

It is primarily used to handle protocol-independent requests.

Purpose: To create servlets that can process requests and responses.

Interfaces and Classes:

Interfaces Classes
Servlet GenericServlet

ServletRequest ServletInputStream

ServletResponse ServletOutputStream

RequestDispatcher ServletRequestWrapper

ServletConfig ServletResponseWrapper

ServletContext ServletRequestEvent

SingleThreadModel ServletContextEvent

Filter ServletRequestAttributeEvent

FilterConfig ServletContextAttributeEvent

ServletRequestListener ServletException

Servlet Interface

The Servlet interface defines a collection of methods that a servlet must


implement, either directly or indirectly (by extending GenericServlet or HttpServlet ).

It provides the necessary functionalities for:

Initializing the servlet

Handling client requests

Destroying the servlet

Methods of Servlet interface:

1. void init(ServletConfig config)

This method is used to initialize the servlet with parameters provided by the
ServletConfig object.

It is called once when the servlet is first loaded, and it's typically used
to set up resources like database connections.

2. void destroy()

This method is used to clean up resources like database connections, threads,


and file handles before the servlet is destroyed.

It’s called when the servlet is about to be removed from memory.

3. void service(ServletRequest request, ServletResponse response)

This is the core method for handling client requests.

Advanced Java Programming 116


It’s called each time a request is made to the servlet, and it processes the
request and generates a response.

4. ServletConfig getServletConfig()

This method returns the ServletConfig object, which contains the configuration
information for the servlet, such as initialization parameters.

5. String getServletInfo()

This method provides metadata about the servlet, such as its author, version,
and other copyright information.

Example:

import javax.servlet.*;
import java.io.*;

public class Main implements Servlet {


// Initialize the servlet
@Override
public void init(ServletConfig config) {
System.out.println("Servlet is initialized");
}

// Handle the client's request and generate the response


@Override
public void service(ServletRequest req, ServletResponse res) throws IOExceptio
n, ServletException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print("<html><body>");
out.print("<strong>A Simple Servlet</strong>");
out.print("</body></html>");
}

// Destroy the servlet and clean up resources


@Override
public void destroy() {
System.out.println("Servlet is destroyed");
}
}

ServletContext Interface

A ServletContext object represents the context of the web application and is created by
the web container for each web application.

It provides a way for servlets and JSPs within the same web app to communicate and
share configuration information.

The ServletContext object can only be accessed after the web application's
initialization and can be used by any servlet or JSP within the web app to get
configuration details.

Methods of ServletContext Interface:

1. Object getAttribute(String name) :

Retrieves the attribute (usually a value or object) with the given name from
the application scope.

If the attribute is not found, it returns null .

2. String getInitParameter(String name) :

Advanced Java Programming 117


Retrieves the initialization parameter value associated with the given
parameter name from the web application's deployment descriptor ( web.xml ).

If the parameter doesn't exist, it returns null .

3. Enumeration getInitParameterNames() :

Returns an enumeration of all initialization parameter names from the web


application's web.xml as a collection of String objects.

4. void setAttribute(String name, Object obj) :

Sets an object as an attribute in the application scope with the specified


attribute name. This makes it available to all servlets and JSPs in the web
application.

5. void removeAttribute(String name) :

Removes the attribute with the given name from the application context.

ServletConfig Interface

The ServletConfig interface is used to provide configuration information to a servlet


when it is initialized by the web container.

This information is typically obtained from the web.xml file (also known as the
Deployment Descriptor) and is accessible by the servlet to configure itself
properly.

Methods of ServletConfig Interface:

1. String getInitParameter(String name) :

Retrieves the value of a specific initialization parameter by its name, which


was defined in the web.xml file.

If the parameter doesn't exist, it returns null .

2. Enumeration getInitParameterNames() :

Returns an enumeration of all the initialization parameter names for the


servlet.

If the servlet has no initialization parameters, it returns an empty


enumeration.

3. ServletContext getServletContext() :

Returns the ServletContext object, which provides information about the web
application as a whole.

This object allows access to context-wide resources and configuration


details.

4. String getServletName() :

Returns the name of the servlet instance as defined in the web.xml file or by
the servlet container.

ServletRequest Interface

When a servlet receives a request from a client, it is given two objects:


ServletRequest and ServletResponse .

The ServletRequest interface handles the communication from the client to the server
and allows the servlet to access various details about the request.

The ServletRequest interface provides information such as:

Names of the parameters sent by the client.

The protocol (e.g., HTTP methods like POST and PUT) used by the client.

The name of the remote host (client) making the request.

The server that received the request.

Advanced Java Programming 118


An InputStream to read binary data from the request body.

Methods of ServletRequest Interface:

1. Object getAttribute(String name) :

Returns the value of the specified attribute as an object.

2. Enumeration getAttributeNames() :

Returns an enumeration of all attribute names associated with the request.

3. String getParameter(String name) :

Returns the value of a specific request parameter as a String .

4. Enumeration getParameterNames() :

Returns an enumeration of all the parameter names in the request.

5. String[] getParameterValues(String name) :

Returns an array of String values for the specified request parameter.

ServletResponse Interface

The ServletResponse interface provides methods for the servlet to send a response back
to the client.

It allows the servlet to:

1. Set the content type and length of the response.

2. Provide an output stream or writer for sending data.

Subclasses of ServletResponse , such as HttpServletResponse , offer more protocol-specific


features.

For example, HttpServletResponse includes methods to manipulate HTTP-specific headers.

Methods of ServletResponse Interface:

1. Locale getLocale() :

Returns the locale assigned to the response.

2. PrintWriter getWriter() :

Returns a PrintWriter object that can be used to send character text to the
client.

3. void reset() :

Clears any data in the response buffer and resets the status code and
headers.

4. void setLocale(Locale locale) :

Sets the locale for the response.

5. void setContentType(String type) :

Sets the content type for the response (e.g., text/html , application/json ).

The ServletResponse interface is essential for sending responses to the client.

The most important method is getWriter() , which returns a PrintWriter object. You can
use this object to send text, including HTML tags, back to the client.

Example:
index.html :

<html>
<head>
<title>Sending a request</title>
</head>
<body>
<form action="RequestDemoServlet" method="GET">

Advanced Java Programming 119


<br><br>
Author: <input type="text" name="Author">
<input type="submit" name="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>

RequestDemoServlet.java :

import javax.servlet.*;
import java.io.*;

public class RequestDemoServlet implements Servlet {


// Initialize the servlet (called once when the servlet is loaded)
public void init(ServletConfig config) throws ServletException { }

// Destroy the servlet (clean up resources)


public void destroy() { }

// Handle the request from the client and generate the response
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {

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

// Get and display information about the request


out.println("<html><body>");
out.println("Server Port: " + request.getServerPort() + "<br>");
out.println("Server Name: " + request.getServerName() + "<br>");
out.println("Protocol: " + request.getProtocol() + "<br>");
out.println("Content Type: " + request.getContentType() + "<br>");
out.println("Content Length: " + request.getContentLength() + "<br>");
out.println("Remote Address: " + request.getRemoteAddr() + "<br>");
out.println("Remote Host: " + request.getRemoteHost() + "<br>");

// Get and display the "Author" parameter sent by the client


String author = request.getParameter("Author");
out.println("Author Name: " + author + "<br>");

out.println("</body></html>");
}

// Get servlet configuration details (optional)


public String getServletInfo() { return null; }

// Get servlet configuration (optional)


public ServletConfig getServletConfig() { return null; }
}

Problem with the Servlet Interface:

Although everything works fine, there are two issues you might have noticed:

1. Unnecessary Method Implementations:

You have to implement all five methods of the Servlet interface, even though
you only need one or two for most of your work. This makes the code look more
complicated than it needs to be.

Advanced Java Programming 120


2. ServletConfig Object:

The ServletConfig object is passed to the init method, and you need to save it
for use in other methods. While this is not difficult, it adds extra work to
your code.

These problems are solved by using GenericServlet .

GenericServlet Class

javax.servlet.GenericServlet is a class that provides a basic implementation of the Servlet

and ServletConfig interfaces. It makes writing servlets easier and simpler.

The GenericServlet class is a wrapper that implements two important interfaces from the
javax.servlet package: Servlet and ServletConfig . It also implements the java.io.Serializable

interface.

This class provides default implementations for all the methods, most of which are
blank. You can extend GenericServlet and override only the methods you need. This
simplifies your code, as you don't have to implement every method.

After switching your program from a basic servlet to GenericServlet , you only need to
write the service method. All other methods are either already implemented or don't
need to be explicitly written.

Methods of the GenericServlet class:

1. void init(ServletConfig config)

Called once to initialize the servlet.

2. abstract void service(ServletRequest request, ServletResponse response)

This method handles the incoming requests. It is invoked each time a user
requests the servlet.

3. void destroy()

Called once when the servlet is being destroyed.

4. ServletConfig getServletConfig()

Returns the ServletConfig object.

5. String getServletInfo()

Returns information about the servlet, such as the author, version, etc.

6. ServletContext getServletContext()

Returns the ServletContext object.

7. String getInitParameter(String name)

Returns the value of the specified initialization parameter.

8. Enumeration getInitParameterNames()

Returns all initialization parameters defined in the web.xml file.

9. String getServletName()

Returns the name of the servlet.

10. void log(String msg)

Writes a message to the servlet log file.

11. void log(String msg, Throwable t)

Writes a message and a stack trace to the servlet log file.

By using GenericServlet , you can easily extend the functionality of your servlet with
minimal effort.

Example:

import java.io.*;
import javax.servlet.*;

Advanced Java Programming 121


public class GenericServletDemo extends GenericServlet {
public void service(ServletRequest req, ServletResponse res) throws IOExceptio
n, ServletException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();

out.print("<html><body>");
out.print("<b>A Generic servlet</b>");
out.print("</body></html>");
}
}

Problem with GenericServlet :

1. The GenericServlet class is protocol-dependent.

2. Being protocol-dependent means that it can work with multiple protocols such as
HTTP, SMTP, POP3, etc.

3. However, it mainly provides services for requests coming from any protocol.

4. While GenericServlet can handle requests from the HTTP protocol, it doesn't support
all the features (methods) that HTTP provides.

5. Therefore, we need a servlet that supports the full functionality of the HTTP
protocol.

Http Methods

The HttpServlet is used when we need to access all the features (methods) of the HTTP
protocol.

Each HTTP request can use one of the various request methods as specified by the
HTTP standards.

Most commonly used HTTP request methods:

1. GET: The most common HTTP method, used to retrieve data identified by the URL.

2. HEAD: Works like GET but only returns the HTTP headers, not the document body.

3. POST: Similar to GET, but used to transfer data (such as form data) to the
server. The data is included in the body of the request.

4. OPTIONS: Used to query a server about the capabilities it provides, either


generally or for a specific resource.

5. DELETE: Used to delete a resource from the server. The document to be deleted is
specified in the URI.

6. PUT: Similar to GET, but PUT is used to store the data provided in the request
body at the location specified by the URI.

7. TRACE: Used to trace the path of a request through firewalls and proxy servers.
TRACE is useful for debugging network problems and is similar to the
"traceroute" tool.

The javax.servlet.http Package

The javax.servlet.http package is used for developing servlets that work with the HTTP
protocol.

The abstract class HttpServlet extends javax.servlet.GenericServlet and serves as the base
class for HTTP-specific servlets.

The HttpServletRequest and HttpServletResponse interfaces provide additional functionality


for interaction with the client.

Advanced Java Programming 122


This package also includes HttpSession and related classes to support session
tracking.

Interfaces:

1. HttpServletRequest

2. HttpServletResponse

3. HttpSession

4. HttpSessionListener

5. HttpSessionAttributeListener

6. HttpSessionBindingListener

Classes:

1. HttpServlet

2. Cookie

3. HttpServletRequestWrapper

4. HttpServletResponseWrapper

5. HttpSessionEvent

HttpServlet Class

The HttpServlet class extends the javax.servlet.GenericServlet class and adds several methods
specifically designed for HTTP requests.

The most important of these methods are the different doXXX methods that are invoked
when a related HTTP request method is used.

The six main doXXX methods are:

doPost

doPut

doGet

doDelete

doOptions

doTrace

Each doXXX() method is called when the corresponding HTTP method (e.g., GET, POST,
etc.) is used.

For example, the doGet method is called when the servlet receives an HTTP request
sent using the GET method.

Example of doPost method:


Consider this HTML form on the client side:

<form action="Register" method="post">


<input type="text" name="firstName">
<input type="text" name="lastName">
<input type="submit">
</form>

When the user clicks the Submit button, the browser sends an HTTP request to the
server using the POST method. The web server then passes this request to the Register
servlet, and the doPost method of the servlet is invoked.

In the POST method, the parameter name/value pairs from the form are sent in the
request body. For example, if the user enters "Rushikesh" for firstName and "Gunjal"
for lastName , the request body will look like this:

Advanced Java Programming 123


firstName=Rushikesh
lastName=Gunjal

Example of doGet method:


An HTML form can also use the GET method. When a form uses GET, the parameter
name/value pairs are appended to the URL. Upon receiving a GET request, the servlet
calls its doGet method.

In this way, the HTTP method used by the client request determines which doXXX

method gets called in the servlet.

Methods of HttpServlet class:

1. void service(ServletRequest req, ServletResponse res)

This method dispatches the request to the protected service method by


converting the request and response objects into HTTP types.

2. void service(HttpServletRequest req, HttpServletResponse res)

This method receives the request from the service method and sends it to the
correct doXXX() method depending on the type of HTTP request (GET, POST,
etc.).

3. void doGet(HttpServletRequest req, HttpServletResponse res)

This method handles HTTP GET requests.

It is called when the server receives a GET request from the client.

4. void doPost(HttpServletRequest req, HttpServletResponse res)

This method handles HTTP POST requests.

It is called when the server receives a POST request from the client.

5. void doHead(HttpServletRequest req, HttpServletResponse res)

This method handles HTTP HEAD requests.

It is similar to the GET method but does not return the body of the document,
only the headers.

6. void doOptions(HttpServletRequest req, HttpServletResponse res)

This method handles HTTP OPTIONS requests.

It is used to find out the capabilities of the server or a specific resource.

7. void doPut(HttpServletRequest req, HttpServletResponse res)

This method handles HTTP PUT requests.

It is used to send data to the server to store it at a specified resource


location.

8. void doTrace(HttpServletRequest req, HttpServletResponse res)

This method handles HTTP TRACE requests.

It is used to trace the path of a request through multiple proxy servers,


useful for debugging network issues.

9. void doDelete(HttpServletRequest req, HttpServletResponse res)

This method handles HTTP DELETE requests.

It is used to delete a resource from the server.

10. long getLastModified(HttpServletRequest req)

This method returns the time when the requested resource was last modified,
measured from midnight on January 1, 1970 (GMT).

Example:

import java.io.*;
import javax.servlet.*;

Advanced Java Programming 124


import javax.servlet.http.*;

public class Main extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) th
rows ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<h1>Hare Krishna!!!</h1>");
}
}

HttpServletRequest Interface

The HttpServletRequest interface is implemented by the server and provides methods to


get information about client requests.

It allows the servlet to extract details about the request, such as:

HTTP parameters (from the query string or the request body, depending on whether
it's a GET or POST request).

Cookies.

Session tracking.

Access to HTTP headers.

The HttpServletRequest interface extends the ServletRequest interface to offer additional


methods specific to HTTP servlets.

Methods of HttpServletRequest Interface

1. Cookie[] getCookies()

Returns an array of all cookies sent by the client with the current request.

2. String getQueryString()

Returns the query string in the URL after the path. For example, in
example.com/page?name=value , the query string is name=value .

3. HttpSession getSession()

Returns the current session associated with this request. If no session


exists, it creates a new one.

Example:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Main extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Setting the response content type
response.setContentType("text/html");

// Writing response to the client


PrintWriter out = response.getWriter();
out.println("<h1>HttpServletRequest Information</h1>");
out.println("Server Port: " + request.getServerPort() + "<br>");
out.println("Server Name: " + request.getServerName() + "<br>");
out.println("Protocol: " + request.getProtocol() + "<br>");
out.println("Content Type: " + request.getContentType() + "<br>");
out.println("Content Length: " + request.getContentLength() + "<br>");
out.println("Remote Address: " + request.getRemoteAddr() + "<br>");
out.println("Remote Host: " + request.getRemoteHost() + "<br>");

Advanced Java Programming 125


}
}

Example Output:

HttpServletRequest Information
Server Port: 8080
Server Name: localhost
Protocol: HTTP/1.1
Content Type: null
Content Length: -1
Remote Address: 127.0.0.1
Remote Host: localhost

HttpServletResponse Interface

The HttpServletResponse interface is implemented by the server to allow a servlet to


send an HTTP response to the client.

It extends the ServletResponse interface to include functionality specific to the HTTP


protocol.

The HttpServletResponse interface provides additional methods for managing HTTP


responses, such as handling cookies, setting headers, sending error messages, and
redirecting requests.

Methods of HttpServletResponse Interface:

1. void addCookie(Cookie cookie)

Adds the given cookie to the response so that the client can store it.

2. void sendRedirect(String location)

Sends a temporary redirect to the client using the specified URL.

Clears the buffer before sending the response.

3. int getStatus()

Retrieves the current HTTP status code of the response.

4. String getHeader(String name)

Returns the value of the response header with the given name.

5. Collection<String> getHeaderNames()

Returns a collection of all the response header names.

6. void setHeader(String name, String value)

Sets a response header with a specific name and value.

If the header already exists, it is replaced.

7. void setStatus(int sc)

Sets the HTTP status code for the response.

8. void sendError(int sc, String msg)

Sends an error response to the client with the specified status code and
error message.

Clears the buffer before sending the response.

Example:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Main extends HttpServlet {

Advanced Java Programming 126


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set the content type of the response
response.setContentType("text/html");

// Get the PrintWriter to write the response


PrintWriter out = response.getWriter();

// Write the response content


out.println("<h1>HttpServletResponse</h1>");
out.println("Status Code: " + response.getStatus() + "<br>");
out.println("Header Names: " + response.getHeaderNames() + "<br>");

// Testing redirection
// response.sendRedirect("http://www.google.com");

out.close();
}
}

Example Output:

HttpServletResponse
Status Code: 200
Header Names: [Content-Type]

Cookie Class

HTTP is a stateless protocol, which means that every time a client (browser) makes
a request to a web server, the server treats it as a new request and does not
remember any previous interactions.

However, there are ways to maintain a session (track user interactions) between the
client and the server. Two common methods are:

1. Cookies

2. HttpSession Object

Cookies:

A web server can assign a unique session ID to a client as a cookie.

This session ID is sent with every subsequent request so that the server can
recognize the client.

However, this method might not always work because some browsers do not support
cookies or block them.

class provides the tools for creating and managing cookies. It


javax.servlet.http.Cookie

includes constructors to create cookies and methods to manage them.

Constructors:

1. Cookie()

Creates a new cookie with no name or value.

2. Cookie(String name, String value)

Creates a cookie with the given name and value.

Methods:

1. void setMaxAge(int expiry)

Sets the cookie's expiry time in seconds. After this time, the cookie will be
deleted.

2. String getName()

Advanced Java Programming 127


Returns the cookie's name. Note: The name cannot be changed after the cookie
is created.

3. String getValue()

Returns the cookie's value.

4. void setName(String name)

Changes the cookie's name.

5. void setValue(String value)

Changes the cookie's value.

Other Necessary Methods for Cookies:


To use cookies in a Java program, we also need the following methods from other
interfaces:

1. void addCookie(Cookie ck)

This method is provided by the HttpServletResponse interface.

It is used to add a cookie to the response object, so it is sent to the


browser.

2. Cookie[] getCookies()

This method is provided by the HttpServletRequest interface.

It returns all cookies sent by the browser.

Example:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Main extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();

// Creating cookies
Cookie cookie1 = new Cookie("name", "Sarthak");
Cookie cookie2 = new Cookie("name", "Nikhil");

// Adding cookies to response


response.addCookie(cookie1);
cookie1.setMaxAge(60 * 60); // 1 hour expiry

response.addCookie(cookie2);
cookie2.setMaxAge(60 * 60); // 1 hour expiry

// Printing cookies' details


pw.println("Cookies created");
pw.println(cookie1.getName() + ": " + cookie1.getValue());
pw.println(cookie2.getName() + ": " + cookie2.getValue());
}
}

HttpSession Interface

The HttpSession interface allows identifying a user across multiple page requests or
visits to a website.

It can store information about a user for the duration of a session.

Advanced Java Programming 128


The servlet container uses this interface to manage sessions between an HTTP client
and server.

A session lasts for a specified time, even if the user navigates through multiple
pages or reconnects.

Methods of HttpSession Interface

1. Object getAttribute(String name)

Retrieves an attribute from the session by its name.

Returns the value as an Object .

Throws an IllegalStateException if the session is invalid.

2. java.util.Enumeration getAttributeNames()

Returns all the attribute names in the session.

Provides the names as a java.util.Enumeration .

Throws an IllegalStateException if the session is invalid.

3. long getCreationTime()

Returns the time the session was created in milliseconds since January 1,
1970 (UTC).

Throws an IllegalStateException if the session is invalid.

4. String getId()

Returns the unique identifier for the session.

5. long getLastAccessedTime()

Returns the time (in milliseconds) when the session was last accessed by the
client.

Useful for tracking session activity.

Example:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Main extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
HttpSession s = request.getSession();

if (s != null) {
pw.println("Session Id : ");
String s_id = s.getId();
pw.println(s_id);
} else {
pw.println("Your session is not created yet");
}
}
}

HttpSessionEvent Class

The HttpSessionEvent class is used to notify changes to sessions within a web


application.

It works in combination with the HttpSessionListener interface to monitor and respond to


session events.

Advanced Java Programming 129


listens for notifications of changes to the list of active sessions
HttpSessionListener

in a web application. It provides methods for handling session creation and


destruction.

Methods in HttpSessionListener Interface

There are two key methods in the HttpSessionListener interface that must be implemented
by a servlet programmer:

1. void sessionCreated(HttpSessionEvent e)

This method is called when a session object is created. It allows you to


perform actions when a new session is started.

2. void sessionDestroyed(HttpSessionEvent e)

This method is called when a session is invalidated (destroyed). It allows


you to perform actions when a session ends.

Example:

import javax.servlet.*;
import javax.servlet.http.*;

public class MySessionListener implements HttpSessionListener {

// This method is invoked when a session is created


public void sessionCreated(HttpSessionEvent se) {
System.out.println("HttpSession Created");
HttpSession session = se.getSession();
System.out.println("Session ID: " + session.getId());
session.setMaxInactiveInterval(5 * 60); // 5 minutes in seconds
}

// This method is invoked when a session is destroyed


public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("HttpSession Destroyed");
}
}

HttpSessionBindingEvent Class

The HttpSessionBindingEvent class is used in two main ways:

1. For the HttpSessionAttributeListener interface:

It serves as input to the methods of HttpSessionAttributeListener , which allows tracking


changes to the attributes of a session.

This interface notifies when attributes are added, removed, or replaced in a


session.

2. For the HttpSessionBindingListener interface:

It serves as input to the methods of HttpSessionBindingListener , which notifies when an


object is bound to or unbound from a session.

This is used for objects that need to track when they are added or removed from
a session.

Methods of HttpSessionBindingEvent class:

1. String getName() :

This method retrieves the name of the attribute that was added, removed, or
replaced in the session.

2. Object getValue() :

Advanced Java Programming 130


This method retrieves the value of the attribute that was added, removed, or
replaced. If the attribute was replaced, this method returns the old value
(not the new one).

3. HttpSession getSession() :

This method returns the HttpSession object that had the attribute changed
(added, removed, or replaced).

Example:
Main.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Main extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
HttpSession s = request.getSession();

if (s != null) {
pw.println("Session Id : ");
String s_id = s.getId();
pw.println(s_id);

s.setAttribute("FName", "Meenakshi"); // attributeAdded() is executed


s.setAttribute("FName", "Thalor"); // attributeReplaced() is executed
s.removeAttribute("FName"); // attributeRemoved() is executed
} else {
pw.println("Your session is not created yet");
}
}
}

User.java

import javax.servlet.*;
import javax.servlet.http.*;

public class User implements HttpSessionAttributeListener {

public void attributeAdded(HttpSessionBindingEvent event) {


System.out.println("Attribute added " + event.getName() + " : " + event.getV
alue());
}

public void attributeRemoved(HttpSessionBindingEvent event) {


System.out.println("Attribute removed " + event.getName() + " : " + event.ge
tValue());
}

public void attributeReplaced(HttpSessionBindingEvent event) {


System.out.println("Attribute replaced " + event.getName() + " : " + event.g
etValue());
}
}

Handling httpRequest

Advanced Java Programming 131


The HttpRequest object represents the HTTP request that a browser sends to your web
application.

It allows access to all the information the browser sends, such as parameters and
headers.

The HttpRequest object is primarily used to retrieve request parameters, which are
values sent from the browser along with the request.

These parameters can be sent as part of the URL (in the "query string") or in the
body of an HTTP request.

For example, consider the following URL:

<http://google.com/somePage.html?param1=hello&m2=world>

In this case, the query string part of the URL ( ?param1=hello&m2=world ) contains two
parameters with their respective values:

param1=hello

param2=world

To access these parameters from the HttpRequest object, you can use the following
code:

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
String param1 = request.getParameter("param1");
String param2 = request.getParameter("param2");
}

This code retrieves the values of the parameters ( param1 and param2 ) from the URL. If
no parameter with the given name exists, null is returned.

Request parameters can be sent either:

In the query string (for HTTP GET requests), or

In the body of the request (for HTTP POST requests).

Methods of HttpRequest :

1. Cookie[] getCookies()

Returns an array of all the cookies the client sent with this request.

2. String getQueryString()

Returns the query string contained in the request URL, after the path.

3. HttpSession getSession()

Returns the current session associated with this request. If no session


exists, a new session is created.

Handling httpResponse

The purpose of the HttpResponse object is to represent the HTTP response that your web
application sends back to the browser, in reply to the HTTP request.

To send HTML content back to the browser, you need to get a PrintWriter from the
HttpResponse object.

PrintWriter writer = response.getWriter();


writer.write("<html><body>GET/POST response</body></html>");

In this code:

response.getWriter() is used to get a PrintWriter that allows you to write the response
content.

Advanced Java Programming 132


writer.write() is used to send the HTML content back to the browser.

Handling HTTP GET Request

The doGet() method is called when the browser sends an HTTP request using the GET
method.

This method is used by servlets to handle requests and send back responses when the
user submits a form on a webpage.

Example:
index.html

<html>
<head>
<title>Simple Form</title>
</head>
<body>
<form action="SimpleServlet" method="GET">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<input type="submit" value="Submit">
</form>
</body>
</html>

SimpleServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SimpleServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) th
rows ServletException, IOException {
// Set content type to HTML
response.setContentType("text/html");

// Get the PrintWriter to send the response


PrintWriter out = response.getWriter();

// Get the 'name' parameter from the request


String name = request.getParameter("name");

// Write the response to the browser


out.println("<html><body>");
out.println("<h1>Hare Krishna, " + name + "!</h1>");
out.println("</body></html>");
}
}

Handling HTTP POST Request

The doPost() method is used to handle HTTP requests sent using the POST method.

When a user submits a form on a webpage, the form data is sent to the server using
the POST method.

Example:
index.html

Advanced Java Programming 133


<html>
<head>
<title>Submit Form</title>
</head>
<body>
<h2>Submit your information</h2>
<form action="SubmitServlet" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>

<input type="submit" value="Submit">


</form>
</body>
</html>

SubmitServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SubmitServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response) t
hrows ServletException, IOException {
// Set content type to HTML
response.setContentType("text/html");

// Get the PrintWriter to send the response


PrintWriter out = response.getWriter();

// Retrieve the form data from the request


String name = request.getParameter("name");
String email = request.getParameter("email");

// Write the response to the browser


out.println("<html><body>");
out.println("<h1>Form Submission Successful</h1>");
out.println("<p><b>Name:</b> " + name + "</p>");
out.println("<p><b>Email:</b> " + email + "</p>");
out.println("</body></html>");
}
}

Cookies and Session Tracking

Cookies are a way for a server (or a servlet, as part of the server) to send
information to a client, which stores it. The server can later retrieve this data
from the client.

Session tracking is a mechanism used by servlets to maintain the state of multiple


requests coming from the same user (i.e., requests from the same browser) over a
period of time.

Session management is a mechanism provided by the web container to store session-


related information for a specific user.

Advanced Java Programming 134


Servlet applications use two main techniques for session management:

1. Cookies

2. Session Object

Concept of Session

A session is defined as "a collection of HTTP requests shared between a client and
a web server over a period of time."

It refers to a specific interval of time.

A session is used to store all the information that can be obtained from the client
through all the requests made by the client.

Concept of Session:

Session Tracking

Session tracking is a way to maintain the state (data) of a user. It is also known
as session management in Servlets.

Session tracking involves collecting detailed information from web pages and
storing user-generated data. Since the HTTP protocol is stateless, session tracking
techniques are used to maintain the state.

Session Tracking:

Each time a user makes a request to the server, the server treats it as a new
request. Therefore, session tracking is essential to recognize and maintain the
state of a particular user.

Session Management with HttpSession

The servlet container uses the HttpSession interface to create a session between an
HTTP client and an HTTP server.

The session persists for a specified time period and can span multiple connections
or page requests from the user.

Advanced Java Programming 135


How it works:

1. When the client makes its first request, the Web Container generates a unique
session ID and sends it back to the client in the response.

2. For subsequent requests, the client sends back the session ID with each request.

3. The Web Container uses this ID to find the matching session and associates it
with the incoming request.

The HttpSession object, which implements the HttpSession interface, is created by the
servlet container and is returned when the getSession() method of HttpServletRequest is
called.

The HttpSession object provides methods to read, add, and remove session data. It also
allows you to view session information, such as the session ID, creation time, and
the last time the session was accessed.

The syntax of the getSession() methods is as follows:

1. - This method returns the current session associated with the


HttpSession getSession()

request. If no session exists, it creates a new one and returns it.

2. - This method returns the HttpSession object if the


HttpSession getSession(boolean flag)

request has an associated session. If no session exists, it returns null .

Example:
index.html

<html>
<body>
<form method="post" action="ValidateServlet">
User: <input type="text" name="user" /><br />
Password: <input type="text" name="pass" /><br />
<input type="submit" value="submit" />
</form>
</body>
</html>

ValidateServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ValidateServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String name = request.getParameter("user");
String pass = request.getParameter("pass");

if (pass.equals("1234")) {
// Creating a session
HttpSession session = request.getSession();
session.setAttribute("user", name);
response.sendRedirect("WelcomeServlet");

Advanced Java Programming 136


} else {
PrintWriter out = response.getWriter();
out.println("Wrong password");
out.close();
}
}
}

WelcomeServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class WelcomeServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

HttpSession session = request.getSession();


String user = (String) session.getAttribute("user");

out.println("Hare Krishna " + user);


out.close();
}
}

Cookies

A cookie is a small piece of data that is sent back and forth between the client
(browser) and the server with each HTTP request and response.

While cookies can be created using client-side scripting languages like JavaScript,
they are typically created by server resources like servlets.

When a servlet sends a cookie to the client, the cookie is stored in the browser's
cache. Then, when the user sends another request, the browser automatically
includes the cookie in the request. This allows the server to recognize the user as
the same person who made the previous request.

How Cookies Work:

By default, each HTTP request is treated as a new one.

In the cookies technique, a cookie is added to the HTTP response from the
servlet, and it is stored in the browser’s cache.

On subsequent requests, the cookie is sent back to the server, helping the
server recognize the user.

Types of Cookies in Servlets:

1. Non-persistent Cookie:

Valid only for a single session (as long as the browser is open).

It is removed when the browser is closed.

2. Persistent Cookie:

Valid across multiple sessions.

It is not removed when the browser is closed but stays until the user logs
out or signs out.

In servlet programming, cookies are represented by the Cookie class in the


javax.servlet.http package.

Advanced Java Programming 137


To create a cookie, you use the Cookie class constructor, passing two strings: the
name and value of the cookie.

For example, the following code creates a cookie called c with the name "userName"
and the value "Jay":

Cookie c = new Cookie("userName", "Jay");

Then, the cookie is added to the HTTP response using the addCookie method of the
HttpServletResponse interface:

response.addCookie(c);

Advantages of Cookies:

1. They are the simplest way to maintain state.

2. Cookies are stored on the client side (in the browser).

Disadvantages of Cookies:

1. They won’t work if cookies are disabled in the browser.

2. Cookies can only store textual information.

Example - Sending and Receiving non-persistent cookies

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class SimpleServlet extends HttpServlet {


/* Process the HTTP GET request */
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Create two cookies


Cookie cl = new Cookie("userName", "Meenakshi");
Cookie c2 = new Cookie("password", "abc");

// Add cookies to the response


response.addCookie(cl);
response.addCookie(c2);

// Set content type for the response


response.setContentType("text/html");

// Get the PrintWriter object to write HTML content


PrintWriter out = response.getWriter();

// Display a message with a form


out.println("Please click the button to see the cookies sent to you.<br>");
out.println("<form method='POST'><input type='submit' value='Submit'></form
>");
}

/* Process the HTTP POST request */


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

// Set content type for the response


response.setContentType("text/html");

Advanced Java Programming 138


// Get the PrintWriter object to write HTML content
PrintWriter out = response.getWriter();

// Display the list of cookies


out.println("<H2>List of All Cookies:</H2>");

// Retrieve the cookies from the request


Cookie[] cookies = request.getCookies();

// If cookies are present, display their name and value


if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
out.println("<B>Cookie Name:</B> " + cookie.getName() + "<BR>");
out.println("<B>Cookie Value:</B> " + cookie.getValue() + "<BR>");
}
} else {
out.println("No cookies found.");
}
}
}

The cookies you created in this example will last only as long as the browser is
open. When the browser is closed, the cookies are deleted.

To make cookies last longer, you can choose to persist them by setting an
expiration time.

The javax.servlet.http.Cookie class provides the setMaxAge(int seconds) method, which allows you
to set the maximum age of the cookie in seconds. This determines how long the
cookie will persist, even after the browser is closed.

If you set a value for setMaxAge() , the cookie will be stored for the specified
duration (in seconds) and won't be deleted when the browser closes.

🧟‍♂️ Final Practical


🥸 MCQS
🥶 W-23

Advanced Java Programming 139

You might also like