Advanced Java Programming: Chapter 1 - Abstract Windowing Toolkit (AWT)
Advanced Java Programming: Chapter 1 - Abstract Windowing Toolkit (AWT)
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.
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 .
AWT Classes
The AWT classes are contained in the java.awt package. It is one of Java's largest
packages.
Class Description
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.
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.
Method Description
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 .
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.
Method Description
void setFont(Font f) Sets the font of this container.
4. Panel:
The Panel class is a concrete subclass of Container . It doesn’t add any new
methods; it simply implements 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.
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
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.
There are two commonly used constructors for creating Frame objects:
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:
import java.awt.*;
import java.awt.*;
Panel Class
By default, Panel uses FlowLayout as its layout manager, which arranges components in
a left-to-right flow.
import java.awt.*;
f.add(panel);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
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.
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.
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
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;
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.
1. Labels
2. Buttons
3. CheckBox
5. Choice Controls
6. Lists
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.
Labels are passive controls, meaning they do not interact with the user.
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
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.*;
add(one);
add(two);
add(three);
}
Buttons
The Button class is used to create a push button control that generates an ActionEvent
A push button is a component containing a label, and it can generate an event when
pressed.
3. void setEnabled(boolean enable) : Enables or disables the button. A disabled button cannot
be clicked.
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.*;
Main() {
setLayout(null);
setVisible(true);
setSize(500, 300);
setTitle("Button Example");
ok = new Button("OK");
cancel = new Button("Cancel");
add(ok);
add(cancel);
}
CheckBox
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.
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).
Example:
import java.awt.*;
Main() {
setLayout(null);
setVisible(true);
setSize(300, 300);
setTitle("Checkbox Example");
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.
2. void setSelectedCheckbox(Checkbox checkbox) : This method sets the specified checkbox as the
selected one in the group.
Example:
import java.awt.*;
Main() {
setLayout(null);
setVisible(true);
setSize(300, 300);
setTitle("Radio Buttons Example");
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.
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.
7. : Highlights and selects the first item in the list that matches
void select(String str)
Example:
import java.awt.*;
Main() {
setLayout(null);
setVisible(true);
setSize(300, 200);
setTitle("Choice Example");
Lists
The List class in Java provides a scrollable list for selecting one or more items.
It is more flexible than the Choice class, which only displays a single selected
item.
1. List() : Creates a new scrolling list with a default number of visible lines.
lines ( rows ).
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.
7. String getSelectedItem() : Returns the text of the currently selected item in the list.
Example:
import java.awt.*;
Main() {
setLayout(null);
setVisible(true);
setSize(300, 200);
setTitle("List Example");
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.
2. Scrollbar(int style) : Creates a scrollbar with the specified orientation. You can set
the orientation to either Scrollbar.HORIZONTAL or Scrollbar.VERTICAL .
specified orientation, initial value, thumb size, and range. This constructor
allows you to set:
1. int getMaximum() : Returns the maximum value that the scrollbar can report.
2. int getMinimum() : Returns the minimum value that the scrollbar can report.
its current value, the visible size of the scrollbar, and the minimum and
maximum values.
Example:
import java.awt.*;
Main() {
setLayout(null);
setVisible(true);
setSize(400, 400);
setTitle("Scrollbar Example");
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.
This class is used for allowing users to input and edit text in graphical user
interfaces (GUIs).
initial text and a set number of columns to define the width of the text field.
2. void setText(String text) : Sets the text content displayed on the TextField to the
specified string.
Example:
import java.awt.*;
Main() {
setLayout(null);
setSize(300, 200);
setVisible(true);
setTitle("TextField Example");
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.
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.
specified text, rows, columns, and scrollbar visibility. The scrollbars parameter
can be:
1. void setColumns(int columns) : Sets the number of columns for this text area.
3. void setRows(int rows) : Sets the number of rows for this 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.
Example:
import java.awt.*;
Main() {
setLayout(null);
setSize(400, 300);
setVisible(true);
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() :
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.
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 .
Example:
import java.awt.*;
public Main() {
setLayout(new FlowLayout());
setTitle("FlowLayout Demo");
setSize(200, 150);
setVisible(true);
}
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.
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.
Example:
import java.awt.*;
public Main() {
setLayout(new BorderLayout(3, 3));
GridLayout
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.
1. GridLayout() : Creates a GridLayout manager with the default number of rows and
columns.
specified number of rows and columns, along with horizontal and vertical
spacing. By default, rows=1, cols=0, hgap=0, vgap=0.
Example:
import java.awt.*;
public Main() {
setLayout(new GridLayout(2, 3, 3, 3));
setTitle("GridLayout Demo");
setSize(300, 200);
setVisible(true);
}
The CardLayout manager arranges components as cards, displaying one card at a time.
Only one card is visible at a time, and the container acts as a stack of cards.
1. void first(Container container) : Displays the first component in the specified container.
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.
Example:
import java.awt.*;
Main() {
setTitle("CardLayout Example");
setSize(300, 200);
setVisible(true);
setLayout(card);
add(first, "Card1");
add(second, "Card2");
add(third, "Card3");
}
GridBagLayout
The GridBagLayout layout manager is powerful and flexible, but it is more complicated
to use than other layout managers.
Unlike GridLayout , components in GridBagLayout can have different sizes and can span
multiple rows or columns.
Position components
Each component in a GridBagLayout has its own GridBagConstraints object associated with it.
Variable Role
Example:
import java.awt.*;
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
setTitle("GridBagLayout Example");
setSize(400, 300);
setVisible(true);
}
A menuBar displays a list of top-level menu choices. Each choice is associated with a
dropdown menu.
Hierarchy of Menu:
Menu Controls:
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.
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.
2. Create instances of the Menu class that define the selections displayed on the
bar.
Constructor Description
Example:
import java.awt.*;
mBar.add(colors);
mBar.add(exit);
setTitle("Menu Demo");
setSize(400, 400);
setVisible(true);
}
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.
Constructor Description
Method Description
You can create a checkable menu item by using the CheckboxMenuItem class, which is a
subclass of MenuItem .
1. CheckboxMenuItem()
2. CheckboxMenuItem(String itemName)
Example:
import java.awt.*;
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);
}
Dialog Boxes
A dialog box is a GUI object used to display messages or obtain user input.
Child Window: Dialog boxes are always child windows of a top-level window.
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.
Example:
import java.awt.*;
setLayout(new FlowLayout());
setSize(300, 200);
setBackground(Color.YELLOW);
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.
1. FileDialog(Frame parent) : This constructor creates a file dialog box for loading a
file.
the specified parent frame and a title bar with the given name ( boxName ).
This constructor creates a file dialog box with the specified parent frame
and title ( boxName ).
This allows you to easily implement file selection dialogs for both opening
and saving files in Java applications.
Example:
import java.awt.*;
class Main {
public static void main(String args[]) {
Frame f = new SampleFrame("File Dialog Demo");
f.setVisible(true);
f.setSize(100, 100);
Chapter 2 - Swing
Introduction to Swing
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 considered "lightweight" because they are not implemented with
platform-specific code.
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.
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
MVC architecture is the design foundation for all Swing components, separating
common features of GUI applications:
MVC Architecture:
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.
AWT Swing
AWT stands for Abstract Windowing Swing is also called Java Foundation
Toolkit. Classes (JFC).
The top-level container is the root of a hierarchy, containing all other Swing
components in the window.
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.
Secondary Containers:
Panels are used to group and layout relevant components and are considered
intermediate containers.
Advantages:
Swing offers paint debugging support to help when creating your own 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.
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 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
import javax.swing.*;
import java.awt.*;
Main() {
jf = new JFrame("JFrame Ex");
jf.setLayout(new FlowLayout());
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(400, 400);
jf.setVisible(true);
}
import javax.swing.*;
import java.awt.*;
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("JFrame Ex");
setSize(400, 400);
setVisible(true);
}
JApplet
Swing applets add support for features like menu bars and layering of components,
making them more versatile than regular AWT applets.
1. Root Pane
Swing containers like JApplet , JFrame , and JDialog rely on a JRootPane for their
structure.
Components are added to these areas instead of directly to the root pane.
2. Content Pane
The content pane and menu bar are located in the Frame-Content-Layer.
3. Glass Pane
Components are added to the content pane of Swing applets, not directly to the
applet.
Swing applets use BorderLayout by default, unlike regular applets that use
FlowLayout .
JLabel
Constructor Description
Method Description
void setHorizontalAlignment(int Sets the horizontal alignment of
alignment)
Example:
import javax.swing.*;
add(jl);
}
Icons
In Swing, many components like labels, buttons, and tabbed panes can display an
icon, which is a fixed-size picture.
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.
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.
Method Description
Example:
import javax.swing.*;
frame.add(label);
frame.setSize(250, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
JTextField
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.*;
setLayout(null);
setSize(300, 300);
setTitle("JTextField Example");
setVisible(true);
}
JTextArea
The JTextArea component allows users to enter and edit multiple lines of text.
JTextArea does not handle scrolling directly. Instead, it can be placed inside a
JScrollPane for scrolling functionality.
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.*;
setLayout(null);
setSize(300, 300);
setTitle("JTextField Example");
setVisible(true);
}
Combo Boxes
A JComboBox is a Swing component that combines a text field and a dropdown list.
JComboBox is similar to the Choice component in AWT but offers more flexibility.
2. JComboBox(Object[] items) : Creates a combo box with items from the given array.
Example:
import javax.swing.*;
setLayout(null);
setSize(300, 300);
setTitle("Checkbox example");
JButton
4. JButton(String str, Icon i) : Creates a button with both text and an icon.
5. void setVerticalTextPosition(int pos) : Adjusts the position of the text vertically relative
to the icon.
Example:
import javax.swing.*;
setLayout(null);
setSize(300, 300);
setTitle("JButton Example");
setVisible(true);
}
JRadioButton
These buttons allow users to select one option at a time within a group.
2. JRadioButton(String text) : Creates a radio button with the specified text label.
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.*;
add(b1);
add(b2);
add(b3);
setLayout(null);
setSize(300, 300);
setTitle("JRadioButton Example");
setVisible(true);
}
JCheckBox
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.*;
add(b1);
add(b2);
add(b3);
add(b4);
setLayout(null);
setSize(300, 300);
setTitle("JCheckBox Example");
setVisible(true);
}
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.
The JTabbedPane class is used to create tabbed panes, and it extends JComponent .
Constructors of JTabbedPane :
1. JTabbedPane()
2. JTabbedPane(int tabPlacement)
You can specify both tab placement (as above) and the layout policy:
Adding Tabs:
Tabs are added to a JTabbedPane using the method:
Example:
import javax.swing.*;
add(tabbedPane);
}
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.
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. 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).
Example:
import javax.swing.*;
import java.awt.*;
int b = 1;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
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);
}
JTree
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.
1. JTree(Hashtable ht) : Creates a tree using a hash table where each element in the
table is a node in the tree.
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.
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.
Example:
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
Main() {
f = new JFrame();
f.setLayout(new BorderLayout());
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");
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.
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.
2. Create a JScrollPane to make the table scrollable (define the scroll bar policies).
Example:
import javax.swing.*;
Object[][] data = {
{1, "Jay", 25},
{2, "Rushikesh", 33},
{3, "Sanket", 36},
};
add(scrollPane);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("JTable Example");
setSize(400, 300);
setVisible(true);
}
JToolTip
A tooltip is a small pop-up text that appears when the mouse cursor hovers over a
component in a GUI.
In Java Swing, tooltips can be added to almost any component using the
setToolTipText(String s) method.
Example:
import javax.swing.*;
add(button);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
JProgressBar
The JProgressBar class in Java is used to display the progress of a task visually.
Additionally, the progress bar can display a string or text showing the task's
current state or percentage.
2. JProgressBar(int min, int max) : Creates a horizontal progress bar with the specified
minimum and maximum values.
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.*;
JProgressBar progressBar;
public Main() {
progressBar = new JProgressBar(0, 100);
progressBar.setBounds(50, 50, 300, 30);
progressBar.setStringPainted(true);
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.
Event Classes:
Event Handling is the process of controlling events and deciding how to respond
when they occur.
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:
Examples:
Clicking a button.
Scrolling a page.
2. Background Events:
Examples:
Timer expiration.
System interrupts.
Mouse actions.
Keyboard inputs.
Both AWT and Swing components in Java use the Event Delegation Model.
In this model:
The listener waits for the event, processes it when received, and then returns.
Listeners must register with the source to receive notifications about the event.
3. Listener: The object that processes the event after receiving it.
Events
It is generated when a user interacts with graphical user interface (GUI) elements.
Examples of events:
1. Pressing a button.
Source
Example: addMouseMotionListener() .
All listeners are notified and receive a copy of the event (called
multicasting).
TooManyListenersException
Event Listener
Requirements of a listener:
How it works:
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:
It is a subclass of EventObject .
It serves as the superclass for all AWT-based events in the delegation event model.
Types of Events:
These events are defined in the java.awt.event package and are widely used in GUI-based
applications.
ActionEvent Class
ALT_MASK
CTRL_MASK
META_MASK
SHIFT_MASK
This constructor creates an ActionEvent object with the given source, event ID,
and command.
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.
For example, when a button is pressed, the action event will have the button’s
label as its command name.
ItemEvent Class
The ItemEvent class defines two constants to represent the state of an item:
Additionally, the constant ITEM_STATE_CHANGED is used to signify that the item's state
has changed.
1. getItem()
This method returns a reference to the item that generated the event.
2. getItemSelectable()
3. getStateChange()
This method returns the state change of the item (either SELECTED or DESELECTED ).
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.
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:
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
There are eight types of mouse events, which are identified by the following
constants:
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()
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.
Constructor:
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
The WindowEvent class defines the following constants to identify event types:
Syntax:
Window getWindow()
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 ?
2. You can create a new class that extends the adapter class and override only the
required methods.
mouseDragged()
mouseMoved()
If you are interested only in the mouseDragged() event, you can override it, while the
empty mouseMoved() method will handle other events.
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
Inner Classes
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.
Can access all members (including private ones) of the outer class.
Example:
class OuterClass {
private String message = "Hare Krishna!!";
Defined like a member inner class but marked with the static keyword.
Example:
class OuterClass {
static String staticMessage = "Static Hare Krishna!!";
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);
}
}
greeting.sayHello();
}
}
The delegation event model in Java is used to handle events like mouse clicks, key
presses, etc.
1. Event Source
The object where the event occurs (e.g., a button, text field).
2. Event Listener
How It Works ?
When an event occurs, the event source invokes the corresponding method in the
listener.
ActionListener Interface
Example:
import java.awt.*;
import java.awt.event.*;
public Main() {
button = new Button("Click Me");
button.setBounds(50, 100, 80, 30);
add(button);
button.addActionListener(this);
setSize(200, 200);
ItemListener Interface
This interface is implemented to respond when the state of an item changes, such as
selecting or deselecting a checkbox or list item.
Example:
import java.awt.*;
import java.awt.event.*;
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);
}
KeyListener Interface
Example:
import java.awt.*;
import java.awt.event.*;
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);
}
MouseListener Interface
A class implementing this interface can respond to mouse actions like clicks,
movements, and when the mouse enters or exits a component.
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.
Example:
import java.awt.*;
import java.awt.event.*;
public Main() {
label = new Label();
label.setBounds(50, 100, 200, 30);
add(label);
setSize(400, 300);
setLayout(null);
setVisible(true);
addMouseListener(this);
}
MouseMotionListener Interface
It defines two methods that respond to mouse dragging and movement actions.
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 Main() {
label = new Label();
label.setBounds(50, 100, 200, 30);
add(label);
setSize(400, 300);
setLayout(null);
setVisible(true);
addMouseMotionListener(this);
}
TextListener Interface
Example:
import java.awt.*;
import java.awt.event.*;
public Main() {
textField = new TextField();
textField.setBounds(50, 100, 200, 30);
textField.addTextListener(this);
add(textField);
add(label);
setSize(400, 300);
setLayout(null);
setVisible(true);
}
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.
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.
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 WindowEventDemo() {
setSize(400, 300);
setTitle("Window Listener Example");
addWindowListener(this);
setVisible(true);
}
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.
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
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
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).
A server can accept multiple clients connected to the same port, but each session
remains unique.
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.
Ports are transport layer addresses used by TCP (Transmission Control Protocol) and
UDP (User Datagram Protocol) to manage communication between applications.
1. Well-known ports: Reserved for specific protocols (e.g., FTP on port 21, Telnet
on port 23, HTTP on port 80).
TCP/IP reserves the lower 1,024 ports for well-known protocols, such as:
Protocols like HTTP define how clients interact with these ports. For example, when
a client requests a file from an HTTP server:
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).
Each computer, also known as a host, on the Internet has a unique IP address
that distinguishes it from other computers.
During transmission, a message is divided into multiple packets, and each packet
may take a different route across the Internet.
Client-Server Interaction:
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.
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.
TCP UDP
Reliable Unreliable
Connection-oriented Connectionless
Uses retransmission and flow control through windowing No retransmission or flow control
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.
It defines how email servers communicate to forward messages from the sender to
the receiver.
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.
The client connects to the server on TCP port 110 and downloads the emails to
the local computer.
Delete mode: Emails are deleted from the server after being downloaded.
Keep mode: Emails stay on the server, so you can access them later.
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.
Proxy Servers
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.
Additional Features:
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.
IP Address:
Subtract 2 because:
IP Classes:
1. Class A:
2. Class B:
3. Class C:
4. Class D:
No subnet mask.
5. Class E:
No subnet mask.
IP Class Summary:
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:
Java is widely used for network programming due to its extensive support for
handling network resources through the java.net package.
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.
Interface Purpose
CookiePolicy Defines policies for cookie acceptance.
CookieStore Stores cookies.
FileNameMap Maps file names to MIME types.
SocketImplFactory Creates socket implementations.
1. InetAddress :
on the internet.
3. Socket :
4. ServerSocket :
5. DatagramPacket :
6. DatagramSocket :
InetAddress
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.
Using host names is more convenient and understandable than raw IP addresses.
methods for:
Factory Methods
The InetAddress class doesn't have visible constructors, so we need to use factory
methods to create an InetAddress object.
This method returns an InetAddress object containing the IP address and host
name of the given host.
This method returns an InetAddress object containing the local host's name and
IP address.
This method creates an InetAddress object using both an IP address and a host
name.
This method determines all the IP addresses associated with a given host name
and returns them in an array.
Example:
import java.net.*;
Instance Methods
The InetAddress class has several useful methods that can be used on the objects
returned by the methods mentioned earlier.
Compares the current object with the specified object and returns true if both
have the same Internet address, otherwise false .
2. byte[] getAddress()
3. String getHostAddress()
4. String getHostName()
5. int hashCode()
6. boolean isMulticastAddress()
7. String toString()
Returns a string that contains both the hostname and IP address of the
object.
Example:
import java.net.*;
TCP/IP Sockets
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:
Socket Class
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 : A class that is used by clients to connect to the server and begin protocol
exchanges.
1. Socket() :
Creates an unconnected socket. You need to use the connect() method to connect
it to a server.
Similar to the previous constructor but takes an InetAddress object for the
host.
Connects to the specified host and port and creates a socket on the local
machine at the specified address 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).
Returns the input stream of the socket, which is connected to the output
stream of the remote socket.
Returns the output stream of the socket, which is connected to the input
stream of the remote socket.
import java.net.*;
import java.io.*;
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:
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.
1. ServerSocket(int port)
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.
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()
Use the bind() method to bind it to a specific address and port later.
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()
Blocks until a client connects or the socket times out (if a timeout is set
using setSoTimeout() ).
Sets the timeout value for how long the server socket waits for a client
during the accept() method.
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 ... "
SimpleServer.java
import java.net.*;
import java.io.*;
SimpleClient.java
import java.net.*;
import java.io.*;
// 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());
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.*;
Socket s = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream
()));
OutputStream o = s.getOutputStream();
PrintStream ps = new PrintStream(o);
System.out.println("Checking...");
OddEvenClient.java
import java.net.*;
import java.io.*;
OutputStream o = s.getOutputStream();
PrintStream ps = new PrintStream(o);
ps.println(n); // Send the number to the server
Whois
The WHOIS protocol is a simple directory service that provides information about
Internet resources such as domain names, IP addresses, or autonomous systems.
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:
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.
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;
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);
URL
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
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.
It is separated from the protocol by double slashes ( // ) and may end with a
slash ( / ) or optionally a colon ( : ).
3. Port Number:
4. File Path:
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
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.
2. URL(String protocol, String host, int port, String file) : Creates a URL object from the specified
protocol, host, port number, and file.
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.
The URL class also provides methods for retrieving individual components of the URL
and interacting with the resource.
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.
8. boolean equals(Object obj) : Compares the URL with another object and returns true if
they are equal, otherwise false.
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:
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
It provides more control over the interaction with a server compared to the URL
class.
Purposes of URLConnection :
You can inspect the headers sent by the server and respond accordingly.
You can also set the headers for the client request.
can send data back to the server using methods like POST or PUT,
URLConnection
3. URLConnection can write data to the server as well as read data from it.
However, the actual connection to the resource is not created until you call the
connect() method.
1. abstract void connect() - Opens a communication link to the resource referred to by the
URL.
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).
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.
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.*;
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.
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.
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.
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.
Length
Host
Server Port
4. DatagramPacket(byte[] buf, int off, int len, InetAddress addr, int port)
1. InetAddress getAddress()
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()
Sets the data in the datagram. The offset is set to zero, and the length is
set to the number of bytes in data .
DatagramSocket Class
In addition to the DatagramPacket class, Java also supports the DatagramSocket class for
sending and receiving datagram packets.
1. DatagramSocket()
Constructs a datagram socket and binds it to any available port on the local
host.
2. DatagramSocket(int port)
4. DatagramSocket(DatagramSocketImpl impl)
5. DatagramSocket(SocketAddress bindaddr)
1. void close()
2. InetAddress getLocalAddress()
3. int getLocalPort()
Returns the port number on the local host to which this socket is bound.
4. void receive(DatagramPacket p)
5. void send(DatagramPacket p)
This class helps manage the communication channels between different networked
devices using UDP (connectionless communication).
Unlike TCP communication, the delivery, arrival time, and content of a datagram are
not guaranteed.
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.
import java.io.*;
import java.net.*;
while (true) {
// Get message input from the user
System.out.println("Client Says:");
message = reader.readLine();
import java.io.*;
import java.net.*;
while (true) {
// Receive message from the client
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveDat
a.length);
serverSocket.receive(receivePacket);
OddEvenServer.java :
import java.io.*;
import java.net.*;
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";
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
OddEvenClient.java :
import java.io.*;
import java.net.*;
} catch (Exception e) {
// Print any exception that occurs
e.printStackTrace();
}
}
}
Java is known for its "Write Once, Run Everywhere" philosophy, meaning it can run
on any platform that supports Java.
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.
JDBC
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.
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
It defines a set of interfaces and classes that allow Java applications to interact
with databases.
java.sql : This package contains core Java objects of the JDBC API.
JDBC Architecture:
JDBC follows a layered architecture with two main layers:
There are four main interfaces that every driver layer must implement, along with
one class that bridges the application and driver layers:
2. Connection: Manages the connection between the application and the database.
JDBC Objects:
1. Date Object: Inherited from the Java Date object, it provides methods for
accessing date values.
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.
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.
ODBC
Features of ODBC:
DBMS Independence: ODBC achieves this by using an ODBC driver, which acts as a
translator between the application and the DBMS.
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:
1. Application:
2. Driver Manager:
3. Driver:
Sends SQL queries to the specific database and returns the results to the
application.
4. Data Source:
Includes the associated operating system, DBMS, and network platform (if
applicable) used to access the database.
The ODBC API (Open Database Connectivity) uses SQL (Structured Query Language) as
the primary language for interacting with databases.
ODBC Connection:
The application can be written in any programming language, such as Java, C++,
or others.
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.
ODBC JDBC
Stands for Open Database Connectivity. Stands for Java Database Connectivity.
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.
JDBC Architecture
JDBC supports two-tier and three-tier processing models for accessing a database.
Goals of JDBC:
JDBC Architecture:
1. Application:
SQL statements are executed, and results are retrieved using JDBC methods in
the application.
Provides the connection between the JDBC manager and the specific driver.
3. Driver Manager:
Responsible for loading the appropriate driver for the user application.
4. Driver:
5. Data Source:
Refers to the database or the data repository that the application interacts
with to fetch or store data.
The network usually connects the back end (server) to the front end (client),
although both can exist on the same hardware.
Characteristics:
Clients handle tasks like graphics rendering and data entry validation.
Advantages:
Disadvantages:
1. Limited Scalability – Each client requires a separate session with the database.
The middle tier handles the business logic, so if business rules change, only the
middle tier needs to be modified.
Three-Tier Architecture:
1. Client Tier:
2. Middle Tier:
This layer also contains the JDBC driver for database connections.
Advantages
1. Flexibility – Changes can be made to one layer without affecting the others.
3. Clear Separation – Business logic is separated from the database, making the
system more organized.
Disadvantages
4. Higher Costs and Time – More parts to configure and purchase, making it costly
and time-consuming.
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:
2. Type 2:
Also depends on native software (like C or C++ DLLs) to interact with the
database.
3. Type 3:
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.
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.
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:
2. Broad database support: Allows connectivity to any database that has an ODBC
driver.
Disadvantages:
1. Slow execution time: Performance is often slower due to the additional layers
involved.
3. Java Native Interface (JNI): Uses JNI to make ODBC calls, which can add
complexity.
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.
The Type 2 JDBC driver wraps a native API with Java classes.
Since it uses local native code, a Type 2 driver is expected to have better
performance than a Type 1 driver.
Advantages:
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.
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.
The requests can be sent to any database, making this driver database-independent.
Advantages:
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.
3. Costly: Type 3 drivers are usually more expensive compared to other types of
JDBC drivers.
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.
Advantages:
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 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.
Interface Description
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:
3. Statement Interface:
execute()
executeQuery()
executeUpdate()
4. PreparedStatement Interface:
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.
Driver Interface
To connect to different databases, JDBC requires specific drivers for each one.
It implements the protocol for transferring SQL queries and results between the
client (Java application) and the database.
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.
Act as an Interface: It acts as an interface between the user and the drivers,
keeping track of registered drivers and managing connections.
Method Description
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.
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
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.*;
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
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.
When you call this method, a Connection object is created, establishing a permanent
connection between the Java application and the database.
Method Description
Example:
import java.sql.*;
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.
Statement st = con.createStatement();
1. executeQuery(String sql)
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()
Example:
import java.sql.*;
Statement st = con.createStatement();
System.out.println("Statement object created");
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
ResultSet Interface
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.
Method Description
Example:
import java.sql.*;
while (rs.next()) {
int rollNo = rs.getInt("Rollno");
String name = rs.getString("Name");
System.out.println("Rollno: " + rollNo + ", Name: " + name);
}
rs.close();
st.close();
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 :
Example:
In this example, the ? acts as a placeholder, and you will specify the actual value
to be used in the query later.
Sets an integer value for the specified parameter at the given index.
Sets a string value for the specified parameter at the given index.
Sets a double value for the specified parameter at the given index.
Sets a Date value for the specified parameter at the given index.
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()
Sets a NULL value for the specified parameter at the given index.
import java.sql.*;
// Close resources
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The following program demonstrates the creation of Connection and Statement objects and
performs multiple operations on a database:
import java.sql.*;
// Establishing Connection
Connection con = DriverManager.getConnection(url);
System.out.println("Connection to database established.");
// 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.");
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.
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.
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 have access to the entire family of Java APIs, including the JDBC API to
access enterprise databases.
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:
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:
Servlet
GenericServlet
HttpServlet
ServletRequest
ServletResponse
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.
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:
Servlet Processing:
CGI Servlet
CGI creates a new process for each Servlet creates a thread for each request and
request. services it in that thread.
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.
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.
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.
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.
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).
The web server serves static content and forwards requests for servlets to the
servlet container for processing.
Types of Servlets
Generic Servlets
For example:
It provides a foundation for creating servlets that can handle different types of
protocols.
HTTP Servlets
Example:
HTTP servlets have built-in support for the HTTP protocol and are particularly
useful in a Sun Java System Web Server environment.
Common Methods:
servlet types, but HTTP servlets have additional handling to route requests
based on the HTTP transfer method.
HTTP-specific Methods:
For HTTP servlets, overriding these methods (like doGet() or doPost() ) allows for
handling different types of HTTP requests.
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.
1. Initialization:
2. Request Handling:
3. Termination:
4. Garbage Collection:
The HTTP request from the client is sent to the web server.
For multiple requests, the servlet container creates threads, each executing the
service() method.
Servlet Methods:
1. init() Method:
Syntax:
2. service() Method:
Called for each request to handle the logic of processing client data.
Roles of service() :
Can also handle other HTTP methods like doPut() and doDelete() .
HTTP-Specific Methods:
1. doGet() Method:
Used when:
Syntax:
2. doPost() Method:
Syntax:
3. destroy() Method:
Syntax:
Open NetBeans.
In the dialog, select Java Web > Web Application , and click Next .
Once the project is created, locate the project directory in the Projects tab.
Click Finish .
A web.xml file is automatically created in the WEB-INF folder. Below is the structure
of the file:
<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>
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
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>");
The output will display in your browser, showing a simple HTML page with the
message:
Servlet API
1. javax.servlet Package
This package is used for handling requests that are not specific to any
protocol.
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.
This package also provides HttpSession and related classes to enable session
tracking.
javax.servlet Package
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.
Interfaces Classes
Servlet GenericServlet
ServletRequest ServletInputStream
ServletResponse ServletOutputStream
RequestDispatcher ServletRequestWrapper
ServletConfig ServletResponseWrapper
ServletContext ServletRequestEvent
SingleThreadModel ServletContextEvent
Filter ServletRequestAttributeEvent
FilterConfig ServletContextAttributeEvent
ServletRequestListener ServletException
Servlet Interface
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()
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.*;
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.
Retrieves the attribute (usually a value or object) with the given name from
the application scope.
3. Enumeration getInitParameterNames() :
Removes the attribute with the given name from the application context.
ServletConfig Interface
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.
2. Enumeration getInitParameterNames() :
3. ServletContext getServletContext() :
Returns the ServletContext object, which provides information about the web
application as a whole.
4. String getServletName() :
Returns the name of the servlet instance as defined in the web.xml file or by
the servlet container.
ServletRequest Interface
The ServletRequest interface handles the communication from the client to the server
and allows the servlet to access various details about the request.
The protocol (e.g., HTTP methods like POST and PUT) used by the client.
2. Enumeration getAttributeNames() :
4. Enumeration getParameterNames() :
ServletResponse Interface
The ServletResponse interface provides methods for the servlet to send a response back
to the client.
1. Locale getLocale() :
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.
Sets the content type for the response (e.g., text/html , application/json ).
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">
RequestDemoServlet.java :
import javax.servlet.*;
import java.io.*;
// 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();
out.println("</body></html>");
}
Although everything works fine, there are two issues you might have noticed:
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.
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.
GenericServlet Class
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.
This method handles the incoming requests. It is invoked each time a user
requests the servlet.
3. void destroy()
4. ServletConfig getServletConfig()
5. String getServletInfo()
Returns information about the servlet, such as the author, version, etc.
6. ServletContext getServletContext()
8. Enumeration getInitParameterNames()
9. String getServletName()
By using GenericServlet , you can easily extend the functionality of your servlet with
minimal effort.
Example:
import java.io.*;
import javax.servlet.*;
out.print("<html><body>");
out.print("<b>A Generic servlet</b>");
out.print("</body></html>");
}
}
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.
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.
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 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.
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.
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.
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:
In this way, the HTTP method used by the client request determines which doXXX
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.).
It is called when the server receives a GET request from the client.
It is called when the server receives a POST request from the client.
It is similar to the GET method but does not return the body of the document,
only the headers.
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.*;
HttpServletRequest Interface
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.
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()
Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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
Adds the given cookie to the response so that the client can store it.
3. int getStatus()
Returns the value of the response header with the given name.
5. Collection<String> getHeaderNames()
Sends an error response to the client with the specified status code and
error message.
Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// 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:
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.
Constructors:
1. Cookie()
Methods:
Sets the cookie's expiry time in seconds. After this time, the cookie will be
deleted.
2. String getName()
3. String getValue()
2. Cookie[] getCookies()
Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Creating cookies
Cookie cookie1 = new Cookie("name", "Sarthak");
Cookie cookie2 = new Cookie("name", "Nikhil");
response.addCookie(cookie2);
cookie2.setMaxAge(60 * 60); // 1 hour expiry
HttpSession Interface
The HttpSession interface allows identifying a user across multiple page requests or
visits to a website.
A session lasts for a specified time, even if the user navigates through multiple
pages or reconnects.
2. java.util.Enumeration getAttributeNames()
3. long getCreationTime()
Returns the time the session was created in milliseconds since January 1,
1970 (UTC).
4. String getId()
5. long getLastAccessedTime()
Returns the time (in milliseconds) when the session was last accessed by the
client.
Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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
There are two key methods in the HttpSessionListener interface that must be implemented
by a servlet programmer:
1. void sessionCreated(HttpSessionEvent e)
2. void sessionDestroyed(HttpSessionEvent e)
Example:
import javax.servlet.*;
import javax.servlet.http.*;
HttpSessionBindingEvent Class
This is used for objects that need to track when they are added or removed from
a session.
1. String getName() :
This method retrieves the name of the attribute that was added, removed, or
replaced in the session.
2. Object getValue() :
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.*;
if (s != null) {
pw.println("Session Id : ");
String s_id = s.getId();
pw.println(s_id);
User.java
import javax.servlet.*;
import javax.servlet.http.*;
Handling httpRequest
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.
<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:
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.
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()
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.
In this code:
response.getWriter() is used to get a PrintWriter that allows you to write the response
content.
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.*;
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
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
SubmitServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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.
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."
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.
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.
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.
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.*;
if (pass.equals("1234")) {
// Creating a session
HttpSession session = request.getSession();
session.setAttribute("user", name);
response.sendRedirect("WelcomeServlet");
WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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.
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.
1. Non-persistent Cookie:
Valid only for a single session (as long as the browser is open).
2. Persistent Cookie:
It is not removed when the browser is closed but stays until the user logs
out or signs out.
For example, the following code creates a cookie called c with the name "userName"
and the value "Jay":
Then, the cookie is added to the HTTP response using the addCookie method of the
HttpServletResponse interface:
response.addCookie(c);
Advantages of Cookies:
Disadvantages of Cookies:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
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.