0% found this document useful (0 votes)
6 views84 pages

Adv Java

This document provides an overview of GUI programming in Java, focusing on the use of Swing and JavaFX for creating graphical user interfaces. It details various GUI components, their functionalities, and the Java Foundation Classes (JFC) that support GUI development. Additionally, it covers event handling and the architecture of Swing components, including classes like JFrame, JPanel, and JButton.

Uploaded by

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

Adv Java

This document provides an overview of GUI programming in Java, focusing on the use of Swing and JavaFX for creating graphical user interfaces. It details various GUI components, their functionalities, and the Java Foundation Classes (JFC) that support GUI development. Additionally, it covers event handling and the architecture of Swing components, including classes like JFrame, JPanel, and JButton.

Uploaded by

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

Unit 1: GUI Programming

GUI Java Programming

-> GUI, which stands for Graphical User Interface, is a user-friendly visual experience builder for Java
applications.

-> It comprises graphical units like buttons, labels, windows, etc. via which users can connect with an
application.

-> Swing and JavaFX are two commonly used applications to create GUIs in Java.

-> Swing was designed with a flexible architecture to make the elements customizable and easy to
plug-and-play which is why it is the first choice for java developers while creating GUIs.

-> As far as JavaFX is concerned, it consists of a totally different set of graphic components along with
new features and terminologies.

Elements of GUI:

-> A GUI comprises an array of user interface elements.

-> All these elements are displayed when a user is interacting with an application and they are as follows:

1. Input commands such as buttons, check boxes, dropdown lists and text fields.

2. Informational components like banners, icons, labels or notification dialogs.

3. Navigational units like menus, sidebars and breadcrumbs.

Java Foundation Classes (JFC)

-> Java Foundation Classes (JFC) is a set of libraries in Java used for building graphical user interfaces
(GUIs) and adding rich graphical functionality to Java applications.

-> JFC is a part of the Java Standard Edition (Java SE) and is built on top of the Abstract Window Toolkit
(AWT).

Swing

-> Swing is a part of the Java Foundation Classes (JFC) and is used to create Graphical User Interface
(GUI) applications in Java.

-> It provides a rich set of lightweight, platform-independent, and flexible UI components.


Features of Swing:

1. Lightweight: Unlike AWT, Swing components do not depend on native OS components.

2. Pluggable Look and Feel (PLAF): You can change the UI theme without modifying the application
logic.

3. Rich Set of Components: Provides advanced components like tables (JTable), trees (JTree), tabbed
panes (JTabbedPane), etc.

4. Event-Driven Programming: Uses event listeners to handle user interactions.

5. MVC Architecture: Uses the Model-View-Controller (MVC) pattern to separate UI and logic.

Java Swing Class Hierarchy

Swing Component

-> A component is an independent visual control and Java Swing Framework contains a large set of these
components which provide rich functionalities and allow high level of customization.

-> They all are derived from JComponent class.

-> All these components are lightweight components.

-> This class provides some common functionality like pluggable look and feel, support for accessibility,
drag and drop, layout, etc.

Swing Container

-> A container holds a group of components.

-> It provides a space where a component can be managed and displayed.

-> Containers are of two types:

A. Top level Containers

-> It inherits Component and Container of AWT.

-> It cannot be contained within other containers.

-> Heavyweight.

-> Example: JFrame, JDialog, JApplet

B. Lightweight Containers

-> It inherits JComponent class.


-> It is a general purpose container.

-> It can be used to organize related components together.

-> Example: JPanel

Creating a Frame

-> There are three ways to create a frame:

1. By creating the object of Frame class (association)

2. By extending Frame class (inheritance)

3. Create a frame using Swing inside main()

-> We can write the code of swing inside the main(), constructor or any other method.

Class JFrame

-> A Frame is a top-level window with a title and a border.

-> A frame, implemented as an instance of the JFrame class, is a window that has decorations such as a
border, a title, and supports button components that close or iconify the window.

-> Applications with a GUI usually include at least one frame.

-> JFrame works like the main window where components like labels, buttons, textfields are added to
create a GUI.

Basic functionalities:

1. public void setTitle(String title)

-> Sets the title for this frame to the specified string.

2. public void setSize(int width, int height)

-> Resizes this component so that it has width and height .

3. public void setLayout(LayoutManager manager)

-> Sets the LayoutManager.

-> LayoutManagers are used to arrange components in a particular manner.

4. public void setLocationRelativeTo(Component c)


-> Sets the location of the window relative to the specified component according to the following
scenarios.

-> If the component is null, or the GraphicsConfiguration associated with this component is null, the
window is placed in the center of the screen.

5. public void setDefaultCloseOperation(int operation)

-> Sets the operation that will happen by default when the user initiates a "close" on this frame.

-> You must specify one of the following choices:

-> DO_NOTHING_ON_CLOSE (defined in WindowConstants): Don’t do anything; require the program to


handle the operation in the windowClosing method of a registered WindowListener object.

-> HIDE_ON_CLOSE (defined in WindowConstants): Automatically hide the frame after invoking any
registered WindowListener objects.

-> DISPOSE_ON_CLOSE (defined in WindowConstants): Automatically hide and dispose the frame after
invoking any registered WindowListener objects.

-> EXIT_ON_CLOSE (defined in JFrame): Exit the application using the System exit method. Use this
only in applications.

-> The value is set to HIDE_ON_CLOSE by default. Changes to the value of this property cause the firing
of a property change event, with property name "defaultCloseOperation".

6. public void setVisible(boolean b)

-> Shows or hides this Window depending on the value of parameter b.

-> If true, makes the Window visible, otherwise hides the Window.

class JPanel

-> The JPanel class provides general-purpose containers for lightweight components.

-> It doesn’t have title bar.

public void setBackground(Color bg)

-> Sets the background color of this component.

Displaying information in a container

class JLabel
-> A display area for a short text string or an image, or both.

-> A label does not react to input events.

-> You can specify where in the label’s display area the label’s contents are aligned by setting the vertical
and horizontal alignment.

-> By default, labels are vertically centered in their display area.

public void setBounds(int x,


int y,
int width,
int height)

-> Moves and resizes this component.

-> The new location of the top-left corner is specified by x and y, and the new size is specified by width
and height.

-> Parameters:
x - the new x-coordinate of this component
y - the new y-coordinate of this component
width - the new width of this component
height - the new height of this component

public void setText(String text)

-> Defines the single line of text this component will display.

-> If the value of text is null or empty string, nothing is displayed.

-> The default value of this property is null.

Class JButton

-> The JButton class is used to create a labeled button that has platform independent implementation.

Class JTextField

-> JTextField is a lightweight component that allows the editing of a single line of text.

Class JPasswordField

-> JPasswordField is a lightweight component that allows the editing of a single line of text where the view
indicates something was typed, but does not show the original characters.

-> It is a text component specialized for password entry.


-> It inherits JTextField class.

Class JTextArea

-> A JTextArea is a multi-line area that displays plain text.

-> It allows the editing of multiple line text.

-> It inherits JTextComponent class

Class JCheckBox

-> The JCheckBox class is used to create a checkbox.

-> It is used to turn an option on (true) or off (false).

-> Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".

-> It inherits JToggleButton class.

Class JRadioButton

-> The JRadioButton class is used to create a radio button.

-> It is used to choose one option from multiple options.

-> It is widely used in exam systems or quiz.

-> Used with a ButtonGroup object to create a group of buttons in which only one button at a time can be
selected. (Create a ButtonGroup object and use its add method to include the JRadioButton objects in the
group.)

-> ButtonGroup class is used to create a multiple-exclusion scope for a set of buttons.

-> Creating a set of buttons with the same ButtonGroup object means that turning "on" one of those
buttons turns off all other buttons in the group.

Class JComboBox

-> A component that combines a button or editable field and a drop-down list.

-> The user can select a value from the drop-down list, which appears at the user’s request.

-> If you make the combo box editable, then the combo box includes an editable field into which the user
can type a value.
Class JList

-> A component that displays a list of objects and allows the user to select one or more items.

-> A separate model, ListModel, maintains the contents of the list.

-> It’s easy to display an array or Vector of objects, using the JList constructor that automatically builds a
read-only ListModel instance.

-> Simple, dynamic-content, JList applications can use the DefaultListModel class to maintain list
elements.

-> This class implements the ListModel interface.

public void setSelectedIndex(int index)

-> Selects a single cell. Does nothing if the given index is greater than or equal to the model size.

Class JMenuBar

-> An implementation of a menu bar.

-> You add JMenu objects to the menu bar to construct a menu.

-> When the user selects a JMenu object, its associated JPopupMenu is displayed, allowing the user to
select one of the JMenuItems on it.

Class JMenu

-> An implementation of a menu -- a popup window containing JMenuItems that is displayed when the
user selects an item on the JMenuBar.

Class JMenuItem

-> An implementation of an item in a menu. A menu item is essentially a button sitting in a list.

Class JTable

-> The JTable is used to display and edit regular two-dimensional tables of cells.

-> The JTable has many facilities that make it possible to customize its rendering and editing but provides
defaults for these features so that simple tables can be set up easily.

-> The JTable class is used to display data in tabular form. It is composed of rows and columns.
Working with 2D Shapes :

-> paintComponent is a method in the JComponent class (which is a superclass of many Swing
components such as JPanel) that is called automatically by Swing to paint the component on the screen.

-> When a component needs to be displayed, Swing invokes paintComponent to render the component’s
appearance on the screen.

-> Graphics2D class extends the Graphics class to provide more sophisticated control over geometry,
coordinate transformations, color management, and text layout.

-> This is the fundamental class for rendering 2-dimensional shapes, text and images on the Java(tm)
platform.

Line

-> Syntax:
public abstract void drawLine(int x1,
int y1,
int x2,
int y2)

-> Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context’s
coordinate system.

-> Parameters:
x1 - the first point’s x coordinate.
y1 - the first point’s y coordinate.
x2 - the second point’s x coordinate.
y2 - the second point’s y coordinate.

Rectangle

-> Syntax:
public void drawRect(int x,
int y,
int width,
int height)

-> Draws the outline of the specified rectangle.

-> The left and right edges of the rectangle are at x and x + width.

-> The top and bottom edges are at y and y + height.

-> The rectangle is drawn using the graphics context’s current color.

-> Parameters:
x - the x coordinate of the rectangle to be drawn.
y - the y coordinate of the rectangle to be drawn.
width - the width of the rectangle to be drawn.
height - the height of the rectangle to be drawn.

Triangle[Polygon]

-> Syntax:
public abstract void drawPolygon(int[] xPoints,
int[] yPoints,
int nPoints)

-> Draws a closed polygon defined by arrays of x and y coordinates.

-> Each pair of (x, y) coordinates defines a point.

-> This method draws the polygon defined by nPoint line segments, where the first nPoint - 1 line
segments are line segments from (xPoints[i - 1], yPoints[i - 1]) to (xPoints[i], yPoints[i]), for 1 ≤ i ≤ nPoints.

-> The figure is automatically closed by drawing a line connecting the final point to the first point, if those
points are different.

-> Parameters:
xPoints - a an array of x coordinates.
yPoints - a an array of y coordinates.
nPoints - a the total number of points.

Circle

-> Syntax:

public abstract void drawOval(int x,


int y,
int width,
int height)

-> Draws the outline of an oval. The result is a circle or ellipse that fits within the rectangle specified by
the x, y, width, and height arguments.

-> The oval covers an area that is width + 1 pixels wide and height + 1 pixels tall.

-> Parameters:
x - the x coordinate of the upper left corner of the oval to be drawn.
y - the y coordinate of the upper left corner of the oval to be drawn.
width - the width of the oval to be drawn.
height - the height of the oval to be drawn.

Using Color

Class Color
-> The Color class is used to encapsulate colors in the default sRGB color space or colors in arbitrary
color spaces identified by a ColorSpace.

-> Constructors:

Color(float r, float g, float b)


-> Creates an opaque sRGB color with the specified red, green, and blue values in the range (0.0 - 1.0).

Color(int r, int g, int b)


-> Creates an opaque sRGB color with the specified red, green, and blue values in the range (0 - 255).

-> A Color object is used with the setBackground(Color c) and setForeground(Color c) methods of the
swing components.

-> The background color is the color with which a component is painted, where as the foreground color is
usually the color of the text displayed in the component.

public void setBackground(Color bg)

-> Sets the background color of this component.

-> The background color is used only if the component is opaque, and only by subclasses of JComponent
or ComponentUI implementations.

public void setForeground(Color fg)

-> Sets the foreground color of this component.

-> It is up to the look and feel to honor this property, some may choose to ignore it.

Using special Fonts for Text

Class Font

-> The Font class represents fonts, which are used to render text in a visible way.

-> A font provides the information needed to map sequences of characters to sequences of glyphs and to
render sequences of glyphs on Graphics and Component objects.

-> Constructor:

Font(String name, int style, int size)

-> Creates a new Font from the specified name, style and point size.

Characters and Glyphs

-> A character is a symbol that represents an item such as a letter, a digit, or punctuation in an abstract
way.
-> For example, ’g’, LATIN SMALL LETTER G, is a character.

-> A glyph is a shape used to render a character or a sequence of characters. In simple writing systems,
such as Latin, typically one glyph represents one character.

-> In general, however, characters and glyphs do not have one-to-one correspondence.

-> For example, the character ’á’ LATIN SMALL LETTER A WITH ACUTE, can be represented by two
glyphs: one for ’a’ and one for ’·’.

-> Java distinguishes between physical and logical fonts.

i. Physical Fonts:

-> Actual font libraries (e.g., TrueType, PostScript) with glyph data.

-> Examples: Helvetica, Palatino.

-> Limited writing system support.

-> Can be bundled using createFont().

ii. Logical Fonts:

-> Standardized font families in Java (Serif, SansSerif, Monospaced, Dialog, DialogInput).

-> Mapped to physical fonts by the runtime, varying by implementation and locale.

Displaying Images

Class Image

-> The abstract class Image is the superclass of all classes that represent graphical images.

Class ImageIcon

-> An implementation of the Icon interface that paints Icons from Images.

-> Constructor:

ImageIcon(String filename)

-> Creates an ImageIcon from the specified file.

drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer)


-> Draws as much of the specified image as is currently available.

pack()

-> Causes this Window to be sized to fit the preferred size and layouts of its subcomponents.

Event Handling

Event

-> Change in the state of an object is known as Event, i.e., event describes the change in the state of the
source.

-> Events are generated as a result of user interaction with the graphical user interface components.

-> Some of the event generation activities are moving the mouse pointer, clicking on a button, pressing
the keyboard key, selecting an item from the list, and so on.

Event Handling

-> Event Handling is the mechanism that controls the event and decides what should happen if an event
occurs.

-> This mechanism has a code which is known as an event handler, that is executed when an event
occurs.

-> Java uses the Delegation Event Model to handle the events.

-> This model defines the standard mechanism to generate and handle the events.

-> The Delegation Event Model has the following key participants.

1. Source

-> The source is an object on which the event occurs.

-> Source is responsible for providing information of the occurred event to it’s handler. Java provide us
with classes for the source object.

2. Listener

-> It is also known as event handler.

-> The listener is responsible for generating a response to an event.

-> From the point of view of Java implementation, the listener is also an object. The listener waits till it
receives an event. Once the event is received, the listener processes the event and then returns.
ActionEvent and ActionListener

-> Action listeners are probably the easiest — and most common — event handlers to implement. You
implement an action listener to define what should be done when an user performs certain operation.

-> An action event occurs, whenever an action is performed by the user. Examples: When the user clicks
a button, chooses a menu item, presses Enter in a text field.

-> The result is that an actionPerformed message is sent to all action listeners that are registered on the
relevant component.

-> To write an Action Listener, follow the steps given below:

1. Declare an event handler class and specify that the class either implements an ActionListener
interface or extends a class that implements an ActionListener interface. For example:

public class MyClass implements ActionListener {

2. Register an instance of the event handler class as a listener on one or more components. For
example:

someComponent.addActionListener(instanceOfMyClass);

3. Include code that implements the methods in listener interface. For example:

public void actionPerformed(ActionEvent e) {


...//code that reacts to the action...
}

-> Both ActionEvent class and ActionListener interface are found in java.awt.event package.

-> ActionListener interface has only one method:

public abstract void actionPerformed(ActionEvent e);

KeyEvent and KeyListener

-> Key events indicate when the user is typing at the keyboard.

-> Specifically, key events are fired by the component with the keyboard focus when the user presses or
releases keyboard keys.

-> Notifications are sent about two basic kinds of key events:

1. The typing of a Unicode character


2. The pressing or releasing of a key on the keyboard

-> The first kind of event is called a key-typed event. The second kind is either a key-pressed or
key-released event.

-> Both KeyEvent Class and KeyListener interface are found in java.awt.event package.

-> KeyListener interface has three methods:

1. public abstract void keyPressed (KeyEvent e);


2. public abstract void keyReleased (KeyEvent e);
3. public abstract void keyTyped (KeyEvent e);

MouseEvent Class and MouseListener

-> Mouse events notify when the user uses the mouse (or similar input device) to interact with a
component.

-> Mouse events occur when the cursor enters or exits a component’s onscreen area and when the user
presses or releases one of the mouse buttons.

-> Both MouseEvent Class and MouseListener interface are found in java.awt.event package.

-> MouseListener interface has five methods:

1. public abstract void mouseClicked(MouseEvent e);


2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);

Adapter Classes

-> In Java’s event handling mechanism, adapter classes are abstract classes provided by the Java AWT
(Abstract Window Toolkit) package for receiving various events.

-> Adapter classes in Java Swing are used to handle events without implementing all methods of a
listener interface.

-> These are abstract classes that provide empty implementations of listener methods.

-> The adapter classes in Java are


- WindowAdapter
- KeyAdapter
- MouseAdapter
- FocusAdapter
- ContainerAdapter
- ComponentAdapter

Class KeyAdapter
-> An abstract adapter class for receiving keyboard events.

-> The methods in this class are empty.

-> This class exists as convenience for creating listener objects.

-> Extend this class to create a KeyEvent listener and override the methods for the events of interest.

class MouseAdapter

-> An abstract adapter class for receiving mouse events.

-> The methods in this class are empty.

-> This class exists as convenience for creating listener objects.

-> Mouse events let you track when a mouse is pressed, released, clicked, moved, dragged, when it
enters a component, when it exits and when a mouse wheel is moved.

-> Extend this class to create a MouseEvent (including drag and motion events) or/and
MouseWheelEvent listener and override the methods for the events of interest.

Layout Managers

-> A layout manager is an object that implements the LayoutManager interface and determines the size
and position of the components within a container.

-> Although components can provide size and alignment hints, a container’s layout manager has the final
say on the size and position of the components within the container.

-> LayoutManager is an interface that is implemented by all the classes of layout managers.

-> Several AWT and Swing classes provide layout managers for general use:

BorderLayout
BoxLayout
CardLayout
FlowLayout
GridBagLayout
GridLayout
GroupLayout
SpringLayout

Class FlowLayout

-> The FlowLayout class provides a very simple layout manager that is used, by default, by the JPanel
objects.
-> The FlowLayout class puts components in a row, sized at their preferred size.

-> If the horizontal space in the container is too small to put all the components in one row, the
FlowLayout class uses multiple rows.

-> If the container is wider than necessary for a row of components, the row is, by default, centered
horizontally within the container.

-> The line alignment is determined by the align property. The possible values are:
LEFT
RIGHT
CENTER
LEADING
TRAILING

-> Constructors

FlowLayout()
-> Constructs a new FlowLayout with a centered alignment and a default 5-unit horizontal and vertical
gap.

FlowLayout(int align)
-> Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical
gap.

FlowLayout(int align, int hgap, int vgap)


-> Creates a new flow layout manager with the indicated alignment and the indicated horizontal and
vertical gaps.

Class GridLayout

-> The GridLayout class is a layout manager that lays out a container’s components in a rectangular grid.

-> The container is divided into equal-sized rectangles, and one component is placed in each rectangle.

-> Constructors

GridLayout()
-> Creates a grid layout with a default of one column per component, in a single row.

GridLayout(int rows, int cols)


-> Creates a grid layout with the specified number of rows and columns.

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


-> Creates a grid layout with the specified number of rows and columns.

Class BorderLayout
-> A border layout lays out a container, arranging and resizing its components to fit in five regions: north,
south, east, west, and center.

-> Each region may contain no more than one component, and is identified by a corresponding constant:
NORTH, SOUTH, EAST, WEST, and CENTER.

-> Constructors:

BorderLayout()
-> Constructs a new border layout with no gaps between components.

BorderLayout(int hgap, int vgap)


-> Constructs a border layout with the specified gaps between components.

Class CardLayout

-> A CardLayout object is a layout manager for a container.

-> It treats each component in the container as a card.

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

-> Constructors:

CardLayout()
-> Creates a new card layout with gaps of size zero.

CardLayout(int hgap, int vgap)


-> Creates a new card layout with the specified horizontal and vertical gaps.

Class BoxLayout

-> A layout manager that allows multiple components to be laid out either vertically or horizontally.

-> The components will not wrap so, for example, a vertical arrangement of components will stay vertically
arranged when the frame is resized.

-> The BoxLayout manager is constructed with an axis parameter that specifies the type of layout that will
be done. There are four choices:

i. X_AXIS - Components are laid out horizontally from left to right.


ii. Y_AXIS - Components are laid out vertically from top to bottom.
iii. LINE_AXIS - Components are laid out the way words are laid out in a line, based on the container’s
ComponentOrientation property.
iv. PAGE_AXIS - Components are laid out the way text lines are laid out on a page, based on the
container’s ComponentOrientation property.

-> Constructor:

BoxLayout(Container target, int axis)


-> Creates a layout manager that will lay out components along the given axis.
Class GridBagLayout

-> The GridBagLayout class is a flexible layout manager that aligns components vertically, horizontally or
along their baseline without requiring that the components be of the same size.

-> Each GridBagLayout object maintains a dynamic, rectangular grid of cells, with each component
occupying one or more cells, called its display area.

-> Constructor:

GridBagLayout()
-> Creates a grid bag layout manager.

class GroupLayout

-> GroupLayout is a LayoutManager that hierarchically groups components in order to position them in a
Container.

-> GroupLayout is intended for use by builders, but may be hand-coded as well. Grouping is done by
instances of the Group class.

-> GroupLayout supports two types of groups: a sequential group and a parallel group.

-> Constructor:

GroupLayout(Container host)
-> Creates a GroupLayout for the specified Container.

Class SpringLayout

-> A SpringLayout lays out the children of its associated container according to a set of constraints.

-> Each constraint, represented by a Spring object, controls the vertical or horizontal distance between
two component edges.

-> Unlike many layout managers, SpringLayout doesn’t automatically set the location of the components it
manages.

-> If you hand-code a GUI that uses SpringLayout, remember to initialize component locations by
constraining the west/east and north/south locations.

-> Depending on the constraints you use, you may also need to set the size of the container explicitly.

-> Constructor:

SpringLayout()
-> Constructs a new SpringLayout.
Swing MVC Desing Pattern

-> Swing uses the model-view-controller architecture (MVC) as the fundamental design behind each of its
components.

-> Essentially, MVC breaks GUI components into three elements.

-> Each of these elements plays a crucial role in how the component behaves.

Model

-> The model encompasses the state data for each component.

-> There are different models for different types of components.

-> For example, the model of a menu may simply contain a list of the menu items the user can select
from.

-> Note that this information remains the same no matter how the component is painted on the screen.

-> Model data always exists independent of the component’s visual representation.

View

-> The view refers to how you see the component on the screen.

-> For a good example of how views can differ, look at an application window on two different GUI
platforms. Almost all window frames will have a titlebar spanning the top of the window. However, the
titlebar may have a close box on the left side (like the older MacOS platform), or it may have the close
box on the right side (as in the Windows 95 platform). These are examples of different types of views for
the same window object.

Controller

-> The controller is the portion of the user interface that dictates how the component interacts with events.

-> Events come in many forms — a mouse click, gaining or losing focus, a keyboard event that triggers a
specific menu command, or even a directive to repaint part of the screen.

-> The controller decides how each component will react to the event—if it reacts at all.

MVC Interaction

-> The Model receives commands and data from the Controller.
-> It stores these data and updates the View.

-> The View lets to present data provided by the Model to the user.

-> The Controller accepts inputs from the user and converts it to commands for the Model or the View.

Unit 2: Database Programming

JDBC

-> JDBC stands for Java Database Connectivity.

-> JDBC is a Java API to connect and execute the query with the database.

-> It is a part of JavaSE (Java Standard Edition).

-> JDBC API uses JDBC drivers to connect with the database.

Components of JDBC :

1. JDBC API:

-> It provides various methods and interfaces for easy communication with the database.

-> It provides two packages as follows which contains the java SE and java EE platforms to exhibit
WORA(write once run everywhere) capabilities.

i. java.sql.*;
ii. javax.sql.*;

2. JDBC Driver manager:

-> It loads database-specific driver in an application to establish a connection with a database.

-> It is used to make a database-specific call to the database to process the user request.

3. JDBC Test suite:

-> It is used to test the operation(such as insertion, deletion, updation) being performed by JDBC Drivers.

4. JDBC-ODBC Bridge Drivers:

-> It connects database drivers to the database.

-> This bridge translates JDBC method call to the ODBC function call.
-> It makes the use of sun.jdbc.odbc package that includes native library to access ODBC
characteristics.

JDBC Driver

-> JDBC Driver is a software component that enables java application to interact with the database.

-> There are 4 types of JDBC drivers:

1. JDBC-ODBC bridge driver


2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1. JDBC-ODBC bridge driver(Type-1 Driver)

-> The JDBC-ODBC bridge driver uses ODBC driver to connect to the database.

-> The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.

-> This is now discouraged because of thin driver.

-> Advantages:
1. Easy to use.
2. Can be easily connected to any database.

-> Disadvantages:
1. Performance degraded because JDBC method call is converted into the ODBC function calls.
2. The ODBC driver needs to be installed on the client machine.

2. Native-API driver(Type-2 Driver)

-> The Native API driver uses the client-side libraries of the database.

-> The driver converts JDBC method calls into native calls of the database API.

-> It is not written entirely in java.

-> Advantage:
1. Performance upgraded than JDBC-ODBC bridge driver.

-> Disadvantages:
1. The Native driver needs to be installed on the each client machine.
1. The Vendor client library needs to be installed on client machine.

3. Network Protocol driver(Type-3 Driver)


-> The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol.

-> It is fully written in java.

-> Advantage:
1. No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.

-> Disadvantages:
1. Network support is required on client machine.
2. Requires database-specific coding to be done in the middle tier.
3. Maintenance of Network Protocol driver becomes costly because it requires database-specific coding
to be done in the middle tier.

4. Thin driver(Type-4 Driver)

-> The thin driver converts JDBC calls directly into the vendor-specific database protocol.

-> That is why it is known as thin driver.

-> It is fully written in Java language.

-> Advantages:
1. Better performance than all other drivers.
2. No software is required at client side or server side.

-> Disadvantage:
1. Drivers depend on the Database.

Which Driver should be Used?

-> If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is
4 (Thin driver).

-> If your Java application is accessing multiple types of databases at the same time, type 3 (Network
Protocol driver) is the preferred driver.

-> Type 2 drivers (Native-API driver) are useful in situations, where a type 3 or type 4 driver is not
available yet for your database.

-> The type 1 driver (JDBC-ODBC bridge driver) is not considered a deployment-level driver, and is
typically used for development and testing purposes only.

Typical uses of JDBC:

1. Connecting to a Database
-> JDBC is used to establish a connection between a Java application and a database using drivers.
2. Executing SQL Queries
-> You can run SQL queries like SELECT, INSERT, UPDATE, and DELETE using Statement or
PreparedStatement.

3. Retrieving and Processing Results


-> After running a SELECT query, you can use the ResultSet to iterate through returned data.

4. Prepared Statements (Preventing SQL Injection)


PreparedStatement is commonly used for secure, parameterized queries.

5. Batch Processing
-> Efficiently insert or update multiple rows using batching.

6. Transaction Management
-> Handle database transactions manually for better control.

7. Calling Stored Procedures


-> JDBC can call database-stored procedures using CallableStatement.

8. Resource Management
-> Always close JDBC resources (Connection, Statement, ResultSet) to avoid memory leaks.

Structured query language

-> Structured query language (SQL) is a standardized, domain-specific programming language that
excels at handling data relationships.

-> It is used extensively for storing, manipulating and retrieving data in systems such as MySQL, SQL
Server and Oracle.

-> When data needs to be retrieved from a database, SQL is used to make the request.

-> SQL is used by database administrators, developers and data analysts for tasks such as data
definition, access control, data sharing, writing data integration scripts and running analytical queries.

5 Different Types of SQL Commands

-> Various types of SQL commands serve different purposes in managing and manipulating databases.

-> These types of commands include data definition language (DDL), which defines and modifies
database structure; data manipulation language (DML), which is used to manipulate data within tables;
data control language (DCL), which governs the access privileges and permissions; transactional control
language(TCL), which manages the transactional aspect of database operations; and data query
language (DQL), which allows retrieval and organization of data from a database.

1. DDL or Data Definition Language


-> Data definition language (DDL) is a collection of SQL commands that are used to build, change, and
delete database structures.

-> They describe the database schema and are used to design the layout of the objects stored in the
database.

-> DDL commands do not affect the data in the database.

-> The DDL statements are:

ALTER ... (All statements beginning with ALTER, except ALTER SESSION and ALTER SYSTEM)
ANALYZE
ASSOCIATE STATISTICS
AUDIT
COMMENT
CREATE ... (All statements beginning with CREATE)
DISASSOCIATE STATISTICS
DROP ... (All statements beginning with DROP)
FLASHBACK ... (All statements beginning with FLASHBACK)
GRANT
NOAUDIT
PURGE
RENAME
REVOKE
TRUNCATE

2. DML or Data Manipulation Language

-> DML (Data Manipulation Language) refers to SQL instructions that deal with the alteration of
information stored within a database, which constitutes the majority of SQL queries.

-> This is a SQL statement component that governs the database and information access.

-> The DCL statements are categorized together with data manipulation statements.

-> The data manipulation language statements are:

CALL
DELETE
EXPLAIN PLAN
INSERT
LOCK TABLE
MERGE
SELECT
UPDATE

3. DCL or Data Control Language

-> These SQL commands comprise GRANT and REVOKE, which primarily interact with the database
system’s rights, permits, and other restrictions.
-> The list of DCL commands:

GRANT: It grants people database access or special privileges on database objects.

REVOKE: It removes the user’s access permissions granted using the GRANT command.

4. TCL or Transaction Control Language

-> A transaction is a collection of tasks that are executed as a single entity.

-> Each transaction commences with a particular task and finishes when all of the tasks throughout the
group are accomplished.

-> The transaction fails when one or more of the tasks misses.

-> As a consequence, a transaction has just two outcomes: either it succeeds or it fails.

-> The transaction control statements are:

COMMIT
ROLLBACK
SAVEPOINT
SET TRANSACTION
SET CONSTRAINT

5. DQL or Data Query Language

-> Data query language (DQL) is a set of SQL commands that are used to query data inside schema
objects.

-> It fetches a schema relationship based on the query provided. With these commands, you can retrieve
data from the database and create a structure for it.

-> DQL has a SELECT command and its clauses that allow the user to extract data and execute actions
on single or multiple tables.

-> Query results for this command are stored in a temporary table that is later retrieved by the application
or the front end to access the content of the database.

-> SELECT: It is used to retrieve data from the database.

Database URL Information

Class DriverManager

-> The basic service for managing a set of JDBC drivers.

-> As part of its initialization, the DriverManager class will attempt to load the driver classes referenced in
the "jdbc.drivers" system property.
-> This allows a user to customize the JDBC Drivers used by their applications.

-> The DriverManager methods getConnection and getDrivers have been enhanced to support the Java
Standard Edition Service Provider mechanism.

-> getConnection functionalities:

1. public static Connection getConnection(String url) throws SQLException

-> Attempts to establish a connection to the given database URL.

-> The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.

2. public static Connection getConnection(String url, Properties info) throws SQLException

-> Attempts to establish a connection to the given database URL.

-> info - a list of arbitrary string tag/value pairs as connection arguments; normally at least a "user" and
"password" property should be included.

3. public static Connection getConnection(String url, String user, String password) throws SQLException

-> Attempts to establish a connection to the given database URL.

Database connection URLs

-> A JDBC URL provides a way of identifying a database so that the appropriate driver recognizes it and
connects to it.

-> A JDBC URL is referred to as a database connection URL.

-> After the driver is loaded, an application must specify the correct database connection URL to connect
to a specific database.

-> A JDBC URL always starts with jdbc:. After that, the format for the database connection URL depends
on the JDBC driver.

-> Following lists down the popular JDBC driver names and database URL.

1. MySQL
JDBC driver name: com.mysql.jdbc.Driver

URL format: jdbc:mysql://hostname/ databaseName

2. ORACLE
JDBC driver name: oracle.jdbc.driver.OracleDriver

URL format: jdbc:oracle:thin:@hostname:portNumber:databaseName


3. DB2
JDBC driver name: COM.ibm.db2.jdbc.net.DB2Driver

URL format: jdbc:db2:hostname:portNumber/databaseName

4. Sybase
JDBC driver name: com.sybase.jdbc.SybDriver

URL format: jdbc:sybase:Tds:hostname:portNumber/databaseName

Java Database Connectivity with 5 Steps

-> There are 5 steps to connect any java application with the database using JDBC.

-> These steps are as follows:

1. Register the Driver class

2. Create connection

3. Create statement

4. Execute queries

5. Close connection

1. Register the driver class

-> The forName() method of Class class is used to register the driver class.

-> This method is used to dynamically load the driver class.

-> Syntax:
Class.forName("com.mysql.cj.jdbc.Driver");

2. Create the connection object

-> The getConnection() method of DriverManager class is used to establish connection with the
database.

-> Syntax:

public static Connection getConnection(String url)throws SQLException

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

-> Example:
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root",
"bijay2055");

3. Create the Statement object

-> Once a connection is established we can interact with the database.

-> The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods that
enable us to send SQL commands and receive data from our database.

-> Use of JDBC Statement is as follows:

Statement statement = connection.createStatement();

4. Execute the query

a. boolean execute(String sql) throws SQLException

-> Executes the given SQL statement, which may return multiple results.

-> Returns true if the first result is a ResultSet object; false if it is an update count or there are no results.

b. ResultSet executeQuery(String sql) throws SQLException

-> Executes the given SQL statement, which returns a single ResultSet object.

c. int executeUpdate(String sql) throws SQLException

-> Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an
SQL statement that returns nothing, such as an SQL DDL statement.

-> Returns either


(1) the row count for SQL Data Manipulation Language (DML) statements or
(2) 0 for SQL statements that return nothing.

5. Close the connection object

-> By closing connection object statement and ResultSet will be closed automatically.

-> The close() method of Connection interface is used to close the connection.

Creating the statement objects

-> There are three main interfaces:

1. Statement
2. CallableStatement
3. PreparedStatement

Interface Statement

-> From the connection interface, you can create the object for this interface.

-> The object used for executing a static SQL statement and returning the results it produces.

-> It is generally used for general–purpose access to databases and is useful while using static SQL
statements at runtime.

-> Basic functionalities:

a. boolean execute(String sql) throws SQLException


b. ResultSet executeQuery(String sql) throws SQLException
c. int executeUpdate(String sql) throws SQLException

d. void close() throws SQLException

-> Releases this Statement object’s database and JDBC resources immediately instead of waiting for this
to happen when it is automatically closed.

-> It is generally good practice to release resources as soon as you are finished with them to avoid tying
up database resources.

Interface PreparedStatement

-> A SQL statement is pre-compiled and stored in a PreparedStatement object.

-> This object can then be used to efficiently execute this statement multiple times.

-> The PreparedStatement interface is a subinterface of Statement.

-> It is used to execute parameterized query.

-> The prepareStatement() method of Connection interface is used to return the object of
PreparedStatement.

-> Basic functionalities:

i. setBoolean(int, boolean): Set a parameter to a Java boolean value.

ii. setByte(int, byte): Set a parameter to a Java byte value.

iii. setBytes(int, byte[]): Set a parameter to a Java array of bytes.

iv. setShort(int, short): Set a parameter to a Java short value.

v. setDouble(int, double): Set a parameter to a Java double value.


vii. setFloat(int, float): Set a parameter to a Java float value.

viii. setInt(int, int): Set a parameter to a Java int value.

ix. setLong(int, long): Set a parameter to a Java long value.

x. setString(int, String): Set a parameter to a Java String value.

xi. setDate(int, Date): Set a parameter to a java.sql.Date value.

xii. setTime(int, Time): Set a parameter to a java.sql.Time value.

xiii. setTimestamp(int, Timestamp): Set a parameter to a java.sql.Timestamp value.

Interface ResultSet

-> A ResultSet object is a table of data representing a database result set, which is usually generated by
executing a statement that queries the database.

-> You access the data in a ResultSet object through a cursor.

-> Note that this cursor is not a database cursor.

-> This cursor is a pointer that points to one row of data in the ResultSet.

-> Initially, the cursor is positioned before the first row.

-> The method ResultSet.next moves the cursor to the next row.

-> This method returns false if the cursor is positioned after the last row.

-> This method repeatedly calls the ResultSet.next method with a while loop to iterate through all the data
in the ResultSet.

Viewing a ResultSet

-> There is a get method for each of the possible data types, and each get method has two versions −

a. One that takes in a column name.

b. One that takes in a column index.(The column index starts at 1, meaning the first column of a row is 1,
the second column of a row is 2, and so on.)

-> Basic functionalities for Viewing a ResultSet:

a. getBoolean(int columnIndex): Retrieves the value of the designated column in the current row of this
ResultSet object as a boolean.
b. getBoolean(String columnLabel): Retrieves the value of the designated column in the current row of
this ResultSet object as a boolean.
c. getByte(int columnIndex): Retrieves the value of the designated column in the current row of this
ResultSet object as a byte.
d. getByte(String columnLabel): Retrieves the value of the designated column in the current row of this
ResultSet object as a byte.
e. getInt(int columnIndex): Retrieves the value of the designated column in the current row of this
ResultSet object as an int.
f. getInt(String columnLabel): Retrieves the value of the designated column in the current row of this
ResultSet object as an int.
g. getString(int columnIndex): Retrieves the value of the designated column in the current row of this
ResultSet object as a String.
h. getString(String columnLabel): Retrieves the value of the designated column in the current row of this
ResultSet object as a String .

-> There are get methods for each of the primitive data types, as well as String, Object, URL and the
SQL data types in the java.sql package.

Types of ResultSet

1. ResultSet.TYPE_FORWARD_ONLY

-> The cursor can only move forward in the result set.

2. ResultSet.TYPE_SCROLL_INSENSITIVE

-> The cursor can scroll forward and backward, and the result set is not sensitive to changes made by
others to the database that occur after the result set was created.

3. ResultSet.TYPE_SCROLL_SENSITIVE.

-> The cursor can scroll forward and backward, and the result set is sensitive to changes made by others
to the database that occur after the result set was created.

Note: If you do not specify any ResultSet type, you will automatically get one that is
TYPE_FORWARD_ONLY.

Concurrency of ResultSet

1. ResultSet.CONCUR_READ_ONLY

-> Creates a read-only result set. This is the default

2. ResultSet.CONCUR_UPDATABLE

-> Creates an updateable result set.

Navigating a Result Set

-> There are several methods in the ResultSet interface that involve moving the cursor, including −
1. public void beforeFirst() throws SQLException : Moves the cursor just before the first row.

2. public void afterLast() throws SQLException : Moves the cursor just after the last row.

3. public boolean first() throws SQLException: Moves the cursor to the first row.

4. public void last() throws SQLException : Moves the cursor to the last row.

5. public boolean absolute(int row) throws SQLException : Moves the cursor to the specified row.

6. public boolean relative(int row) throws SQLException : Moves the cursor the given number of rows
forward or backward, from where it is currently pointing.

7. public boolean previous() throws SQLException : Moves the cursor to the previous row. This method
returns false if the previous row is off the result set.

8. public boolean next() throws SQLException : Moves the cursor to the next row. This method returns
false if there are no more rows in the result set.

9. public int getRow() throws SQLException : Returns the row number that the cursor is pointing to.

10. public void moveToInsertRow() throws SQLException : Moves the cursor to a special row in the result
set that can be used to insert a new row into the database. The current cursor location is remembered.

11. public void moveToCurrentRow() throws SQLException : Moves the cursor back to the current row if
the cursor is currently at the insert row; otherwise, this method does nothing.

Updating a Result Set

-> The ResultSet interface contains a collection of update methods for updating the data of a result set.

-> As with the get methods, there are two update methods for each data type −

a. One that takes in a column name.

b. One that takes in a column index.

-> Basic functionalities for updating data of a ResultSet:

a. updateBoolean(int columnIndex, boolean x): Updates the designated column with a boolean value.
b. updateBoolean(String columnLabel, boolean x): Updates the designated column with a boolean value.
c. updateInt(int columnIndex, int x): Updates the designated column with an int value.
d. updateInt(String columnLabel, int x): Updates the designated column with an int value.
e. updateString(int columnIndex, String x): Updates the designated column with a String value.
f. updateString(String columnLabel, String x): Updates the designated column with a String value.

-> There are update methods for the eight primitive data types, as well as String, Object, URL, and the
SQL data types in the java.sql package.

-> Updating a row in the result set changes the columns of the current row in the ResultSet object, but not
in the underlying database.

-> To update your changes to the row in the database, you need to invoke one of the following methods.
1. public void updateRow() : Updates the current row by updating the corresponding row in the database.

2. public void deleteRow() : Deletes the current row from the database.

3. public void refreshRow() : Refreshes the data in the result set to reflect any recent changes in the
database.

4. public void cancelRowUpdates() : Cancels any updates made on the current row.

5. public void insertRow() : Inserts a row into the database. This method can only be invoked when the
cursor is pointing to the insert row.

Interface CallableStatement

-> The interface used to execute SQL stored procedures.

-> The JDBC API provides a stored procedure SQL escape syntax that allows stored procedures to be
called in a standard way for all RDBMSs.

-> A procedure (often called a stored procedure) is a collection of pre-compiled SQL statements stored
inside the database.

-> A procedure always contains a name, parameter lists, and SQL statements.

-> It can be reused over and over again.

-> Declaration:

CallableStatement prepareCall(String sql) throws SQLException

MySQL procedure parameter has one of three modes:

1. IN parameter

-> It is the default mode.

-> It takes a parameter as input, such as an attribute.

-> When we define it, the calling program has to pass an argument to the stored procedure.

-> This parameter’s value is always protected.

2. OUT parameters

-> It is used to pass a parameter as output.

-> Its value can be changed inside the stored procedure, and the changed (new) value is passed back to
the calling program.

-> It is noted that a procedure cannot access the OUT parameter’s initial value when it starts.
3. INOUT parameters

-> It is a combination of IN and OUT parameters.

-> It means the calling program can pass the argument, and the procedure can modify the INOUT
parameter, and then passes the new value back to the calling program.

boolean wasNull() throws SQLException

-> Reports whether the last column read had a value of SQL NULL.

-> Note that you must first call one of the getter methods on a column to try to read its value and then call
the method wasNull to see if the value read was SQL NULL.

Interface RowSet

-> A JDBC RowSet object holds tabular data in a style that makes it more adaptable and simpler to use
than a result set.

-> A RowSet object may make a connection with a data source and maintain that connection throughout
its life cycle, in which case it is called a connected rowset.

-> A rowset may also make a connection with a data source, get data from it, and then close the
connection. Such a rowset is called a disconnected rowset.

-> A disconnected rowset may make changes to its data while it is disconnected and then send the
changes back to the original source of the data, but it must reestablish a connection to do so.

-> Oracle has defined five RowSet interfaces for the most frequent uses of a RowSet:

1. JdbcRowSet
-> JdbcRowSet is different than the other four RowSet implementations – because it’s always connected
to the database and because of this it’s most similar to the ResultSet object.

2. CachedRowSet
-> A CachedRowSet object is unique because it can operate without being connected to its data source

-> CachedRowSet gets its name due to the fact it caches its data in memory so that it can operate on its
own data instead of the data stored in a database.

3. WebRowSet
-> In addition to offering the capabilities of a CachedRowSet object, it can write itself to an XML
document and can also read that XML document to convert itself back to a WebRowSet.

4. JoinRowSet
-> JoinRowSet lets us create a SQL JOIN between RowSet objects when these are in memory.

-> This is significant because it saves us the overhead of having to create one or more connections.
5. FilteredRowSet
-> FilteredRowSet lets us cut down the number of rows that are visible in a RowSet object so that we
can work with only the data that is relevant to what we are doing.

Interface JdbcRowSet

-> Because it is always connected to its database, an instance of JdbcRowSet can simply take calls
invoked on it and in turn call them on its ResultSet object.

-> Another advantage of a JdbcRowSet object is that it can be used to make a ResultSet object scrollable
and updatable. All RowSet objects are by default scrollable and updatable.

-> You Can get a JdbcRowSet using the method:

RowSetProvider.newFactory().createJdbcRowSet()

-> In order to connect JdbcRowSet with the database, the JdbcRowSet interface provides methods for
configuring Java bean properties which are depicted below:
void setURL(String url);
void setUserName(String user_name);
void setPassword(String password);
void setCommand(String query);

Unit 3 : Java Beans

Java Bean

-> Java Beans are an essential component of Java programming that allows for the creation of reusable
and interoperable software components.

-> Java Beans are reusable software components that adhere to a specific set of conventions and
guidelines defined by Sun Microsystems (now Oracle).

-> They are essentially Java classes that encapsulate data and functionality, making them easily
accessible and manageable.

-> Java Beans follow the principle of “Write Once, Run Anywhere” and can be integrated seamlessly into
various Java development frameworks.

-> A bean is a Java class with method names that follow the JavaBeans guidelines.

-> A bean builder tool uses introspection to examine the bean class.

-> Based on this inspection, the bean builder tool can figure out the bean’s properties, methods, and
events.
Characteristics of Java Beans

-> Java Beans possess several key characteristics that set them apart from regular Java classes.

-> These characteristics include:

1. Public Default Constructor:


-> Java Beans must have a public default constructor to allow the framework or application to instantiate
them.

2. Private Fields with Public Accessors:


-> Encapsulated fields within a Java Bean should be declared as private, with public getter and setter
methods to access and modify the data.

3. Serializable:
-> Java Beans should implement the Serializable interface, enabling their state to be saved and
restored.

4. Event Support:
-> Java Beans can support events by implementing appropriate listener interfaces, allowing other
components to be notified of state changes.

Advantages of JavaBeans:

1. Reusability – Beans can be reused across different parts of an application.

2. Encapsulation – Data is protected and accessed only through getters/setters.

3. Easy to manipulate – IDEs and GUI tools can work with JavaBeans easily.

4. Framework support – Widely supported in Java frameworks (e.g., Spring, JSP, JSF).

5. Maintainability – Clear separation of properties makes code easier to manage.

6. Serializable – Can be easily saved/transferred between systems (e.g., over a network).

Disadvantages of JavaBeans:

1. Boilerplate code – Writing getters, setters, and constructors can be repetitive.

2. No business logic enforcement – Beans are just data holders; logic must be elsewhere.

3. Limited functionality – Mainly used for data transfer, not processing.

4. Mutable by default – Unless carefully managed, can lead to thread-safety issues.

5. Reflection overhead – Frameworks using beans often rely on reflection, which can affect performance.

Introspection
-> Introspection in JavaBeans refers to the ability to examine and manipulate a bean’s properties,
methods, and events at runtime.

-> This dynamic behavior allows tools and frameworks to work with JavaBeans without prior knowledge of
their structure.

-> Introspection is primarily used for tasks like data binding, code generation, and serialization.

-> To perform introspection, Java uses a combination of reflection and naming conventions to discover
the properties and methods of a JavaBean.

Reflection

-> Reflection in Java is a feature that allows a program to inspect and manipulate classes, methods,
fields, and constructors at runtime, even if their names are not known until runtime.

-> In the context of JavaBeans, reflection is the underlying mechanism that powers introspection.

How It Works in JavaBeans:


-> When frameworks (like JSP, Spring, or GUI builders) work with JavaBeans, they need to:

1. Discover a bean’s properties (like name, age)

2. Access getter/setter methods

3. Possibly create new instances of beans at runtime

-> They do this using reflection to analyze the structure of the bean class.

Java Naming Conventions for Introspection

-> JavaBeans follow specific naming conventions to expose their properties and methods to
introspection:

1. Property Accessors: JavaBeans should provide getter and setter methods for each property. The getter
method is named getProperty() for a property named property, and the setter method is named
setProperty(value) for the same property.

2. Event Handling Methods: For events, JavaBeans should provide methods that follow the pattern
addXXXListener() and removeXXXListener(), where XXX represents the event type.

3. Boolean Properties: For boolean properties, the getter method can use either isProperty() or
getProperty() as its name.

Class Introspector

-> The Introspector class provides a standard way for tools to learn about the properties, events, and
methods supported by a target Java Bean.
-> For each of those three kinds of information, the Introspector will separately analyze the bean’s class
and superclasses looking for either explicit or implicit information and use that information to build a
BeanInfo object that comprehensively describes the target bean.

getBeanInfo

-> Introspect on a Java Bean and learn about all its properties, exposed methods, and events.

-> Syntax:

public static BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException

Interface BeanInfo

-> Use the BeanInfo interface to create a BeanInfo class and provide explicit information about the
methods, properties, events, and other features of your beans.

Class PropertyDescriptor

-> A PropertyDescriptor describes one property that a Java Bean exports via a pair of accessor methods.

Properties

-> JavaBean properties, accessed through getter and setter methods, define the state of a bean.

-> To define a property in a bean class, supply public getter and setter methods.

-> They can be categorized into several types:

1. Simple Properties:

-> Represent a single value of a specific data type, such as String, int, or a custom object.

-> Each simple property has a corresponding getter and setter method.

-> Example:

private String name;

public String getName() { return name; }


public void setName(String name) { this.name = name; }

2. Indexed Properties:
-> Manage an array or list of values of the same data type.

-> They provide methods to access individual elements by index, as well as the entire array or list.

-> Example:

private String[] hobbies;

public String[] getHobbies() { return hobbies; }


public void setHobbies(String[] hobbies) { this.hobbies = hobbies; }

public String getHobby(int index) { return hobbies[index]; }


public void setHobby(int index, String hobby) { hobbies[index] = hobby; }

3. Boolean Properties :

-> The accessor and mutator method should follow standard naming conventions.

-> The getter methods follow an optional design pattern.

-> Example:

private boolean connect;


public boolean isConnect() {
return connect;
}
public void setConnect(boolean connect) {
this.connect = connect;
}

4. Bound Properties:

-> Allow other objects to be notified when their value changes. This is achieved through the
PropertyChangeListener interface and PropertyChangeEvent class.

-> When a bound property is modified, a property change event is fired, triggering the registered
listeners.

5. Constrained Properties:

-> Enable vetoing changes to their values. Before a constrained property is modified, a
VetoableChangeListener is notified.

-> The listener can either approve the change or throw a PropertyVetoException to reject it.

6. Read-Only and Write-Only Properties:

-> Some properties might only have a getter method (read-only) or a setter method (write-only), restricting
how they can be accessed or modified.
Bound Properties

-> A bound property notifies listeners when its value changes.

-> This has two implications:

1. The bean class includes addPropertyChangeListener() and removePropertyChangeListener() methods


for managing the bean’s listeners.
2. When a bound property is changed, the bean sends a PropertyChangeEvent to its registered
listeners.

-> PropertyChangeEvent and PropertyChangeListener live in the java.beans package.

-> The java.beans package also includes a class, PropertyChangeSupport, that takes care of most of the
work of bound properties.

-> This handy class keeps track of property listeners and includes a convenience method that fires
property change events to all registered listeners.

Class PropertyChangeEvent

-> A "PropertyChange" event gets delivered whenever a bean changes a "bound" or "constrained"
property.

-> A PropertyChangeEvent object is sent as an argument to the PropertyChangeListener and


VetoableChangeListener methods.

-> Normally PropertyChangeEvents are accompanied by the name and the old and new value of the
changed property.

getPropertyName

-> public String getPropertyName()

-> Gets the programmatic name of the property that was changed.

-> Returns: The programmatic name of the property that was changed. May be null if multiple properties
have changed.

getNewValue

-> public Object getNewValue()

-> Gets the new value for the property, expressed as an Object.

-> Returns: The new value for the property, expressed as an Object. May be null if multiple properties
have changed.

getOldValue
-> public Object getOldValue()

-> Gets the old value for the property, expressed as an Object.

-> Returns: The old value for the property, expressed as an Object. May be null if multiple properties have
changed.

Interface PropertyChangeListener

-> A "PropertyChange" event gets fired whenever a bean changes a "bound" property.

-> You can register a PropertyChangeListener with a source bean so as to be notified of any bound
property updates.

propertyChange

-> void propertyChange(PropertyChangeEvent evt)

-> This method gets called when a bound property is changed.

-> Parameters:
evt - A PropertyChangeEvent object describing the event source and the property that has changed.

Class PropertyChangeSupport

-> This is a utility class that can be used by beans that support bound properties.

-> It manages a list of listeners and dispatches PropertyChangeEvents to them.

-> You can use an instance of this class as a member field of your bean and delegate these types of work
to it.

-> The PropertyChangeListener can be registered for all properties or for a property specified by name.

addPropertyChangeListener

-> public void addPropertyChangeListener(PropertyChangeListener listener)

-> Add a PropertyChangeListener to the listener list.

-> The listener is registered for all properties.

-> The same listener object may be added more than once, and will be called as many times as it is
added.

-> If listener is null, no exception is thrown and no action is taken.

-> Parameters:
listener - The PropertyChangeListener to be added

removePropertyChangeListener

-> public void removePropertyChangeListener(PropertyChangeListener listener)

-> Remove a PropertyChangeListener from the listener list.

-> This removes a PropertyChangeListener that was registered for all properties.

-> If listener was added more than once to the same event source, it will be notified one less time after
being removed.

-> If listener is null, or was never added, no exception is thrown and no action is taken.

-> Parameters:
listener - The PropertyChangeListener to be removed

firePropertyChange

-> public void firePropertyChange(String propertyName,int oldValue,int newValue)

-> Reports an integer bound property update to listeners that have been registered to track updates of all
properties or a property with the specified name.

-> No event is fired if old and new values are equal.

-> This is merely a convenience wrapper around the more general firePropertyChange(String, Object,
Object) method.

-> Parameters:
propertyName - the programmatic name of the property that was changed
oldValue - the old value of the property
newValue - the new value of the property

Constrained Properties

-> A constrained property is a special kind of bound property.

-> For a constrained property, the bean keeps track of a set of veto listeners.

-> When a constrained property is about to change, the listeners are consulted about the change.

-> Any one of the listeners has a chance to veto the change, in which case the property remains
unchanged.

-> The veto listeners are separate from the property change listeners. Fortunately, the java.beans
package includes a VetoableChangeSupport class that greatly simplifies constrained properties.
Interface VetoableChangeListener

-> A VetoableChange event gets fired whenever a bean changes a "constrained" property.

-> You can register a VetoableChangeListener with a source bean so as to be notified of any constrained
property updates.

vetoableChange

-> void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException

-> This method gets called when a constrained property is changed.

-> Parameters: evt - a PropertyChangeEvent object describing the event source and the property that has
changed.

Class VetoableChangeSupport

-> This is a utility class that can be used by beans that support constrained properties.

-> It manages a list of listeners and dispatches PropertyChangeEvents to them.

-> You can use an instance of this class as a member field of your bean and delegate these types of work
to it.

-> The VetoableChangeListener can be registered for all properties or for a property specified by name.

addVetoableChangeListener

-> public void addVetoableChangeListener(VetoableChangeListener listener)

-> Add a VetoableChangeListener to the listener list.

-> The listener is registered for all properties.

-> The same listener object may be added more than once, and will be called as many times as it is
added.

-> If listener is null, no exception is thrown and no action is taken.

-> Parameters: listener - The VetoableChangeListener to be added

removeVetoableChangeListener

-> public void removeVetoableChangeListener(VetoableChangeListener listener)

-> Remove a VetoableChangeListener from the listener list.

-> This removes a VetoableChangeListener that was registered for all properties.
-> If listener was added more than once to the same event source, it will be notified one less time after
being removed.

-> If listener is null, or was never added, no exception is thrown and no action is taken.

-> Parameters: listener - The VetoableChangeListener to be removed

fireVetoableChange

-> public void fireVetoableChange(String propertyName, Object oldValue, Object newValue) throws
PropertyVetoException

-> Reports a constrained property update to listeners that have been registered to track updates of all
properties or a property with the specified name.

-> Any listener can throw a PropertyVetoException to veto the update.

-> If one of the listeners vetoes the update, this method passes a new "undo" PropertyChangeEvent that
reverts to the old value to all listeners that already confirmed this update and throws the
PropertyVetoException again.

-> No event is fired if old and new values are equal and non-null.

-> This is merely a convenience wrapper around the more general


fireVetoableChange(PropertyChangeEvent) method.

-> Parameters:
propertyName - the programmatic name of the property that is about to change
oldValue - the old value of the property
newValue - the new value of the property

-> Throws: PropertyVetoException - if one of listeners vetoes the property update

Design Patterns

-> Property design patterns are used to identify the properties of a Bean.

-> Property design patterns are closely related to accessor and mutator methods.

Types of property design patterns:

a. Simple property design patterns


b. Boolean property design patterns
c. Indexed property design patterns
d. Multicast Event Design Patterns

A. Simple property design pattern

-> Simple properties in JavaBeans consist of all single-valued properties, which include all built-in Java
data types as well as classes and interfaces.
-> For example, properties of type int, long, float, Color, Font, and boolean are all considered simple
properties.

-> The design patterns for simple property accessor and mutator methods as follow:
public PropertyType getPropertyName();
public void setPropertyName(PropertyType x);

B. Boolean property design pattern

-> Boolean properties have an optional design pattern for the getter method that can be used to make it
more clear that the property is boolean.

-> The design pattern for the boolean getter method follows:

public boolean isPropertyName();

-> Following is an example of a pair of accessor and mutator methods for a boolean property named
visible:

public boolean isVisible();


public void setVisible(boolean v);

C. Indexed property design pattern

-> An indexed property is a property representing an array of values.

-> Indexed properties require slightly different accessor methods, it only makes sense that their design
patterns differ a little from those of other properties.

-> Following are the design patterns for indexed properties:

public PropertyType getPropertyName(int index);


public void setPropertyName(int index, PropertyType x);
public PropertyType[] getPropertyName();
public void setPropertyName(PropertyType[] x);

-> The first pair of design patterns defines accessor methods for getting and setting individual elements in
an indexed property.

-> The second pair of patterns defines accessor methods for getting and setting the entire property array
as a whole.

D. Multicast Event Design Patterns

-> Beans that support multiple event listeners are multicast event sources.

-> The automatic JavaBeans introspection facility uses a pair of special event registration methods for
Beans that broadcast to multiple event listeners: one method allows interested parties to be added as
listeners, and the other allows listeners to be removed.

-> Following are the design patterns governing these event registration methods:
public void addEventListenerType (EventListenerType x);
public void removeEventListenerType (EventListenerType x);

Bean Persistence

-> A bean has the property of persistence when its properties, fields, and state information are saved to
and retrieved from storage.

-> Component models provide a mechanism for persistence that enables the state of components to be
stored in a non-volatile place for later retrieval.

-> The mechanism that makes persistence possible is called serialization.

-> Object serialization means converting an object into a data stream and writing it to storage.

-> Any applet, application, or tool that uses that bean can then "reconstitute" it by deserialization.

-> The object is then restored to its original state.

Controlling Serialization

-> You can control the level of serialization that your beans undergo.

-> Three ways to control serialization are:

1. Automatic serialization, implemented by the Serializable interface. The Java serialization software
serializes the entire object, except transient and static fields.

2. Customized serialization. Selectively exclude fields you do not want serialized by marking with the
transient (or static) modifier.

3. Customized file format, implemented by the Externalizable interface and its two methods. Beans are
written in a specific file format.

Bean Customization

-> Customization provides a means for modifying the appearance and behavior of a bean within an
application builder so it meets your specific needs.

-> There are several levels of customization available for a bean developer to allow other developers to
get maximum benefit from a bean’s potential functionality.

-> A bean’s appearance and behavior can be customized at design time within beans-compliant builder
tools.

-> There are two ways to customize a bean:

1. By using a property editor:


-> Each bean property has its own property editor.

-> The NetBeans GUI Builder usually displays a bean’s property editors in the Properties window.

-> The property editor that is associated with a particular property type edits that property type.

2. By using customizers:

-> Customizers give you complete GUI control over bean customization.

-> Customizers are used where property editors are not practical or applicable. Unlike a property editor,
which is associated with a property, a customizer is associated with a bean.

Interface Customizer

-> A customizer class provides a complete custom GUI for customizing a target Java Bean.

-> Each customizer should inherit from the java.awt.Component class so it can be instantiated inside an
AWT dialog or panel.

-> Each customizer should have a null constructor.

setObject

-> void setObject(Object bean)

-> Set the object to be customized.

-> This method should be called only once, before the Customizer has been added to any parent AWT
container.

-> Parameters:bean - The object to be customized.

Interface BeanInfo

-> public interface BeanInfo

-> Use the BeanInfo interface to create a BeanInfo class and provide explicit information about the
methods, properties, events, and other features of your beans.

-> When developing your bean, you can implement the bean features required for your application task
omitting the rest of the BeanInfo features.

-> They will be obtained through the automatic analysis by using the low-level reflection of the bean
methods and applying standard design patterns.

-> You have an opportunity to provide additional bean information through various descriptor classes.
-> The SimpleBeanInfo class is a convenient basic class for BeanInfo classes.

-> You can override the methods and properties of the SimpleBeanInfo class to define specific
information.

Class SimpleBeanInfo

-> public class SimpleBeanInfo extends Object implements BeanInfo

-> This is a support class to make it easier for people to provide BeanInfo classes.

JavaBeans API

-> The Java Bean API provides specifications for creating reusable software components in Java.

-> These components, known as Beans, adhere to specific conventions enabling them to be easily
manipulated and integrated within development environments.

-> The core API resides in the java.beans package, which offers classes and interfaces for defining Bean
properties, events, and customizers.

Unit 4: Servlets and JSP

Servlet

-> A servlet is a Java programming language class that is used to extend the capabilities of servers that
host applications accessed by means of a request-response programming model.

-> Although servlets can respond to any type of request, they are commonly used to extend the
applications hosted by web servers.

-> For such applications, Java Servlet technology defines HTTP-specific servlet classes.

-> The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets.

-> All servlets must implement the Servlet interface, which defines life-cycle methods.

-> When implementing a generic service, you can use or extend the GenericServlet class provided with
the Java Servlet API.

-> The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific
services.
Servlet Architecture

Components of Servlet Architecture

1. Client:

-> A web browser that sends HTTP requests to the server and processes the response.

2. Web Server:

-> Handles client requests and serves content. It can be:

i. Static: Serves fixed content like HTML/CSS.

ii. Dynamic: Works with servlets/JSP to generate dynamic content.

3. Web Container:

-> Part of the web server that manages servlets.

-> Key responsibilities:

i. Manages servlet lifecycle (init(), service(), destroy())

ii. Maps URLs to servlets

How does a Servlet Request flow?

1. The request will get originate from web browser to get and send data from to server.

2. Request will use HTTP or HTTPS protocol to get or send data to server.

3. The request from web browser will first reach to web server(apache tomcat, JBoss, etc.).

4. Web server will call specific servlet program depending on servlet URL mapping, request type(GET,
POST, DELETE etc. ), content type etc.

5. Web browser can send or get data from server in predefined formats such as JSON, XML, binary etc.

6. Servlet class will collect data from web browser. Servlet class will process the data collected from
browser. Servlet class will and save/store same data in database.

7. Servlet class can also collect data from database and send back to browser in same predefined
format.

8. Servlet class will process data using third party API data and other classes within application server.
Pros of Java Servlets:

1. Platform Independent:
-> Runs on any server with a compatible Java container (e.g., Tomcat).

2. Efficient & Scalable:


-> Handles multiple requests using a single thread-per-request model.

3. Robust Performance:
-> Uses Java’s memory management and multithreading capabilities.

4. Secure:
-> Java provides built-in security features like sandboxing, authentication, and encryption.

5. Integration Friendly:
-> Easily integrates with databases, JSP, and other Java EE technologies.

6. Reusable & Maintainable:


-> Code can be modular, making it easier to update and maintain.

7. Persistent Objects:
-> Unlike CGI, servlets remain in memory, allowing data caching and reduced response time.

Cons of Java Servlets:

1. Verbose Syntax:
-> Java code can be lengthy and harder to read, especially for UI rendering.

2. Complex for Beginners:


-> Requires knowledge of Java, HTTP, and servlet API to get started.

3. Not Ideal for UI Logic:


-> Mixing HTML and Java code can make the servlet messy and hard to maintain.

4. Server Dependency:
-> Needs a servlet container (e.g., Tomcat) to run, adding configuration overhead.

5. Limited Frontend Tools:


-> Lacks the rich UI capabilities of modern frontend frameworks.

CGI (Common Gateway Interface)

-> CGI is a standard protocol that allows web servers to execute external programs (scripts) and generate
dynamic content in response to user requests.

How it works:

-> For each HTTP request, the server launches a new process to run the CGI script, often written in
languages like Perl, Python, or C.
Key Features:

1. Platform-independent

2. Simple to implement

3. Can be written in various programming languages

Advantages:

1. Easy to write and understand

2. Language flexibility

3. Works with most web servers

Disadvantages:

1. Poor performance due to new process per request

2. High resource consumption

3. Less scalable for high-traffic websites

Difference between servlet and CGI(Common Gateway Interface)

Notes:

-> In functionality, servlets lie somewhere between Common Gateway Interface (CGI) programs and
proprietary server extensions such as the Netscape Server API (NSAPI).

-> Unlike CGI programs and NSAPI modules, you do not need to modify servlets to be platform or server
specific.

Servlet Life Cycle:

-> The servlet life cycle is a sequence of steps that a servlet goes through from its creation to its
destruction.

-> The life cycle consists of four stages:

1. Loading:
-> The servlet container loads the servlet class into the memory when the web application starts or when
the servlet is first accessed.

2. Initialization:

-> The servlet container creates an instance of the servlet and initializes it by calling its init() method.

-> This method is called only once during the life cycle of the servlet and is used for performing
initialization tasks such as opening a database connection or reading configuration parameters.

3. Request Processing:

-> The servlet container calls the service() method of the servlet to process client requests. This method
is called each time the servlet receives a request from the client.

4. Destruction:

-> The servlet container calls the destroy() method of the servlet when the web application is stopped or
when the servlet is removed from the container.

-> This method is used for performing cleanup tasks such as closing the database connection or releasing
system resources.

Apache Tomcat

Download Link: https://tomcat.apache.org/download-90.cgi

-> Apache Tomcat (called "Tomcat" for short) is a free and open-source implementation of the Jakarta
Servlet, Jakarta Expression Language, and WebSocket technologies.

-> It provides a "pure Java" HTTP web server environment in which Java code can also run.

-> Thus it is a Java web application server, although not a full JEE application server.

A Simple Servlet

Interface Servlet

-> public interface Servlet

-> Defines methods that all servlets must implement.

-> A servlet is a small Java program that runs within a Web server. Servlets receive and respond to
requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.

-> To implement this interface, you can write a generic servlet that extends javax.servlet.GenericServlet
or an HTTP servlet that extends javax.servlet.http.HttpServlet.

-> This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from
the server.

-> These are known as life-cycle methods and are called in the following sequence:

1. The servlet is constructed, then initialized with the init method.

2. Any calls from clients to the service method are handled.

3. The servlet is taken out of service, then destroyed with the destroy method, then garbage collected
and finalized.

-> In addition to the life-cycle methods, this interface provides the getServletConfig method, which the
servlet can use to get any startup information, and the getServletInfo method, which allows the servlet to
return basic information about itself, such as author, version, and copyright.

init

-> void init(ServletConfig config) throws ServletException

-> Called by the servlet container to indicate to a servlet that the servlet is being placed into service.

-> The servlet container calls the init method exactly once after instantiating the servlet.

-> The init method must complete successfully before the servlet can receive any requests.

-> The servlet container cannot place the servlet into service if the init method

1. Throws a ServletException

2. Does not return within a time period defined by the Web server

service

-> void service(ServletRequest req, ServletResponse res) throws ServletException, IOException

-> Called by the servlet container to allow the servlet to respond to a request.

-> This method is only called after the servlet’s init() method has completed successfully.

-> The status code of the response always should be set for a servlet that throws or sends an error.

-> Servlets typically run inside multithreaded servlet containers that can handle multiple requests
concurrently.

-> Developers must be aware to synchronize access to any shared resources such as files, network
connections, and as well as the servlet’s class and instance variables.

destroy

-> void destroy()


-> Called by the servlet container to indicate to a servlet that the servlet is being taken out of service.

-> This method is only called once all threads within the servlet’s service method have exited or after a
timeout period has passed.

-> After the servlet container calls this method, it will not call the service method again on this servlet.

-> This method gives the servlet an opportunity to clean up any resources that are being held (for
example, memory, file handles, threads) and make sure that any persistent state is synchronized with the
servlet’s current state in memory.

Class PrintWriter

-> public class PrintWriter extends Writer

-> Prints formatted representations of objects to a text-output stream.

-> This class implements all of the print methods found in PrintStream.

-> It does not contain methods for writing raw bytes, for which a program should use unencoded byte
streams.

Class GenericServlet

-> public abstract class GenericServlet extends Object implements Servlet, ServletConfig, Serializable

-> Defines a generic, protocol-independent servlet. To write an HTTP servlet for use on the Web, extend
HttpServlet instead.

-> GenericServlet implements the Servlet and ServletConfig interfaces. GenericServlet may be directly
extended by a servlet, although it’s more common to extend a protocol-specific subclass such as
HttpServlet.

-> GenericServlet makes writing servlets easier. It provides simple versions of the lifecycle methods init
and destroy and of the methods in the ServletConfig interface.

-> GenericServlet also implements the log method, declared in the ServletContext interface.

-> To write a generic servlet, you need only override the abstract service method.

Class HttpServlet

-> public abstract class HttpServlet extends GenericServlet

-> Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site.

-> A subclass of HttpServlet must override at least one method, usually one of these:

i. doGet, if the servlet supports HTTP GET requests


ii. doPost, for HTTP POST requests

iii. doPut, for HTTP PUT requests

iv. doDelete, for HTTP DELETE requests

v. init and destroy, to manage resources that are held for the life of the servlet

vi. getServletInfo, which the servlet uses to provide information about itself

-> There’s almost no reason to override the service method. service handles standard HTTP requests by
dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above).

-> Likewise, there’s almost no reason to override the doOptions and doTrace methods.

-> Servlets typically run on multithreaded servers, so be aware that a servlet must handle concurrent
requests and be careful to synchronize access to shared resources.

-> Shared resources include in-memory data such as instance or class variables and external objects
such as files, database connections, and network connections.

doGet

-> protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,


IOException

-> Called by the server (via the service method) to allow a servlet to handle a GET request.

-> Overriding this method to support a GET request also automatically supports an HTTP HEAD request.

-> A HEAD request is a GET request that returns no body in the response, only the request header fields.

-> When overriding this method, read the request data, write the response headers, get the response’s
writer or output stream object, and finally, write the response data.

-> It’s best to include content type and encoding. When using a PrintWriter object to return the response,
set the content type before accessing the PrintWriter object.

-> The servlet container must write the headers before committing the response, because in HTTP the
headers must be sent before the response body.

-> Where possible, set the Content-Length header (with the ServletResponse.setContentLength(int)
method), to allow the servlet container to use a persistent connection to return its response to the client,
improving performance.

-> The content length is automatically set if the entire response fits inside the response buffer.

-> When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding
header), do not set the Content-Length header.

-> The GET method should be safe, that is, without any side effects for which users are held responsible.
-> For example, most form queries have no side effects.

-> If a client request is intended to change stored data, the request should use some other HTTP
method.

-> The GET method should also be idempotent, meaning that it can be safely repeated.

-> Sometimes making a method safe also makes it idempotent.

-> For example, repeating queries is both safe and idempotent, but buying a product online or modifying
data is neither safe nor idempotent.

-> If the request is incorrectly formatted, doGet returns an HTTP "Bad Request" message.

doPost

-> protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,


IOException

-> Called by the server (via the service method) to allow a servlet to handle a POST request.

-> The HTTP POST method allows the client to send data of unlimited length to the Web server a single
time and is useful when posting information such as credit card numbers.

-> When overriding this method, read the request data, write the response headers, get the response’s
writer or output stream object, and finally, write the response data.

-> It’s best to include content type and encoding. When using a PrintWriter object to return the response,
set the content type before accessing the PrintWriter object.

-> The servlet container must write the headers before committing the response, because in HTTP the
headers must be sent before the response body.

-> Where possible, set the Content-Length header (with the ServletResponse.setContentLength(int)
method), to allow the servlet container to use a persistent connection to return its response to the client,
improving performance.

-> The content length is automatically set if the entire response fits inside the response buffer.

-> When using HTTP 1.1 chunked encoding (which means that the response has a Transfer-Encoding
header), do not set the Content-Length header.

-> This method does not need to be either safe or idempotent.

-> Operations requested through POST can have side effects for which the user can be held accountable,
for example, updating stored data or buying items online.

-> If the HTTP POST request is incorrectly formatted, doPost returns an HTTP "Bad Request" message.
Java Web Application Directory Structure

1. web-app (Context Root)

-> This is the root directory of the web application.

-> It acts as the base (context root) when the app is deployed on the server.

-> All content, both dynamic and static, resides under this folder.

2. WEB-INF/

-> A special directory that is not accessible directly via a browser.

-> Contains internal resources like configuration files, classes, and libraries.

a. classes/
-> Contains compiled Java class files, including servlets and utility classes.

-> Also stores package structures if any.

b. lib/

-> Stores JAR files (Java libraries) that the application depends on.

c. web.xml

-> The deployment descriptor.

-> Used to configure servlets, filters, listeners, and other settings.

3. Static Resources

-> HTML, CSS, JavaScript, and image files are placed outside WEB-INF.

-> These files are publicly accessible by the browser.

-> Used for UI content and client-side functionality.

Tags used in web.xml file:

1. <servlet>

-> Defines a servlet component in the web application.

-> It tells the server which class to load as a servlet.

2. <servlet-name> (inside <servlet> and <servlet-mapping>)


-> It’s an identifier or label used to refer to the servlet.

-> Used to link the servlet definition with its URL mapping.

-> Should be the same in both <servlet> and <servlet-mapping>.

3. <servlet-class>

-> Specifies the fully qualified class name (with package, if any) of the servlet.

-> This class must extend HttpServlet and contain doGet() or doPost() methods.

4. <servlet-mapping>

-> Maps the servlet to a specific URL pattern.

-> When a user accesses that URL, the corresponding servlet is executed.

5. <url-pattern>

-> Defines the URL endpoint that triggers the servlet.

Servlet Vs GenericServlet Vs HttpServlet

The Servlet API

-> Packages:

1. javax.servlet

-> The javax.servlet package contains a number of classes and interfaces that describe and define the
contracts between a servlet class and the runtime environment provided for an instance of such a class
by a conforming servlet container.

2. javax.servlet.http

-> The javax.servlet.http package contains a number of classes and interfaces that describe and define
the contracts between a servlet class running under the HTTP protocol and the runtime environment
provided for an instance of such a class by a conforming servlet container.

Reading Servlet Parameters

-> An HTTP request from a Web browser can contain more than the URL, such as information about the
client, the browser, cookies, and user query parameters.
-> Use query parameters to carry user input from the browser.

-> Use the GET method appends parameters to the URL address, and the POST method includes them
in the HTTP request body.

-> HTTP servlets need not deal with these details; information in a request is available through the
HttpServletRequest object and can be accessed using the request.getParameter() method, regardless of
the send method.

Interface HttpServletRequest

-> public interface HttpServletRequest extends ServletRequest

-> Extends the ServletRequest interface to provide request information for HTTP servlets.

-> The servlet container creates an HttpServletRequest object and passes it as an argument to the
servlet’s service methods (doGet, doPost, etc).

getParameter

-> String getParameter(String name)

-> Returns the value of a request parameter as a String, or null if the parameter does not exist.

-> Request parameters are extra information sent with the request.

-> For HTTP servlets, parameters are contained in the query string or posted form data.

-> You should only use this method when you are sure the parameter has only one value.

-> If the parameter might have more than one value, use getParameterValues(java.lang.String).

-> If you use this method with a multivalued parameter, the value returned is equal to the first value in the
array returned by getParameterValues.

getRequestDispatcher

-> RequestDispatcher getRequestDispatcher(String path)

-> Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.

-> A RequestDispatcher object can be used to forward a request to the resource or to include the
resource in a response.

-> The resource can be dynamic or static.

getCookies
-> public Cookie[] getCookies()

-> Returns an array containing all of the Cookie objects the client sent with this request.

-> This method returns null if no cookies were sent.

getSession

-> HttpSession getSession(boolean create)

-> Returns the current HttpSession associated with this request or, if there is no current session and
create is true, returns a new session.

-> If create is false and the request has no valid HttpSession, this method returns null.

Interface HttpServletResponse

-> public interface HttpServletResponse extends ServletResponse

-> Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response.
For example, it has methods to access HTTP headers and cookies.

-> The servlet container creates an HttpServletResponse object and passes it as an argument to the
servlet’s service methods (doGet, doPost, etc).

getWriter

-> PrintWriter getWriter() throws IOException

-> Returns a PrintWriter object that can send character text to the client.

-> The PrintWriter uses the character encoding returned by getCharacterEncoding().

setContentType

-> void setContentType(String type)

-> Sets the content type of the response being sent to the client, if the response has not been committed
yet.

-> The given content type may include a character encoding specification, for example,
text/html;charset=UTF-8.

-> The response’s character encoding is only set from the given content type if this method is called
before getWriter is called.
addCookie

-> void addCookie(Cookie cookie)

-> Adds the specified cookie to the response.

-> This method can be called multiple times to set more than one cookie.

sendRedirect

-> void sendRedirect(java.lang.String location) throws IOException

-> Sends a temporary redirect response to the client using the specified redirect location URL and clears
the buffer.

-> The buffer will be replaced with the data set by this method. Calling this method sets the status code to
SC_FOUND 302 (Found).

HTTP cookie

-> HTTP cookie – a small piece of text that a website sends to a browser and that the browser sends back
on subsequent visits to the site.

-> It is mainly used to maintain a session , e.g. by generating and sending back a temporary identifier
after logging in .

-> However, it can be used more broadly by remembering any data that can be encoded as a string of
characters .

-> This means that the user does not have to enter the same information each time they return to the
page or go from one page to another

Pros of Cookies:

-> Simple to implement – Easy to create, read, and manage in both server and client-side code.

-> Persistent storage – Can store small data across sessions.

-> No server storage needed – Data is stored on the client side.

-> Stateless protocol helper – Helps maintain user sessions in HTTP (which is stateless).

-> Automatic handling – Browsers automatically send cookies with every request to the same domain.

Cons of Cookies

-> Size limit – Limited to ~4KB per cookie.

-> Security risk – Vulnerable to theft (e.g., via XSS or packet sniffing if not encrypted).
-> User control – Users can delete or block cookies at any time.

-> Performance impact – Sent with every HTTP request, which can increase bandwidth usage.

-> Not suitable for sensitive data – Should not store passwords or private info.

Class Cookie

-> public class Cookie extends Object implements Cloneable, Serializable

-> Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the
browser, and later sent back to the server.

-> A cookie’s value can uniquely identify a client, so cookies are commonly used for session
management.

-> A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.

-> Some Web browsers have bugs in how they handle the optional attributes, so use them sparingly to
improve the interoperability of your servlets.

-> The servlet sends cookies to the browser by using the


HttpServletResponse.addCookie(javax.servlet.http.Cookie) method, which adds fields to HTTP response
headers to send cookies to the browser, one at a time.

-> The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit
cookie size to 4 KB each.

-> The browser returns cookies to the servlet by adding fields to HTTP request headers.

-> Cookies can be retrieved from a request by using the HttpServletRequest.getCookies() method.

-> Several cookies might have the same name but different path attributes.

-> Cookies affect the caching of the Web pages that use them.

-> HTTP 1.0 does not cache pages that use cookies created with this class.

-> This class does not support the cache control defined with HTTP 1.1.

-> This class supports both the Version 0 (by Netscape) and Version 1 (by RFC 2109) cookie
specifications.

-> By default, cookies are created using Version 0 to ensure the best interoperability.

Constructor:

-> Cookie(String name, String value)

-> Constructs a cookie with the specified name and value.


Method Summary:

setValue

-> public void setValue(String newValue)

-> Assigns a new value to this Cookie.

-> If you use a binary value, you may want to use BASE64 encoding.

-> With Version 0 cookies, values should not contain white space, brackets, parentheses, equals signs,
commas, double quotes, slashes, question marks, at signs, colons, and semicolons.

-> Empty values may not behave the same way on all browsers.

getName

-> public String getName()

-> Returns the name of the cookie. The name cannot be changed after creation.

getValue

-> public String getValue()

-> Gets the current value of this Cookie.

setMaxAge

-> public void setMaxAge(int expiry)

-> Sets the maximum age in seconds for this Cookie.

-> A positive value indicates that the cookie will expire after that many seconds have passed.

-> Note that the value is the maximum age when the cookie will expire, not the cookie’s current age.

-> A negative value means that the cookie is not stored persistently and will be deleted when the Web
browser exits.

-> A zero value causes the cookie to be deleted.

-> Parameters:

expiry - an integer specifying the maximum age of the cookie in seconds;


if negative, means the cookie is not stored;
if zero, deletes the cookie
Session Tracking / Session Management

-> Session tracking is the process of remembering and documenting user interactions over time.

-> Session management is another name for it.

Why session tracking is needed?

1. Session tracking is needed to maintain the state of a user.

2. To track the interactions of the user based on which some actions can be taken on subsequent
requests

3. One example can be on online shopping platform where your cart details have to be recorded

Session tracking techniques

1. URL Rewriting
2. Cookies
3. Hidden Form Fields
4. HttpSession object

1. URL Rewriting

-> Simply appending the URL with some data or token as the session id which can be decoded at the
server end, which can associate that data with its stored session values and can identify the legitimate
request can be done by URL rewriting.

-> This appending can be done in the form of passing query parameters with a sessionid value.

-> This can be accessed at the server side to identify the client request.

-> Though this can help to maintain the information flow between the server and the client and would be
independent of the browser, but this is generated dynamically.

-> Thus, this will not be considered a choice for static pages.

String urlWithSessionId = response.encodeURL("/api");

2. Cookies

-> To address the client subsequent request, the web server assigns a unique session ID as a cookie to
the web client so that for the next oncoming requests, this cookie can be passed and the server can
identify its validity and can process the request.

-> This is not considered an efficient approach as it is browser dependent and some browser at times
doesn’t support a cookie.

3. Hidden Form Fields


-> A web server can also pass a hidden HTML form field as an input element along with a unique session
ID as follows.

<input type = "hidden" name = "sessionId" value = "12345">

-> This simply adds the name and value on each and every request which the client sends to the server
and the response is received, the session_id value can be used to track different browser actions.

-> Since clicking on a regular ankle tag (<a href="">) hypertext link doesn’t results into form submission,
so this can’t support general session tracking and so can’t be an efficient way to handle the transmission
of information.

HttpSession

-> The HttpSession is another option for storing user-related data across different requests.

-> A session is a server-side storage holding contextual data.

-> Data isn’t shared between different session objects (client can access data from its session only).

-> It also contains key-value pairs, but in comparison to a cookie, a session can contain object as a value.

-> The storage implementation mechanism is server-dependent.

-> A session is matched with a client by a cookie or request parameters.

Interface HttpSession

-> public interface HttpSession

-> Provides a way to identify a user across more than one page request or visit to a Web site and to store
information about that user.

-> The servlet container uses this interface to create a session between an HTTP client and an HTTP
server.

-> The session persists for a specified time period, across more than one connection or page request
from the user.

-> A session usually corresponds to one user, who may visit a site many times. The server can maintain
a session in many ways such as using cookies or rewriting URLs.

-> This interface allows servlets to

1. View and manipulate information about a session, such as the session identifier, creation time, and
last accessed time

2. Bind objects to sessions, allowing user information to persist across multiple user connections
-> When an application stores an object in or removes an object from a session, the session checks
whether the object implements HttpSessionBindingListener.

-> If it does, the servlet notifies the object that it has been bound to or unbound from the session.

-> Notifications are sent after the binding methods complete.

-> For session that are invalidated or expire, notifications are sent after the session has been invalidated
or expired.

getAttribute

-> Object getAttribute(String name)

-> Returns the object bound with the specified name in this session, or null if no object is bound under the
name.

setAttribute

-> void setAttribute(String name, Object value)

-> Binds an object to this session, using the name specified.

-> If an object of the same name is already bound to the session, the object is replaced.

Interface RequestDispatcher

-> public interface RequestDispatcher

-> Defines an object that receives requests from the client and sends them to any resource (such as a
servlet, HTML file, or JSP file) on the server.

-> The servlet container creates the RequestDispatcher object, which is used as a wrapper around a
server resource located at a particular path or given by a particular name.

-> This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher
objects to wrap any type of resource.

forward

-> void forward(ServletRequest request, ServletResponse response) throws ServletException,


IOException

-> Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.

-> This method allows one servlet to do preliminary processing of a request and another resource to
generate the response.
-> For a RequestDispatcher obtained via getRequestDispatcher(), the ServletRequest object has its path
elements and parameters adjusted to match the path of the target resource.

-> forward should be called before the response has been committed to the client (before response body
output has been flushed).

-> If the response already has been committed, this method throws an IllegalStateException.

-> Uncommitted output in the response buffer is automatically cleared before the forward.

-> The request and response parameters must be either the same objects as were passed to the calling
servlet’s service method or be subclasses of the ServletRequestWrapper or ServletResponseWrapper
classes that wrap them.

-> This method sets the dispatcher type of the given request to DispatcherType.FORWARD.

include

-> void include(ServletRequest request, ServletResponse response) throws ServletException,


IOException

-> Includes the content of a resource (servlet, JSP page, HTML file) in the response.

-> In essence, this method enables programmatic server-side includes.

-> The ServletResponse object has its path elements and parameters remain unchanged from the
caller’s.

-> The included servlet cannot change the response status code or set headers; any attempt to make a
change is ignored.

-> The request and response parameters must be either the same objects as were passed to the calling
servlet’s service method or be subclasses of the ServletRequestWrapper or ServletResponseWrapper
classes that wrap them.

-> This method sets the dispatcher type of the given request to DispatcherType.INCLUDE.

JavaServer Pages Technology

-> JavaServer Pages (JSP) technology allows you to easily create web content that has both static and
dynamic components.

-> JSP technology makes available all the dynamic capabilities of Java Servlet technology but provides a
more natural approach to creating static content.

-> The main features of JSP technology are as follows:

1. A language for developing JSP pages, which are text-based documents that describe how to process
a request and construct a response

2.An expression language for accessing server-side objects


3. Mechanisms for defining extensions to the JSP language

JSP Page

-> A JSP page is a text document that contains two types of text: static data, which can be expressed in
any text-based format (such as HTML, SVG, WML, and XML), and JSP elements, which construct
dynamic content.

-> JavaServer Pages (JSP) allows dynamic content injection into static contents using Java and Java
Servlets.

-> We can make requests to a Java Servlet, perform relevant logic, and render a specific view server-side
to be consumed client-side.

-> JSP brings more tools to the table like Expression Language (EL) & JSTL (JSP Standard Tag Library),
which makes development smoother.

-> A JSP page mixes HTML with JSP tags. This combination simplifies management compared to
Servlets since you can separate design from logic.

Pros of JSP:

1. Easy to use for dynamic content: Combines HTML with Java code directly.

2. Better separation of concerns than servlets alone (especially with MVC).

3. Faster development for UI pages compared to writing HTML in servlets.

4. Automatic compilation by the server (no manual compile step).

5. Built-in objects (like request, response, session, etc.) simplify coding.

6. Reusable components via custom tags, JSP tag libraries (JSTL).

7. Supports Expression Language (EL) for cleaner syntax.

Cons of JSP:

1. Hard to maintain if too much Java code is embedded in HTML.

2. Not ideal for complex business logic — should be in servlets or back-end.

3. Slower first-time load due to compilation step.

4. Debugging is harder than plain Java classes.

5. Outdated for modern web apps — newer frameworks (e.g., JSF, Spring MVC, Thymeleaf) are
preferred.

6. Tight coupling of view and logic if not carefully structured.


Lifecycle of a JSP Page

-> When a user makes a request, a JSP page goes through several stages:

1. Translation: The JSP page is converted into a Servlet by a JSP translator.

2. Compilation: The generated servlet is compiled into a class file.

3. Class Loading: The classloader loads the compiled class.

4. Instantiation: An object of the generated servlet is created.

5. Initialization: The container invokes the jspInit() method.

6. Request Processing: The container calls the _jspService() method to handle the request.

8. Destruction: The container invokes the jspDestroy() method when the JSP is no longer needed.

Servlet Vs JSP

Overview of JSP Syntax Elements

-> directives, which convey information regarding the JSP page as a whole

-> scripting elements, which are Java coding elements such as declarations, expressions, scriptlets, and
comments

-> objects and scopes, where JSP objects can be created either explicitly or implicitly and are accessible
within a given scope, such as from anywhere in the JSP page or the session

-> actions, which create objects or affect the output stream in the JSP response (or both)

Directives

-> Directives provide instruction to the JSP container regarding the entire JSP page.

-> This information is used in translating or executing the page.

-> The basic syntax is as follows:

<%@ directive attribute1="value1" attribute2="value2"... %>

-> The JSP 1.1 specification supports the following directives:

1. page--Use this directive to specify any of a number of page-dependent attributes, such as the scripting
language to use, a class to extend, a package to import, an error page to use, or the JSP page output
buffer size.
Example:

<%@ page language="java" import="packages.mypackage" errorPage="boof.jsp" %>

2. include--Use this directive to specify a resource that contains text or code to be inserted into the JSP
page when it is translated. Specify the path of the resource relative to the URL specification of the JSP
page.

Example:

<%@ include file="/jsp/userinfopage.jsp" %>

3. taglib--Use this directive to specify a library of custom JSP tags that will be used in the JSP page.
Vendors can extend JSP functionality with their own sets of tags. This directive indicates the location of a
tag library description file and a prefix to distinguish use of tags from that library.

Example:

<%@ taglib uri="/oracustomtags" prefix="oracust" %>

Scripting Elements

-> JSP scripting elements include the following categories of snippets of Java code that can appear in a
JSP page:

1. declarations

-> These are statements declaring methods or member variables that will be used in the JSP page.

-> A JSP declaration uses standard Java syntax within the <%!...%> declaration tags to declare a
member variable or method.

-> This will result in a corresponding declaration in the generated servlet code.

Example:

<%! double f1=0.0; %>

2. expressions

-> These are Java expressions that are evaluated, converted into string values as appropriate, and
displayed where they are encountered on the page.

-> A JSP expression does not end in a semi-colon, and is contained within <%=...%> tags.

Example:
<P><B> Today is <%= new java.util.Date() %>. Have a nice day! </B></P>

3. scriptlets

-> These are portions of Java code intermixed within the markup language of the page.

-> A scriptlet, or code fragment, may consist of anything from a partial line to multiple lines of Java code.

-> You can use them within the HTML code of a JSP page to set up conditional branches or a loop, for
example.

-> A JSP scriptlet is contained within <%...%> scriptlet tags, using normal Java syntax.

Example :

<% if (pageBean.getNewName().equals("")) { %>


I don’t know you.
<% } else { %>
Hello <%= pageBean.getNewName() %>.
<% } %>

4. comments

-> These are developer comments embedded within the JSP code, similar to comments embedded within
any Java code.

-> Comments are contained within <%--...--%> tags.

-> Unlike HTML comments, these comments are not visible when a user views the page source.

Example:

<%-- Execute the following branch if no user name is entered. --%>

Implicit Objects

-> JSP technology makes available to any JSP page a set of implicit objects.

-> These are Java class instances that are created automatically by the JSP mechanism and that allow
interaction with the underlying servlet environment.

-> The following implicit objects are available:

-page

-> This is an instance of the JSP page implementation class that was created when the page was
translated; page is synonymous with this within a JSP page.

-request
-> This represents an HTTP request and is an instance of a class that implements the
javax.servlet.http.HttpServletRequest interface, which extends the javax.servlet.ServletRequest interface.

-response

-> This represents an HTTP response and is an instance of a class that implements the
javax.servlet.http.HttpServletResponse interface, which extends the javax.servlet.ServletResponse
interface.

-> The response and request objects for a particular request are associated with each other.

-pageContext

-> This represents the page context of a JSP page, which is provided for storage and access of all page
scope objects of a JSP page instance.

-> A pageContext object is an instance of the javax.servlet.jsp.PageContext class.

-> The pageContext object has page scope, making it accessible only to the JSP page instance with
which it is associated.

-session

-> This represents an HTTP session and is an instance of the javax.servlet.http.HttpSession class.

application

-> This represents the servlet context for the Web application and is an instance of the
javax.servlet.ServletContext class.

-> The application object is accessible from any JSP page instance running as part of any instance of the
application within a single JVM.

-out

-> This is an object that is used to write content to the output stream of a JSP page instance.

-> It is an instance of the javax.servlet.jsp.JspWriter class, which extends the java.io.Writer class.

-> The out object is associated with the response object for a particular request.

-config

-> This represents the servlet configuration for a JSP page and is an instance of a class that implements
the javax.servlet.ServletConfig interface.

-exception (JSP error pages only)


-> This implicit object applies only to JSP error pages--these are pages to which processing is forwarded
when an exception is thrown from another JSP page; they must have the page directive isErrorPage
attribute set to true.

Framework

-> A framework is a predefined set of tools, libraries, and conventions that provides a structured way to
build software applications efficiently.

-> It serves as a foundation that developers can build upon rather than starting from scratch.

Why Do We Need a Framework?

1. Code Reusability: Common functionalities (e.g., database access, routing) are built-in — write less
code.

2. Standardization: Enforces consistent architecture and design patterns (like MVC).

3. Productivity Boost: Speeds up development by reducing boilerplate code and setup.

4. Built-in Tools: Comes with form handling, validation, session management, security, etc.

5. Fewer Bugs: Well-tested components reduce the chances of introducing new bugs.

6. Better Security: Many frameworks come with built-in protections against common threats (e.g., SQL
injection, XSS).

7. Scalability: Designed to handle projects from small to enterprise scale.

8. Community Support: Popular frameworks have large communities, tutorials, and third-party tools.

Disadvantages of Using a Framework

1. Learning Curve: Requires time to learn the structure, rules, and conventions of the framework.

2. Less Flexibility: You must follow the framework’s way of doing things — limited freedom to design
differently.

3. Heavyweight: Some frameworks are large and may include features you don’t need, increasing
memory and load time.

4. Overhead: Abstraction layers can introduce performance overhead compared to plain code.

5. Tight Coupling: Code may become tightly coupled to the framework, making migration difficult.

6. Frequent Updates: Frameworks evolve; staying up-to-date can require refactoring code often.

7. Debugging Complexity: Framework internals can be hard to trace when something breaks.

8. One Size Doesn’t Fit All: A framework might not suit every project’s needs or scale.
Popular Java Frameworks for Web Development

1. Spring
2. Grails
3. Google Web Toolkit (GWT)
4. Struts
5. JavaServer Faces (JSF)
6. Hibernate
7. Play
8. Vaadin
9. Wicket
10. Dropwizard

1. Spring

-> Spring MVC and Spring Boot made Java modern, reactive, and cloud-ready to build high-performance
complex web applications

2. Grails

-> It is a dynamic full-stack Java framework based on the MVC design pattern. which is easy to learn and
most suitable for beginners

3. Hibernate

-> A stable, lightweight ORM Java framework that can easily communicate with any database and is more
convenient when working with multiple databases.

Unit 5: RMI

Java Remote Method Invocation(Java RMI)

-> Java Remote Method Invocation (Java RMI) enables the programmer to create distributed Java
technology-based to Java technology-based applications, in which the methods of remote Java objects
can be invoked from other Java virtual machines, possibly on different hosts.

-> RMI uses object serialization to marshal and unmarshal parameters and does not truncate types,
supporting true object-oriented polymorphism.

-> When two JVMs need to communicate, Java RMI is one option we have to make that happen.

RMI Architecture

1. Application Layer
-> This layer is the actual systems, i.e. client and server, which are involved in communication.

-> The Java program on the client side communicates with the Java program on the server side.

2. Stub

-> It is an object that resides on the client machine and acts as a proxy for the remote object.

-> It is like a gateway for the client program.

-> The stub has the same methods as a remote object.

-> When the client calls on the stub object, the stub forwards this request to a remote object (Skeleton)
via RMI infrastructure, which is then executed on the server.

-> Stub Performs the following events:

1. Initiates connection with remote JVM.

2. Writes and transmits (Marshals) parameters to remote JVM.

3. Waits for the result.

4. Reads (Unmarshalls) the returned result.

5. Pass the received result to the caller.

3. Skeleton

-> The server object, which is located in a server machine, is referred to as the Skeleton.

-> Stub communicates with the server application with the help of an intermediate Skeleton object.

-> The responsibility of the skeleton object is to send parameters to method implementation and send the
return values back to the client.

-> Skeleton Performs the following events:

1. Reads the parameter passed by the client.

2. Invokes the method on an actual Remote object.

3. Transmit/pass the result to the caller.

4. Stub / Skeleton layer

-> The Proxy Layer, also known as the Stub/Skeleton layer, intercepts calls made by the client and
redirects them to the remote object.

-> Stub and Skeleton are the proxies for the client and server.
-> The Stub and Skeleton objects are like an interface between an application and the rest of the RMI
System.

-> This layer aims to transfer data to Remote Reference Layer by Object Serialization.

-> This process of converting data/objects into a byte stream is known as Marshalling, and the reverse is
known as Unmarshalling.

-> Marshaling is performed when requesting the object from the server, and Unmarshalling is performed
when data/object reference is received from the server.

5. Remote Reference Layer(RRL)

-> The Remote Reference Layer connects the proxy layer to the RMI mechanism.

-> This layer is responsible for communicating and transferring objects between client and server.

-> This layer defines and supports the invocation semantics of the RMI connection.

-> The remote Reference Layer maintains the session during the method call. i.e. it manages the
references made by the client to the remote server object.

-> This layer is also responsible for handling duplicated objects.

6. Transport Layer

-> The transport layer is responsible for setting up communication between the two machines.

-> This layer uses standard TCP/IP protocol for connection.

-> This layer performs the actual transportation of data.

-> This layer is part of the Remote Reference Layer.

Roles of client and server

Server Roles:

1. Hosting Remote Objects:

-> The server is responsible for creating and managing the remote objects that provide the services to
clients.

2. Making Objects Accessible:

-> The server makes these remote objects accessible to clients through the RMI registry.

3. Responding to Client Requests:

-> When a client invokes a method on a remote object, the server receives the request, executes the
method on the server-side object, and then sends the result back to the client.

4. Implementing Methods:

-> The server application implements the methods of the remote objects.

Client Roles:

1. Obtaining Remote Object References:

-> The client obtains a reference to a remote object from the server’s RMI registry or through other
mechanisms.

2. Invoking Methods:

-> The client then invokes methods on the remote object, which triggers actions on the server.

3. Processing Results:

-> The client receives the results of the method invocation from the server and processes them
accordingly.

4. Using Remote Services:

-> The client ultimately uses the services provided by the remote objects on the server to achieve its
goals.

Remote Method Calls

-> Java Remote Method Invocation (RMI) is a Java API that allows a Java program to invoke methods of
remote Java objects running on another Java Virtual Machine (JVM), potentially on a different host.

Steps in a Remote Method Call:

1. Client Lookup:

-> The client uses Naming.lookup() to find the remote object in the RMI registry.

2. Method Invocation:

-> The client calls a method on the stub as if it were a local object.

3. Stub Processing:

-> The stub marshals (serializes) the method parameters and sends them to the server.

4. Skeleton Processing:

-> The skeleton receives the marshaled parameters, unmarshals them, and invokes the method on the
remote object.

5. Remote Object Execution:


-> The remote object executes the method.

6. Result Return:

-> The remote object returns the result to the skeleton.

7. Skeleton Processing:

-> The skeleton marshals the result and sends it back to the stub.

8. Stub Processing:

-> The stub receives the marshaled result, unmarshals it, and returns it to the client.

Parameter Marshalling and Unmarshalling

-> Marshalling is the process of converting method parameters into a byte stream for transmission over
the network.

-> This process is also known as serialization.

-> When a client invokes a method on a stub, the stub marshals the parameters before sending them to
the server.

-> Similarly, when the server returns a value, it marshals the return value before sending it back to the
client.

-> Unmarshalling is the reverse process of converting the byte stream back into objects.

-> RMI uses Java’s serialization mechanism to perform marshalling and unmarshalling.

-> Primitive types are bundled with a header, while objects are serialized.

-> When passing remote objects as parameters, the stub for that remote object is passed instead of the
actual object.

-> The stub hides the serialization of parameters and the network-level communication in order to present
a simple invocation mechanism to the caller.

RMI Programming Model

Overview of RMI Interfaces and Classes

-> The interfaces and classes that are responsible for specifying the remote behavior of the RMI system
are defined in the java.rmi package hierarchy.

-> The following figure shows the relationship between several of these interfaces and classes:

Relationship between several of these interfaces and classes


1. The java.rmi.Remote Interface

-> In RMI, a remote interface is an interface that declares a set of methods that may be invoked from a
remote Java virtual machine.

-> A remote interface must satisfy the following requirements:

a. A remote interface must at least extend, either directly or indirectly, the interface java.rmi.Remote.

b. Each method declaration in a remote interface or its super-interfaces must satisfy the requirements of a
remote method declaration as follows:

i. A remote method declaration must include the exception java.rmi.RemoteException (or one of its
superclasses such as java.io.IOException or java.lang.Exception) in its throws clause, in addition to any
application-specific exceptions (note that application specific exceptions do not have to extend
java.rmi.RemoteException).

ii. In a remote method declaration, a remote object declared as a parameter or return value (either
declared directly in the parameter list or embedded within a non-remote object in a parameter) must be
declared as the remote interface, not the implementation class of that interface.

2. The RemoteException Class

-> The java.rmi.RemoteException class is the superclass of exceptions thrown by the RMI runtime during
a remote method invocation.

-> To ensure the robustness of applications using the RMI system, each remote method declared in a
remote interface must specify java.rmi.RemoteException (or one of its superclasses such as
java.io.IOException or java.lang.Exception) in its throws clause.

-> The exception java.rmi.RemoteException is thrown when a remote method invocation fails for some
reason. Some reasons for remote method invocation failure include:

1. Communication failure (the remote server is unreachable or is refusing connections; the connection is
closed by the server, etc.)

2. Failure during parameter or return value marshalling or unmarshalling

3. Protocol errors

-> The class RemoteException is a checked exception (one that must be handled by the caller of a
remote method and is checked by the compiler), not a RuntimeException.

3. The RemoteObject Class and its Subclasses

-> RMI server functions are provided by java.rmi.server.RemoteObject and its subclasses,
java.rmi.server.RemoteServer and java.rmi.server.UnicastRemoteObject.

-> The class java.rmi.server.RemoteObject provides implementations for the java.lang.Object methods,
hashCode, equals, and toString that are sensible for remote objects.

-> The methods needed to create remote objects and export them (make them available to remote
clients) are provided by the class UnicastRemoteObject.

-> The java.rmi.server.UnicastRemoteObject class defines a singleton (unicast) remote object whose
references are valid only while the server process is alive.

Implementing a Remote Interface

-> The general rules for a class that implements a remote interface are as follows:

i. The class usually extends java.rmi.server.UnicastRemoteObject, thereby inheriting the remote


behavior provided by the classes java.rmi.server.RemoteObject and java.rmi.server.RemoteServer.

ii. The class can implement any number of remote interfaces.

iii. The class can extend another remote implementation class.

iv. The class can define methods that do not appear in the remote interface, but those methods can only
be used locally and are not available remotely.

RMI registry

-> RMI registry is a namespace on which all server objects are placed.

-> Each time the server creates an object, it registers this object with the RMIregistry (using bind() or
reBind() methods). These are registered using a unique name known as bind name.

-> To invoke a remote object, the client needs a reference of that object.

-> At that time, the client fetches the object from the registry using its bind name (using lookup() method).

Parameters and Return Values in Remote Methods

-> An argument to, or a return value from, a remote object can be any object that is serializable.

-> This includes primitive types, remote objects, and non-remote objects that implement the
java.io.Serializable interface.

-> A non-remote object, that is passed as a parameter of a remote method invocation or returned as a
result of a remote method invocation, is passed by copy; that is, the object is serialized using the object
serialization mechanism of the Java SE platform.

-> A remote object passed as a parameter can only implement remote interfaces.

-> Within a single remote method call, the RMI system maintains referential integrity among the objects
passed as parameters or as a return value in the call.

-> Parameters in an RMI call are written to a stream that is a subclass of the class
java.io.ObjectOutputStream in order to serialize the parameters to the destination of the remote call.
-> In a similar manner to parameter passing in RMI as described above, a return value (or exception) is
written to a subclass of ObjectOutputStream and has the same replacement behavior as parameter
transmission.

Remote object activation

-> In RMI, activation allows objects to begin execution on an as-needed basis.

-> When an activatable remote object is accessed (via a method invocation) if that remote object is not
currently executing, the system initiates the object’s execution inside an appropriate JVM.

-> An active object is a remote object that is instantiated and exported in a JVM on some system.

-> A passive object is one that is not yet instantiated (or exported) in a JVM, but which can be brought into
an active state.

-> Transforming a passive object into an active object is a process known as activation.

-> Activation requires that an object be associated with a JVM, which may entail loading the class for that
object into a JVM and the object restoring its persistent state (if any).

-> In the RMI system, we use lazy activation.

-> Lazy activation defers activating an object until a client’s first use (i.e., the first method invocation).

-> During a remote method invocation, if the "live" reference for a target object is unknown, the faulting
reference engages in the activation protocol.

-> The activation protocol involves several entities: the faulting reference, the activator, an activation
group, and the remote object being activated.

-> The activator (usually one per host) is the entity which supervises activation by being both:

i. a database of information that maps activation identifiers to the information necessary to activate an
object, and

ii. a manager of Java virtual machines, that starts up JVMs (when necessary) and forwards requests for
object activation (along with the necessary information) to the correct activation group inside a remote
JVM.

-> An activation group (one per JVM) is the entity which receives a request to activate an object in the
JVM and returns the activated object back to the activator.

-> A faulting reference uses an activation identifier and calls the activator (an internal RMI interface) to
activate the object associated with the identifier.

Simple Client Server Application

-> Developing and running RMI applications involves the following steps:

1. Define the remote interface


2. Implement the remote interface
3. Develop the Server program
4. Develop the Client program
5. Compile the Java source files
6. Execute the application

Interface Remote

-> public interface Remote

-> The Remote interface serves to identify interfaces whose methods may be invoked from a non-local
virtual machine.

-> Any object that is a remote object must directly or indirectly implement this interface.

-> Only those methods specified in a "remote interface", an interface that extends java.rmi.Remote are
available remotely.

-> Implementation classes can implement any number of remote interfaces and can extend other remote
implementation classes.

-> RMI provides some convenience classes that remote object implementations can extend which
facilitate remote object creation.

-> These classes are java.rmi.server.UnicastRemoteObject and java.rmi.activation.Activatable.

Class LocateRegistry

-> public final class LocateRegistry

-> LocateRegistry is used to obtain a reference to a bootstrap remote object registry on a particular host
(including the local host), or to create a remote object registry that accepts calls on a specific port.

Class Naming

-> public final class Naming

-> The Naming class provides methods for storing and obtaining references to remote objects in a remote
object registry.

-> Each method of the Naming class takes as one of its arguments a name that is a java.lang.String in
URL format (without the scheme component) of the form:
//host:port/name

where host is the host (remote or local) where the registry is located, port is the port number on which the
registry accepts calls, and where name is a simple string uninterpreted by the registry.

Both host and port are optional.

If host is omitted, the host defaults to the local host.

If port is omitted, then the port defaults to 1099, the "well-known" port that RMI’s registry, rmiregistry,
uses.

rebind

-> public static void rebind(String name, Remote obj) throws RemoteException, MalformedURLException

-> Rebinds the specified name to a new remote object.

-> Any existing binding for the name is replaced.

lookup

-> public static Remote lookup(String name) throws NotBoundException, MalformedURLException,


RemoteException

-> Returns a reference, a stub, for the remote object associated with the specified name.

CORBA

-> The Common Object Request Broker Architecture (or CORBA) is an industry standard developed by
the Object Management Group (OMG) to aid in distributed objects programming.

-> It is important to note that CORBA is simply a specification.

-> CORBA was designed to be platform and language independent.

-> Therefore, CORBA objects can run on any platform, located anywhere on the network, and can be
written in any language that has Interface Definition Language (IDL) mappings.

-> Similar to RMI, CORBA objects are specified with interfaces.

-> Interfaces in CORBA, however, are specified in IDL.

-> While IDL is similar to C++, it is important to note that IDL is not a programming language.

-> For a detailed introduction to CORBA.

-> There are a number of steps involved in developing CORBA applications. These are:

1. Define an interface in IDL


2. Map the IDL interface to Java (done automatically)
3. Implement the interface
4. Develop the server
5. Develop a client
6. Run the naming service, the server, and the client.

CORBA vs. RMI

-> Code-wise, it is clear that RMI is simpler to work with since the Java developer does not need to be
familiar with the Interface Definition Language (IDL). In general, however, CORBA differs from RMI in the
following areas:

1. CORBA interfaces are defined in IDL and RMI interfaces are defined in Java. RMI-IIOP allows you to
write all interfaces in Java (see RMI-IIOP).

2. CORBA supports in and out parameters, while RMI does not since local objects are passed by copy
and remote objects are passed by reference.

3. CORBA was designed with language independence in mind. This means that some of the objects can
be written in Java, for example, and other objects can be written in C++ and yet they all can interoperate.
Therefore, CORBA is an ideal mechanism for bridging islands between different programming languages.
On the other hand, RMI was designed for a single language where all objects are written in Java. Note
however, with RMI-IIOP it is possible to achieve interoperability.

4. CORBA objects are not garbage collected. As we mentioned, CORBA is language independent and
some languages (C++ for example) does not support garbage collection. This can be considered a
disadvantage since once a CORBA object is created, it continues to exist until you get rid of it, and
deciding when to get rid of an object is not a trivial task. On the other hand, RMI objects are garbage
collected automatically.

You might also like