Introduction to Swing in Java
Swing is a part of Java Foundation Classes (JFC) used to create Graphical User Interface
(GUI) applications in Java. It is built on top of AWT (Abstract Window Toolkit) but provides
a richer set of components, more flexibility, and is completely written in Java.
� Key Features of Swing:
1. Lightweight Components
Swing components are not tied to native platform components, unlike AWT.
2. Pluggable Look and Feel
You can change how your application looks (Windows, Metal, Nimbus, etc.) without
changing the code logic.
3. MVC Architecture
Swing follows the Model-View-Controller architecture to separate data, UI, and control
logic.
4. Rich Set of Components
Includes buttons, tables, trees, scroll panes, lists, etc.
5. Double Buffering
Reduces flickering when updating graphics.
6. Platform Independent
Since it's purely Java, Swing applications are cross-platform.
� Common Swing Components:
Component Class Description
Frame JFrame Main window
Button JButton Clickable button
Label JLabel Displays text or image
TextField JTextField Single-line input field
TextArea JTextArea Multi-line text area
Checkbox JCheckBox Selectable box
Radio JRadioButton Part of a group of exclusive options
ComboBox JComboBox Dropdown list
Panel JPanel Container to hold components
� Basic Example:
import javax.swing.*;
public class MySwingApp
{
public static void main(String[] args)
{
// Create a frame
JFrame frame = new JFrame("My First Swing App");
// Create a button
JButton button = new JButton("Click Me");
// Set frame layout and add button
frame.setLayout(null);
button.setBounds(100, 100, 120, 30);
frame.add(button);
// Set frame properties
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
� How to Run a Swing Program:
1. Write your code in a .java file.
2. Compile it: javac MySwingApp.java
3. Run it: java MySwingApp
Swing vs AWT in Java
AWT (Abstract Window
Feature/Aspect Swing
Toolkit)
Java Foundation Classes (older Java Foundation Classes (newer and
Belongs To
part) extended)
Heavyweight – relies on native
Component Type Lightweight – mostly written in Java
OS GUI
Pluggable look and feel
Look and Feel Native OS look only
(customizable)
Faster (more optimized in modern
Performance Slower due to native calls
systems)
Portability Less portable (depends on OS) Fully portable (pure Java components)
Event Handling Old model (1.0 event model) Improved delegation event model
Richness of
Limited components Rich set (tables, trees, sliders, etc.)
Components
Extensibility Not easily extensible Highly extensible and customizable
More prone to thread-related
Threading Issues Better event dispatch handling
bugs
Follows MVC (Model-View-
Support for MVC No clear separation
Controller) pattern
Example Button (Button), TextField JButton, JTextField, JTable, JTree,
Components (TextField) etc.
� Example:
AWT Button:
import java.awt.*;
public class AWTExample
{
public static void main(String[] args)
{
Frame f = new Frame("AWT Example");
Button b = new Button("Click Me");
b.setBounds(50, 50, 80, 30);
f.add(b);
f.setSize(200, 200);
f.setLayout(null);
f.setVisible(true);
}
}
Swing Button:
import javax.swing.*;
public class SwingExample
{
public static void main(String[] args)
{
JFrame f = new JFrame("Swing Example");
JButton b = new JButton("Click Me");
b.setBounds(50, 50, 100, 30);
f.add(b);
f.setSize(250, 250);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Components and Containers in Swing
In Java Swing, user interfaces are built using components (like buttons, text fields, etc.) and
containers (which hold and organize components).
� 1. What are Components in Swing?
Components are the building blocks of a GUI. These are the objects that users interact with.
� Common Swing Components:
Component Class Name Description
Label JLabel Displays text or image
Button JButton Clickable button
Text Field JTextField Single-line text input
Text Area JTextArea Multi-line text input
Password Field JPasswordField Hides input characters
Check Box JCheckBox Allows selection/deselection
Radio Button JRadioButton One option in a group
Combo Box JComboBox Drop-down list
List JList Displays a list of selectable items
Table JTable Displays data in tabular form
Slider JSlider Allows value selection from a range
� 2. What are Containers in Swing?
Containers are special components that hold and organize other components, including both
basic components and other containers.
� Types of Containers:
Container Class Name Description
Top-level JFrame, JDialog, JApplet Main window or popups
General-purpose JPanel Used to group components together
Scroll Pane JScrollPane Adds scrollbars to a component like JTextArea
Tabbed Pane JTabbedPane Tabbed interface
Container Class Name Description
Split Pane JSplitPane Divides container into resizable sections
Layered Pane JLayeredPane Overlapping components in layers
� Example: JFrame with Components and Panel
import javax.swing.*;
public class SwingComponentsExample
{
public static void main(String[] args)
{
// Create the main container - JFrame
JFrame frame = new JFrame("Swing Components Example");
// Create a JPanel container
JPanel panel = new JPanel();
// Add components
JLabel label = new JLabel("Enter Name:");
JTextField textField = new JTextField(15);
JButton button = new JButton("Submit");
// Add components to the panel
panel.add(label);
panel.add(textField);
panel.add(button);
// Add panel to frame
frame.add(panel);
// Frame settings
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Layout Managers in Swing (Java)
A Layout Manager in Swing is used to control the positioning and sizing of components
inside a container (like JFrame or JPanel). Instead of placing components manually using
setBounds(), layout managers automatically arrange them.
✅ Why Use Layout Managers?
Adjusts components automatically as window resizes
Supports different screen sizes and resolutions
Reduces the need for manual positioning
✅ Common Layout Managers in Swing:
Layout Manager Class Name Description
FlowLayout FlowLayout Places components left to right in a row
BorderLayout BorderLayout Divides container into 5 regions (N, S, E, W, Center)
GridLayout GridLayout Arranges components in rows and columns
BoxLayout BoxLayout Places components in a single row or column
GridBagLayout GridBagLayout Flexible and complex grid-based layout
CardLayout CardLayout Stacks components like cards (one visible at a time)
GroupLayout GroupLayout Used in GUI builders (like NetBeans) for complex UI
✅ Examples of Layout Managers
✅⃣ FlowLayout
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout()); // Default is center aligned
panel.add(new JButton("One"));
panel.add(new JButton("Two"));
panel.add(new JButton("Three"));
✅⃣ BorderLayout
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JButton("South"), BorderLayout.SOUTH);
frame.add(new JButton("East"), BorderLayout.EAST);
frame.add(new JButton("West"), BorderLayout.WEST);
frame.add(new JButton("Center"), BorderLayout.CENTER);
✅⃣ GridLayout
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2, 2)); // 2 rows, 2 columns
panel.add(new JButton("1"));
panel.add(new JButton("2"));
panel.add(new JButton("3"));
panel.add(new JButton("4"));
✅⃣ BoxLayout
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); // Vertical
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
✅⃣ CardLayout (used for switching views)
JPanel cardPanel = new JPanel(new CardLayout());
cardPanel.add(new JButton("Card 1"), "First");
cardPanel.add(new JButton("Card 2"), "Second");
CardLayout cl = (CardLayout)(cardPanel.getLayout());
cl.show(cardPanel, "Second"); // Show card by name
✅ Summary Table:
Layout Flexibility Use Case
FlowLayout Simple Buttons in a row
BorderLayout Medium Divide window into sections
GridLayout Uniform Keypads, forms
BoxLayout Vertical/Horizontal stacking Menus, forms
CardLayout Advanced Wizard-style UIs, tab switching
GridBagLayout Very flexible Complex forms and custom alignments
Swing Packages in Java
Swing is part of the Java Foundation Classes (JFC) and is provided through several packages
that offer a wide range of classes for creating Graphical User Interfaces (GUIs).
� 1. javax.swing
This is the main package used for most Swing GUI components.
� Common Classes:
Class Description
JFrame Top-level window (main window)
JButton Push button
JLabel Display text or image
JTextField Single-line text input
JTextArea Multi-line text input
JCheckBox Checkbox option
JRadioButton Radio button
JComboBox Drop-down list
JPanel Generic container
JList List of items
JTable Tabular data display
JScrollPane Adds scrollbars
JMenuBar, JMenu, JMenuItem Menu components
� 2. javax.swing.event
This package contains event listener interfaces and classes that help respond to user actions on
Swing components.
� Example Classes:
Class/Interface Purpose
ListSelectionListener Handles list selection events
TableModelListener Listens for changes in table data
TreeSelectionListener Listens to tree selection events
ChangeListener Listens for changes in sliders or spinners
� 3. javax.swing.border
This package is used to create and customize borders around Swing components.
� Common Classes:
Class Description
BorderFactory Factory for standard borders
LineBorder Simple line border
EmptyBorder Blank space border
TitledBorder Border with a title
EtchedBorder Sunken or raised etched border
� 4. javax.swing.table
Provides classes and interfaces for managing data in tables (JTable).
� Example:
Class/Interface Description
TableModel Interface to define table data
DefaultTableModel Default implementation of TableModel
TableColumn Represents a column in JTable
� 5. javax.swing.tree
Contains classes and interfaces used with JTree (hierarchical tree structures).
� Example:
Class/Interface Description
TreeModel Defines tree data structure
DefaultTreeModel Default implementation
TreeNode Node in a tree
� 6. javax.swing.plaf and sub-packages
These packages define look and feel (appearance) of Swing components.
� Sub-packages include:
javax.swing.plaf.basic
javax.swing.plaf.metal
javax.swing.plaf.nimbus
These contain UI delegate classes that implement how components are drawn.
� Summary:
Package Purpose
javax.swing Core Swing components
javax.swing.event Event handling for Swing
javax.swing.border Borders for components
javax.swing.table Table data handling
javax.swing.tree Tree structure handling
javax.swing.plaf Look and feel customization
A Simple Swing Application in Java
Here is a basic Swing application that creates a window with a label, text field, and a button.
When the button is clicked, it displays a greeting message.
✅ Example Code:
import javax.swing.*;
import java.awt.event.*;
public class SimpleSwingApp
{
public static void main(String[] args)
{
// Create a new frame (window)
JFrame frame = new JFrame("Simple Swing App");
// Create components
JLabel label = new JLabel("Enter your name:");
JTextField textField = new JTextField();
JButton button = new JButton("Greet");
// Set layout to null for manual positioning
frame.setLayout(null);
// Set bounds (x, y, width, height)
label.setBounds(50, 30, 120, 25);
textField.setBounds(180, 30, 150, 25);
button.setBounds(120, 80, 100, 30);
// Add components to the frame
frame.add(label);
frame.add(textField);
frame.add(button);
// Add action listener to the button
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String name = textField.getText();
JOptionPane.showMessageDialog(frame, "Hello, " + name + "!");
}
});
// Set frame properties
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
✅ How to Run:
1. Save the code as SimpleSwingApp.java
2. Compile it:
bash
CopyEdit
javac SimpleSwingApp.java
3. Run it:
java SimpleSwingApp
✅ What This Program Does:
Displays a window titled “Simple Swing App”
Asks the user to enter their name
Shows a greeting message in a popup when the button is clicked
Event Handling in Swing (Java)
Event Handling is a fundamental concept in building interactive GUI applications. In Swing,
event handling allows your program to respond to user actions like clicking buttons, typing
text, selecting checkboxes, etc.
� What is an Event?
An event is an object that describes a change of state — like:
A button was clicked
A key was pressed
A mouse was moved
� Event Handling Mechanism in Swing
Swing uses the event delegation model, which involves:
Component Role
Event Source The component that generates the event (e.g. JButton)
Event Object Encapsulates the event details (e.g. ActionEvent)
Event Listener Interface that receives the event (e.g. ActionListener)
� Basic Steps:
1. Create a component (e.g. button)
2. Register an event listener (e.g. ActionListener)
3. Implement the handler method (actionPerformed())
� Example: Button Click Event
import javax.swing.*;
import java.awt.event.*;
public class EventExample
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Event Handling Example");
JButton button = new JButton("Click Me");
button.setBounds(100, 100, 120, 30);
// Add ActionListener to the button
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(frame, "Button Clicked!");
}
});
frame.add(button);
frame.setSize(300, 250);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
� Commonly Used Event Listener Interfaces
Listener Interface Method to Implement Triggered By
ActionListener actionPerformed() Button, menu, etc.
ItemListener itemStateChanged() Checkboxes, combo boxes
KeyListener keyPressed(), keyReleased(), keyTyped() Keyboard input
MouseListener mouseClicked(), etc. Mouse events (click, enter, etc.)
MouseMotionListener mouseMoved(), mouseDragged() Mouse movement
WindowListener windowClosing(), etc. Window events
FocusListener focusGained(), focusLost() Component focus
� Example: Handling Text Input and Button Click
JTextField textField = new JTextField();
JButton button = new JButton("Show Text");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String input = textField.getText();
JOptionPane.showMessageDialog(null, "You typed: " + input);
}
});
� Summary
Concept Description
Event Source Component that triggers the event
Event Object Encapsulates the event info
Event Listener Interface to handle the event
Delegation Model Separates logic from the component
Painting in Swing (Java)
In Swing, painting refers to drawing custom graphics (like shapes, text, images) on a
component — typically by overriding the paintComponent() method of a JPanel or similar
container.
� Why Use Painting?
You use custom painting in Swing to:
Draw shapes (lines, rectangles, circles)
Display custom graphics or images
Create game UIs, animations, or data visualizations
� Core Concepts:
Concept Description
Graphics class Used to draw on components (2D rendering)
paintComponent() Method where custom drawing code is written
JPanel Commonly extended to perform custom painting
repaint() Requests the component to be redrawn (calls paintComponent())
� Simple Example: Drawing Shapes
import javax.swing.*;
import java.awt.*;
public class PaintingExample extends JPanel
{
// Override the paintComponent method
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g); // call parent method for proper rendering
// Set color and draw shapes
g.setColor(Color.BLUE);
g.fillRect(50, 50, 100, 60); // filled rectangle
g.setColor(Color.RED);
g.drawOval(200, 50, 100, 100); // outlined oval
g.setColor(Color.GREEN);
g.drawString("Hello, Swing!", 120, 200); // draw text
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Painting in Swing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PaintingExample panel = new PaintingExample(); // custom JPanel
frame.add(panel);
frame.setSize(400, 300);
frame.setVisible(true);
}
}
� What Happens Here?
paintComponent(Graphics g) is called automatically when the panel is shown or updated.
You use the Graphics object (g) to draw shapes or text.
You should always call super.paintComponent(g) first to avoid painting bugs.
� Drawing with Graphics2D
To draw more advanced shapes (rotations, strokes, anti-aliasing), use Graphics2D:
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(3)); // set line thickness
g2.drawLine(10, 10, 100, 100);
� To Update Graphics:
Call:
repaint();
This schedules a repaint and will re-invoke paintComponent().
� Summary
Term Meaning
JPanel Base component for drawing
paintComponent() Override this to perform custom painting
Graphics / Graphics2D Provides drawing methods like drawLine()
repaint() Refreshes the component's drawing
Exploring Swing: JLabel and ImageIcon in Java
In Swing, JLabel is used to display text, an image, or both, and ImageIcon is used to load and
display images in GUI components like labels, buttons, etc.
� What is JLabel?
A component used to display a short string or an image icon.
Cannot get user input (unlike JTextField).
You can align text/images and apply styles.
� What is ImageIcon?
A class in javax.swing package.
Used to load images from files or resources.
Can be passed to components like JLabel, JButton, etc.
� Example: Display Text and Image using JLabel and
ImageIcon
import javax.swing.*;
public class LabelWithImage
{
public static void main(String[] args)
{
// Create a frame
JFrame frame = new JFrame("JLabel and ImageIcon Example");
// Load an image using ImageIcon
ImageIcon icon = new ImageIcon("java_logo.png"); // Make sure the file exists
// Create a JLabel with text and icon
JLabel label = new JLabel("Java Swing", icon, JLabel.CENTER);
// Set label properties
label.setHorizontalTextPosition(JLabel.CENTER); // text center
label.setVerticalTextPosition(JLabel.BOTTOM); // text below the image
// Add label to frame
frame.add(label);
// Frame settings
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
� Key Methods of JLabel
Method Description
setText(String) Sets the label’s text
setIcon(Icon) Sets the image icon
setHorizontalTextPosition(...) Aligns text horizontally (LEFT, CENTER, RIGHT)
setVerticalTextPosition(...) Aligns text vertically (TOP, CENTER, BOTTOM)
setFont(Font) Sets the font style
setForeground(Color) Sets the text color
� Notes:
The image file (java_logo.png) should be in the project directory or use a full path.
You can resize icons using:
ImageIcon originalIcon = new ImageIcon("image.png");
Image image = originalIcon.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH);
ImageIcon resizedIcon = new ImageIcon(image);
� Summary
Component Purpose
JLabel Display static text, image, or both
ImageIcon Load images from file or resource
Swing Text Field – JTextField in Java
JTextField is a component in Swing that allows the user to enter and edit a single line of text.
� Syntax
JTextField textField = new JTextField(int columns);
columns: number of characters wide (not characters limit)
� Basic Example
import javax.swing.*;
public class TextFieldExample
{
public static void main(String[] args)
{
JFrame frame = new JFrame("JTextField Example");
// Create a label and a text field
JLabel label = new JLabel("Enter Name:");
JTextField textField = new JTextField(20);
JButton button = new JButton("Submit");
// Add action listener to button
button.addActionListener(e -> {
String name = textField.getText();
JOptionPane.showMessageDialog(frame, "Hello, " + name + "!");
});
// Layout
frame.setLayout(null);
label.setBounds(30, 30, 100, 30);
textField.setBounds(130, 30, 150, 30);
button.setBounds(100, 80, 100, 30);
frame.add(label);
frame.add(textField);
frame.add(button);
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
� Common Methods of JTextField
Method Description
getText() Gets the current text
setText(String text) Sets the text
setEditable(boolean) Enables/disables editing
setColumns(int n) Sets the width in columns
setToolTipText(String) Shows a tooltip on hover
setFont(Font) Changes font style and size
setForeground(Color) Changes text color
Feature Use
Text input Collect user input from a form or GUI
Simple to use Can be added with .add(textField)
Combine with JButton To trigger actions like search or login
Swing Buttons in Java: JButton and JToggleButton
Swing provides several types of buttons to handle user interaction. Two commonly used ones
are:
� 1. JButton – Standard Push Button
A JButton is used to perform an action when clicked, such as submitting a form or opening a
dialog.
� Example:
import javax.swing.*;
public class JButtonExample
{
public static void main(String[] args)
{
JFrame frame = new JFrame("JButton Example");
JButton button = new JButton("Click Me");
button.setBounds(100, 100, 120, 40);
frame.add(button);
// Add ActionListener to the button
button.addActionListener(e -> {
JOptionPane.showMessageDialog(frame, "Button was clicked!");
});
frame.setSize(300, 250);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
� Common JButton Methods
Method Description
setText("...") Sets the button label
getText() Returns the label text
setEnabled(false) Disables the button
addActionListener(...) Responds to button clicks
setIcon(...) Adds an image icon
� 2. JToggleButton – Toggle ON/OFF Button
A JToggleButton is like a switch: it stays pressed in or out (selected/unselected) and is useful for
ON/OFF or YES/NO features.
� Example:
import javax.swing.*;
public class JToggleButtonExample
{
public static void main(String[] args)
{
JFrame frame = new JFrame("JToggleButton Example");
JToggleButton toggleButton = new JToggleButton("OFF");
toggleButton.setBounds(100, 100, 120, 40);
toggleButton.addActionListener(e -> {
if (toggleButton.isSelected()) {
toggleButton.setText("ON");
} else {
toggleButton.setText("OFF");
}
});
frame.add(toggleButton);
frame.setSize(300, 250);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
� Common JToggleButton Methods
Method Description
setText("...") Sets the button label
isSelected() Returns true if the button is ON
setSelected(true) Sets the toggle to ON
addActionListener(...) Handles toggle state changes
Button Type Use Case Toggles State?
JButton Simple click interaction ❌ No
JToggleButton ON/OFF switch-like behavior ❌ Yes
Swing: Check Boxes (JCheckBox) and Radio Buttons (JRadioButton) in
Java
☑ JCheckBox – Multiple Selection
Allows user to select multiple options.
Each box can be independently selected.
Example:
import javax.swing.*;
public class CheckBoxExample
{
public static void main(String[] args)
{
JFrame frame = new JFrame("JCheckBox Example");
JCheckBox c1 = new JCheckBox("Java");
JCheckBox c2 = new JCheckBox("Python");
c1.setBounds(100, 50, 100, 30);
c2.setBounds(100, 80, 100, 30);
JButton btn = new JButton("Submit");
btn.setBounds(100, 120, 100, 30);
btn.addActionListener(e -> {
String msg = "Selected: ";
if (c1.isSelected()) msg += "Java ";
if (c2.isSelected()) msg += "Python";
JOptionPane.showMessageDialog(frame, msg);
});
frame.add(c1); frame.add(c2); frame.add(btn);
frame.setSize(300, 250);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
JRadioButton – Single Selection
Used when only one option should be selected at a time.
Requires a ButtonGroup to make them behave like radio buttons.
Example:
import javax.swing.*;
public class RadioButtonExample
{
public static void main(String[] args)
{
JFrame frame = new JFrame("JRadioButton Example");
JRadioButton r1 = new JRadioButton("Male");
JRadioButton r2 = new JRadioButton("Female");
r1.setBounds(100, 50, 100, 30);
r2.setBounds(100, 80, 100, 30);
// Group the radio buttons
ButtonGroup group = new ButtonGroup();
group.add(r1);
group.add(r2);
JButton btn = new JButton("Submit");
btn.setBounds(100, 120, 100, 30);
btn.addActionListener(e -> {
String gender = r1.isSelected() ? "Male" : r2.isSelected() ? "Female" : "None";
JOptionPane.showMessageDialog(frame, "Selected: " + gender);
});
frame.add(r1); frame.add(r2); frame.add(btn);
frame.setSize(300, 250);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Component Allows Multiple? Requires Grouping? Common Use
JCheckBox ✅ Yes ✅ No Multi-select forms
JRadioButton ✅ No ✅ Yes (ButtonGroup) Gender, Choices
JTree in Java Swing
A JTree displays a hierarchical tree structure (like folders and files).
✅ Example in Java (Swing):
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample
{
public static void main(String[] args)
{
JFrame frame = new JFrame("JTree Example");
// Create the root and children
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Courses");
DefaultMutableTreeNode cs = new DefaultMutableTreeNode("Computer Science");
DefaultMutableTreeNode mech = new DefaultMutableTreeNode("Mechanical");
DefaultMutableTreeNode civil = new DefaultMutableTreeNode("Civil");
root.add(cs);
root.add(mech);
root.add(civil);
JTree tree = new JTree(root);
JScrollPane scrollPane = new JScrollPane(tree);
frame.add(scrollPane);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
✅ Equivalent in JavaScript (for Web)
If you want to create a tree structure in JavaScript (for web apps), use:
1. HTML + JavaScript TreeView (Custom or with libraries)
Use nested <ul> and <li> elements.
Optionally enhanced with JavaScript.
2. JavaScript Libraries:
jsTree (jQuery plugin)
FancyTree
React TreeView
✅ Example using plain HTML + JavaScript:
<ul>
<li>Courses
<ul>
<li>Computer Science</li>
<li>Mechanical</li>
<li>Civil</li>
</ul>
</li>
</ul>
Component Java (Swing) JavaScript Equivalent (Web)
Tree View JTree <ul>/<li>, jsTree, FancyTree, etc.
Usage Desktop Applications Web Applications
Swing JTable in Java
In Java Swing, JTable is a powerful component used to display tabular data in a GUI, like rows
and columns in an Excel sheet or database table.
✅ Key Features of JTable
Displays data in rows and columns
Editable by default (can be disabled)
Supports scrolling, sorting, and selection
Works well with data from arrays or models
✅ Basic Example of JTable
import javax.swing.*;
public class JTableExample
{
public static void main(String[] args)
{
JFrame frame = new JFrame("JTable Example");
// Column Headers
String[] columnNames = { "ID", "Name", "Marks" };
// Table Data (2D array)
String[][] data = {
{ "101", "Alice", "90" },
{ "102", "Bob", "85" },
{ "103", "Charlie", "88" }
};
// Create JTable with data and column names
JTable table = new JTable(data, columnNames);
// Add table to scroll pane for scrolling
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane);
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
✅ Common JTable Methods
Method Description
getRowCount() Returns number of rows
getColumnCount() Returns number of columns
getValueAt(row, column) Gets value at a specific cell
setValueAt(value, row, col) Sets value in a specific cell
setEnabled(false) Makes table non-editable
setRowSelectionAllowed(true) Allows row selection
✅ Creating a Non-Editable Table
To make the table non-editable, use a custom TableModel:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class NonEditableJTable
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Non-Editable JTable");
String[] columns = { "ID", "Name", "Grade" };
Object[][] data = {
{ "1", "Alice", "A" },
{ "2", "Bob", "B+" }
};
DefaultTableModel model = new DefaultTableModel(data, columns) {
public boolean isCellEditable(int row, int column) {
return false; // make all cells non-editable
}
};
JTable table = new JTable(model);
frame.add(new JScrollPane(table));
frame.setSize(350, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Description
Feature
JTable Displays tabular data
JScrollPane Provides scrollable table view
DefaultTableModel Allows custom behavior (editable, updatable)
Server-Side Java Overview
Server-side Java refers to Java technologies used to create web applications that run on a server
rather than on the client (browser). The main technologies include:
Servlets
JSP (JavaServer Pages)
Spring Framework
Java EE (Jakarta EE)
Why Server-side Java Over Applets?
Java Applets (client-side Java) were once used to run Java programs in browsers, but they have
major drawbacks:
Feature Java Applets Server-Side Java
Execution Runs on client browser Runs on server
Security Often blocked by browsers (insecure) More secure and controlled
Performance Depends on client machine Handled by server (usually better)
Compatibility Needs Java plugin in browser Works with any browser (no plugin)
Deployment Hard to manage Easier to manage and update
Support Deprecated by all major browsers Actively supported and evolving
✅ Advantages of Server-Side Java Over Applets:
Cross-browser and platform compatibility
No need for Java plug-ins
Better control over code and data
Centralized deployment and updates
Enhanced security
Scalable and reliable for enterprise apps
Servlet Alternatives and Their Advantages
1. JSP (JavaServer Pages)
o Alternative to: Using raw servlets for HTML generation
o Advantages:
Easier to write HTML with embedded Java code
Clean separation of presentation and logic using JSP + Servlets
Good for dynamic page generation
2. Spring Framework (Spring MVC)
o Alternative to: Traditional Java EE Servlets
o Advantages:
More flexible and powerful
Uses Dependency Injection (DI)
Easier to test and manage
Supports REST APIs easily
3. JSF (JavaServer Faces) (part of Java EE)
o Alternative to: Servlets/JSPs
o Advantages:
Component-based UI framework
Tool support with drag-and-drop design
Simplifies UI state management
4. Struts (Apache Struts)
o Alternative to: Basic servlet-based MVC
o Advantages:
Provides structured MVC architecture
Tag libraries simplify form handling and validation
5. Other Alternatives:
o Grails (Groovy-based)
o Play Framework (Scala/Java)
o JAX-RS for RESTful web services
Server-Side Java Overview
Server-side Java refers to Java technologies used to create web applications that run on a server
rather than on the client (browser). The main technologies include:
Servlets
JSP (JavaServer Pages)
Spring Framework
Java EE (Jakarta EE)
Why Server-side Java Over Applets?
Java Applets (client-side Java) were once used to run Java programs in browsers, but they have
major drawbacks:
Feature Java Applets Server-Side Java
Execution Runs on client browser Runs on server
Security Often blocked by browsers (insecure) More secure and controlled
Performance Depends on client machine Handled by server (usually better)
Compatibility Needs Java plugin in browser Works with any browser (no plugin)
Deployment Hard to manage Easier to manage and update
Support Deprecated by all major browsers Actively supported and evolving
✅ Advantages of Server-Side Java Over Applets:
Cross-browser and platform compatibility
No need for Java plug-ins
Better control over code and data
Centralized deployment and updates
Enhanced security
Scalable and reliable for enterprise apps
Servlet Alternatives and Their Advantages
1. JSP (JavaServer Pages)
o Alternative to: Using raw servlets for HTML generation
o Advantages:
Easier to write HTML with embedded Java code
Clean separation of presentation and logic using JSP + Servlets
Good for dynamic page generation
2. Spring Framework (Spring MVC)
o Alternative to: Traditional Java EE Servlets
o Advantages:
More flexible and powerful
Uses Dependency Injection (DI)
Easier to test and manage
Supports REST APIs easily
3. JSF (JavaServer Faces) (part of Java EE)
o Alternative to: Servlets/JSPs
o Advantages:
Component-based UI framework
Tool support with drag-and-drop design
Simplifies UI state management
4. Struts (Apache Struts)
o Alternative to: Basic servlet-based MVC
o Advantages:
Provides structured MVC architecture
Tag libraries simplify form handling and validation
5. Other Alternatives:
o Grails (Groovy-based)
o Play Framework (Scala/Java)
o JAX-RS for RESTful web services
Common Gateway Interface (CGI) in Servlets
✅ What is CGI (Common Gateway Interface)?
CGI is a standard protocol used in web servers to execute external programs or scripts (like
Perl, Python, or C) that generate dynamic content for web pages.
✅ How CGI Works:
1. A client (browser) sends an HTTP request to the web server.
2. The server starts a new process to run the CGI script.
3. The script processes input (e.g., form data), and sends back HTML output.
4. The server returns the script’s output to the client.
✅ Servlets vs CGI – Key Differences
Feature CGI Servlets
Runs as threads inside the server
Execution Creates a new OS process per request
process
Performance Slower due to process creation overhead Faster and more scalable
Platform Can be written in any language Written in Java
Security Less secure if not managed properly More secure with Java's security features
No persistence (new process = new
Persistence Can maintain state using session objects
state)
Scalability Poor for high-traffic sites Good for high concurrency
✅✅ How Servlets Improve Over CGI
Servlets are Java-based server-side components that serve as a better alternative to CGI by:
Eliminating the overhead of process creation (uses threads)
Offering built-in support for session tracking and cookies
Being portable and secure using Java APIs
Supporting features like database connectivity, filters, listeners, etc.
✅ Example Flow: CGI vs Servlet
✅ CGI Example:
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "<html><body><h1>Hello from CGI!</h1></body></html>";
✅ Servlet Example:
public class HelloServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body><h1>Hello from Servlet!</h1></body></html>");
}
}
Proprietary APIs in Servlets
✅ What are Proprietary APIs?
Proprietary APIs are non-standard, vendor-specific interfaces or classes provided by specific
companies (like Apache, Oracle, IBM, etc.) that extend or enhance servlet functionality
beyond the standard Java Servlet API.
These APIs are not defined by the official Java Servlet Specification (like those from
javax.servlet.*) and may only work with specific servlet containers (e.g., Apache Tomcat,
WebLogic, WebSphere).
✅ Examples of Proprietary APIs in Servlets
Proprietary API Vendor Purpose / Use
Tomcat internal APIs for advanced
org.apache.catalina.* Apache Tomcat
configurations
com.sun.web.* or Oracle
Web container-specific extensions
com.sun.servlet.* (GlassFish)
com.ibm.servlet.* IBM WebSphere IBM-specific servlet enhancements
weblogic.servlet.* Oracle WebLogic WebLogic-specific APIs and features
✅ Why Use Proprietary APIs?
Access to low-level features of the server (e.g., Tomcat-specific request handling)
Performance tuning and monitoring
Advanced security or session management
Clustering or server-specific deployment options
✅✅ Drawbacks of Using Proprietary APIs
Issue Explanation
❌ Portability Loss Code tied to a specific server; hard to migrate
❌ Non-standard Not officially supported in Java EE / Jakarta EE
❌ Future Compatibility Risk Vendor may change or remove API without notice
❌ Limited Documentation May not be well-documented or community-supported
Active Server Pages (ASP) in Relation to Servlets
✅ What is Active Server Pages (ASP)?
ASP (Active Server Pages) is a server-side scripting technology developed by Microsoft to
create dynamic web pages, usually written in VBScript or JavaScript. It runs on Internet
Information Services (IIS).
✅ Comparison: ASP vs Java Servlets
Feature ASP (Active Server Pages) Java Servlets
Language VBScript, JavaScript Java
Platform Windows (IIS) Platform-independent (runs on any OS)
Speed and Performance Interpreted, slower Compiled Java bytecode, faster
Portability Windows-only Cross-platform
Scalability Limited High scalability
Security Basic Strong type-checking and secure APIs
Object-Oriented Support Weak Full support (Java is OOP)
Session Management Built-in Built-in via HttpSession
State Management ViewState, Session, Cookies Request, Session, Context, Cookies
✅ How ASP and Servlets Are Related
They serve the same purpose: handling server-side logic for web applications. However:
ASP is Microsoft’s proprietary technology.
Java Servlets are platform-independent and standardized by the Java EE (now
Jakarta EE) specification.
✅ Servlets as a Better Alternative to ASP
Advantages of Servlets over ASP
Platform independence (write once, run anywhere)
Strongly typed, object-oriented language (Java)
Better performance due to Java Virtual Machine
Large open-source and enterprise ecosystem
Integration with powerful frameworks (Spring, Hibernate)
Server-Side JavaScript
✅ What is Server-Side JavaScript?
Server-side JavaScript (SSJS) refers to using JavaScript to write code that runs on the server,
not in the browser. Unlike traditional JavaScript (which runs in the client-side browser), SSJS
handles backend operations like:
Handling HTTP requests/responses
Accessing databases
Managing sessions
File system operations
✅ Popular Server-Side JavaScript Platform: Node.js
✅ Node.js
A runtime environment that lets you run JavaScript on the server
Built on Google Chrome’s V8 engine
Uses non-blocking I/O and an event-driven architecture for high performance
✅ Basic Node.js Example
// Simple server with Node.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Hello from Server-Side JavaScript!</h1>');
});
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
✅ Client-side vs Server-side JavaScript
Feature Client-Side JavaScript Server-Side JavaScript (Node.js)
Runs on Browser Server
Main Use DOM manipulation, UI updates API, DB operations, file handling
Access to Files No Yes
Feature Client-Side JavaScript Server-Side JavaScript (Node.js)
Security Restrictions Yes (sandboxed) Fewer restrictions
Examples Form validation, animations Authentication, database queries
✅ Advantages of Server-Side JavaScript
Advantage Description
� Same Language (JS) Use JavaScript on both frontend and backend
� Fast I/O Event-driven, non-blocking architecture
� Rich Package Ecosystem Access to 2M+ packages via npm
� Scalable Ideal for real-time apps (e.g., chat, games)
� Active Community Constant improvements and a large developer base
✅ Common Server-Side JS Frameworks
Framework Use Case
Express.js Lightweight web application framework
NestJS Scalable, enterprise-level architecture
Meteor.js Full-stack JS platform (client + server)
Socket.io Real-time bidirectional communication
Servlet Architecture
Java Servlet architecture defines the structure and lifecycle of a Java Servlet, which is a Java
class used to build web applications that run on the server-side and handle HTTP
requests/responses.
� Key Components of Servlet Architecture
1. Web Client
Usually a web browser or any HTTP client
Sends requests (like form submissions, URL clicks)
2. Web Server (Servlet Container)
Receives the request and forwards it to the appropriate servlet
Examples: Apache Tomcat, Jetty, GlassFish
3. Servlet
A Java class that extends HttpServlet
Handles requests, processes data, and sends back responses
4. Servlet Container
Also called a Servlet Engine
Manages the lifecycle of servlets:
o Loading
o Instantiating
o Request handling (via service() method)
o Destruction
� Servlet Lifecycle (Core of Architecture)
The lifecycle of a servlet is controlled by the Servlet Container, and includes the following
methods:
Lifecycle
Description
Method
Called once when the servlet is first loaded. Used for initialization (e.g., DB
init()
connections).
service() Called for each request. Handles HTTP methods (doGet(), doPost(), etc.).
Called once when the servlet is being removed (e.g., server shutdown). Used to
destroy()
release resources.
Servlet Lifecycle Flow (Step-by-Step)
1. Client sends HTTP request (GET/POST).
2. Web server forwards the request to the Servlet container.
3. Servlet container:
o Loads servlet class (if not loaded)
o Creates instance (only once)
o Calls init() method
4. For each request:
o Calls service() method
o Depending on request type:
Calls doGet(), doPost(), etc.
5. Sends HTTP response back to client
6. On shutdown, calls destroy() to clean up resources
�� Servlet Class Hierarchy
java.lang.Object
↳ javax.servlet.GenericServlet
↳ javax.servlet.http.HttpServlet
Most servlets extend HttpServlet to handle HTTP requests.
� Servlet Architecture Diagram (Text Representation)
[ Client (Browser) ]
↓ HTTP Request
[ Web Server / Servlet Container ]
↓ forwards request
[ Servlet ]
┌────────────┐
│ init() │ ← runs once
└────────────┘
┌────────────┐
│ service() │ ← runs per request
└────────────┘
┌────────────┐
│ destroy() │ ← runs on shutdown
└────────────┘
↑ HTTP Response
[ Client (Browser) ]
Servlet Life Cycle in Java
The Servlet Life Cycle defines how a servlet is loaded, initialized, invoked, and eventually
destroyed by the Servlet Container (like Apache Tomcat).
� Stages of Servlet Life Cycle
There are 3 main life cycle methods defined in the javax.servlet.Servlet interface:
Method Purpose Called By
init() Initializes the servlet (runs once) Servlet Container
service() Handles client requests (runs many times) Servlet Container
destroy() Cleans up resources before shutdown Servlet Container
� Step-by-Step Servlet Life Cycle Flow
1. Servlet Class Loading
The servlet container loads the servlet class using classloader when the servlet is first
requested (or at startup if configured).
2. Instantiation
The container creates an instance of the servlet using the default constructor.
3. Initialization – init()
The container calls the init(ServletConfig config) method once.
Used to perform initial setup like:
o Database connections
o Reading config parameters
4. Request Handling – service()
The container calls the service(HttpServletRequest req, HttpServletResponse res) method for every
client request.
It automatically routes the request to:
o doGet() → for HTTP GET
o doPost() → for HTTP POST
o doPut(), doDelete(), etc.
5. Destruction – destroy()
The container calls destroy() before shutting down the servlet.
Used to release resources:
o Close DB connections
o Stop background threads
� Servlet Life Cycle Methods in Code
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class MyServlet extends HttpServlet
{
public void init() throws ServletException
{
System.out.println("Servlet initialized");
// Initialization code here
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Handle GET request
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello from doGet()</h1>");
}
public void destroy() {
System.out.println("Servlet destroyed");
// Cleanup code here
}
}
�� Diagram – Servlet Life Cycle (Text Version)
[ Client Request ]
↓
[ Servlet Container ]
↓
[ Class Loaded → Object Created ]
↓
[ init() → called once ]
↓
[ service() → called for each request ]
↓
[ doGet() / doPost() → process request ]
↓
[ Response sent to client ]
↓
[ destroy() → called once at end ]
GenericServlet
� What is GenericServlet?
It is an abstract class in the javax.servlet package.
Implements the Servlet interface and provides default implementations of init(), destroy(),
and getServletConfig().
You only need to override the service() method.
� When to use:
When you're building non-HTTP based servlets (like FTP or SMTP), which is rare in
practice.
� Example:
import javax.servlet.*;
import java.io.*;
public class MyGenericServlet extends GenericServlet {
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h2>Hello from GenericServlet!</h2>");
}
}
�⃣ HttpServlet
� What is HttpServlet?
A subclass of GenericServlet found in javax.servlet.http package.
Designed to handle HTTP requests.
Provides doGet(), doPost(), doPut(), and doDelete() methods.
You usually override doGet() or doPost() based on the type of HTTP request.
� Example:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class MyHttpServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h2>Hello from HttpServlet (GET)!</h2>");
}
}
�⃣ First Servlet Example (Step-by-Step)
� Directory Structure (Typical for Tomcat):
MyApp/
│
├── WEB-INF/
│ ├── web.xml
│ └── classes/
│ └── FirstServlet.class
� FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1>Welcome! This is your first servlet.</h1>");
}
}
� web.xml (Deployment Descriptor)
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0">
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
▶� Access the Servlet:
Once deployed in Tomcat:
http://localhost:8080/MyApp/hello
Apache Tomcat Web Server
✅ What is Tomcat?
Apache Tomcat is a free, open-source Java servlet container developed by the Apache
Software Foundation. It implements the Java Servlet, JSP (JavaServer Pages), and
WebSocket specifications.
✅✅ Steps to Build, Install, and Invoke a Servlet
✅ Step 1: Install Java and Set Environment
1. Install Java JDK (8 or higher).
2. Set JAVA_HOME environment variable.
3. Add JAVA_HOME/bin to your system PATH.
bash
CopyEdit
javac -version
Make sure it prints the Java compiler version.
✅ Step 2: Download and Set Up Apache Tomcat
1. Download Tomcat from:
� https://tomcat.apache.org/download-90.cgi (version 9 recommended)
2. Extract it (e.g., C:\apache-tomcat-9.x.xx).
3. Tomcat folder structure:
bin/ → startup & shutdown scripts
webapps/ → deploy your servlet applications here
conf/ → configuration files like web.xml
logs/ → log files
✅✅ Step 3: Create a Web Application Directory
Let's name your app MyApp:
Folder Structure:
MyApp/
├── WEB-INF/
│ ├── web.xml
│ └── classes/
│ └── FirstServlet.class
✅ Step 4: Write the Servlet Code
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1>Hello from First Servlet!</h1>");
}
}
✅ Step 5: Compile the Servlet
1. Use the Java compiler with the servlet-api.jar (from Tomcat’s lib folder):
javac -classpath "C:\apache-tomcat-9.x.xx\lib\servlet-api.jar" FirstServlet.java
2. Place the compiled .class file into:
MyApp/WEB-INF/classes/
✅ Step 6: Configure web.xml (Deployment Descriptor)
Location: MyApp/WEB-INF/web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0">
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
✅ Step 7: Deploy the Application
1. Copy your MyApp folder to:
C:\apache-tomcat-9.x.xx\webapps\
2. Your final path should be:
C:\apache-tomcat-9.x.xx\webapps\MyApp\
▶✅ Step 8: Start Tomcat
1. Navigate to C:\apache-tomcat-9.x.xx\bin
2. Run:
startup.bat
3. Open your browser and go to:
http://localhost:8080/MyApp/hello
� You should see:
Hello from First Servlet!
✅ Optional: Stop Tomcat
Run:
shutdown.bat
Passing and Retrieving Parameters in Servlets
In Java Servlets, you can pass parameters (like form inputs or query strings) from the client
(browser) and retrieve them in the servlet using the HttpServletRequest object.
✅ Ways to Pass Parameters to Servlets
✅⃣ Using URL Query String (GET method)
Example:
http://localhost:8080/MyApp/HelloServlet?name=John&age=25
✅⃣ Using HTML Form (POST method)
<form action="HelloServlet" method="post">
Name: <input type="text" name="name">
Age: <input type="text" name="age">
<input type="submit" value="Submit">
</form>
✅ Retrieving Parameters in the Servlet
Use request.getParameter(String name)
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String name = request.getParameter("name");
String age = request.getParameter("age");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h2>Hello, " + name + "!</h2>");
out.println("<p>You are " + age + " years old.</p>");
}
✅ Works in both doGet() and doPost() depending on the form method.
✅ Handling Multiple Values (e.g., checkboxes)
HTML:
<form action="HobbyServlet" method="post">
<input type="checkbox" name="hobby" value="Reading">Reading
<input type="checkbox" name="hobby" value="Music">Music
<input type="checkbox" name="hobby" value="Sports">Sports
<input type="submit" value="Submit">
</form>
Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String[] hobbies = request.getParameterValues("hobby");
PrintWriter out = response.getWriter();
out.println("<h3>Your hobbies:</h3>");
for (String hobby : hobbies) {
out.println("<p>" + hobby + "</p>");
}
}
✅✅ Other Useful Methods
Method Description
getParameter(String) Returns single parameter value
getParameterValues(String) Returns array for multiple values
getParameterNames() Returns all parameter names as Enumeration
Server-Side Include and Cookies in Java Servlets
Let’s break it into two parts:
� Part 1: Server-Side Include in Servlets
Server-side includes in servlets allow you to include the content of one resource (like a JSP,
HTML, or another servlet) inside another servlet's response using the RequestDispatcher.
� Syntax:
RequestDispatcher rd = request.getRequestDispatcher("header.html");
rd.include(request, response);
� Example: Including header and footer
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Include header
RequestDispatcher header = request.getRequestDispatcher("header.html");
header.include(request, response);
// Main content
out.println("<h2>Welcome to My Servlet Page!</h2>");
// Include footer
RequestDispatcher footer = request.getRequestDispatcher("footer.html");
footer.include(request, response);
}
✅ This keeps the code modular and reusable (like including same header/footer on every page).
� Part 2: Cookies in Servlets
Cookies are small pieces of data stored on the client side. Servlets can create, send, and read
cookies using the javax.servlet.http.Cookie class.
� 1. Setting a Cookie (Server to Client)
Cookie cookie = new Cookie("username", "John");
cookie.setMaxAge(3600); // 1 hour in seconds
response.addCookie(cookie);
� 2. Reading Cookies (Client to Server)
Cookie[] cookies = request.getCookies();
if (cookies != null)
{
for (Cookie cookie : cookies)
{
if (cookie.getName().equals("username"))
{
out.println("Welcome back, " + cookie.getValue());
}
}
}
� Cookie Methods You Should Know
Method Description
new Cookie(name, value) Create a cookie
setMaxAge(seconds) Expiration time in seconds (0 = delete)
addCookie(cookie) Adds cookie to response
getCookies() Returns array of cookies from request
getName() / getValue() Get name or value of a cookie
Filters in Servlets
✅ What is a Filter in Java Servlets?
A Filter is a Java class that can intercept and modify requests and responses in a servlet-
based web application.
Filters run before and/or after the servlet.
Used for pre-processing or post-processing of:
o HTTP requests
o HTTP responses
✅ Common Uses of Filters
Purpose Description
✅ Authentication Block or allow users based on login/session
✅ Logging Log all incoming requests and outgoing responses
✅ Compression Compress the response (e.g., GZIP)
✅ Input Validation Check and sanitize request parameters
✅ Response Modification Change headers or body before sending response
✅ Filter Life Cycle
1. init() – Called once when the filter is initialized.
2. doFilter() – Called every time a matching request is received.
3. destroy() – Called when the filter is taken out of service.
✅✅ Filter Class Example
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter("/welcome") // URL pattern
public class LoggingFilter implements Filter
{
public void init(FilterConfig config) throws ServletException
{
System.out.println("LoggingFilter initialized.");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
System.out.println("Request received at: " + new java.util.Date());
// Pass the request to the next filter or servlet
chain.doFilter(request, response);
System.out.println("Response sent at: " + new java.util.Date());
}
public void destroy() {
System.out.println("LoggingFilter destroyed.");
}
}
✅ Alternative Configuration in web.xml
<filter>
<filter-name>LoggingFilter</filter-name>
<filter-class>LoggingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoggingFilter</filter-name>
<url-pattern>/welcome</url-pattern>
</filter-mapping>
✅ Filter Flow (How it Works)
[Client Request]
↓
[Filter(s)] → pre-processing (e.g., logging, auth)
↓
[Servlet]
↓
[Filter(s)] → post-processing (e.g., compress response)
↓
[Response to Client]
Security Issues in Java Servlets
While Java Servlets are robust and run inside a secured environment (Servlet container like
Tomcat), there are still common security vulnerabilities developers must guard against.
Common Security Issues in Servlets
⃣ Injection Attacks (SQL Injection)
Cause: Unsanitized input directly used in SQL queries.
Risk: Attackers can manipulate or steal database data.
Prevention:
Use PreparedStatement instead of string concatenation in SQL.
PreparedStatement ps = con.prepareStatement("SELECT * FROM users WHERE email = ?");
ps.setString(1, userEmail);
⃣ Cross-Site Scripting (XSS)
Cause: Outputting unvalidated user input in the response.
Risk: Injected JavaScript runs in victim’s browser.
Prevention:
Escape HTML special characters in output.
String safe = StringEscapeUtils.escapeHtml4(userInput);
out.println(safe);
⃣ Cross-Site Request Forgery (CSRF)
Cause: Unauthorized commands sent by a trusted user’s browser.
Risk: Actions performed without user consent.
Prevention:
Use CSRF tokens in forms.
Validate the token on form submission.
⃣ Session Hijacking
Cause: Session ID exposed via URL or insecure cookies.
Risk: Attacker steals or guesses the session ID.
Prevention:
Use HttpOnly and Secure flags on cookies.
Regenerate session ID after login.
request.getSession().invalidate();
request.getSession(true); // New session
⃣ Directory Traversal
Cause: Allowing path input from user (../../etc/passwd).
Risk: Accessing unauthorized files.
Prevention:
Never trust user-supplied file paths.
Restrict file access to specific directories.
⃣ Information Leakage
Cause: Stack traces or debug messages shown to user.
Risk: Reveals internal structure or logic to attackers.
Prevention:
Catch exceptions and show friendly error pages.
Log details only on server side, not in response.
⃣ Improper Authentication / Authorization
Cause: Skipping login checks or not restricting access.
Risk: Unauthorized users accessing protected resources.
Prevention:
Use session validation:
if (session.getAttribute("user") == null)
{
response.sendRedirect("login.jsp");
}
Protect URLs with <security-constraint> in web.xml.
General Servlet Security Best Practices
Practice Benefit
Input validation Prevents injection and XSS
Output encoding Prevents XSS
Secure session management Prevents hijacking
Use HTTPS Encrypts data in transit
Minimal exception exposure Prevents info leakage
Use authentication filters Controls access to protected areas
Configure web.xml security Enforces role-based access