MODULE 1: THE JAVA GRAPHICAL USER INTERFACE PROGRAMMING
1.1 Basics of Swing NOTES
Swing Application Program interface (API) is a set of extensible Graphical
User interface (GUI) Components
Swing API helps to create JAVA based Front End/GUI Applications
Swing component follows a Model-View-Controller MVC architecture
View: A single API is sufficient to support multiple looks and feel
Controller: Helps in navigation across web requests based on user
data and lands on a page with appropriate data to be shown to the user
Model: Represents the business logic and data representations,
populates all the values needed by the business logic
1.2 Swing Features
Light Weight: Swing components are independent of native Operating
System's API
Rich Controls: Swing provides a rich set of advanced controls like
Tree, TabbedPane, Slider, ColorPicker, and Table controls.
Highly Customizable: Swing controls can be customized in a very
easy way as visual appearance is independent of internal
representation.
Pluggable look-and-feel: Swing based GUI Application look and feel
can be changed at run-time, based on available values.
1.3 Swing Components
Swing components are the interactive elements in a Java application.
1.3.1 ImageIcon
The ImageIcon component creates an icon sized-image from an
image residing at the source.
1 DDE SRMIST- MCA Self Learning Material
NOTES ImageIcon homeIcon = new ImageIcon("< ---Path of the image here--- >");
This returns an icon of a home button. The string parameter is the path at
which the source image is present.
1.3.2 JButton
JButton class is used to create a push-button on the UI.
The button can contain some display text or image.
It generates an event when clicked and double-clicked.
A JButton can be implemented in the application by calling one of its
constructors.
JButton btn = new JButton("Ok");
This constructor returns a button with text Ok on it.
JButton btn1 = new JButton(homeIcon);
It returns a button with a homeIcon on it.
JButton btn2 = new JButton(homeIcon, "Home");
It returns a button with the home icon and text Home.
1.3.3 JLabel
JLabel class is used to render a read-only text label or images on the
UI.
It does not generate any event.
JLabel textLbl = new JLabel("This is a text label.");
This constructor returns a label with text.
JLabel imgLabel = new JLabel(homeIcon);
It returns a label with a home icon.
2 DDE SRMIST- MCA Self Learning Material
1.3.4 JTextField
NOTES
JTextField renders an editable single-line text box.
It accepts the input in the form of non-formatted text in the box.
To initialize the text field, call its constructor and pass an optional
integer parameter to it.
This parameter sets the width of the box measured by the number of
columns.
It does not limit the number of characters that can be input in the
box.
JTextField txtBox = new JTextField(20);
It renders a text box of 20 column width.
1.3.5 JTextArea
JTextArea class renders a multi-line text box.
Similar to the JTextField, it takes in non-formatted text in the field.
The constructor for JTextArea also expects two integer parameters
which define the height and width of the text-area in columns.
It does not restrict the number of characters that the user can input
in the text-area.
JTextArea txtArea = new JTextArea("This text is default text for text area",
5, 20);
The above code renders a multi-line text-area of height 5 rows and width 20
columns, with default text initialized in the text-area.
1.3.6 JPasswordField
JPasswordField is a subclass of JTextField class.
It renders a text-box that masks the user input text with bullet points.
This is used for inserting passwords into the application.
3 DDE SRMIST- MCA Self Learning Material
JPasswordField pwdField = new JPasswordField(15);
NOTES
var pwdValue = pwdField.getPassword();
It returns a password field of 15 column width. The getPassword method
gets the value entered by the user.
1.3.7 JCheckBox
JCheckBox renders a check-box with a label.
The check-box has two states – on/off.
When selected, the state is on and a small tick is displayed in the
box.
CheckBox chkBox = new JCheckBox("Show Help", true);
It returns a checkbox with the label Show Help. Notice the second parameter
in the constructor. It is a boolean value that indicates the default state of the
check-box. True means the check-box is defaulted to on state.
1.3.8 JRadioButton
JRadioButton is used to render a group of radio buttons in the UI.
A user can select one choice from the group.
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton rb1 = new JRadioButton("Easy", true);
JRadioButton rb2 = new JRadioButton("Medium");
JRadioButton rb3 = new JRadioButton("Hard");
radioGroup.add(rb1);
radioGroup.add(rb2);
radioGroup.add(rb3);
4 DDE SRMIST- MCA Self Learning Material
The above code creates a button group and three radio button elements. All
three elements are then added to the group. This ensures that only one
NOTES
option out of the available options in the group can be selected at a time. The
default selected option is set to “rb1”.
1.3.9 JList
JList component renders a scrollable list of elements.
A user can select a value or multiple values from the list.
This select behavior is defined in the code by the developer.
DefaultListItem cityList = new DefaultListItem();
cityList.addElement("Mumbai"):
cityList.addElement("London"):
cityList.addElement("New York"):
cityList.addElement("Sydney"):
cityList.addElement("Tokyo"):
JList cities = new JList(cityList);
cities.setSelectionModel(ListSelectionModel.SINGLE_SELECTION);
The above code renders a list of cities with 5 items in the list. The selection
restriction is set to SINGLE_SELECTION. If multiple selections is to be
allowed, set the behavior to MULTIPLE_INTERVAL_SELECTION.
1.3.10 JComboBox
JComboBox class is used to render a dropdown of the list of options.
String[] cityStrings = { "Mumbai", "London", "New York", "Sydney", "Tokyo"
};
JComboBox cities = new JComboBox(cityList);
5 DDE SRMIST- MCA Self Learning Material
cities.setSelectedIndex(3);
NOTES The default selected option can be specified through the setSelectedIndex
method. The above code sets Sydney as the default selected option.
1.3.11 JFileChooser
JFileChooser class renders a file selection utility.
This component lets a user select a file from the local system.
JFileChooser fileChooser = new JFileChooser();
JButton fileDialogBtn = new JButton("Select File");
fileDialogBtn.AddEventListner(new ActionListner()
fileChooser.showOpenDialog();
})
var selectedFile = fileChooser.getSelectedFile();
The above code creates a file chooser dialog and attaches it to the button.
The button click would open the file chooser dialog. The selected file is
returned through the getSelectedFile method.
1.3.12 JTabbedPane
JTabbedPane is another very useful component that lets the user
switch between tabs in an application.
This is a highly useful utility as it lets the user browse more content
without navigating to different pages.
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Tab 1", new JPanel());
6 DDE SRMIST- MCA Self Learning Material
tabbedPane.addTab("Tab 2", new JPanel());
The above code creates a two tabbed panel with headings Tab 1 and Tab 2. NOTES
1.3.13 JSlider
JSlider component displays a slider which the user can drag to change its
value. The constructor takes three arguments – minimum value, maximum
value, and initial value.
JSlider volumeSlider = new JSlider(0, 100, 50);
var volumeLevel = volumeSlider.getValue();
The above code creates a slider from 0 to 100 with an initial value set to 50.
The value selected by the user is returned by the getValue method.
1.4. Containers and Frames
Containers are an integral part of SwingING GUI components. A container
provides a space where a component can be located. A Container in AWT is a
component itself and it provides the capability to add a component to itself.
Following are certain noticable points to be considered.
Sub classes of Container are called as Container. For example,
JPanel, JFrame and JWindow.
Container can add only a Component to itself.
A default layout is present in each container which can be
overridden using setLayout method.
The list of commonly used containers while designed GUI using SWING.
JPanel is the simplest container. It provides space in which any other
component can be placed, including other panels.
JFrame is a top-level window with a title and a border.
JWindow object is a top-level window with no borders and no menubar.
7 DDE SRMIST- MCA Self Learning Material
NOTES 1.4.1 Jpanel
JPanel is the simplest container. It provides space in which any other
component can be placed, including other panels.
Constructors
JPanel(boolean isdoubleBuffered)
Creates a new JPanel with FlowLayout and the specified buffering strategy.
JPanel(LayoutManager layout)
Creates a new buffered JPanel with the specified layout manager.
JPanel(LayoutManager layout, boolean isdoubleBuffered)
Creates a new JPanel with the specified layout manager and buffering strategy.
Methods
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JPanel.
PanelUI getUI()
Returns the look and feel (L&F) object that renders this component.
String getUIClassID()
Returns a string that specifies the name of the L&F class which
renders this component.
protected String paramString()
Returns a string representation of this JPanel.
void setUI(PanelUI ui)
Sets the look and feel (L&F) object that renders this component.
void updateUI()
8 DDE SRMIST- MCA Self Learning Material
Resets the UI property with a value from the current look and feel.
NOTES
1.4.2 JFrame
A JFrame is a top-level window with a title and a border.
Constructors
JFrame()
Constructs a new frame that is initially invisible.
JFrame(GraphicsConfiguration gc)
Creates a Frame in the specified GraphicsConfiguration of a screen device
and a blank title.
JFrame(String title)
Creates a new, initially invisible Frame with the specified title.
JFrame(String title, GraphicsConfiguration gc)
Creates a JFrame with the specified title and the specified
GraphicsConfiguration of a screen device.
Methods
protected void addImpl(Component comp, Object constraints, int
index)
Adds the specified child Component.
protected void frameInit()
Called by the constructors to init the JFrame properly.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JFrame.
Container getContentPane()
Returns the contentPane object for this frame.
int getDefaultCloseOperation()
9 DDE SRMIST- MCA Self Learning Material
Returns the operation that occurs when the user initiates a "close" on
NOTES this frame.
Graphics getGraphics()
Creates a graphics context for this component.
JMenuBar getJMenuBar()
Returns the menubar set on this frame.
JLayeredPane getLayeredPane()
Returns the layeredPane object for this frame.
protected String paramString()
Returns a string representation of this JFrame.
protected void processWindowEvent(WindowEvent e)
Processes window events occurring on this component.
void remove(Component comp)
Removes the specified component from the container.
void repaint(long time, int x, int y, int width, int height)
Repaints the specified rectangle of this component within time
milliseconds.
void setContentPane(Container contentPane)
Sets the contentPane property.
void setDefaultCloseOperation(int operation)
Sets the operation that will happen by default when the user initiates a
"close" on this frame.
void setIconImage(Image image)
Sets the image to be displayed as the icon for this window.
void setJMenuBar(JMenuBar menubar)
10 DDE SRMIST- MCA Self Learning Material
Sets the menubar for this frame.
NOTES
void setLayeredPane(JLayeredPane layeredPane)
Sets the layeredPane property.
void setLayout(LayoutManager manager)
Sets the LayoutManager.
void update(Graphics g)
Just calls paint(g).
1.4.5 JWindow
A JWindow object is a top-level window with no borders and no MenuBar.
Constructors
JWindow()
Creates a window with no specified owner.
JWindow(Frame owner)
Creates a window with the specified owner frame.
JWindow(GraphicsConfiguration gc)
Creates a window with the specified GraphicsConfiguration of a screen device.
JWindow(Window owner)
Creates a window with the specified owner window.
JWindow(Window owner, GraphicsConfiguration gc)
Creates a window with the specified owner window and GraphicsConfiguration
of a screen device.
Methods
protected void addImpl(Component comp, Object constraints, int
index)
Adds the specified child Component.
protected JRootPane createRootPane()
11 DDE SRMIST- MCA Self Learning Material
NOTES Called by the constructor methods to create the default rootPane.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JWindow.
Container getContentPane()
Returns the Container which is the contentPane for this window.
Component getGlassPane()
Returns the glassPane Component for this window.
Graphics getGraphics()
Creates a graphics context for this component.
JLayeredPane getLayeredPane()
Returns the layeredPane object for this window.
JRootPane getRootPane()
Returns the rootPane object for this window.
TransferHandler getTransferHandler()
Gets the transferHandler property.
protected boolean isRootPaneCheckingEnabled()
Returns whether calls to add and setLayout are forwarded to the
contentPane.
protected String paramString()
Returns a string representation of this JWindow.
void remove(Component comp)
Removes the specified component from the container.
void repaint(long time, int x, int y, int width, int height)
Repaints the specified rectangle of this component within time
milliseconds.
void setContentPane(Container contentPane)
Sets the contentPane property for this window.
void setGlassPane(Component glassPane)
Sets the glassPane property.
void setLayeredPane(JLayeredPane layeredPane)
Sets the layeredPane property.
void setLayout(LayoutManager manager)
12 DDE SRMIST- MCA Self Learning Material
Sets the LayoutManager.
void update(Graphics g)
NOTES
Calls paint(g).
protected void windowInit()
Called by the constructors to init the JWindow properly.
1.5 Layout managers
Layout refers to the arrangement of components within the container.
In another way, it could be said that layout is placing the components at a
particular position within the container.
The task of laying out the controls is done automatically by the Layout
Manager.
It is possible to lay out the controls by hand, however, it becomes very
difficult because of the following two reasons.
It is very tedious to handle a large number of controls within the
container.
Usually, the width and height information of a component is
not given when we need to arrange them.
Java provides various layout managers to position the controls.
Properties like size, shape, and arrangement varies from one layout
manager to the other.
When the size of the applet or the application window changes, the size,
shape, and arrangement of the components also changes in response, i.e., the
layout managers adapt to the dimensions of the appletviewer or the
application window.
The layout manager is associated with every Container object.
Each layout manager is an object of the class that implements the
LayoutManager interface.
13 DDE SRMIST- MCA Self Learning Material
The interfaces defining the functionalities of Layout Managers are given
NOTES below,
LayoutManager
The LayoutManager interface declares those methods which need to be
implemented by the class, whose object will act as a layout manager.
LayoutManager2
The LayoutManager2 is the sub-interface of the LayoutManager. This interface
is for those classes that know how to layout containers based on layout
constraint object.
AWT Layout Manager Classes
The list of commonly used Layout types is given here,
BorderLayout
The borderlayout arranges the components to fit in the five regions:
east, west, north, south, and center.
CardLayout
The CardLayout object treats each component in the container as a card.
Only one card is visible at a time.
FlowLayout
The FlowLayout is the default layout. It layout the components in a
directional flow.
GridLayout
The GridLayout manages the components in the form of a rectangular
grid.
14 DDE SRMIST- MCA Self Learning Material
GridBagLayout
This is the most flexible layout manager class. The object of NOTES
GridBagLayout aligns the component vertically, horizontally, or along
their baseline without requiring the components of the same size.
GroupLayout
The GroupLayout hierarchically groups the components in order to
position them in a Container.
SpringLayout
A SpringLayout positions the children of its associated container
according to a set of constraints.
1.5.1 BorderLayout
The class BorderLayout arranges the components to fit in the five regions
called east, west, north, south, and center.
Each region can contain only one component and each component in each
region is identified by the corresponding constant namely, NORTH, SOUTH,
EAST, WEST, and CENTER.
Class Declaration
Following is the declaration for java.awt.BorderLayout class,
public class BorderLayout extends Object implements LayoutManager2,
Serializable
Fields
Following are the fields for java.awt.BorderLayout class,
static String AFTER_LAST_LINE − Synonym for PAGE_END.
static String AFTER_LINE_ENDS − Synonym for LINE_END.
static String BEFORE_FIRST_LINE − Synonym for
PAGE_START.
static String BEFORE_LINE_BEGINS − Synonym for
LINE_START.
15 DDE SRMIST- MCA Self Learning Material
static String CENTER − The center layout constraint (middle
NOTES of the container).
static String EAST − The east layout constraint (right side of
the container).
static String LINE_END − The component goes at the end of
the line direction for the layout.
static String LINE_START − The component goes at the
beginning of the line direction for the layout.
static String NORTH − The north layout constraint (top of the
container).
static String PAGE_END − The component comes after the last
line of the layout's content.
static String PAGE_START − The component comes before
the first line of the layout's content.
static String SOUTH − The south layout constraint (bottom of
the container).
static String WEST − The west layout constraint (left side of
the container).
Constructors
BorderLayout()
Constructs a new border layout with no gaps between the components.
BorderLayout(int hgap, int vgap)
Constructs a border layout with the specified gaps between the
components.
Methods
void addLayoutComponent(Component comp, Object constraints)
Adds the specified component to the layout, using the specified constraint
object.
16 DDE SRMIST- MCA Self Learning Material
void addLayoutComponent(String name, Component comp)
If the layout manager uses a per-component string, adds the component comp NOTES
to the layout, associating it with the string specified by name.
int getHgap()
Returns the horizontal gap between the components.
float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
float getLayoutAlignmentY(Container parent)
Returns the alignment along the y axis.
int getVgap()
Returns the vertical gap between the components.
void invalidateLayout(Container target)
Invalidates the layout, indicating that if the layout manager has cache
information it should be discarded.
void layoutContainer(Container target)
Lays out the container argument using this border layout.
Dimension maximumLayoutSize(Container target)
Returns the maximum dimensions for this layout given the components in the
specified target container.
Dimension minimumLayoutSize(Container target)
Determines the minimum size of the target container using this layout
manager.
Dimension preferredLayoutSize(Container target)
Determines the preferred size of the target container using this layout
manager, based on the components in the container.
void removeLayoutComponent(Component comp)
17 DDE SRMIST- MCA Self Learning Material
Removes the specified component from this border layout.
NOTES
void setHgap(int hgap)
Sets the horizontal gap between the components.
void setVgap(int vgap)
Sets the vertical gap between the components.
String toString()
Returns a string representation of the state of this border layout.
1.5.2 CardLayout
The class CardLayout arranges 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.
Class Declaration
Following is the declaration for java.awt.CardLayout class,
public class CardLayout extends Object implements LayoutManager2,
Serializable
Constructors
CardLayout()
Creates a new card layout with the gaps of size zero.
CardLayout(int hgap, int vgap)
Creates a new card layout with the specified horizontal and vertical gaps.
Methods
void addLayoutComponent(Component comp, Object constraints)
Adds the specified component to this card layout's internal table of names.
void addLayoutComponent(String name, Component comp)
If the layout manager uses a per-component string, adds the component comp
to the layout, associating it with the string specified by name.
18 DDE SRMIST- MCA Self Learning Material
void first(Container parent)
Flips to the first card of the container. NOTES
int getHgap()
Gets the horizontal gap between the components.
float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
float getLayoutAlignmentY(Container parent)
Returns the alignment along the y axis.
int getVgap()
Gets the vertical gap between the components.
void invalidateLayout(Container target)
Invalidates the layout, indicating that if the layout manager has cache
information, it should be discarded.
void last(Container parent)
Flips to the last card of the container.
void layoutContainer(Container parent)
Lays out the specified container using this card layout.
Dimension maximumLayoutSize(Container target)
Returns the maximum dimensions for this layout given the components in the
specified target container.
Dimension minimumLayoutSize(Container parent)
Calculates the minimum size for the specified panel.
void next(Container parent)
Flips to the next card of the specified container.
Dimension preferredLayoutSize(Container parent)
19 DDE SRMIST- MCA Self Learning Material
Determines the preferred size of the container argument using this card
NOTES layout.
void previous(Container parent)
Flips to the previous card of the specified container.
void removeLayoutComponent(Component comp)
Removes the specified component from the layout.
void setHgap(int hgap)
Sets the horizontal gap between the components.
void setVgap(int vgap)
Sets the vertical gap between the components.
void show(Container parent, String name)
Flips to the component that was added to this layout with the specified name,
using addLayoutComponent.
String toString()
Returns a string representation of the state of this card layout.
1.5.3 FlowLayout
The class FlowLayout components in a left-to-right flow.
Class Declaration
Following is the declaration for java.awt.FlowLayout class,
public class FlowLayout extends Object implements LayoutManager,
Serializable
Fields
Following are the fields for java.awt.BorderLayout class,
static int CENTER − This value indicates that each row of components
should be centered.
20 DDE SRMIST- MCA Self Learning Material
static int LEADING − This value indicates that each row of components
should be justified to the leading edge of the container's orientation. For
NOTES
example, to the left in left-to-right orientations.
static int LEFT − This value indicates that each row of components
should be left-justified.
static int RIGHT − This value indicates that each row of components
should be right-justified.
static int TRAILING − This value indicates that each row of components
should be justified to the trailing edge of the container's orientation. For
example, to the right in left-to-right orientations.
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.
Methods
void addLayoutComponent(String name, Component comp)
Adds the specified component to the layout.
int getAlignment()
Gets the alignment for this layout.
int getHgap()
21 DDE SRMIST- MCA Self Learning Material
Gets the horizontal gap between the components.
NOTES
int getVgap()
Gets the vertical gap between the components.
void layoutContainer(Container target)
Lays out the container.
Dimension minimumLayoutSize(Container target)
Returns the minimum dimensions needed to layout the visible components
contained in the specified target container.
Dimension preferredLayoutSize(Container target)
Returns the preferred dimensions for this layout given the visible
components in the specified target container.
void removeLayoutComponent(Component comp)
Removes the specified component from the layout.
void setAlignment(int align)
Sets the alignment for this layout.
void setHgap(int hgap)
Sets the horizontal gap between the components.
void setVgap(int vgap)
Sets the vertical gap between the components.
22 DDE SRMIST- MCA Self Learning Material
String toString()
NOTES
Returns a string representation of this FlowLayout object and its values.
1.5.4 GridLayout
The class GridLayout arranges the components in a rectangular grid.
Class Declaration
Following is the declaration for java.awt.GridLayout class,
public class GridLayout extends Object implements LayoutManager,
Serializable
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.
Methods
void addLayoutComponent(String name, Component comp)
Adds the specified component with the specified name to the layout.
int getColumns()
Gets the number of columns in this layout.
int getHgap()
Gets the horizontal gap between the components.
23 DDE SRMIST- MCA Self Learning Material
int getRows()
NOTES Gets the number of rows in this layout.
int getVgap()
Gets the vertical gap between the components.
void layoutContainer(Container parent)
Lays out the specified container using this layout.
Dimension minimumLayoutSize(Container parent)
Determines the minimum size of the container argument using this grid
layout.
Dimension preferredLayoutSize(Container parent)
Determines the preferred size of the container argument using this grid
layout.
void removeLayoutComponent(Component comp)
Removes the specified component from the layout.
void setColumns(int cols)
Sets the number of columns in this layout to the specified value.
void setHgap(int hgap)
Sets the horizontal gap between the components to the specified value.
void setRows(int rows)
Sets the number of rows in this layout to the specified value.
void setVgap(int vgap)
Sets the vertical gap between the components to the specified value.
String toString()
Returns the string representation of this grid layout's values.
1.5.5 GridBagLayout
24 DDE SRMIST- MCA Self Learning Material
The class GridBagLayout arranges the components in a horizontal and
vertical manner.
NOTES
Class Declaration
Following is the declaration for java.awt.GridBagLayout class,
public class GridBagLayout extends Object implements LayoutManager2,
Serializable
Fields
Following are the fields for java.awt.GridBagLayout class,
static int DEFAULT_SIZE − Indicates the size from the component or
the gap should be used for a particular range value.
static int PREFERRED_SIZE − Indicates the preferred size from the
component or the gap should be used for a particular range value.
Constructors
GridBagLayout()
Creates a grid bag layout manager.
Methods
void addLayoutComponent(Component comp, Object constraints)
Adds the specified component to the layout, using the specified constraints
object.
void addLayoutComponent(String name, Component comp)
Adds the specified component with the specified name to the layout.
protected void adjustForGravity(GridBagConstraints constraints,
Rectangle r)
Adjusts the x, y width and height fields to the correct values depending on the
constraint geometry and pads.
25 DDE SRMIST- MCA Self Learning Material
protected void AdjustForGravity(GridBagConstraints constraints,
NOTES Rectangle r)
This method is obsolete and supplied for backwards compatability only; new
code should call adjustForGravity instead.
protected void arrangeGrid(Container parent)
Lays out the grid.
protected void ArrangeGrid(Container parent)
This method is obsolete and supplied for backwards compatability only; new
code should call arrangeGrid instead.
GridBagConstraints getConstraints(Component comp)
Gets the constraints for the specified component.
float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
float getLayoutAlignmentY(Container parent)
Returns the alignment along the y axis.
int[][] getLayoutDimensions()
Determines column widths and row heights for the layout grid.
protected java.awt.GridBagLayoutInfo getLayoutInfo(Container parent,
int sizeflag)
Fills in an instance of GridBagLayoutInfo for the current set of managed
children.
protected java.awt.GridBagLayoutInfo GetLayoutInfo(Container parent,
int sizeflag)
This method is obsolete and supplied for backwards compatability only; new
code should call getLayoutInfo instead.
Point getLayoutOrigin()
Determines the origin of the layout area, in the graphics coordinate space of the
26 DDE SRMIST- MCA Self Learning Material
target container.
NOTES
double[][] getLayoutWeights()
Determines the weights of the layout grid's columns and rows.
protected Dimension getMinSize(Container parent,
java.awt.GridBagLayoutInfo info)
Figures out the minimum size of the master based on the information from
getLayoutInfo().
protected Dimension GetMinSize(Container parent,
java.awt.GridBagLayoutInfo info)
This method is obsolete and supplied for backwards compatability only; new
code should call getMinSize instead.
void invalidateLayout(Container target)
Invalidates the layout, indicating that if the layout manager has cached
information it should be discarded.
void layoutContainer(Container parent)
Lays out the specified container using this grid bag layout.
Point location(int x, int y)
Determines which cell in the layout grid contains the point specified by (x, y).
protected GridBagConstraints lookupConstraints(Component comp)
Retrieves the constraints for the specified component.
Dimension maximumLayoutSize(Container target)
Returns the maximum dimensions for this layout given the components in the
specified target container.
Dimension minimumLayoutSize(Container parent)
Determines the minimum size of the parent container using this grid bag
layout.
27 DDE SRMIST- MCA Self Learning Material
Dimension preferredLayoutSize(Container parent)
NOTES Determines the preferred size of the parent container using this grid bag
layout.
void removeLayoutComponent(Component comp)
Removes the specified component from this layout.
void setConstraints(Component comp, GridBagConstraints constraints)
Sets the constraints for the specified component in this layout.
String toString()
Returns a string representation of this grid bag layout's values.
1.5.6 GroupLayout
The class GroupLayout hierarchically groups the components in order to
position them in a Container.
Class Declaration
Following is the declaration for javax.swing.GroupLayout class,
public class GroupLayout extends Object implements LayoutManager2
Fields
Following are the fields for javax.swing.GroupLayout class,
static int DEFAULT_SIZE − Indicates the size from the
component or the gap should be used for a particular range
value.
static int PREFERRED_SIZE − Indicates the preferred size
from the component or the gap should be used for a particular
range value.
Constructors
GroupLayout(Container host)
Creates a GroupLayout for the specified Container.
Methods
28 DDE SRMIST- MCA Self Learning Material
void addLayoutComponent(Component component, Object constraints)
Notification that a Component has been added to the parent container. NOTES
void addLayoutComponent(String name, Component component)
Notification that a Component has been added to the parent container.
GroupLayout.ParallelGroup createBaselineGroup(boolean resizable, boolean
anchorBaselineToTop)
Creates and returns a ParallelGroup that aligns its elements along the baseline.
GroupLayout.ParallelGroup createParallelGroup()
Creates and returns a ParallelGroup with an alignment of Alignment.LEADING.
GroupLayout.ParallelGroup createParallelGroup(GroupLayout.Alignment
alignment)
Creates and returns a ParallelGroup with the specified alignment.
GroupLayout.ParallelGroup createParallelGroup(GroupLayout.Alignment
alignment, boolean resizable)
Creates and returns a ParallelGroup with the specified alignment and resize
behavior.
GroupLayout.SequentialGroup createSequentialGroup()
Creates and returns a SequentialGroup.
boolean getAutoCreateContainerGaps()
Returns true if the gaps between the container and the components that border the
container are automatically created.
boolean getAutoCreateGaps()
Returns true if the gaps between the components are automatically created.
boolean getHonorsVisibility()
Returns whether the component visiblity is considered when sizing and positioning
the components.
29 DDE SRMIST- MCA Self Learning Material
float getLayoutAlignmentX(Container parent)
NOTES Returns the alignment along the x axis.
float getLayoutAlignmentY(Container parent)
Returns the alignment along the y axis.
LayoutStyle getLayoutStyle()
Returns the LayoutStyle used for calculating the preferred gap between the
components.
void invalidateLayout(Container parent)
Invalidates the layout, indicating that if the layout manager has cache information it
should be discarded.
void layoutContainer(Container parent)
Lays out the specified container.
void linkSize(Component... components)
Forces the specified components to have the same size regardless of their preferred,
minimum, or maximum sizes.
void linkSize(int axis, Component... components)
Forces the specified components to have the same size along the specified axis
regardless of their preferred, minimum, or maximum sizes.
Dimension maximumLayoutSize(Container parent)
Returns the maximum size for the specified container.
Dimension minimumLayoutSize(Container parent)
Returns the minimum size for the specified container.
Dimension preferredLayoutSize(Container parent)
Returns the preferred size for the specified container.
void removeLayoutComponent(Component component)
Notifies that a Component has been removed from the parent container.
30 DDE SRMIST- MCA Self Learning Material
void replace(Component existingComponent, Component newComponent)
Replaces an existing component with a new one. NOTES
void setAutoCreateContainerGaps(boolean autoCreateContainerPadding)
Sets whether a gap between the container and the components that touch the border
of the container should automatically be created.
void setAutoCreateGaps(boolean autoCreatePadding)
Sets whether a gap between the components should automatically be created.
void setHonorsVisibility(boolean honorsVisibility)
Sets whether the component visiblity is considered when sizing and positioning the
components.
void setHonorsVisibility(Component component, boolean honorsVisibility)
Sets whether the component's visiblity is considered for sizing and positioning.
void setHorizontalGroup(GroupLayout.Group group)
Sets the Group that positions and sizes the components along the horizontal axis.
void setLayoutStyle(LayoutStyle layoutStyle)
Sets the LayoutStyle used to calculate the preferred gaps between the components.
void setVerticalGroup(GroupLayout.Group group)
Sets the Group that positions and sizes the components along the vertical axis.
String toString()
Returns a string representation of this GroupLayout.
1.5.7 SpringLayout
The class SpringLayout positions the children of its associated container
according to a set of constraints.
Class Declaration
Following is the declaration for javax.swing.SpringLayout class,
public class SpringLayout extends Object implements LayoutManager2
31 DDE SRMIST- MCA Self Learning Material
Fields
NOTES Following are the fields for javax.swing.SpringLayout class,
static String BASELINE − Specifies the baseline of a component.
static String EAST − Specifies the right edge of a component's bounding
rectangle.
static String HEIGHT − Specifies the height of a component's bounding
rectangle.
static String HORIZONTAL_CENTER − Specifies the horizontal center
of a component's bounding rectangle.
static String NORTH − Specifies the top edge of a component's
bounding rectangle.
static String SOUTH − Specifies the bottom edge of a component's
bounding rectangle.
static String VERTICAL_CENTER − Specifies the vertical center of a
component's bounding rectangle.
static String WEST − Specifies the left edge of a component's bounding
rectangle.
static String WIDTH − Specifies the width of a component's bounding
rectangle.
Constructors
SpringLayout()
Creates a new SpringLayout.
Methods
void addLayoutComponent(Component component, Object constraints)
If constraints are an instance of SpringLayout.Constraints, associates the
constraints with the specified component.
void addLayoutComponent(String name, Component c)
32 DDE SRMIST- MCA Self Learning Material
Has no effect, since this layout manager does not use a per-component string.
NOTES
Spring getConstraint(String edgeName, Component c)
Returns the spring controlling the distance between the specified edge of the
component and the top or left edge of its parent.
SpringLayout.Constraints getConstraints(Component c)
Returns the constraints for the specified component.
float getLayoutAlignmentX(Container p)
Returns 0.5f (centered).
float getLayoutAlignmentY(Container p)
Returns 0.5f (centered).
void invalidateLayout(Container p)
Invalidates the layout, indicating that if the layout manager has cache
information it should be discarded.
void layoutContainer(Container parent)
Lays out the specified container.
Dimension maximumLayoutSize(Container parent)
Calculates the maximum size dimensions for the specified container, given
the components it contains.
Dimension minimumLayoutSize(Container parent)
Calculates the minimum size dimensions for the specified container, given the
33 DDE SRMIST- MCA Self Learning Material
components it contains.
NOTES
Dimension preferredLayoutSize(Container parent)
Calculates the preferred size dimensions for the specified container, given the
components it contains.
void putConstraint(String e1, Component c1, int pad, String e2,
Component c2)
Links edge e1 of component c1 to edge e2 of component c2, with a fixed
distance between the edges.
void putConstraint(String e1, Component c1, Spring s, String e2,
Component c2)
Links edge e1 of component c1 to edge e2 of component c2.
void removeLayoutComponent(Component c)
Removes the constraints associated with the specified component.
Code to demonstrate Layout
//import statements
import java.awt.*;
import javax.swing.*;
public class FlowLayoutExample
JFrame frameObj;
// constructor
FlowLayoutExample()
34 DDE SRMIST- MCA Self Learning Material
// creating a frame object
frameObj = new JFrame();
NOTES
// creating the buttons
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");
// adding the buttons to frame
frameObj.add(b1);
frameObj.add(b2);
frameObj.add(b3);
frameObj.add(b4);
frameObj.add(b5);
frameObj.add(b6);
frameObj.add(b7);
frameObj.add(b8);
frameObj.add(b9);
frameObj.add(b10);
35 DDE SRMIST- MCA Self Learning Material
// parameter less constructor is used
NOTES // therefore, alignment is center
// horizontal as well as the vertical gap is 5 units.
frameObj.setLayout(new FlowLayout());
frameObj.setSize(300, 300);
frameObj.setVisible(true);
// main method
public static void main(String argvs[])
new FlowLayoutExample();
1.6 Menu
It is known that every top-level window has a menu bar associated with it.
This menu bar consists of various menu choices available to the end user.
Further, each choice contains a list of options, which is called drop-down
menus.
Menu and MenuItem controls are subclass of MenuComponent class.
Menu Hierarchy
The following figure shows the hierarchy of Menu and the associated classes
and interfaces.
36 DDE SRMIST- MCA Self Learning Material
NOTES
Figure. Menu Hierarchy
Menu Controls
JMenuBar
The JMenuBar object is associated with the top-level window.
JMenuItem
The items in the menu must belong to the JMenuItem or any of its subclass.
JMenu
The JMenu object is a pull-down menu component which is displayed from the
menu bar.
JCheckboxMenuItem
JCheckboxMenuItem is the subclass of JMenuItem.
JRadioButtonMenuItem
JRadioButtonMenuItem is the subclass of JMenuItem.
JPopupMenu
JPopupMenu can be dynamically popped up at a specified position within a
component.
1.6.1 JMenuBar
The JMenuBar class provides an implementation of a menu bar.
37 DDE SRMIST- MCA Self Learning Material
Class Declaration
NOTES Following is the declaration for javax.swing.JMenuBar class,
public class JMenuBar extends JComponent implements Accessible,
MenuElement
Constructors
JMenuBar()
Creates a new menu bar.
Methods
void add(JMenu c)
Adds menu to the menu bar. Adds JMenu object to the Menu bar.
void add(Component c)
Add component to the end of JMenu
void add(Component c, int index)
Add component to the specified index of JMenu
void add(JMenuItem menuItem)
Adds menu item to the end of the menu.
void add(String s)
Creates a menu item with specified string and appends it to the end
of menu.
JMenuItem getItem(int index)
Returns the specified menuitem at the given index
1.6.2 JMenuItem
The JMenuItem class represents the actual item in a menu.
All items in a menu should derive from class JMenuItem, or one of its
subclasses.
38 DDE SRMIST- MCA Self Learning Material
By default, it embodies a simple labeled menu item.
Class Declaration
NOTES
public class JMenuItem extends AbstractButton implements Accessible,
MenuElement
Constructors
JMenuItem()
Creates a JMenuItem with no set text or icon.
JMenuItem(Action a)
Creates a menu item whose properties are taken from the specified Action.
JMenuItem(Icon icon)
Creates a JMenuItem with the specified icon.
JMenuItem(String text)
Creates a JMenuItem with the specified text.
JMenuItem(String text, Icon icon)
Creates a JMenuItem with the specified text and icon.
JMenuItem(String text, int mnemonic)
Creates a JMenuItem with the specified text and keyboard mnemonic.
Methods
Protectedvoid
actionPropertyChanged(Action action, String propertyName)
Updates the button's state in response to property changes in the
associated action.
void addMenuDragMouseListener(MenuDragMouseListener l)
Adds a MenuDragMouseListener to the menu item.
void addMenuKeyListener(MenuKeyListener l)
Adds a MenuKeyListener to the menu item.
protected void configurePropertiesFromAction(Action a)
39 DDE SRMIST- MCA Self Learning Material
Sets the properties on this button to match those in the specified Action.
NOTES protected void MenuDragMouseDragged(MenuDragMouseEvent event)
Notifies all listeners that have registered interest for notification on
this event type.
protected void MenuDragMouseEntered(MenuDragMouseEvent event)
Notifies all listeners that have registered interest for notification on this
event type.
40 DDE SRMIST- MCA Self Learning Material
protected void fireDragMouseReleased(MenuDragMouseEvent event)
Notifies all listeners that have registered interest for notification on this
NOTES
event type.
protected void fireMenuKeyPressed(MenuKeyEvent event)
Notifies all listeners that have registered interest for notification on this
event type.
protected void fireMenuKeyReleased(MenuKeyEvent event)
Notifies all listeners that have registered interest for notification on this
event type.
protected void fireMenuKeyTyped(MenuKeyEvent event)
Notifies all listeners that have registered interest for notification on this
event type.
KeyStroke getAccelerator()
Returns the KeyStroke which serves as an accelerator for the menu item.
AccessibleContext getAccessibleContext()
Returns the AccessibleContext associated with this JMenuItem.
Component getComponent()
Returns the java.awt.Component used to paint this object.
MenuDragMouseListener[] getMenuDragMouseListeners()
Returns an array of all the MenuDragMouseListeners added to this
JMenuItem with addMenuDragMouseListener().
MenuKeyListener[] getMenuKeyListeners()
Returns an array of all the MenuKeyListeners added to this JMenuItem
with addMenuKeyListener().
MenuElement[] getSubElements()
This method returns an array containing the sub-menu components for
this menu component.
String getUIClassID()
Returns the suffix used to construct the name of the L&F class used to
render this component.
protected void init(String text, Icon icon)
Initializes the menu item with the specified text and icon.
boolean isArmed()
Returns whether the menu item is "armed".
41 DDE SRMIST- MCA Self Learning Material
void updateUI()
NOTES Resets the UI property with a value from the current look and feel.
1.6.3 JMenu
The JMenu class represents the pull-down menu component which is
deployed from a menu bar.
Class Declaration
public class JMenu extends JMenuItem implements Accessible,
MenuElement
Fields
Following is the field for java.awt.Component class,
protected JMenu.WinListener popupListener
The window-closing listener for the popup.
Constructors
JMenu()
Constructs a new JMenu with no text.
JMenu(Action a)
Constructs a menu whose properties are taken from the Action supplied.
JMenu(String s)
Constructs a new JMenu with the supplied string as its text.
JMenu(String s, boolean b)
Constructs a new JMenu with the supplied string as its text and specified as a
tear-off menu or not.
Methods
Method and Description
JMenuItem
add(Action a)
Creates a new menu item attached to the specified Action object and appends it
42 DDE SRMIST- MCA Self Learning Material
to the end of this menu.
Component
NOTES
add(Component c)
Appends a component to the end of this menu.
Component
add(Component c, int index)
Adds the specified component to this container at the given position.
JMenuItem
add(JMenuItem menuItem)
Appends a menu item to the end of this menu.
JMenuItem
add(String s)
Creates a new menu item with the specified text and appends it to the end of this
menu.
void
addMenuListener(MenuListener l)
Adds a listener for menu events.
void
addSeparator()
Appends a new separator to the end of the menu.
void
applyComponentOrientation(ComponentOrientation o)
Sets the ComponentOrientation property of this menu and all components
contained within it.
protected PropertyChangeListener
createActionChangeListener(JMenuItem b)
Returns a properly configured PropertyChangeListener which updates the
control as changes to the Action occur.
protected JMenuItem
createActionComponent(Action a)
Factory method which creates the JMenuItem for Actions added to the JMenu.
protected JMenu.WinListener
createWinListener(JPopupMenu p)
43 DDE SRMIST- MCA Self Learning Material
Creates a window-closing listener for the popup.
NOTES void
doClick(int pressTime)
Programmatically performs a "click".
protected void
fireMenuCanceled()
Notifies all listeners that have registered interest for notification on this event
type.
protected void
fireMenuDeselected()
Notifies all listeners that have registered interest for notification on this event
type.
protected void
fireMenuSelected()
Notifies all listeners that have registered interest for notification on this event
type.
AccessibleContext
getAccessibleContext()
Gets the AccessibleContext associated with this JMenu.
Component
getComponent()
Returns the java.awt.Component used to paint this MenuElement.
int
getDelay()
Returns the suggested delay, in milliseconds, before submenus are popped up or
down.
JMenuItem
getItem(int pos)
Returns the JMenuItem at the specified position.
Int
getItemCount()
Returns the number of items on the menu, including separators.
Component
44 DDE SRMIST- MCA Self Learning Material
getMenuComponent(int n)
Returns the component at position n.
NOTES
Int
getMenuComponentCount()
Returns the number of components on the menu.
Component[]
getMenuComponents()
Returns an array of Components of the menu's subcomponents.
MenuListener[]
getMenuListeners()
Returns an array of all the MenuListeners added to this JMenu with
addMenuListener().
JPopupMenu
getPopupMenu()
Returns the popupmenu associated with this menu.
protected Point
getPopupMenuOrigin()
Computes the origin for the JMenu's popup menu.
MenuElement[]
getSubElements()
Returns an array of MenuElements containing the submenu for this menu
component.
String
getUIClassID()
Returns the name of the L&F class that renders this component.
JMenuItem
insert(Action a, int pos)
Inserts a new menu item attached to the specified Action object at a given
position.
JMenuItem
insert(JMenuItem mi, int pos)
Inserts the specified JMenuitem at a given position.
void
45 DDE SRMIST- MCA Self Learning Material
insert(String s, int pos)
NOTES Inserts a new menu item with the specified text at a given position.
void
insertSeparator(int index)
Inserts a separator at the specified position.
boolean
isMenuComponent(Component c)
Returns true if the specified component exists in the submenu hierarchy.
boolean
isPopupMenuVisible()
Returns true if the menu's popup window is visible.
boolean
isSelected()
Returns true if the menu is currently selected (highlighted).
boolean
isTearOff()
Returns true if the menu can be torn off.
Boolean
isTopLevelMenu()
Returns true if the menu is a 'top-level menu', that is, if it is the direct child of a
menubar.
void
menuSelectionChanged(boolean isIncluded)
Messaged when the menubar selection changes to activate or deactivate this
menu.
protected String
paramString()
Returns a string representation of this JMenu.
protected void
processKeyEvent(KeyEvent evt)
Processes key stroke events such as mnemonics and accelerators.
void
remove(Component c)
46 DDE SRMIST- MCA Self Learning Material
Removes the component c from this menu.
void
NOTES
remove(int pos)
Removes the menu item at the specified index from this menu.
void
remove(JMenuItem item)
Removes the specified menu item from this menu.
void
removeAll()
Removes all menu items from this menu.
void
removeMenuListener(MenuListener l)
Removes a listener for menu events.
void
setAccelerator(KeyStroke keyStroke)
setAccelerator is not defined for JMenu.
void
setComponentOrientation(ComponentOrientation o)
Sets the language-sensitive orientation that is to be used to order the elements
or text within this component.
void
setDelay(int d)
Sets the suggested delay before the menu's PopupMenu is popped up or down.
void
setMenuLocation(int x, int y)
Sets the location of the popup component.
void
setModel(ButtonModel newModel)
Sets the data model for the "menu button" -- the label that the user clicks to open
or close the menu.
void
setPopupMenuVisible(boolean b)
Sets the visibility of the menu's popup.
47 DDE SRMIST- MCA Self Learning Material
void
NOTES setSelected(boolean b)
Sets the selection status of the menu.
void
updateUI()
Resets the UI property with a value from the current look and feel.
1.6.4 JCheckboxMenuItem
The JCheckboxMenuItem class represents a check box which can be included
in a menu. Selecting the check box in the menu changes the control's state
from on to off or from off to on.
Class Declaration
public class JCheckBoxMenuItem extends JMenuItem implements
SwingConstants, Accessible
Constructors
JCheckboxMenuItem()
Creates an initially unselected check box menu item with no set text or icon.
JCheckboxMenuItem(Action a)
Creates a menu item whose properties are taken from the Action supplied.
JCheckboxMenuItem(Icon icon)
Creates an initially unselected check box menu item with an icon.
JCheckboxMenuItem(String text)
Creates an initially unselected check box menu item with text.
JCheckboxMenuItem(String text, boolean b)
Creates a check box menu item with the specified text and selection state.
JCheckboxMenuItem(String text, Icon icon)
Creates an initially unselected check box menu item with the specified text and
icon.
48 DDE SRMIST- MCA Self Learning Material
JCheckboxMenuItem(String text, Icon icon, boolean b)
Creates a checkbox menu item with the specified text, icon, and selection state. NOTES
Methods
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JCheckBoxMenuItem.
Object[] getSelectedObjects()
Returns an array (length 1) containing the check box menu item label or null
if the check box is not selected.
boolean getState()
Returns the selected-state of the item.
String getUIClassID()
Returns the name of the L&F class that renders this component.
protected String paramString()
Returns a string representation of this JCheckBoxMenuItem.
void setState(boolean b)
Sets the selected-state of the item.
1.6.5 JRadioButtonMenuItem
The JRadioButtonMenuItem class represents a check box which can be
included in a menu.
Selecting the check box in the menu changes the control's state
from on to off or from off to on.
Class Declaration
49 DDE SRMIST- MCA Self Learning Material
public class JRadioButtonMenuItem extends JMenuItem implements
NOTES Accessible
Constructors
JRadioButtonMenuItem()
Creates a JRadioButtonMenuItem with no set text or icon.
JRadioButtonMenuItem(Action a)
Creates a radio button menu item whose properties are taken from the Action
supplied.
JRadioButtonMenuItem(Icon icon)
Creates a JRadioButtonMenuItem with an icon.
JRadioButtonMenuItem(Icon icon, boolean selected)
Creates a radio button menu item with the specified image and selection state,
but no text.
JRadioButtonMenuItem(String text)
Creates a JRadioButtonMenuItem with text.
JRadioButtonMenuItem(String text, boolean selected)
Creates a radio button menu item with the specified text and selection state.
JRadioButtonMenuItem(String text, Icon icon)
Creates a radio button menu item with the specified text and Icon.
JRadioButtonMenuItem(String text, Icon icon, boolean selected)
Creates a radio button menu item with the specified text, image, and selection
state.
Methods
AccessibleContext getAccessibleContext()
50 DDE SRMIST- MCA Self Learning Material
Gets the AccessibleContext associated with this JRadioButtonMenuItem.
NOTES
String getUIClassID()
Returns the name of the L&F class that renders this component.
protected String paramString()
Returns a string representation of this JRadioButtonMenuItem.
1.6.6 JPopup
The JPopup menu represents a menu which can be dynamically popped up
at a specified position within a component.
Class Declaration
public class JPopupMenu extends JComponent implements Accessible,
MenuElement
Constructors
JPopupMenu()
Constructs a JPopupMenu without an "invoker".
JPopupMenu(String label)
Constructs a JPopupMenu with the specified title.
Methods
JMenuItem add(Action a)
Appends a new menu item to the end of the menu which dispatches the
specified Action object.
JMenuItem add(JMenuItem menuItem)
Appends the specified menu item to the end of this menu.
JMenuItem add(String s)
51 DDE SRMIST- MCA Self Learning Material
Creates a new menu item with the specified text and appends it to the end of this
NOTES menu.
void addMenuKeyListener(MenuKeyListener l)
Adds a MenuKeyListener to the popup menu.
void addPopupMenuListener(PopupMenuListener l)
Adds a PopupMenu listener.
void addSeparator()
Appends a new separator at the end of the menu.
protected PropertyChangeListener
createActionChangeListener(JMenuItem b)
Returns a properly configured PropertyChangeListener which updates the control
as changes to the Action occur.
protected JMenuItem createActionComponent(Action a)
Factory method which creates the JMenuItem for Actions added to
the JPopupMenu.
protected void PopupMenuCanceled()
Notifies PopupMenuListeners that this popup menu is cancelled.
protected void PopupMenuWillBecomeInvisible()
Notifies PopupMenuListeners that this popup menu will become invisible.
protected void PopupMenuWillBecomeVisible()
Notifies PopupMenuListeners that this popup menu will become visible.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JPopupMenu.
Component getComponent()
Returns this JPopupMenu component.
Component getComponentAtIndex(int i)
Deprecated. replaced by Container.getComponent(int)
int getComponentIndex(Component c)
52 DDE SRMIST- MCA Self Learning Material
Returns the index of the specified component.
static boolean getDefaultLightWeightPopupEnabled() NOTES
Gets the defaultLightWeightPopupEnabled property, which by default is true.
Component getInvoker()
Returns the component which is the 'invoker' of this popup menu.
String getLabel()
Returns the popup menu's label
Insets getMargin()
Returns the margin, in pixels, between the popup menu's border and its
containers.
MenuKeyListener[] getMenuKeyListeners()
Returns an array of all the MenuKeyListeners added to this JPopupMenu with
addMenuKeyListener().
PopupMenuListener[] getPopupMenuListeners()
Returns an array of all the PopupMenuListeners added to this JMenuItem with
addPopupMenuListener().
SingleSelectionModel getSelectionModel()
Returns the model object that handles single selections.
MenuElement[] getSubElements()
Returns an array of MenuElements containing the submenu for this menu
component.
PopupMenuUI getUI()
Returns the look and feel (L&F) object that renders this component.
String getUIClassID()
Returns the name of the L&F class that renders this component.
void insert(Action a, int index)
Inserts a menu item for the specified Action object at a given position.
void insert(Component component, int index)
53 DDE SRMIST- MCA Self Learning Material
Inserts the specified component into the menu at a given position.
NOTES
boolean isBorderPainted()
Checks whether the border should be painted.
boolean isLightWeightPopupEnabled()
Gets the lightWeightPopupEnabled property.
boolean isPopupTrigger(MouseEvent e)
Returns true if the MouseEvent is considered a popup trigger by the JPopupMenu's
currently installed UI.
boolean isVisible()
Returns true if the popup menu is visible (currently being displayed).
void menuSelectionChanged(boolean isIncluded)
Messaged when the menubar selection changes to activate or deactivate this
menu.
void pack()
Lays out the container so that it uses the minimum space needed to display its
contents.
protected void paintBorder(Graphics g)
Paints the popup menu's border if the borderPainted property is true.
protected String paramString()
Returns a string representation of this JPopupMenu.
protected void processFocusEvent(FocusEvent evt)
Processes focus events occurring on this component by dispatching them to any
registered FocusListener objects.
protected void processKeyEvent(KeyEvent evt)
Processes key stroke events such as mnemonics and accelerators.
void
processKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager
manager)
54 DDE SRMIST- MCA Self Learning Material
Processes a key event forwarded from the MenuSelectionManager and changes the
menu selection, if necessary, by using MenuSelectionManager's API.
NOTES
void
processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelection
Manager manager)
This method is required to conform to the MenuElement interface, but it not
implemented.
void remove(int pos)
Removes the component at the specified index from this popup menu.
void removeMenuKeyListener(MenuKeyListener l)
Removes a MenuKeyListener from the popup menu.
void removePopupMenuListener(PopupMenuListener l)
Removes a PopupMenu listener.
void setBorderPainted(boolean b)
Sets whether the border should be painted.
static void setDefaultLightWeightPopupEnabled(boolean aFlag)
Sets the default value of the lightWeightPopupEnabled property.
void setInvoker(Component invoker)
Sets the invoker of this popup menu -- the component in which the popup menu
menu is to be displayed.
void setLabel(String label)
Sets the popup menu's label.
void setLightWeightPopupEnabled(boolean aFlag)
Sets the value of the lightWeightPopupEnabled property, which by default is true.
void setLocation(int x, int y)
Sets the location of the upper left corner of the popup menu using x, y coordinates.
void setPopupSize(Dimension d)
Sets the size of the Popup window using a Dimension object.
55 DDE SRMIST- MCA Self Learning Material
void setPopupSize(int width, int height)
NOTES Sets the size of the Popup window to the specified width and height.
void setSelected(Component sel)
Sets the currently selected component, this will result in a change to the selection
model.
void setSelectionModel(SingleSelectionModel model)
Sets the model object to handle single selections.
void setUI(PopupMenuUI ui)
Sets the L&F object that renders this component.
void setVisible(boolean b)
Sets the visibility of the popup menu.
void show(Component invoker, int x, int y)
Displays the popup menu at the position x,y in the coordinate space of the
component invoker.
void updateUI()
Resets the UI property to a value from the current look and feel.
1.7 JToolBar
JToolBar container allows us to group other components, usually buttons
with icons in a row or column. JToolBar provides a component which is
useful for displaying commonly used actions or controls.
Nested Classes
protected JToolBar.AccessibleJToolBar This class implements
56 DDE SRMIST- MCA Self Learning Material
class accessibility support for the
JToolBar class. NOTES
static class JToolBar.Separator A toolbar-specific separator.
Constructors
JToolBar()
It creates a new tool bar; orientation defaults to HORIZONTAL.
JToolBar(int orientation)
It creates a new tool bar with the specified orientation.
JToolBar(String name)
It creates a new tool bar with the specified name.
JToolBar(String name, int orientation)
It creates a new tool bar with a specified name and orientation.
Methods
JButton add(Action a)
It adds a new JButton which dispatches the action.
protected void addImpl(Component comp, Object constraints, int index)
If a JButton is being added, it is initially set to be disabled.
void addSeparator()
It appends a separator of default size to the end of the tool bar.
protected PropertyChangeListener
57 DDE SRMIST- MCA Self Learning Material
createActionChangeListener(JButton b)
NOTES
It returns a properly configured PropertyChangeListener which updates the
control as changes to the Action occur, or null if the default property change
listener for the control is desired.
protected JButton createActionComponent(Action a)
Factory method which creates the JButton for Actions added to the JToolBar.
ToolBarUI getUI()
It returns the tool bar's current UI.
void setUI(ToolBarUI ui)
It sets the L&F object that renders this component.
void setOrientation(int o)
It sets the orientation of the tool bar.
Code: JToolBar demonstration
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
58 DDE SRMIST- MCA Self Learning Material
public class JToolBarExample {
public static void main(final String args[]) {
NOTES
JFrame myframe = new JFrame("JToolBar Example");
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JToolBar toolbar = new JToolBar();
toolbar.setRollover(true);
JButton button = new JButton("File");
toolbar.add(button);
toolbar.addSeparator();
toolbar.add(new JButton("Edit"));
toolbar.add(new JComboBox(new String[] { "Opt-1", "Opt-2", "Opt-
3", "Opt-4" }));
Container contentPane = myframe.getContentPane();
contentPane.add(toolbar, BorderLayout.NORTH);
JTextArea textArea = new JTextArea();
JScrollPane mypane = new JScrollPane(textArea);
contentPane.add(mypane, BorderLayout.EAST);
myframe.setSize(450, 250);
myframe.setVisible(true);
1.8 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.
59 DDE SRMIST- MCA Self Learning Material
For example, clicking on a button, moving the mouse, entering a character
NOTES through keyboard, selecting an item from the list, and scrolling the page are
the activities that causes an event to occur.
Types of Events
The events can be broadly classified into two categories,
Foreground Events
These events require direct interaction of the user.
They are generated as consequences of a person interacting with the
graphical components in the Graphical User interface.
For example, clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from list, scrolling the
page, etc.
Background Events
These events require the interaction of the end user.
Operating system interrupts, hardware or software failure, timer
expiration, and operation completion are some examples of
background events.
1.9 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.
Source
60 DDE SRMIST- MCA Self Learning Material
The source is an object on which the event occurs.
Source is responsible for providing information of the occurred event
NOTES
to its handler.
Java provide us with classes for the source object.
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.
The benefit of this approach is that the user interface logic is
completely separated from the logic that generates the event.
The user interface element is able to delegate the processing of an
event to a separate piece of code.
In this model, the listener needs to be registered with the source
object so that the listener can receive the event notification. This is an
efficient way of handling the event because the event notifications
are sent only to those listeners who want to receive them.
Steps Involved in Event Handling
Step 1 − The user clicks the button and the event is generated.
Step 2 − The object of concerned event class is created automatically and
information about the source and the event get populated within the same
object.
Step 3 − Event object is forwarded to the method of the registered listener
class.
Step 4 − The method is gets executed and returns.
Callback Methods
61 DDE SRMIST- MCA Self Learning Material
These are the methods that are provided by API provider and are
NOTES defined by the application programmer and invoked by the
application developer.
Here the callback methods represent an event method. In response to
an event, java jre will callback method.
All such callback methods are provided in listener interfaces.
If a component wants some listener to listen to its events, the source
must register itself to the listener.
Event classes represent the event.
Java provides various Event classes and the following are event
classes.
1.9.1 EventObject Class
It is the root class from which all event state objects shall be derived.
All Events are constructed with a reference to the object, the source,
that is logically deemed to be the object upon which the Event in
question initially occurred upon.
This class is defined in java.util package.
Class Declaration
Following is the declaration for java.util.EventObject class,
public class EventObject extends Object implements Serializable
Constructors
EventObject(Object source)
Constructs a prototypical Event.
Methods
Object getSource()
The object on which the Event initially occurred.
String toString()
62 DDE SRMIST- MCA Self Learning Material
Returns a String representation of this EventObject.
NOTES
1.9.2 Event Classes
The list of commonly used Event classes.
AWTEvent
ActionEvent
InputEvent
KeyEvent
MouseEvent
WindowEvent
AdjustmentEvent
ComponentEvent
ContainerEvent
AWTEvent
It is the root event class for all SWING events. This class and its subclasses
supercede the original java.awt.Event class.
Methods
protected void consume()
Consumes this event, if this event can be consumed.
int getID()
Returns the event type.
protected boolean isConsumed()
Returns whether this event has been consumed.
String paramString()
63 DDE SRMIST- MCA Self Learning Material
Returns a string representing the state of this Event.
NOTES
void setSource(Object newSource)
Retargets an event to a new source.
String toString()
Returns a String representation of this object.
ActionEvent
The ActionEvent is generated when the button is clicked or the item of a list is
double-clicked.
Methods
String getActionCommand()
Returns the command string associated with this action.
int getModifiers()
Returns the modifier keys held down during this action event.
long getWhen()
Returns the timestamp of when this event occurred.
String paramString()
Returns a parameter string identifying this action event
InputEvent
The InputEvent class is the root event class for all component-level input events.
Methods
void consume()
Consumes this event so that it will not be processed in the default manner by the
source which originated it.
static int getMaskForButton(int button)
64 DDE SRMIST- MCA Self Learning Material
A method to obtain a mask for any existing mouse button. NOTES
int getModifiers()
Returns the modifier mask for this event.
int getModifiersEx()
Returns the extended modifier mask for this event.
static String getModifiersExText(int modifiers)
Returns a String describing the extended modifier keys and mouse buttons, such as
"Shift", "Button1", or "Ctrl+Shift".
long getWhen()
Returns the difference in milliseconds between the timestamp of when this event
occurred and midnight, January 1, 1970 UTC.
boolean isAltDown()
Returns whether or not the Alt modifier is down on this event.
boolean isAltGraphDown()
Returns whether or not the AltGraph modifier is down on this event.
boolean isConsumed()
Returns whether or not this event has been consumed.
boolean isControlDown()
Returns whether or not the Control modifier is down on this event.
boolean isMetaDown()
Returns whether or not the Meta modifier is down on this event.
boolean isShiftDown()
65 DDE SRMIST- MCA Self Learning Material
Returns whether or not the Shift modifier is down on this event.
NOTES
KeyEvent
On entering the character, the Key event is generated.
Methods
public int getKeyCode()
Returns the integer keyCode associated with the key in this event.
public void setKeyCode(int keyCode)
Set the keyCode value to indicate a physical key.
public char getKeyChar()
Returns the character associated with the key in this event. For example,
the KEY_TYPED event for shift + "a" returns the value for "A".
public void setKeyChar(char keyChar)
Set the keyChar value to indicate a logical character.
public int getKeyLocation()
Returns the location of the key that originated this key event.
public static String getKeyText(int keyCode)
Returns a String describing the keyCode, such as "HOME", "F1" or "A".
public static String getKeyModifiersText(int modifiers)
Returns a String describing the modifier key(s), such as "Shift", or "Ctrl+Shift".
66 DDE SRMIST- MCA Self Learning Material
public boolean isActionKey() NOTES
Returns whether the key in this event is an "action" key.
public String paramString()
Returns a parameter string identifying this event. This method is useful for event
logging and for debugging.
public int getExtendedKeyCode()
Returns an extended key code for the event. The extended key code is a unique
id assigned to a key on the keyboard just like keyCode.
public static int getExtendedKeyCodeForChar(int c)
Returns an extended key code for a unicode character.
MouseEvent
This event indicates a mouse action occurred in a component.
Methods
int getButton()
Returns which, if any, of the mouse buttons has changed state.
int getClickCount()
Returns the number of mouse clicks associated with this event.
Point getLocationOnScreen()
Returns the absolute x, y position of the event.
67 DDE SRMIST- MCA Self Learning Material
int getModifiersEx()
NOTES
Returns the extended modifier mask for this event.
static String getMouseModifiersText(int modifiers)
Returns a String instance describing the modifier keys and mouse buttons that
were down during the event, such as "Shift", or "Ctrl+Shift".
Point getPoint()
Returns the x,y position of the event relative to the source component.
int getX()
Returns the horizontal x position of the event relative to the source component.
int getXOnScreen()
Returns the absolute horizontal x position of the event.
int getY()
Returns the vertical y position of the event relative to the source component.
int getYOnScreen()
Returns the absolute vertical y position of the event.
boolean isPopupTrigger()
Returns whether or not this mouse event is the popup menu trigger event for
the platform.
String paramString()
Returns a parameter string identifying this event.
void translatePoint(int x, int y)
68 DDE SRMIST- MCA Self Learning Material
Translates the event's coordinates to a new position by adding
specified x (horizontal) and y (vertical) offsets. NOTES
WindowEvent
The object of this class represents the change in the state of a window.
Methods
int getNewState()
For WINDOW_STATE_CHANGED events returns the new state of the window.
int getOldState()
For WINDOW_STATE_CHANGED events returns the previous state of the window.
Window getOppositeWindow()
Returns the other Window involved in this focus or activation change.
Window getWindow()
Returns the originator of the event.
String paramString()
Returns a parameter string identifying this event.
AdjustmentEvent
The object of this class represents the adjustment event emitted by Adjustable
objects.
Methods
Adjustable getAdjustable()
Returns the Adjustable object where this event originated.
int getAdjustmentType()
Returns the type of adjustment which caused the value changed event.
69 DDE SRMIST- MCA Self Learning Material
int getValue()
NOTES
Returns the current value in the adjustment event.
boolean getValueIsAdjusting()
Returns true if this is one of multiple adjustment events.
String paramString()
Returns a string representing the state of this Event.
ComponentEvent
The object of this class represents the change in the state of a window.
Methods
Component getComponent()
Returns the originator of the event.
String paramString()
Returns a parameter string identifying this event.
ContainerEvent
The object of this class represents the change in the state of a window.
Methods
Component getChild()
Returns the component that was affected by the event.
Container getContainer()
Returns the originator of the event.
String paramString()
Returns a parameter string identifying this event.
MouseMotionEvent
70 DDE SRMIST- MCA Self Learning Material
The object of this class represents the change in the state of a window.
Methods NOTES
void mouseDragged(MouseEvent e)
Invoked when a mouse button is pressed on a component and then dragged.
void mouseMoved(MouseEvent e)
Invoked when the mouse cursor has been moved onto a component but no
buttons have been pushed.
PaintEvent
The object of this class represents the change in the state of a window.
Methods
Rectangle getUpdateRect()
Returns the rectangle representing the area which needs to be repainted in
response to this event.
String paramString()
Returns a parameter string identifying this event.
void setUpdateRect(Rectangle updateRect)
Sets the rectangle representing the area which needs to be repainted in
response to this event.
1.9.3 EventListener interface
Event listeners represent the interfaces responsible to handle events.
It is a marker interface which every listener interface has to extend. This
class is defined in java.util package.
Class Declaration
Following is the declaration for java.util.EventListener interface,
public interface EventListener
71 DDE SRMIST- MCA Self Learning Material
Event Listener interfaces
NOTES Adapters are abstract classes for receiving various events.
The methods in these classes are empty.
These classes exist as convenience for creating listener objects.
The list of commonly used event listeners is shown below,
ActionListener
ComponentListener
ItemListener
KeyListener
MouseListener
WindowListener
AdjustmentListener
ContainerListener
MouseMotionListener
FocusListener
ActionListener
This interface is used for receiving the action events.
Methods
void actionPerformed(ActionEvent e)
Invoked when an action occurs.
ComponentListener
This interface is used for receiving the component events
Methods
void componentHidden(ComponentEvent e)
Invoked when the component has been made invisible.
72 DDE SRMIST- MCA Self Learning Material
void componentMoved(ComponentEvent e)
NOTES
Invoked when the component's position changes.
void componentResized(ComponentEvent e)
Invoked when the component's size changes.
void componentShown(ComponentEvent e)
Invoked when the component has been made visible.
ItemListener
This interface is used for receiving the item events.
Methods
void itemStateChanged(ItemEvent e)
Invoked when an item has been selected or deselected by the user.
KeyListener
This interface is used for receiving the key events.
Methods
void keyPressed(KeyEvent e)
Invoked when a key has been pressed.
void keyReleased(KeyEvent e)
Invoked when a key has been released.
void keyTyped(KeyEvent e)
Invoked when a key has been typed.
73 DDE SRMIST- MCA Self Learning Material
NOTES
MouseListener
This interface is used for receiving the mouse events.
Methods
void mouseClicked(MouseEvent e)
Invoked when the mouse button has been clicked (pressed and released) on a
component.
void mouseEntered(MouseEvent e)
Invoked when the mouse enters a component.
void mouseExited(MouseEvent e)
Invoked when the mouse exits a component.
void mousePressed(MouseEvent e)
Invoked when a mouse button has been pressed on a component.
void mouseReleased(MouseEvent e)
Invoked when a mouse button has been released on a component.
WindowListener
This interface is used for receiving the window events.
Methods
void windowActivated(WindowEvent e)
Invoked when the Window is set to be the active Window.
void windowClosed(WindowEvent e)
Invoked when a window has been closed as the result of calling dispose on the
74 DDE SRMIST- MCA Self Learning Material
window.
NOTES
void windowClosing(WindowEvent e)
Invoked when the user attempts to close the window from the window's system
menu.
void windowDeactivated(WindowEvent e)
Invoked when a Window is no longer the active Window.
void windowDeiconified(WindowEvent e)
Invoked when a window is changed from a minimized to a normal state.
void windowIconified(WindowEvent e)
Invoked when a window is changed from a normal to a minimized state.
void windowOpened(WindowEvent e)
Invoked the first time a window is made visible.
AdjustmentListener
This interface is used for receiving the adjustment events.
Method
void adjustmentValueChanged(AdjustmentEvent e)
Invoked when the value of the adjustable has changed.
ContainerListener
This interface is used for receiving the container events.
Methods
void componentAdded(ContainerEvent e)
Invoked when a component has been added to the container.
75 DDE SRMIST- MCA Self Learning Material
void componentRemoved(ContainerEvent e)
NOTES
Invoked when a component has been removed from the container.
MouseMotionListener
This interface is used for receiving the mouse motion events.
Methods
void mouseDragged(MouseEvent e)
Invoked when a mouse button is pressed on a component and then dragged.
void mouseMoved(MouseEvent e)
Invoked when the mouse cursor has been moved onto a component but no
buttons have been pushed.
FocusListener
This interface is used for receiving the focus events.
Methods
void focusGained(FocusEvent e)
Invoked when a component gains the keyboard focus.
void focusLost(FocusEvent e)
Invoked when a component loses the keyboard focus.
1.9.4 Swing Adapters
The list of commonly used adapters while listening GUI events in Swing.
FocusAdapter
KeyAdapter
MouseAdapter
MouseMotionAdapter
76 DDE SRMIST- MCA Self Learning Material
WindowAdapter
NOTES
FocusAdapter
An abstract adapter class for receiving focus events.
Methods
void focusGained(FocusEvent e)
Invoked when a component gains the keyboard focus.
void focusLost(FocusEvent e)
Invoked when a component loses the keyboard focus.
KeyAdapter
An abstract adapter class for receiving key events.
Methods
void keyPressed(KeyEvent e)
Invoked when a key has been pressed.
void keyReleased(KeyEvent e)
Invoked when a key has been released.
void keyTyped(KeyEvent e)
Invoked when a key has been typed.
MouseAdapter
An abstract adapter class for receiving mouse events.
Methods
void mouseClicked(MouseEvent e)
Invoked when the mouse button has been clicked (pressed and released)
77 DDE SRMIST- MCA Self Learning Material
on a component.
NOTES
void mouseDragged(MouseEvent e)
Invoked when a mouse button is pressed on a component and then dragged.
void mouseEntered(MouseEvent e)
Invoked when the mouse enters a component.
void mouseExited(MouseEvent e)
Invoked when the mouse exits a component.
void mouseMoved(MouseEvent e)
Invoked when the mouse cursor has been moved onto a component but no
buttons have been pushed.
void mousePressed(MouseEvent e)
Invoked when a mouse button has been pressed on a component.
void mouseReleased(MouseEvent e)
Invoked when a mouse button has been released on a component.
void mouseWheelMoved(MouseWheelEvent e)
Invoked when the mouse wheel is rotated.
MouseMotionAdapter
An abstract adapter class for receiving mouse motion events.
Methods
void mouseDragged(MouseEvent e)
Invoked when a mouse button is pressed on a component and then dragged.
void mouseMoved(MouseEvent e)
Invoked when the mouse button has been moved on a component (with no
78 DDE SRMIST- MCA Self Learning Material
buttons no down).
NOTES
WindowAdapter
An abstract adapter class for receiving window events.
Methods
void windowActivated(WindowEvent e)
Invoked when a window is activated.
void windowClosed(WindowEvent e)
Invoked when a window has been closed.
void windowClosing(WindowEvent e)
Invoked when a window is in the process of being closed.
void windowDeactivated(WindowEvent e)
Invoked when a window is de-activated.
void windowDeiconified(WindowEvent e)
Invoked when a window is de-iconified.
void windowGainedFocus(WindowEvent e)
Invoked when the Window is set to be the focused Window, which means that
the Window, or one of its subcomponents, will receive keyboard events.
void windowIconified(WindowEvent e)
Invoked when a window is iconified.
void windowLostFocus(WindowEvent e)
Invoked when the Window is no longer the focused Window, which means
that keyboard events will no longer be delivered to the Window or any of its
subcomponents.
79 DDE SRMIST- MCA Self Learning Material
void windowOpened(WindowEvent e)
NOTES
Invoked when a window has been opened.
void windowStateChanged(WindowEvent e)
Invoked when a window state is changed.
Module 2: The J2EE Concepts
2.1 Java EE Platform Overview
Java Enterprise Edition (Java EE) can be considered that the Java Enterprise
Edition as an upgraded version of Java SE (Standard Edition).
It adds these upgrades for supporting enterprise-level developer
requirements.
The advanced Java specifications in Java EE are incorporated to make a few
requirements meet.
The following are the few significant reasons for which we need Java EE in
real-time.
Powerful API support
Reduce Development Time
Reduce Application Complexity
System Application Performance
Java EE has various specifications for different purposes. They can perform
reading, writing database management, transaction processing, and web
page designing that may be contained in,
Web specification
Web Service specification
Enterprise specification
80 DDE SRMIST- MCA Self Learning Material
NOTES
Figure. The J2EE platform
Benefits of J2EE
List of benefits that J2EE provides are,
Portability: If a J2EE application is built on a specific platform, it runs the
same way on any other J2EE-compliant platform. This makes it easy to move
applications from one environment to another. For example, moving an
application from one computer to another or relocating an application from a
test server to a production server.
Reusability: The components in J2EE are reused, so the average size of an
application is much smaller than it would be.
Security: Java technology lets programmers handle sensitive data far more
securely than they can in C/C++ programs.
Scalability: J2EE lets developers build applications that run well on both
small, single-processor computers and large, multi-processor systems.
Reliability: Many of the services (such as transaction management and
monitoring) that applications need to be reliable are built into J2EE.
81 DDE SRMIST- MCA Self Learning Material
The J2EE Model
NOTES Enterprise Java BluePrints for the J2EE platform describe the J2EE
application model and best practices for using the J2EE platform. Building on
the J2SE platform, the J2EE application model provides a simplified approach
to developing highly scalable and highly available internet or intranet-based
applications.
J2EE application model supports transaction management, life-cycle
management, resource pooling and are built into the platform and provided
automatically to the components it supports. Component and application
developers are free to focus on specifics such as business logic and user
interfaces.
Another advantage of the J2EE platform is that the application model
encapsulates the layers of functionality in specific types of components.
Business logic is encapsulated in Enterprise JavaBeans (EJB) components.
Client interaction can be presented through plain HTML web pages, through
web pages powered by applets, Java Servlets, or JavaServer Pages technology,
or through stand-alone Java applications. Components communicate
transparently using various standards: HTML, XML, HTTP, SSL, RMI, IIOP.
Reusable J2EE components mean competitive choices for enterprise
developers and IT organizations. The J2EE platform enables them to
assemble applications from a combination of standard, commercially
available components and their own custom components. From general
business application components to vertical market solutions, a range of
standardized J2EE functionality is available off the shelf.
This means that an e-commerce site could be built using a combination of
off-the-shelf EJB components for shopping cart behaviors, modified EJB
components for specialized customer services, and completely customized
layouts using
82 DDE SRMIST- MCA Self Learning Material
JavaServer Pages technology that bring a unique look and feel.
NOTES
This approach means faster development time, better quality, maintainability
and portability, and Web services interoperability across a range of
enterprise platforms. The benefits increase programmer productivity, better
strategic use of computing resources, and greater return on an organization's
technology investments.
Containers and Connectors: Hiding Complexity, Enhancing Portability
The J2EE application model divides enterprise applications into three
fundamental parts: components, containers, and connectors. Components
are the key focus of application developers, while system vendors implement
containers and connectors to conceal complexity and promote portability.
Containers intercede between clients and components, providing services
transparently to both, including transaction support and resource pooling.
Container mediation allows many component behaviors to be specified at
deployment time, rather than in program code.
Connectors sit beneath the J2EE platform, defining a portable service API
that communicates with existing enterprise vendor offerings. Connectors
promote flexibility by enabling a variety of implementations of specific
services. In particular, connectors implementing pluggable messaging
contracts enable bidirectional communication between J2EE components
and enterprise systems.
Flexible User Interaction
The J2EE platform provides choices for graphical user interfaces across a
company's intranet or on the World Wide Web.
Clients can run on desktops, laptops, PDAs, cell phones, and other devices.
Pure client-side user interfaces can use standard HTML and Java applets.
83 DDE SRMIST- MCA Self Learning Material
Support for simple HTML means quicker prototypes, and support for a
NOTES broader range of clients.
Additionally, the J2EE platform supports automatic download of the Java
Plug-in to add applet support where it's lacking.
The J2EE platform also supports stand-alone Java application clients.
For server-side generation of dynamic content, the J2EE platform supports
two types of web component technologies: Java Servlets and JavaServer
Pages (JSP).
Java Servlets enable developers to easily implement server-side behaviors
that take full advantage of the power of the rich Java API. JavaServer Pages
technology combines the ubiquity of HTML with the power of server-side
dynamic content generation. The JSP 2.0 specification supports static
templates, simplified access to Java objects, and easy extensibility.
Enterprise JavaBeans Component Model
Enterprise JavaBeans (EJB) technology enables a simplified approach to
multitier application development, concealing application complexity and
enabling the component developer to focus on business logic.
EJB technology gives developers the ability to model the full range of objects
useful in the enterprise by defining several types of EJB components: session
beans, entity beans, message-driven beans. Session beans represent
behaviors associated with client sessions,for example, a user purchase
transaction on an e-commerce site. Session beans can serve as Web service
endpoints. Entity beans represent collections of data -- such as rows in a
relational database -- and encapsulate operations on the data they represent.
Entity beans are intended to be persistent, surviving as long as the data
they're associated with remains viable.
Message-driven beans allow J2EE applications to process messages
asynchronously. A message-driven bean normally acts as a JMS message
listener, which is similar to an event listener except that it receives JMS
messages instead of events. The messages may be sent by any J2EE
84 DDE SRMIST- MCA Self Learning Material
component--an application client, another enterprise bean, or a Web
component--or by a JMS application or system that does not use J2EE
NOTES
technology.
Web Services Interoperability
The Java 2 Platform, Enterprise Edition version 1.4 is the most complete Web
services platform ever. The platform features Web services support through
the new JAX-RPC 1.1 API, which provides service endpoints based on servlets
and enterprise beans. JAX-RPC 1.1 provides interoperability with Web
services based on the WSDL and SOAP protocols. The J2EE 1.4 platform also
supports the Web Services for J2EE specification, which defines deployment
requirements for Web services and utilizes the JAX-RPC programming model.
In addition to numerous Web services APIs, the J2EE 1.4 platform also
features support for the WS-I Basic Profile 1.0. This means that in addition to
platform independence and complete Web services support, the J2EE 1.4
platform offers platform Web services interoperability.
Expediting Development and Deployment
Based on these flexible component configurations, the J2EE application
model means quicker development, easier customization and greater ability
to deploy powerful enterprise applications. And, because it's based on the
Java programming language, this model enables all J2EE applications to
achieve all the benefits of Java technology: scalability, portability, and
programming ease.
Limitations of J2EE
The limitations of J2EE are,
J2EE doesn’t provide any database access services. “Enterprise JavaBean” can
be used to send queries to an SQL database, but another kind of software is
needed, a Java Database Connectivity (JDBC) driver, to send the actual
queries. For example, to access an Oracle database, it is required to have
Oracle JDBC driver, and to access a MySQL database, it is required to have
MySQL connector/J driver.
85 DDE SRMIST- MCA Self Learning Material
A desktop application cannot be built using J2EE APIs; they only run in
NOTES application servers and communicate with backend J2EE services
(application servers).
Application servers often require separate licenses and must be purchased
separately.
2.2 Distributed Multi-tiered Applications
The J2EE platform uses a multitiered distributed application model.
This means application logic is divided into components according to
function, and the various application components that make up a J2EE
application are installed on different machines depending on which tier in
the multitiered J2EE environment the application component belongs.
Client tier components run on the client machine
Web tier components run on the J2EE server
Business tier components run on the J2EE server
Enterprise information system (EIS) tier software runs on the EIS
server
J2EE multitiered applications are generally considered to be three-tiered
applications because they are distributed over three different locations,
client machines
J2EE server machine
and the database or legacy machines at the back-end
Three-tiered applications that run in this way extend the standard two-tiered
client and server model by placing a multithreaded application server
between
the client application and back-end storage.
86 DDE SRMIST- MCA Self Learning Material
NOTES
Figure. Multitiered Applications
2.3 Web and Business Components
Java EE web components are either servlets or pages created using JSP
technology (JSP pages) and/or Java ServerFaces (JSF) technology.
Servlets are Java programming language classes that dynamically process
requests and construct responses.
JSP pages are text-based documents that execute as servlets but allow a
more natural approach to creating static content.
JavaServer Faces technology builds on servlets and JSP technology and
provides
a user interface component framework for web applications.
Static HTML pages and applets are bundled with web components during
application assembly but are not considered web components by the Java EE
specification. Server-side utility classes can also be bundled with web
components and, like
HTML pages, are not considered web components.
The web tier, like the client tier, might include a JavaBeans component to
manage
the user input and send that input to enterprise beans running in the
business
87 DDE SRMIST- MCA Self Learning Material
tier for processing.
NOTES
Figure. Web Tier and Java EE Applications
2.4 Java EE Containers and the services and types
Generally, thin-client multitiered applications are hard to write because they
involve many lines of intricate code to handle transaction and state
management, multithreading, resource pooling, and other complex low-level
details.
The component-based and platform-independent Java EE architecture makes
applications easy to write because business logic is organized into reusable
components.
In addition, the Java EE server provides underlying services in the form of a
container for every component type.
Containers are the interface between a component and the low-level,
platform-specific functionality that supports the component. Before it can be
executed, a web, enterprise bean, or application client component must be
assembled into a Java EE module and deployed into its container.
The assembly process involves specifying container settings for each
component in the Java EE application and for the Java EE application itself.
88 DDE SRMIST- MCA Self Learning Material
Container settings customize the underlying support provided by the Java EE
server, including such services as security, transaction management, Java
NOTES
Naming and Directory Interface (JNDI) API lookups, and remote connectivity.
The highlights are,
The Java EE security model helps to configure a web component or
enterprise bean so that system resources are accessed only by
authorized users.
The Java EE transaction model helps to specify relationships among
methods that make up a single transaction so that all methods in one
transaction are treated as a single unit.
JNDI lookup services provide a unified interface to multiple naming
and directory services in the enterprise so that application
components can access these services.
The Java EE remote connectivity model manages low-level
communications between clients and enterprise beans. After an
enterprise bean is created, a client invokes methods on it as if it were
in the same virtual machine.
The Java EE architecture provides configurable services, components
within the same application can behave differently based on where they
are deployed. For example, an enterprise bean can have security settings
that allow it a certain level of access to database data in one production
environment and another level of database access in another production
environment.
The container also manages nonconfigurable services, such as
enterprise bean and servlet lifecycles, database connection resource
pooling, data persistence, and access to the Java EE platform APIs.
Container Types
The deployment process installs Java EE application components in the
Java EE containers
89 DDE SRMIST- MCA Self Learning Material
NOTES
Figure. Container and services
2.5 Java EE Application Assembly and Deployment
A Java EE application is packaged into one or more standard units for
deployment to any Java EE platform-compliant system. Each unit contains
A functional component or components, such as an enterprise bean,
web page, servlet, or applet
An optional deployment descriptor that describes its content
Once a Java EE unit has been produced, it is ready to be deployed.
Deployment typically involves using a platform’s deployment tool to specify
location-specific information, such as a list of local users who can access it
and the name of the local database. Once deployed on a local platform, the
application is ready to run.
2.6 Packaging Applications
90 DDE SRMIST- MCA Self Learning Material
A J2EE application is delivered in an Enterprise Archive (EAR) file, a standard
Java Archive (JAR) file with an .ear extension.
NOTES
Using EAR files and modules makes it possible to assemble a number of
different J2EE applications using some of the same components.
No extra coding is needed; it is only a matter of assembling (or packaging)
various J2EE modules into J2EE EAR files.
An EAR file contains J2EE modules and deployment descriptors.
A deployment descriptor is an XML document with an .xml extension that
describes the deployment settings of an application, a module, or a
component. Because deployment descriptor information is declarative, it can
be changed without the need to modify the source code.
At runtime, the J2EE server reads the deployment descriptor and acts upon
the application, module, or component accordingly.
There are two types of deployment descriptors: J2EE and runtime.
A J2EE deployment descriptor is defined by a J2EE specification and
can be used to configure deployment settings on any J2EE-compliant
implementation.
A runtime deployment descriptor is used to configure J2EE
implementation-specific parameters.
Figure. EAR File Structure
2.7 Java EE modules
A Java EE module consists of one or more Java EE components for the
same container type and, optionally, one component deployment
descriptor of that type. An enterprise bean module deployment
91 DDE SRMIST- MCA Self Learning Material
descriptor, for example, declares transaction attributes and security
NOTES authorizations for an enterprise bean. A Java EE module can be deployed
as a stand-alone module.
Java EE modules are of the following types,
EJB modules, which contain class files for enterprise beans and,
optionally, an EJB deployment descriptor. EJB modules are
packaged as JAR files with a .jar extension.
Web modules, which contain servlet class files, web files,
supporting class files, GIF and HTML files, and, optionally, a web
application deployment descriptor. Web modules are packaged as
JAR files with a .war (web archive) extension.
Application client modules, which contain class files and,
optionally, an application client deployment descriptor.
Application client modules are packaged as JAR files with
a .jar extension.
Resource adapter modules, which contain all Java interfaces,
classes, native libraries, and, optionally, a resource adapter
deployment descriptor.
2.8 Getting Started with Web applications
A web application (web app) is an application program that is stored on a
remote server and delivered over the internet through a browser
interface.
Web services are web apps by definition and many, although not all,
websites contain web apps.
Web applications have many benefits are some common benefits include,
Multiple users can access the same version of an application.
Users don't need to install the app.
Users can access the app through various platforms such as a
desktop, laptop or mobile.
92 DDE SRMIST- MCA Self Learning Material
Users can access the app through multiple browsers.
NOTES
2.9 Model View Controller (MVC)2 Architecture & Packaging
The Model-View-Controller (MVC) is a well-known design pattern in the
web development field. It is way to organize our code. It specifies that a
program or application shall consist of data model, presentation
information and control information. The MVC pattern needs all these
components to be separated as different objects.
The MVC pattern architecture consists of three layers,
Model: It represents the business layer of application. It is an object
to carry the data that also contain the logic to update controller if
data is changed.
View: It represents the presentation layer of application. It is used
to visualize the data that the model contains.
Controller: It works on both the model and view. It is used to
manage the flow of application, i.e, data flow in the model object
and to update the view whenever data is changed.
In Java Programming, the Model contains the simple Java classes, the View
used to display the data and the Controller contains the servlets. Due to
this separation the user requests are processed as follows,
Figure. The behavior of MVC Design Pattern
93 DDE SRMIST- MCA Self Learning Material
A client (browser) sends a request to the controller on the server
NOTES side, for a page.
The controller then calls the model. It gathers the requested data.
Then the controller transfers the data retrieved to the view layer.
Now the result is sent back to the browser (client) by the view.
The advantages of MVC architecture are as follows,
MVC has the feature of scalability that in turn helps the growth of
application.
The components are easy to maintain because there is less
dependency.
A model can be reused by multiple views that provides reusability
of code.
The developers can work with the three layers (Model, View, and
Controller) simultaneously.
Using MVC, the application becomes more understandable.
Using MVC, each layer is maintained separately therefore we do not
require to deal with massive code.
The extending and testing of application is easier.
2.10 Web application deployment descriptor (web.xml file)
In a java web application, a file named web.xml is known as deployment
descriptor.
It is a xml file and <web-app> is the root element for it. When a request
comes web server uses web.xml file to map the URL of the request to
the specific code that handle the request.
When a request comes it is matched with url pattern in servlet mapping
attribute. When url is found matched with url pattern then the web
server try to find the servlet name in servlet attributes same as in
servlet mapping attribute. When match is found, control is goes to the
associated servlet class.
94 DDE SRMIST- MCA Self Learning Material
2.11 Web Application Archive (*.WAR file)
NOTES
A web application is a group of HTML pages, JSP pages, servlets, resources,
and source file, which can be managed as a single unit. A Web ARchive
(WAR) file is a packaged web application. WAR files can be used to import
a web application into a web server.
The Java 2 Platform, Enterprise Edition (J2EE) platform (on which Identity
Server is built) uses a component model to create full-scale applications.
A component is self-contained functional software code assembled with
other components into a J2EE application. The J2EE application
components (which can be deployed separately on different servers)
include:
1. Client components (including dynamic web pages, applets, and a
Web browser) that run on the client machine.
2. Web components (including servlets and JSP) that run within a web
container.
3. Business components (code that meets the needs of a particular
enterprise domain such as banking, retail, or finance) that also run
within the web container.
4. Enterprise infrastructure software that runs on legacy machines.
The web components tier in the Identity Server model can be customized
based on each organization’s needs. This appendix concerns itself with this
tier.
Web Components
When a web browser executes a J2EE application, it deploys server-side
objects called web components. There are two types of web
components: Servlets and JavaServer Pages (JSP).
Servlets are small Java programs that dynamically process
requests and construct responses from a web browser; they run
within web containers.
95 DDE SRMIST- MCA Self Learning Material
JSP are text-based documents that contain static template data
NOTES [HTML, Scalable Vector Graphics (SVG), Wireless Markup
Language (WML), or eXtensible Markup Language (XML)], and
elements that construct dynamic content (in the case of Identity
Server, servlets).
When a J2EE application is called, the JSP and corresponding servlets are
constructed by the web browser.
Packaging Web Components
In general, all J2EE components are packaged separately and bundled
together into an Enterprise Archive (EAR) file for application
deployment. The Web Components, in particular, are packaged in web
application archives (WAR). Each WAR contains the servlets and/or JSP, a
deployment descriptor, and related resource files.
In addition to project resources, the WAR file includes a web deployment
descriptor file. The web deployment descriptor is an XML file that
contains deployment information, MIME types, session configuration
details, and other settings for a web application. The web deployment
descriptor file (web.xml) provides information about the WAR file is
shared with the developers, assemblers, and deployers in a Java EE
environment.
Figure. Deploying Java Web Application
Web Application Directory Structure
96 DDE SRMIST- MCA Self Learning Material
Web Applications use a standard directory structure defined in the J2EE
specification. A Web application can be deployed as a collection of files
NOTES
that use this directory structure, known as exploded directory format, or
as an archived file called a WAR file. Deploying a Web Application in
exploded directory format is recommended primarily for use while
developing an application. Deploying a Web Application as a WAR file is
recommended primarily for production environments.
Web Application components are assembled in a directory in order to
stage the WAR file for the jar command. HTML pages, JSP pages, and the
non-Java class files they reference are accessed beginning in the top level
of the staging directory.
Clients can generally browse any location in a Web application with the
exception of the WEB-INF directory. The WEB-INF directory contains the
deployment descriptors for the Web application (web.xmland
weblogic.xml) and two subdirectories for storing compiled Java classes
and library JAR files. These subdirectories are respectively named classes
and lib. JSP taglibs are stored in the WEB-INF directory at the top level of
the staging directory. The Java classes include servlets, helper classes
and, if desired, precompiled JSPs.
The entire directory, once staged, is bundled into a WAR file using the jar
command. The WAR file can be deployed alone or packaged in an
Enterprise Archive (EAR file) with other application components,
including other Web Applications, EJB components, and WebLogic Server
components.
JSP pages and HTTP servlets can access all services and APIs available in
WebLogic Server. These services include EJBs, database connections
through Java Database Connectivity (JDBC), JavaMessaging Service (JMS),
XML, and more.
97 DDE SRMIST- MCA Self Learning Material
NOTES
Figure. Web Application Archive
URLs and Web Applications
The URL can be constructed that a client uses to access a Web Application
using the following pattern:
http://hoststring/ContextPath/servletPath/pathInfo
Where,
hoststring
is either a host name that is mapped to a virtual host
or hostname:portNumber.
ContextPath
is the name of your Web Application.
servletPath
is a servlet that is mapped to the servletPath.
pathInfo
is the remaining portion of the URL, typically a file name.
2.12 Ant build tool
Apache Ant is open source that can be used by JVM based programming
languages.
Ant is a Java library and a software tool used for automate software build
processes such as compile, run, test and assemble Java application. The
following features are supported by ANT
Extensible Architecture
High Performance
Large Community
98 DDE SRMIST- MCA Self Learning Material
Backward Compatibility
Need for a Build Tool NOTES
On an average, a developer spends a substantial amount of time doing
mundane tasks like build and deployment that include,
Compiling the code
Packaging the binaries
Deploying the binaries to the test server
Testing the changes
Copying the code from one location to another
Features of Apache Ant
Features
The features of Apache Ant are listed below,
It is the most complete Java build and deployment tool available.
It is platform neutral and can handle platform specific properties,
such as file separators.
It can be used to perform platform specific tasks such as modifying
the modified time of a file using 'touch' command.
Ant scripts are written using plain XML.
Ant is good at automating complicated repetitive tasks.
Ant comes with a big list of predefined tasks.
Ant provides an interface to develop custom tasks.
Ant can be easily invoked from the command line and it can
integrate with free and commercial IDEs.
Ant Properties
By default, Ant provides the following pre-defined properties that can be
used in the build file,
Properties and Description
99 DDE SRMIST- MCA Self Learning Material
ant.file
NOTES
The full location of the build file.
ant.version
The version of the Apache Ant installation.
Basedir
The basedir of the build, as specified in the basedir attribute of the
project element.
ant.java.version
The version of the JDK that is used by Ant.
ant.project.name
The name of the project, as specified in the name attribute of the project
element.
ant.project.default-target
The default target of the current project.
ant.project.invoked-targets
Comma separated list of the targets that were invoked in the current
project.
ant.core.lib
The full location of the Ant jar file.
ant.home
100 DDE SRMIST- MCA Self Learning Material
The home directory of Ant installation.
NOTES
ant.library.dir
The home directory for Ant library files - typically ANT_HOME/lib folder.
Typically, Ant's build file, called build.xml should reside in the base
directory of the project. However, there is no restriction on the file name
or its location.
For this exercise, create a file called build.xml,
<?xml version="1.0"?>
<project name="Hello World Project" default="info">
<target name="info">
<echo>Hello World - Welcome to Apache Ant!</echo>
</target>
</project>
Note that there should be no blank line(s) or whitespace(s) before the xml
declaration.
All build files require the project element and at least one target element.
The XML element project has three attributes which are as follows,
Attributes and Description
Name
The Name of the project. (Optional)
Default
The default target for the build script. A project may contain any number of
targets. This attribute specifies which target should be considered as the default.
101 DDE SRMIST- MCA Self Learning Material
(Mandatory)
NOTES
Basedir
The base directory (or) the root folder for the project. (Optional)
A target is a collection of tasks that can be run as one unit.
Targets can have dependencies on other targets. For example,
a deploy target may have a dependency on the package target,
the package target may have a dependency on the compile target and so
forth. Dependencies are denoted using the depends attribute.
For example,
<target name="deploy" depends="package">
....
</target>
<target name="package" depends="clean,compile">
....
</target>
<target name="clean" >
....
</target>
<target name="compile" >
....
</target>
The target element has the following attributes,
102 DDE SRMIST- MCA Self Learning Material
Attributes and Description
NOTES
Name
The name of the target (Required)
Depends
Comma separated list of all targets that this target depends on. (Optional)
Description
A short description of the target. (optional)
If
Allows the execution of a target based on the trueness of a conditional
attribute. (optional)
Unless
Adds the target to the dependency list of the specified Extension Point. An
Extension Point is similar to a target, but it does not have any tasks.
(Optional)
The echo task in the above example is a trivial task that prints a message
To run the ant build file, open up command prompt and navigate to the
folder, where the build.xml resides, and then type ant info.
The following output can be seen,
C:\>ant
Buildfile: C:\build.xml
info: [echo] GOD is love - Welcome to Apache Ant!
BUILD SUCCESSFUL
Total time: 0 seconds
Benefits
103 DDE SRMIST- MCA Self Learning Material
Storing the properties in a separate file offers the following benefits,
NOTES It allows to reuse the same build file, with different property settings for
different execution environment. For example, build properties file can be
maintained separately for DEV, TEST, and PROD environments.
It is useful, when the values for a property are not known (in a particular
environment) up-front. This allows to perform the build in other
environments, where the property value is known.
MODULE 3: APPLICATIONS IN DISTRIBUTED ENVIRONMENT
3.1 Remote Method Invocation
Remote Method Invocation (RMI) is technology that supports the access of
an object running on a JVM that is not running on the same host machine.
RMI is used to build distributed applications
It provides remote communication between Java programs.
Package: It is provided in the package java.rmi.*;
An Overview of RMI Applications
RMI applications often comprise two separate programs, a server and a
client. A typical server program creates some remote objects, makes
references to these objects accessible, and waits for clients to invoke
methods on these objects.
A typical client program obtains a remote reference to one or more remote
objects on a server and then invokes methods on them.
RMI provides the mechanism by which the server and the client
communicate and pass information back and forth. Such an application is
sometimes referred to as a distributed object application.
Distributed object applications need to do the following,
Locate remote objects. Applications can use various mechanisms
to obtain references to remote objects. For example, an application
can register its remote objects with RMI's simple naming facility,
104 DDE SRMIST- MCA Self Learning Material
the RMI registry. Alternatively, an application can pass and return
remote object references as part of other remote invocations.
NOTES
Communicate with remote objects. Details of communication
between remote objects are handled by RMI. To the programmer,
remote communication looks similar to regular Java method
invocations.
Load class definitions for objects that are passed
around. Because RMI enables objects to be passed back and forth,
it provides mechanisms for loading an object's class definitions as
well as for transmitting an object's data.
The following illustration depicts an RMI distributed application that uses
the RMI registry to obtain a reference to a remote object.
The server calls the registry to associate (or bind) a name with a remote
object. The client looks up the remote object by its name in the server's
registry and then invokes a method on it.
The illustration also shows that the RMI system uses an existing web
server to load class definitions, from server to client and from client to
server, for objects when needed.
Figure. RMI Registry and Remote Objects
Advantages of Dynamic Code Loading,
One of the central and unique features of RMI is its ability to download the
definition of an object's class if the class is not defined in the receiver's Java
virtual machine.
105 DDE SRMIST- MCA Self Learning Material
All of the types and behavior of an object, previously available only in a
NOTES single Java virtual machine, can be transmitted to another, possibly remote,
Java virtual machine. RMI passes objects by their actual classes, so the
behavior of the objects is not changed when they are sent to another Java
virtual machine.
This capability enables new types and behaviors to be introduced into a
remote Java virtual machine, thus dynamically extending the behavior of an
application. The compute engine example in this trail uses this capability to
introduce new behavior to a distributed program.
Remote Interfaces, Objects, and Methods
A distributed application built by using Java RMI is made up of interfaces
and classes. The interfaces declare methods.
The classes implement the methods declared in the interfaces and,
perhaps, declare additional methods as well.
In a distributed application, some implementations might reside in some
Java virtual machines but not others.
Objects with methods that can be invoked across Java virtual machines are
called remote objects.
An object becomes remote by implementing a remote interface, which has
the following characteristics,
A remote interface extends the interface java.rmi.Remote.
Each method of the interface declares java.rmi.RemoteException in
its throws clause, in addition to any application-specific exceptions.
RMI treats a remote object differently from a non-remote object when the
object is passed from one Java virtual machine to another Java virtual
machine.
Rather than making a copy of the implementation object in the receiving
Java virtual machine, RMI passes a remote stub for a remote object.
The stub acts as the local representative, or proxy, for the remote object
and basically is, to the client, the remote reference. The client invokes a
106 DDE SRMIST- MCA Self Learning Material
method on the local stub, which is responsible for carrying out the method
invocation on the remote object.
NOTES
A stub for a remote object implements the same set of remote interfaces
that the remote object implements.
This property enables a stub to be cast to any of the interfaces that the
remote object implements.
However, only those methods defined in a remote interface are available to
be called from the receiving Java virtual machine.
Creating Distributed Applications by Using RMI
Using RMI to develop a distributed application involves these general
steps:
1. Designing and implementing the components of your distributed
application.
2. Compiling sources.
3. Making classes network accessible.
4. Starting the application.
Designing and Implementing the Application Components
Determine the application architecture, including which components are
local objects and which components are remotely accessible.
This step includes,
Defining the remote interfaces. A remote interface specifies the methods
that can be invoked remotely by a client. Clients program to remote
interfaces, not to the implementation classes of those interfaces. The
design of such interfaces includes the determination of the types of objects
that will be used as the parameters and return values for these methods. If
any of these interfaces or classes do not yet exist, it is required to define
them as well.
Implementing the remote objects. Remote objects must implement one
or more remote interfaces. The remote object class may include
107 DDE SRMIST- MCA Self Learning Material
implementations of other interfaces and methods that are available only
NOTES locally. If any local classes are to be used for parameters or return values of
any of these methods, they must be implemented as well.
Implementing the clients. Clients that use remote objects can be
implemented at any time after the remote interfaces are defined, including
after the remote objects have been deployed.
Compiling Sources
As with any Java program, use the javac compiler to compile the source
files. The source files contain the declarations of the remote interfaces,
their implementations, any other server classes, and the client classes.
Making Classes Network Accessible
In this step, make certain class definitions network accessible, such as the
definitions for the remote interfaces and their associated types, and the
definitions for classes that need to be downloaded to the clients or servers.
Classes definitions are typically made network accessible through a web
server.
Starting the Application
Starting the application includes running the RMI remote object registry, the
server, and the client.
The rest of this section walks through the steps used to create a compute
engine.
Building a Generic Compute Engine
This trail focuses on a simple, yet powerful, distributed application called
a compute engine. The compute engine is a remote object on the server that
takes tasks from clients, runs the tasks, and returns any results. The tasks
are run on the machine where the server is running.
This type of distributed application can enable a number of client machines
to make use of a particularly powerful machine or a machine that has
specialized hardware.
108 DDE SRMIST- MCA Self Learning Material
The novel aspect of the compute engine is that the tasks it runs do not need
to be defined when the compute engine is written or started.
NOTES
New kinds of tasks can be created at any time and then given to the compute
engine to be run. The only requirement of a task is that its class implement a
particular interface.
The code needed to accomplish the task can be downloaded by the RMI
system to the compute engine.
Then, the compute engine runs the task, using the resources on the machine
on which the compute engine is running.
The ability to perform arbitrary tasks is enabled by the dynamic nature of
the Java platform, which is extended to the network by RMI.
RMI dynamically loads the task code into the compute engine's Java virtual
machine and runs the task without prior knowledge of the class that
implements the task.
Such an application, which has the ability to download code dynamically, is
often called a behavior-based application. Such applications usually require
full agent-enabled infrastructures.
With RMI, such applications are part of the basic mechanisms for distributed
computing on the Java platform.
Architecture of an RMI Application
An RMI application includes two programs, a server program (resides on the
server) and a client program (resides on the client).
Inside the server program, a remote object is created and reference of that
object is made available for the client (using the registry).
The client program requests the remote objects on the server and tries to
invoke its methods.
The following diagram shows the architecture of an RMI application.
109 DDE SRMIST- MCA Self Learning Material
NOTES
Figure. Architecture of RMI application
The components RMI architecture
Transport Layer − This layer connects the client and the server. It
manages the existing connection and also sets up new connections.
Stub − A stub is a representation (proxy) of the remote object at
client. It resides in the client system; it acts as a gateway for the
client program.
Skeleton − This is the object which resides on the server side. Stub
communicates with this skeleton to pass request to the remote
object.
Remote Reference Layer RRL − It is the layer which manages the
references made by the client to the remote object.
RMI Registry
Before any object becomes remotely accessible to clients, they must
be registered in the RMIregistry
RMI registry is a namespace on which all server objects are placed.
Each time the server creates an object, it registers this object with
110 DDE SRMIST- MCA Self Learning Material
the RMIregistry (using bind() or reBind() methods). These are
registered using a unique name known as bind name.
NOTES
By default, the registry listens the incoming requests on port 1099
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).
How RMI works?
The following points summarize how an RMI application works,
When the client makes a call to the remote object, it is received
by the stub which then passes this request to the RRL.
When the client-side RRL receives the request, it invokes a
method called invoke() of the object remoteRef. Then, it passes
the request to the RRL on the server side.
The RRL on the server side passes the request to the Skeleton
(proxy on the server) which finally invokes the required object
on the server.
The result is passed all the way back to the client.
111 DDE SRMIST- MCA Self Learning Material
NOTES
Figure. Working principle of RMI Architecture
Goals of RMI
Encouraging distributed applications/client-server applications
To preserve type safety.
Distributed garbage collection.
Minimize the difference between working with local and remote
objects.
Disadvantages
Non-persistent references
Server program is expected to run unconditionally, hence wasting
resources
Steps to write RMI application
1. Create the remote interface(extends Remote Interface)
112 DDE SRMIST- MCA Self Learning Material
2. Provide the implementation of the remote interface (a class that
extends UnicastRemoteObject and implement the remote interface
NOTES
created at step 1)
3. Compile the implementation class and create the stub and
skeleton objects using the rmic tool
4. Start the registry service by rmiregistry tool
(Steps 3 and 4 are done automatically when rmi.jar is included in
the library of a java application when using IDEs(Netbeans)
5. Firstly, start the remote application (run server app.)
6. start the client application
Code: Implementing RMI to simulate withdrawal in ATM processing
Java Interface:InterfaceCh.java(Remote Interface)
//DECLARING INTERFACE
import java.rmi.*;
public interface InterfaceCh extends Remote{
public String withDraw(int msg) throws RemoteException;
//public String receive()throws RemoteException;
Class that implements MyInterface:ClientCl.java
//IMPLEMENTING INTERFACE(REMOTE)
import java.rmi.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.*;
import java.util.*;
public class ClientCl
{
113 DDE SRMIST- MCA Self Learning Material
public static void main (String[] a)
NOTES {
try {
ClientCl ccl=new ClientCl();
ccl.connectRemote();
}
catch (Exception e)
{
System.out.println(“Server failed: “ + e);
}
}
private void connectRemote() throws RemoteException,
NotBoundException
{
Registry reg=LocateRegistry.getRegistry(”localhost”,4444);
InterfaceCh ic=(InterfaceCh) reg.lookup(”Hi”);
System.out.println(”Enter the amount to be withdrawn and esure it
should be atleast 100);
Scanner s=new Scanner(System.in);
String mystr= s.nextLine();
int balance=Integer.parseInt(mystr);
if(balance<100)
{
System.out.println(“Amount should in the multiples of 100”);
System.exit(0);
}
else
{
System.out.println(ic.withDraw(balance));
ClientCl ccm=new ClientCl();
ccm.connectRemote();
114 DDE SRMIST- MCA Self Learning Material
} }}
NOTES
Server Class:ServerCl.java
import java.rmi.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class ServerCl extends UnicastRemoteObject implements
InterfaceCh
{
String str;
int balance=5000;
int i=0;
public ServerCl()throws Exception
{
super();
}
@Override
public String withDraw(int s) throws RemoteException
{
i=i+1;
System.out.println(”Transaction Number=”+i);
balance=balance-s;
return(“Response from SERVER: and your balance
is“+String.valueOf(balance));
}
public static void main (String[] argv) throws RemoteException
{
try {
ServerCl sl=new ServerCl();
115 DDE SRMIST- MCA Self Learning Material
Registry reg=LocateRegistry.createRegistry(4444);
NOTES //reg.rebind(name, reg);
//reg.bind(name, reg);
reg.bind”Hi”,sl);
System.out.println(”Connection established:”);
}
catch(Exception e)
{
}
}
}
3.2 Activation Models
This technology supports the ability to have remote objects
instantiated (activated) on-demand by client requests (the server
program need not be kept running always)
It helps remote object references to remain valid across server
crashes, making the references persistent.
Running a server program 24 hours a day; perhaps it consumes lots
of server resources (memory, database connections, etc.), It is not
necessary to keep it running unless it is being used. Using the RMI
activation service, the server program doesn't start running until the
first client requests is initiated.
After some period of inactivity, the server program shall be shut
down to conserve server resources and then reactivated the next
time a client asks for the server program.
If a remote object is made activatable, it can be registered with the
RMI registry without actually being instantiated. Normally, RMI
remote objects (based on the UnicastRemoteObject interface)
provide only non persistent references to themselves. Such a
reference can be created for a client only if the referenced object
already exists in a remote JVM.
116 DDE SRMIST- MCA Self Learning Material
In addition, the remote reference is valid only during the lifetime of
the remote object (then it shall be garbage collected).
NOTES
Distributed object systems are designed to support long-lived persistent
objects.
Given that these systems will be made up of many thousands (perhaps
millions) of such objects, it would be unreasonable for object
implementations to become active and remain active, taking up valuable
system resources, for indefinite periods of time.
In addition, clients need the ability to store persistent references to objects
so that communication among objects can be re-established after a system
crash, since typically a reference to a distributed object is valid only while
the object is active.
Object activation is a mechanism for providing persistent references to
objects and managing the execution of object implementations. 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.
Active and Passive Objects
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).
117 DDE SRMIST- MCA Self Learning Material
In the RMI system, we use lazy activation. Lazy activation defers
NOTES activating an object until a client's first use (i.e., the first method
invocation).
Lazy Activation
Lazy activation of remote objects is implemented using a faulting remote
reference (sometimes referred to as a fault block).
A faulting remote reference to a remote object "faults in" the active
object's reference upon the first method invocation to the object.
Each faulting reference maintains both a persistent handle (an activation
identifier) and a transient remote reference to the target remote object.
The remote object's activation identifier contains enough information to
engage a third party in activating the object. The transient reference is the
actual "live" reference to the active remote object that can be used to
contact the executing object.
In a faulting reference, if the live reference to a remote object is null, the
target object is not known to be active.
Upon method invocation, the faulting reference (for that object) engages in
the activation protocol to obtain a "live" reference, which is a remote
reference (such as a unicast remote reference) for the newly-activated
object.
Once the faulting reference obtains the live reference, the faulting
reference forwards method invocations to the underlying remote
reference which, in turn, forwards the method invocation to the remote
object.
In more concrete terms, a remote object's stub contains a "faulting"
remote reference type that contains both:
an activation identifier for a remote object, and
a "live" reference (possibly null) containing the "active" remote
reference type of the remote object (for example, a remote
reference type with unicast semantics).
118 DDE SRMIST- MCA Self Learning Material
Note: The RMI system preserves "at most once" semantics for remote
calls. In other words, a call to an activatable or unicast remote object is
NOTES
sent at most once. Thus, if a call to a remote object fails (indicated by
a RemoteException being thrown), the client can be guaranteed that the
remote method executed no more than once (and perhaps not at all).
Activation Protocol
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:
a database of information that maps activation identifiers to the
information necessary to activate an object (the object's class, the
location--a URL path--from which the class can be loaded, specific
data the object may need to bootstrap, etc.), and
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.
Note that the activator keeps the current mapping of activation identifiers
to active objects as a cache, so that the group does not need to be
consulted on each activation request.
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.
The activation protocol is as follows. A faulting reference uses an
activation identifier and calls the activator (an internal RMI interface) to
activate the object associated with the identifier.
119 DDE SRMIST- MCA Self Learning Material
The activator looks up the object's activation descriptor (registered
NOTES previously). The object's descriptor contains:
the object's group identifier, specifying the JVM in which it is
activated,
the object's class name,
a URL path from which to load the object's class code, and
object-specific initialization data in marshalled form (initialization
data might be the name of a file containing the object's persistent
state, for example).
Persistent Remote References
The remote object activation service adds support for persistent remote
references that can be created even if the remote object is not running at
the time of the request and that can persist beyond the lifetime of an
individual server object.
The primary difference between an activatable remote object and a
nonactivatable one is that a remote reference to an activatable object
doesn't need to have a "live" object behind it.
If an activatable object is not running (e.g., it hasn't been constructed yet,
or it has been garbage-collected by its Java VM, or its VM has exited), a
remote reference to the object can still be exported to a client.
The client receives a stub, as usual, and can make remote method
invocations through the stub.
When the first method is invoked, the activation service running on the
server sees that the object is not active and goes about activating the
object for the client.
If the object doesn't have a VM to run in, the activation system starts one.
The object is then activated using information that has been registered
with the activation system.
120 DDE SRMIST- MCA Self Learning Material
This information includes the object's class name, a URL that can load the
class bytecodes if they're not found in the local CLASSPATH, and data to
NOTES
pass into the object's activation constructor. Once the object has been
activated, the method invocation takes place, and the results are
marshaled and sent back to the client.
As long as the object stays running, future method requests are handled as
usual. If the object stops running for some reason (e.g, it is garbage-
collected, or its VM dies), the next method request triggers the activation
service again, and the object is reactivated.
This is what is meant by persistent remote references: remote references
to activatable objects can persist across multiple lifetimes of the actual
server object.
Activation Groups Every activatable RMI object belongs to an activation
group.
Each group of activatable objects runs within the same Java VM on the
server host.
In essence, activation groups are a way of defining collections of
activatable remote objects that should share the same physical address
space.
Activation groups in RMI are more than just a way of organizing remote
objects.
Each activation group is responsible for monitoring, activating, and
reactivating the objects it contains.
121 DDE SRMIST- MCA Self Learning Material
NOTES
Figure. Activation Group
Features
References: The ability to automatically create remote objects,
triggered by the requests for references to these objects.
Activation Groups: Support for activation groups, in which groups
of activatable remote objects are executed in the same JVM, which
is automatically started by the activation service if needed.
Fault Tolerance: The ability to restart remote objects if they exit
or are destroyed due to a system failure of some kind. This can add
a certain degree of fault tolerance to RMI applications.
Activation Groups
In the RMI activation system, activatable objects belong to activation
groups, and each activation group runs within its own JVM. If not
grouped then, activatable objects, simply assigning a new activation
group to each activatable object and each object runs inside a
separate JVM.
An ActivationGroup is registered with the activation system in
roughly the same way as an activatable object.
create an ActivationGroupDesc object that contains the name of the
class for the group, the URL where the class bytecodes can be loaded,
122 DDE SRMIST- MCA Self Learning Material
and a MarshalledObject that is given to the ActivationGroup as
initialization data.
NOTES
Register the ActivationGroupDesc by calling the
static ActivationSystem.registerGroup() method, passing in
the ActivationGroupDesc. The ActivationSystem returns
an ActivationGroupID that can assign specific objects to the group.
ActivationGroupDesc gdesc = new ActivationGroupDesc(null, null);
ActivationGroupID gid =
ActivationGroup.getSystem().registerGroup(gdesc);
ActivationGroup.createGroup(gid, gdesc, 0);
// Make a server object, which registers it with activation system
ServerClass server =
new InterfaceRemot(serverName, codebaseURL, 0);
// Register with naming service
LocateRegistry.getRegistry().rebind(serverName, server);
Defining an activatable remote object
Inherit the remote object implementation from the Activatable class
provided in the java.rmi.activation package
Providing activation constructors in the server implementation
1.protected Activatable(ActivationID id, int port) throws
RemoteException
2. protected Activatable(ActivationID id, int port,
RMIClientSocketFactory csfactory, RMIServerSocketFactory
ssfactory)
123 DDE SRMIST- MCA Self Learning Material
throws RemoteException
NOTES Registering the object (RMI registry) and its activation method with
the activation service
The object activation information includes,
object's class name
URL that can load the class byte codes if they're not found in the
local CLASSPATH
data to pass into the object's activation constructor.
Once the object has been activated, the method invocation takes place, and
the results are marshaled and sent back to the client.
What happen if object dies?
As long as the object stays running, future method requests are handled as
usual. If the object stops running for some reason (e.g, it is garbage-
collected, or its VM dies), the next method request triggers the activation
service again, and the object is reactivated. The above said is the work of
persistent remote references; also, remote references to activatable objects
can persist across multiple lifetimes of the actual server object.
3.3 RMI Custom Sockets
A socket is one end-point of a two-way communication link between
two programs running on the network.
A server application normally listens to a specific port waiting for
connection requests from a client.
When a connection request arrives, the client and the server establish
a dedicated connection over which they can communicate.
During the connection process, the client is assigned a local port
number, and binds a socket to it.
124 DDE SRMIST- MCA Self Learning Material
The client talks to the server by writing to the socket and gets
information from the server by reading from it.
NOTES
The client and the server must agree on a protocol--that is, they
must agree on the language of the information transferred back and
forth through the socket.
Package in java supports Socket Programming
java.net.*;
Use
To connect to the World Wide Web, the socket classes are used to establish
connection between client and server
The sockets accepts connection via port number and stream helps bit
transfer
In the above code:
accept() methods helps establishing the connection on portNumber and
Stream class help to transport bits.
Types
Socket and ServerSocket
125 DDE SRMIST- MCA Self Learning Material
Socket class encapsulates the behavior of the active side. (a.k.a. the
NOTES client)
ServerSocket class encapsulates the behavior of the passive side
(a.k.a. the server)
3.4 Object Serialization
Whenever a client invokes a method that accepts parameters on a remote
object, the parameters are bundled (packed) into a message before being
sent over the network. These parameters may be of primitive type or
objects. In case of primitive type, the parameters are put together and a
header is attached to it. In case the parameters are objects, then they are
serialized. This process is known as marshalling.
At the server side, the packed parameters are unbundled and then
the required method is invoked. This process is known
as unmarshalling.
3.5 RMI IIOP Implemetation
IIOP (Internet Inter-ORB Protocol) is a protocol that makes it
possible for distributed
programs written in different programming languages to
communicate over the Internet.
IIOP is a critical part of a strategic industry standard, the Common
Object Request Broker Architecture (CORBA).
Using CORBA's IIOP and related protocols, a company can write
programs that will be able to communicate with their own or other
company's existing or future programs wherever they are located
and without having to understand anything about the program other
than its service and a name
IIOP is used to enhance Internet and intranet communication for
applications and services
126 DDE SRMIST- MCA Self Learning Material
Common Data Representation (CDR): Provides a standard data
encoding/decoding method
NOTES
Interoperable Object Reference (IOR): The client must have a
program address, known as an IOR, prior to sending a server request.
The IOR is based on the IP address and port numbers of the server
and is usually mapped to a value table created by the client’s
computer.
Message formats defined to support CORBA's ORB specifications
IIOP advantages include,
Better architecture neutrality
Communication transparency
Scalability
Code reusability
CORBA and IIOP assume the client/server model of computing in which a
client program always makes requests and a server program waits to receive
requests from clients
3.6 Common Object Request Broker Architecture
Common Object Request Broker Architecture (CORBA) is technology
with open standard for heterogeneous computing.
A commercial view of RMI that supports interoperability between
OOP modules and the others
A standard designed to facilitate the communication of systems that
are deployed on diverse platforms.
It is an Interface between application components (java and non –
java)
It also supports directory and naming services
CORBA enables collaboration between systems on different operating
systems, programming languages, and computing hardware.
127 DDE SRMIST- MCA Self Learning Material
CORBA normalizes the method-call semantics between application
NOTES objects residing either in the same address-space (application) or in
remote address-spaces
How CORBA is implemented?
The application simply initializes the ORB, and accesses an
internal Object Adapter, which maintains things like reference
counting, object (and reference) instantiation policies, and object
lifetime policies.
The Object Adapter is used to register instances of the generated code
classes. Generated code classes are the result of compiling the user
IDL code, which translates the high-level interface definition into an
OS- and language-specific class base for use by the user application.
Figure. Interoperability between Object Request Brokers
3.7 Interface Definition Language
The Interface Definition Language (IDL) is independent of programming
language, but maps to all of the popular programming languages via Object
Management Group (OMG) standards.
128 DDE SRMIST- MCA Self Learning Material
NOTES
Figure. CORBA implementation
3.8 Naming Services
A naming service maintains a set of bindings. Bindings relate names to
objects. All objects in a naming system are named in the same way (that
is, they subscribe to the same naming convention). Clients use the
naming service to locate objects by name.
There are a number of existing naming services, a few of which are
described below. They each follow the pattern above, but differ in the
details.
COS (Common Object Services) Naming: The naming service for
CORBA applications; allows applications to store and access
references to CORBA objects.
DNS (Domain Name System): The Internet's naming service;
maps people-friendly names (www.srmist.edu.in) into computer-
friendly IP (Internet Protocol) addresses in dotted-quad notation
(207.69.175.36). Interestingly, DNS is a distributed naming
service, meaning that the service and its underlying database is
spread across many hosts on the Internet.
LDAP (Lightweight Directory Access Protocol): Developed by
the University of Michigan; as its name implies, it is a lightweight
version of DAP (Directory Access Protocol), which in turn is part
of X.500, a standard for network directory services. Currently,
over 40 companies endorse LDAP.
129 DDE SRMIST- MCA Self Learning Material
NIS (Network Information System) and NIS+: Network naming
NOTES services developed by Sun Microsystems. Both allow users to
access files and applications on any host with a single ID and
password.
Common features
The primary function of a naming system is to bind names to
objects (or, in some cases, to references to objects -- more on
which in a moment). In order to be a naming service, a service
must at the very least provide the ability to bind names to objects
and to look up objects by name.
Many naming systems don't store objects directly. Instead, they
store references to objects. As an illustration, consider DNS. The
address 207.69.175.36 is a reference to a computer's location on
the Internet, not the computer itself.
Java Naming Directory Interface (JNDI) provides an interface that
supports all this common functionality.
3.9 CORBA Programming Models
The Common Object Request Broker Architecture (CORBA) is a standard
defined by the Object Management Group (OMG) that enables software
components written in multiple computer languages and running on
multiple computers to work together.
CORBA is a standard for distributing objects across networks so that
operations on those objects can be called remotely. CORBA is not
associated with a particular programming language, and any language
with a CORBA binding can be used to call and implement CORBA objects.
Objects are described in a syntax called Interface Definition Language
(IDL).
CORBA includes four components,
Object Request Broker (ORB)
130 DDE SRMIST- MCA Self Learning Material
The Object Request Broker (ORB) handles the communication,
marshaling, and unmarshaling of parameters so that the parameter
NOTES
handling is transparent for a CORBA server and client applications.
CORBA server
The CORBA server creates CORBA objects and initializes them with
an ORB. The server places references to the CORBA objects inside a
naming service so that clients can access them.
Naming service
The naming service holds references to CORBA objects.
CORBA Request node
The CORBA Request node acts as a CORBA client.
The CORBA programming model allows client applications to make
requests to server applications, and to receive responses from them
without direct knowledge of the information source or its location. In a
CORBA environment, applications do not need to include network and
operating system information to communicate; instead, client and server
applications communicate with the Object Request Broker (ORB).
The following figure shows the ORB in a client/server environment.
Figure. The ORB Model
CORBA defines the ORB as an intermediary between client and server
applications.
131 DDE SRMIST- MCA Self Learning Material
The ORB delivers client requests to the appropriate server
NOTES applications and returns the server responses to the requesting client
application.
Using an ORB, a client application can request a service without
knowing the location of the server application or how the server
application will fulfil the request.
In the CORBA model, client applications need to know only what
requests they can make and how to make the requests; they do not
need to be coded with any implementation details of the server or of
the data formats.
Server applications need only know how to fulfil the requests, not
how to return data to the client application.
3.10 JAR File Creation
A Java class can be stored in a Java Archive (jar) file. The classes in a jar file
are stored in a compressed format, much like a zip file. A jar file is a
portable container of classes. The steps are given,
1. Open the text editor and type in the following Java statements.
2. Save the file as CreateAJarFile.java.
3. Open a command prompt and navigate to the directory
containing the Java program. Then type in the command to
compile the source and hit ENTER
4. Test the program prior to placing it in a jar file. Type in the
command to run the Java runtime launcher and then hit Enter.
132 DDE SRMIST- MCA Self Learning Material
NOTES
5. Now create a jar file containing your program. In the
command prompt, make sure you're in the same directory as
the previous step. Type in the following command and
hit Enter.
6. The benefit of storing your class file in a jar file is that the
program can be executed from any location on the file system.
To illustrate this important point, navigate to the directory
above the one where the class file is stored.
7. Execute the Java runtime launcher with the cp (classpath) option.
Notice that the path specified on the classpath option references the
directory that contains the jar file.
UNIT 4: MULTI-TIER APPLICATION DEVELOPMENT
4.1 Server-side programming
The objective of server-side programs is to centrally manage all
programs relating to a particular application example Banking,
insurance, e-shopping, and so on. Clients with bare minimum
requirements like operating systems, web browsers, and internet
connections can experience the power and performance of a server from
a remote location without having to compromise on security and speed.
More importantly, server programs are not only portable but also
possess the capability to generate dynamic responses based on the
user’s request.
Web browsers communicate with web servers using
the HyperText Transfer Protocol (HTTP).
133 DDE SRMIST- MCA Self Learning Material
When a link is clicked on a web page, submit a form, or run a
NOTES search, an HTTP request is sent from the browser to the target
server.
The request includes a URL identifying the affected resource, a
method that defines the required action (for example to get,
delete, or post the resource), and may include additional
information encoded in URL parameters (the field-value pairs
sent via a query string), as POST data (data sent by the HTTP
POST method), or in associated cookies.
Web servers wait for client request messages, process them when
they arrive, and reply to the web browser with an HTTP
response message. The response contains a status line indicating
whether or not the request succeeded (e.g. "HTTP/1.1 200 OK"
for success).
The body of a successful response to a request would contain the
requested resource (e.g. a new HTML page, or an image), which
could then be displayed by the web browser.
Static sites
The diagram given below shows a basic web server architecture
for a static site (a static site is one that returns the same hard-
coded content from the server whenever a particular resource
is requested). When a user wants to navigate to a page, the
browser sends an HTTP "GET" request specifying its URL.
The server retrieves the requested document from its file
system and returns an HTTP response containing the document
and a success status (usually 200 OK). If the file cannot be
retrieved for some reason, an error status is returned (see client
error responses and server error responses).
134 DDE SRMIST- MCA Self Learning Material
NOTES
Figure. Web server architecture (static)
Dynamic sites
A dynamic website is one where some of the response content is
generated dynamically, only when needed. On dynamic website,
the HTML pages are normally created by inserting data from a
database into placeholders in HTML templates (this is a much
more efficient way of storing large amounts of content than
using static websites).
A dynamic site can return different data for a URL based on
information provided by the user or stored preferences and can
perform other operations as part of returning a response (e.g.
sending notifications).
Most of the code to support a dynamic website must run on the
server. Creating this code is known as "server-side
programming" (or sometimes "back-end scripting").
The diagram given below shows a simple architecture for
a dynamic website. As in the previous diagram, browsers send
HTTP requests to the server, then the server processes the
requests and returns appropriate HTTP responses.
Requests for static resources are handled in the same way as for
static sites (static resources are any files that don't change —
typically: CSS, JavaScript, Images, pre-created PDF files, etc.).
135 DDE SRMIST- MCA Self Learning Material
NOTES
Figure. Web server Architecture (dynamic)
In figure, Requests for dynamic resources are instead forwarded (2) to
server-side code (shown in the diagram as a Web Application). For
"dynamic requests" the server interprets the request, reads required
information from the database (3), combines the retrieved data with
HTML templates (4), and sends back a response containing the
generated HTML (5,6).
The important advantages of server-side programs are,
All the programs reside in one machine called the server,
therefore any number of remote machines (called clients) can
access the server programs.
To add new functionalities to existing applications, add
programs on the server-side. The client doesn’t need to modify
anything.
Migrating to newer versions, architectures, design patterns,
adding patches, and switching to new databases can be done at
the server side without bothering about the client’s hardware
or software capabilities.
Issues related to enterprise applications like resource
management, concurrency, session management, security, and
performance are managed by server-side applications.
136 DDE SRMIST- MCA Self Learning Material
They are portable and possess the capability to generate
dynamic and user-based content for example displaying
NOTES
transaction information of credit card or debit cards depending
on the user’s choice.
4.2 Servlets
Servlets are Java classes that are loaded and executed by a servlet
container, and can run as a component in a Web-server or a Java
Enterprise Edition Application server.
Servlets are designed to accept a response from a client (usually a
web browser), process that request, and return a response to the
client.
The base class for all servlets is javax.servlet.GenericServlet,
which defines a generic, protocol-independent servlet.
The most common used type of servlet is an HTTP servlet which
extends thejavax.servlet.http.HttpServlet class which is a subclass
of javax.servlet.GenericServlet.
When creating a servlet, that extends
the javax.servlet.http.HttpServlet class, there must be the
behavior of overriding one or more methods to respond to
specific HTTP requests.
Figure. Client – Server Communication
137 DDE SRMIST- MCA Self Learning Material
When a client request is received by a web server, it will deliver
NOTES the request to the servlet container that will start and deliver the
request to the servlet.
The Servlet receives the request and returns a response to its
container which will deliver the response to the web server that
returns the response to the client.
The request types are given below,
HTTP Description HttpServlet Method
reques
t
GET Retrieves doGet(HttpServletRequest
information request,
identified by a HttpServletResponse
request Uniform response)
Resource Identifier
(URI).
POST Requests doPost(HttpServletRequest
that the request,
server pass HttpServletResponse
the body of response)
the request
to the
resource
identified by
the request
URI for
processing.
HEAD Returns only the doHead(HttpServletRequest
header of the request,
138 DDE SRMIST- MCA Self Learning Material
response that HttpServletResponse
would be returned response)
NOTES
by a GET request.
PUT Uploads data to the doPut(HttpServletRequest
server to be stored request,
at the given request HttpServletResponse
URI. The main response)
difference between
this and POST is
that the server
should not further
process a PUT
request, but simply
store it at the
request URI.
DELET Deletes the doDelete(HttpServletReques
E resource identified t request,
by the request URI. HttpServletResponse
response)
Code: Servlet
package app.simple;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SimpleServlet extends HttpServlet
139 DDE SRMIST- MCA Self Learning Material
{
NOTES // doGet receives the GET request.
@Override
protected void doGet(HttpServletRequest request,HttpServletResponse
response)
{
try
{
response.setContentType("text/html");
PrintWriter printWriter = response.getWriter();
printWriter.println("<h2>");
printWriter.println("It works fine!");
printWriter.println("</h2>");
}
catch (IOException ioException)
{
ioException.printStackTrace();
}
}
}
Creating a Deployment Descriptor
To run this Servlet, it should have to be deployed it to a web-server
or a Application server. To deploy means to install the Servlet with
some instruction to a such server.
The instructions are mainly defined to be deployment descriptors.
The standard part of the deployment descriptor should be in an
XML-file with the name web.xml.
Deployment descriptor file: web.xml
140 DDE SRMIST- MCA Self Learning Material
<?xml version="1.0" encoding="UTF-8"?>
<web-app
NOTES
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>ServletSimpleApp</display-name>
<servlet>
<servlet-name>SimpleServlet</servlet-name>
<servlet-class>app.simple.SimpleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SimpleServlet</servlet-name>
<url-pattern>/SimpleServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>SimpleServlet</welcome-file>
</welcome-file-list>
</web-app>
141 DDE SRMIST- MCA Self Learning Material
NOTES 4.3 JavaServer Pages
Java Server Pages (JSP) is a technology that allows developers to create
dynamic web pages using a combination of HTML, XML, and Java code. JSP
pages are executed on a web server, and the resulting output is sent to the
client's web browser. JSP provides a way to easily access Java code and
objects from within a web page, simplifying the creation of dynamic web
pages. JSP pages are typically used in conjunction with Java servlets, which
handle data processing and client requests. JSP is part of the Java EE
platform and is supported by most web servers and servlet containers.
JSP is a part of Java Enterprise Edition (Java EE).
JSP is similar to HTML pages, but they also contain Java code
executed on the server side.
Server-side scripting means the JSP code is processed on the web
server rather than the client machine.
A JSP page is a file with a ".jsp" extension that can contain a
combination of HTML Tags and JSP codes.
To create a web page, JSP uses a combination of HTML or XML
markup, JSP tags, expressions, and Java code.
JSP tags begin with <% and end with %>.
JSP expressions are used to insert dynamic content into the
page and begin with <%= and end with %>.
JSP can use JavaBeans to store and retrieve data.
JSP requires a Java development environment and a Java Servlet
Container such as Apache Tomcat or Jetty.
JSP is widely used in the industry for creating enterprise web
applications.
JSP is an improved extended version of Servlet technology.
142 DDE SRMIST- MCA Self Learning Material
A JavaServer Pages component is a type of Java servlet that is
designed to fulfill the role of a user interface for a Java web
NOTES
application. Web developers write JSPs as text files that combine
HTML or XHTML code, XML elements, and embedded JSP
actions and commands.
Using JSP, input can be collected from users through web page
forms, present records from a database or another source, and
create web pages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving
information from a database or registering user preferences,
accessing JavaBeans components, passing control between
pages and sharing information between requests, pages etc.
Why Use JSP?
JavaServer Pages often serve the same purpose as programs
implemented using the Common Gateway Interface (CGI). But
JSP offer several advantages in comparison with the CGI.
Performance is significantly better because JSP allows
embedding Dynamic Elements in HTML Pages itself instead of
having a separate CGI files.
JSP are always compiled before it's processed by the server
unlike CGI/Perl which requires the server to load an
interpreter and the target script each time the page is
requested.
JavaServer Pages are built on top of the Java Servlets API, so
like Servlets, JSP also has access to all the powerful Enterprise
Java APIs, including JDBC, JNDI, EJB, JAXP etc.
JSP pages can be used in combination with servlets that handle
the business logic, the model supported by Java servlet
template engines.
Finally, JSP is an integral part of Java EE, a complete platform
for enterprise class applications. This means that JSP can play
143 DDE SRMIST- MCA Self Learning Material
a part in the simplest applications to the most complex and
NOTES demanding.
Advantages of JSP
The list of other advantages of using JSP over other technologies,
Jsp vs. Active Server Pages (ASP): The advantages of JSP are
twofold. First, the dynamic part is written in Java, not Visual
Basic or other MS specific language, so it is more powerful and
easier to use. Second, it is portable to other operating systems
and non-Microsoft Web servers.
Jsp vs. Pure Servlets: It is more convenient to write (and to
modify!) regular HTML than to have plenty of println
statements that generate the HTML.
Jsp vs. Server-Side Includes (SSI): SSI is really only intended for
simple inclusions, not for "real" programs that use form data,
make database connections, and the like.
Jsp vs. JavaScript: JavaScript can generate HTML dynamically on
the client but can hardly interact with the web server to perform
complex tasks like database access and image processing etc.
Life cycle of JSP Page
JSP life cycle is also managed by container. Usually, every web container
that contains servlet container also contains JSP container for managing
JSP pages. JSP pages life cycle phases are:
Translation - JSP pages doesn’t look like normal java classes,
actually JSP container parse the JSP pages and translate them to
generate corresponding servlet source code. If JSP file name is
home.jsp, usually its named as home_jsp.java.
Compilation - If the translation is successful, then container
compiles the generated servlet source file to generate class file.
Class Loading - Once JSP is compiled as servlet class, its
lifecycle is similar to servlet and it gets loaded into memory.
144 DDE SRMIST- MCA Self Learning Material
Instance Creation - After JSP class is loaded into memory, its
object is instantiated by the container.
NOTES
Initialization - The JSP class is then initialized and it
transforms from a normal class to servlet. After initialization,
ServletConfig and ServletContext objects become accessible to
JSP class.
Request Processing - For every client request, a new thread is
spawned with ServletRequest and ServletResponse to process
and generate the HTML response.
Destroy - Last phase of JSP life cycle where it’s unloaded into
memory.
JSP lifecycle methods
jspInit() declared in JspPage interface. This method is called only
once in JSP lifecycle to initialize config params.
_jspService(HttpServletRequest request, HttpServletResponse
response) declared in HttpJspPage interface and response for
handling client requests.
jspDestroy() declared in JspPage interface to unload the JSP from
memory.
Code: Simple JSP
<%-- simple jsp to display a phrase with increasing font size --%>
<%@ page import="java.io.*"%>
<html>
<head>
<title>TRIAL JSP</title>
</head>
<body bgcolor=pink>
<% out.println(new java.util.Date());%>
<%
int i;
145 DDE SRMIST- MCA Self Learning Material
for(i=1;i<=7;i++) {
NOTES out.write("<br>");
out.print("<font size="+i+">GOD IS GREAT");
// out.println("</font>");
%>
<%
}
%>
</body>
</html>
4.4 Applet to Applet Communication
The design of a web application may demand the communication
between applets and in order to establish communication between
applets, java.applet.AppletContext class provides the facility of
communication between applets. The name of applet is provided
through the HTML file. It provides getApplet() method that returns the
object of Applet.
The following syntax may help to access the other applets from an
applet,
public Applet getApplet(String name){}
Code: Applet to Applet Communication
Code: Applet1
import java.applet.Applet;
import java.awt.Button;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
146 DDE SRMIST- MCA Self Learning Material
public class Applet1 extends Applet implements ActionListener {
TextField textField;
NOTES
Button button;
public void init() {
textField = new TextField("", 25);
button = new Button("pass to Applet2");
button.addActionListener(this);
add(textField);
add(button);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() instanceof Button) {
String textMsg = textField.getText().trim();
Applet2 applet2 = (Applet2) getAppletContext().getApplet("Applet2");
if (applet2 != null) {
applet2.add(textMsg);
} else {
System.out.println("Applet2 not found");
}
}
}
}
Code: Applet 2
import java.applet.Applet;
import java.awt.*;
public class Applet2 extends Applet {
public void init() {
Label label = new Label("Message from 1st Applet");
add(label);
147 DDE SRMIST- MCA Self Learning Material
TextField textfield = new TextField(50);
NOTES add(textfield);
String s = getDocumentBase().toString();
String s1 = s.substring(s.indexOf('?') + 1);
s1 = s1.substring("message=".length());
s1 = s1.replace('+', ' ');
textfield.setText(s1);
}
}
Code: HTML 1
<html>
<body>
<applet code="Applet1" name="Applet" height="300"
width="350"></applet>
</body>
</html>
Code: HTML 2
<html>
<body>
<applet code="Applet2" name="Applet2" height="300"
width="350"></applet>
</body>
</html>
4.5 Applet to servlet communication
Applet is a compiled Java class that can be sent over the
network. Applets are an alternative to HTML form page for
developing websites. HTML form gives good performance, takes
less time to load but has poor security. Whereas, Applets give
poor performance, take time to load but have good security.
148 DDE SRMIST- MCA Self Learning Material
Similar to HTML-to-servlet communication we need to perform
applet-to servlet communication. In HTML-to-servlet
NOTES
communication the browser window automatically forms
request URL and automatically forms query string having form
data, when submit button is clicked. In applet-to-servlet
communication all these activities should be taken care of by
the programmers manually or explicitly as event handling
operation.
The following figure shows the behavior of Applet to
Servlet Communication
Figure. Applet to Servlet Communication
The following steps may be followed create an application that
established the connection between applet and servlet
Code: applet to servlet communication
Code: Servlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import Java.util.*;
public class wishsrv extends HttpServlet {
public void service(HttpServletRequest req,HttpServletResponse res)
throws ServletException , IOException {
149 DDE SRMIST- MCA Self Learning Material
//general settings
NOTES PrintWriter pw=res.getWriter{);
setContentType("text/html") ;
//read form data
String name=req.getParameter("uname") i
//generate wish message
Calendar cl=Calendar.getlnstance();
int h=cl.get(Calendar.HOUR_OF_DAY);
if (h<=12)
pw. println ("Good Morning :"+name) i
elseif(h<=16}
pw.println("Good Afternoon: "+name);
elseif(h<=20}
pw.println("Good Evening :"+name);
else
pw.println("Good Night :"+name);
//close stream obj
pw.close();
}//doGet
} / /class
Code: web.xml
Configure MyServletprogram with /testurl url pattern and also
configure Main.html as welcome file.
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/testurl</url-pattren>
150 DDE SRMIST- MCA Self Learning Material
</servlet-mapping>
NOTES
<welcome-file-list>
<welcome-file>Main.html</welcome-file>
</welcome-file-list>
</web-app>
Code: Main.html
<frameset rows = "40% , *">
<frame name = "f1" SYC = "Form.html">
<frame = "f2" />
</frameset>
Code: Applet
// MyApplet. Java
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.net.*;
public class MyApplet extends Applet implements ActionListener {
Button b;
TextField tfl;
Label l1;
public void init ()
{
l1 = new Label ("User name :");
add(l1) ;
tfl = new TextField(10);
add(tf1) ;
b=new Button("Send");
b.addActionListener(this) ;
add(b) ;
151 DDE SRMIST- MCA Self Learning Material
}
NOTES public void actionPerformed(ActionEvent ae)
{
try{
//read text value
String name=tfl.getText().replace();
//frame query String
String qrystr=(“?uname=”+name) ;
//frame request url having query String
String url=(“https://ecomputernotes.com:2020/AtoSApp/testurl”+qrystr);
//create URL class object
URL requrl = new URL (ur1);
//getAppletContext obj
AppletContext apc=getAppletContext();
}
catch(Exception ee)
{}
}
}
Code: Html
<applet code= "MyApplet.class" width= "500" height= "500">
</applet>
4.6 Java DataBase Connectivity
JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming
language and a wide range of databases.
The JDBC library includes APIs for each of the tasks commonly associated
with database usage:
Making a connection to a database
152 DDE SRMIST- MCA Self Learning Material
Creating SQL or MySQL statements
Executing that SQL or MySQL queries in the database
NOTES
Viewing and modifying the resulting records
4.7 Applications on databases
Online encyclopedias (Wikipedia)
Social media websites (Facebook)
CRM systems (Salesforce)
Email systems (Gmail)
E-commerce websites (Amazon)
4.8 Prepared Statements
A PreparedStatement is a pre-compiled SQL statement.
It is a subinterface of Statement.
Prepared Statement objects have some useful additional features than
Statement objects.
Instead of hard coding queries, PreparedStatement object provides a
feature to execute a parameterized query.
Advantages of PreparedStatement
When PreparedStatement is created, the SQL query is passed as
a parameter. This Prepared Statement contains a pre-compiled
SQL query, so when the PreparedStatement is executed, DBMS
can just run the query instead of first compiling it.
PreparedStatement can be used and supplied with different
parameters at the time of execution.
An important advantage of PreparedStatements is that they
prevent SQL injection attacks.
Syntax
153 DDE SRMIST- MCA Self Learning Material
public PreparedStatement prepareStatement(String query
NOTES )throws SQLException{}
Steps to use PreparedStatement
1. Create Connection to Database
Connection myCon =
DriverManager.getConnection(path,username,password)
2. Prepare Statement
PreparedStatement myStmt;
myStmt = myCon.prepareStatement(select * from
students where age> ? and state = ?);
3. Set parameter values for type and position
myStmt.setInt(1,10);
myStmt.setString(2,"TamilNadu");
4. Execute the Query
ResultSet myRs= myStmt.executeQuery();
Why to use PreparedStatement?
The performance of the application will be faster if the
PreparedStatement interface is used as the query is
compiled only once
The PreparedStatement interface is a subinterface of
Statement. It is used to execute parameterized query.
Method and Description
public void sets the integer
setInt(int value to the given
paramIndex, int parameter index.
154 DDE SRMIST- MCA Self Learning Material
value)
NOTES
public void sets the String
setString(int value to the given
paramIndex, parameter index.
String value)
public void sets the float value
setFloat(int to the given
paramIndex, parameter index.
float value)
public void sets the double
setDouble(int value to the given
paramIndex, parameter index.
double value)
public int executes the query.
executeUpdate() It is used for create,
drop, insert,
update, delete etc.
public ResultSet executes the select
executeQuery() query. It returns an
instance of
ResultSet.
4.9 Creating Prepared Statement object
Code:
import java.sql.*;
155 DDE SRMIST- MCA Self Learning Material
class InsertPrepared{
NOTES public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localh
ost:1521:xe","system","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(
?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}catch(Exception e){ System.out.println(e);}
4.10 Assign values for Prepared Statement parameters
import java.sql.*;
import java.io.*;
156 DDE SRMIST- MCA Self Learning Material
class TrialClass{
public static void main(String args[])throws Exception{
NOTES
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localh
ost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("insert into emp130 value
s(?,?,?)");
BufferedReader br=new BufferedReader(new InputStreamReader(Syste
m.in));
do{
System.out.println("enter id:");
int id=Integer.parseInt(br.readLine());
System.out.println("enter name:");
String name=br.readLine();
System.out.println("enter salary:");
float salary=Float.parseFloat(br.readLine());
ps.setInt(1,id);
ps.setString(2,name);
ps.setFloat(3,salary);
int i=ps.executeUpdate();
System.out.println(i+" records affected");
System.out.println("Do want to continue: y/n");
157 DDE SRMIST- MCA Self Learning Material
String s=br.readLine();
NOTES if(s.startsWith("n")){
break;
}while(true);
con.close();
}}
4.11 Multimedia streaming applications
Multimedia applications deals with one of more of the data types that
include text, images, audio and video
Streaming is nothing but the process of transmission, processing, and
rendering multimedia information over the network
Multimedia basics in Java
In broad sense, multimedia is the processing of audio, video,
image/graphics, and text in such a way that one can create them, linked
them, interact with them and all these things in a real time fashion.
Processing of all these, although requires extra hardware support, and
presently, number of professional tools are readily available in the market,
but Java is unique because of its incomparable feature of portability.
Audio basics
To play an audio data, it requires a specific format that the working platform
can support.
Java can play back audio data over a wide range of platforms.
According to Java convention, all audio data should come from a Universal
Resource Locator (URL) in a .au audio file.
158 DDE SRMIST- MCA Self Learning Material
In order to use existing sounds in formats such as .wav or .aiff, one need to
convert these to .au using a sound program that supports audio conversion.
NOTES
If one try to use .wav then Java is unable to support it and throws an
InvalidAudioFormatException, which will not play the audio.
The .au file refers to an 8-bit, 8Khz encoded audio file. This format doesn't
represent the state of the art in audio fidelity, but is adequate for most
sound clips.
Image basics
Java is popular because it has the promise of creating rich graphical
experiences.
Java has a number of classes designed to deal with images and image
manipulation. Java follows both Joint Photographic Expert Group (JPEG) and
Graphics Interchange Format (GIF) as the formats for image data.
In general, JPEG images are better suited to natural color images such as
photo graphs, and GIF images are best for graphical logos, rules, and button
images.
Code: Image implementation in Applet
import java.applet.*;
import java.awt.*;
public class ImageTest extends Applet {
Image mona;
public void init ( ) {
mona = getImage (getDocumentBase ( ),
"monalisa.gif ");
public void point (Graphics g ) {
g.drawImage (mona, 0, 0, this);
159 DDE SRMIST- MCA Self Learning Material
}
NOTES
}
Applications
Voice Mail.
Electronic Mail.
Multimedia based FAX.
Office Needs.
Employee Training.
Sales and Other types of Group Presentation.
Records Management.
4.12 Java Media Framework
The Java Media Framework (JMF) is an application programming
interface (API) for incorporating time-based media into Java
applications and applets.
JMF is designed to
Be easy to program
Support capturing media data
Enable the development of media streaming and
conferencing applications in Java
Enable advanced developers and technology providers to
implement custom solutions based on the existing API and
easily integrate new features with the existing framework
Provide access to raw media data
Enable the development of custom, downloadable
demultiplexers, codecs, effects processors, multiplexers,
and renderers (JMF plug-ins)
JMF uses intermediary objects called managers to integrate new
implementations of key interfaces that define the behavior and interaction of
160 DDE SRMIST- MCA Self Learning Material
objects used to capture, process, and present time-based media. The four
mangers of JMF are,
NOTES
Manager: handles the construction of Players, Processors,
DataSources, and DataSinks.
PackageManager: maintains a registry of packages that
contain JMF classes, such as custom Players, Processors,
DataSources, and DataSinks.
CaptureDeviceManager: maintains a registry of available
capture devices.
PlugInManager: maintains a registry of available JMF plug-
in processing components, such as Multiplexers,
Demultiplexers, Codecs, Effects, and Renderers.
JMF media players usually use DataSources to manage the transfer
ofmedia-content.
A DataSource encapsulates both the location of media and the
protocol and software used to deliver the media.
A DataSource is identified by either a JMF MediaLocator or a URL
(universal resource locator).
A MediaLocator is similar to a URL and can be constructed from a
URL, but can be constructed even if the corresponding protocol
handler is not installed on the system.
A standard data source uses a byte array as the unit of transfer.
A buffer data source uses a Buffer object as its unit of transfer.
Data Format:
An AudioFormat describes the attributes specific to an
audio format, such as sample rate, bits per sample, and
number of channels.
A VideoFormat encapsulates information relevant to video
data.
4.13 XML Introduction
161 DDE SRMIST- MCA Self Learning Material
XML stands for eXtensible Markup Language
NOTES XML is a markup language much like HTML
XML was designed to store and transport data
XML was designed to be self-descriptive
XML is a W3C Recommendation
XML was designed to carry data - with focus on what data is (HTML
was designed to display data - with focus on how data looks)
XML tags are not predefined (like HTML tags)
XML simplifies data sharing
XML simplifies data transport
XML simplifies platform changes
XML simplifies data availability
With XML, the author must define both the tags and the document
structure.
Code:XML
<note>
<date>2015-09-01</date>
<hour>08:30</hour>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
</note>
162 DDE SRMIST- MCA Self Learning Material
NOTES
MODULE 5: ENTERPRISE APPLICATIONS AND FRAMEWORK
5.1 Server-Side Component Architecture
Enterprise JavaBeans (EJB) is an architecture for server-side
component based distributed applications written in Java.
The library covers aspects such as the setting and getting of execution
settings, persistence of those settings, execution feedback, job control
(for example, interrupting execution), SQL generation, and returned
objects.
5.2 EJB Introduction
Enterprise JavaBeans (EJB) is a specification for developing large-
scale, distributed business applications on the Java platform.
It is a specification to develop secured, robust and scalable
distributed applications.
163 DDE SRMIST- MCA Self Learning Material
To run EJB application, an application server is needed (EJB
NOTES Container). The popular application servers include, Jboss, Glassfish,
Weblogic, Websphere etc.
EJB performs
life cycle management,
security,
transaction management, and
object pooling.
EJB application is deployed on the server and therefore it is called as
server- side component.
5.3 EJB Architecture
The server-based architecture that follows the specifications and
requirements of the enterprise environment.
EJB is conceptually based on the Java RMI (Remote Method
Invocation) specification.
In EJB, the beans are run in a container having four-tier architecture.
This architecture consists of four layers, i.e., Client layer, Web layer,
Application layer, and Data layer.
The EJB architecture consists of three main components: enterprise
beans (EJBs), the EJB container, and the Java application server. EJBs
run inside an EJB container, and the EJB container runs inside a Java
application server.
164 DDE SRMIST- MCA Self Learning Material
NOTES
Figure. Logical representation of how EJBs are invoked and deployed
by using RMI
Application Layer
The containers of the EJB cannot be self-deployed. In order to deploy
the containers, it requires the Application server.
In the EJB architecture, the Application server is the outermost layer
that holds or contains the Container to be deployed.
The application layer plays an important role in executing the
application developed using the beans. It provides the necessary
environment to execute those applications.
Most popular application servers are Web-logic, Tomcat, JBoss, Web-
sphere, Wildfly, and Glassfish.
The main tasks of the application server are,
Manage Interfaces
Execution of the processes
Connecting to the database
Manage other resources.
Container
165 DDE SRMIST- MCA Self Learning Material
In EJB architecture, the Container is the second outermost layer. It is a
NOTES very important layer for enterprise beans that are contained in it. For
the enterprise bean, the Container provides various supporting
services and are given,
It provides support for transactional services such as registering the
objects, assign remote interfaces, purge the instances.
It provides support for monitoring the object's activities and
coordinating distributed components.
It provides support for security services.
It provides support for the pooling of resources.
It provides support for managing the Life-cycle of beans and their
concurrency.
It provides support to concentrate on business logic.
Beans
Java beans of the enterprise are installed in the Container in the same
way as a Plain old java object (POJO) is installed and registered to the
Container. For developing secured, large scale and robust business
applications, beans provide business logic.
Types of EJB
There are three types of Enterprise Java Beans or EJB available, which
are as follows:
Stateless Enterprise Java Beans
Stateful Enterprise Java Beans
Message-driven Enterprise Java Beans
Disadvantages of EJB
Requires application server
Requires only java client. For other language client, it is required to go
for webservice.
166 DDE SRMIST- MCA Self Learning Material
Complex to understand and develop ejb applications
NOTES
5.4 Session Beans
Session bean encapsulates business logic only, it can be invoked by local,
remote and webservice client.
It can be used for calculations, database access etc.
The life cycle of session bean is maintained by the application server (EJB
Container).
Types of Session Bean
There are 3 types of session bean.
Stateless Session Bean: It doesn't maintain state of a client between
multiple method calls.
Stateful Session Bean: It maintains state of a client across multiple
requests.
Singleton Session Bean: One instance per application, it is shared
between clients and supports concurrent access.
Life Cycle of Stateless Session Bean
The following steps describe the life cycle of a stateless session bean
instance,
The bean instance's life cycle starts when the container decides to
instantiate a bean instance. This decision is based on the caching policy
and client demand. For example, if more clients want the session bean
services, the container instantiates more beans. The container allows to
specify the caching policy in a vendor-specific deployment descriptor.
The container instantiates the bean using the newInstance method and
then calls the methods setSessionContext and ejbCreate. The container
also sets the transaction context and security attributes (as set in the
deployment descriptor). Now the bean is ready to serve any client.
167 DDE SRMIST- MCA Self Learning Material
The container calls a business method on the instance, based on the client
NOTES call. Note that container could use the same instance to serve multiple
clients.
The container decides to remove the bean instance. This could be because
the container wants to reduce the number of instances in the method-
ready pool. This is based on the caching policy and reduced demand.
Container calls the ejbRemove() method of the bean instance.
Figure. Life cycle of a stateless session bean
Life Cycle of Stateful Session Bean
The following steps describe the lifecycle of a stateful session bean instance,
The bean instance's life cycle starts when a client
invokes create<method>(...) on the session bean's home
interface. The container instantiates a new session bean
using newInstance() and then calls
the setSessionContext method, followed
by ejbCreate<method>(...).
The instance is now ready to serve the client's business
methods.
168 DDE SRMIST- MCA Self Learning Material
The container decides to evict your instance from memory. This
decision is based on the container's caching policy and reduced
NOTES
demand. The container invokes the ejbPassivate() method on
the instance and swaps it out to secondary storage.
If a client invokes a session object whose session bean instance
has been passivated, the container will activate the instance. To
activate the session bean instance, the container restores the
instance's state from secondary storage and
issues ejbActivate() method on it. The session bean instance is
again ready for client methods.
When the client calls remove on the home or component
interface to remove the session object, the container
issues ejbRemove() on the bean instance. This ends the lives of
the session bean instance and the associated session object.
Note that a container can also invoke the ejbRemove() method
on the instance without a client call to remove the session
object after the lifetime of the EJB object has expired.
Figure. Life cycle of stateful session bean
5.5 Entity Beans
An entity bean, in the context of Java Platform 2, Enterprise Edition
(J2EE), represents the business objects retained at the end of a
session in a persistent storage mechanism. Busi.ness objects may
include items like customer name, account number and/or account
balance, etc
169 DDE SRMIST- MCA Self Learning Material
In J2EE, a relational database is a persistent storage mechanism. In
NOTES a relational database, there is a table for each entity bean and every
bean instance corresponds to a particular table row.
The following are characteristics differentiating entity beans from
session beans:
Entity beans are retained after the end of a session, unlike
session beans.
Entity beans permit shared data access.
Entity beans have a primary key or a unique identifier.
The two different types of entity bean persistence are bean-
managed and container-managed. An entity bean is persistent
because it is stored in a relational database, where data exists after
a session ends.
Multiple clients may share entity beans. Entity transaction
management is important because at any given time, different
clients may need to access and change the same data. Each bean’s
transaction management is provided by the Enterprise JavaBeans
(EJB) container, which guarantees data integrity.
Each entity bean is identified by a unique object identifier, which is
used by the client to locate a specific entity bean.
Entity beans may be used when a bean is a business object and not
a method. For example, a bank account is a business object,
whereas bank account verification is a business method. An entity
beam may also be used if a bean’s state should remain persistent.
An entity bean has the following three states,
Does not exist. In this state, the bean instance simply does not
exist.
Pooled state. When WebLogic server is first started, several bean
instances are created and placed in the pool. A bean instance in the
pooled state is not tied to particular data, that is, it does not
correspond to a record in a database table. Additional bean
170 DDE SRMIST- MCA Self Learning Material
instances can be added to the pool as needed, and a maximum
number of instances can be set (for more information, see
NOTES
the @Entity Annotation).
Ready state. A bean instance in the ready state is tied to particular
data, that is, it represents an instance of an actual business object.
The various state transitions as well as the methods available during the
various states are discussed below.
Figure. Life Cycle of Entity Bean
5.6 Persistent Entity Beans
An entity bean manages its data persistentcy through callback methods,
which are defined in the javax.ejb.EntityBean interface. When it is
required to implement the EntityBean interface in the bean class, it is
required to develop the callback functions as designated by the type of
persistence that could be chosen between bean-managed persistence and
container-managed persistence. The container invokes the callback
functions at designated times. That is, the contract between the container
and the entity bean designates the order that the callback methods are
invoked and who manages the bean's persistent data.
171 DDE SRMIST- MCA Self Learning Material
Uniquely Identified by a Primary Key
NOTES Each entity bean has a persistent identity associated with it. That is, the
entity bean contains a unique identity that can be retrieved if there is a
primary key. Given the primary key, a client can retrieve the entity bean.
If the bean is not available, the container instantiates the bean and
repopulates the persistent data for you.
The type for the unique key is defined by the bean provider.
Performing Complex Logic Involving Dependent Objects
When designing your EJB application, it is required to keep in mind the
aspects of each type of object.
Session beans are typically used for performing simple tasks for a
remote client.
Entity beans are typically used for performing complex tasks that
involve coarse-grained persistence for remote clients.
Java object ts, persistent or otherwise, are used for simple tasks for
local clients.
Enterprise JavaBeans are remote objects and are used for interacting with
clients over a network. Remote objects have a higher overhead for
verifying security and transaction information. Thus, when the application
is designed, it can have an entity or session bean interacting with the
client, also, the application may have the Enterprise Java Bean invoke
other dependent Java objects to perform tasks or manage persistent data.
Entity beans are normally used to manage complex, coarse-grained
persistent data for a remote client. Be careful to separate the difference
between an entity bean and a persistent object. An entity bean should be
more than just a persistent object; it should manage and return complex
data to justify using a remote object for managing data.
172 DDE SRMIST- MCA Self Learning Material
NOTES
Figure. Persistence management in Entity Bean
5.7 Java Frameworks
Java EE (Enterprise Edition) frameworks are powerful tools to create
complicated and broad bodies of enterprise applications.
The popular Fameworks are given here,
Spring
The Spring, by Pivotal, is the most used and well-known framework. It is
an inversion of the container and controlled by the Java programming
language.
This framework has integrated advanced features, resources, and utilities.
Developers use these resources to create almost any type of applications.
The spring framework runs on the JVM and works well with other
programming languages like Groovy and Kotlin.
Spring framework is used to perform recurring tasks in programming such
as data processing, messaging, and security. It may be easy to produce the
business logics. The configuration of the Spring framework is very
complicated to other framework’s, but it has many advanced features to
provide useful enterprise edition applications.
Highlights
173 DDE SRMIST- MCA Self Learning Material
Easy test-ability and Backward compatibility
NOTES Supports a large number of packages and classes
Provides efficient Eco-system and community
Useful documentation to learn the framework more effectively
Enables to lead flexible code base like Plain Old Java Objects
(POJOs)
Hibernate
Hibernate is another most popular Java Framework. It is also called Object
Relational Mapping (ORM) framework of Java and widely used to built
database structures. Hibernate provides query language for database
management called HQL
This framework provides smooth integration between the databases and
Java-based web applications.
Highlights
Provides a secure and robust application base
HQL integrated with independent database commands
It offers collections like Set, Map, and List to enhance applications
Simple to change data into multiple databases.
Struts
Apache Struts is a free, open-source, and MVC framework, which used to
build elegant and attractive Java applications. It is used MVC, i.e., Model View
Controller, to develop interactive Java-web applications.
The Apache Software Foundation develops the Struts framework, and it has
a secure plug-in architecture, and it enables to extend the framework by
creating JAR files to the classpath of Java-web applications. The framework
integrates with various plugins, and many of these plugins will let
incorporating Struts with different Java frameworks like JSF, JUnit, Spring,
etc.
174 DDE SRMIST- MCA Self Learning Material
Highlights
It works efficiently with SOAP, AJAX, and REST API’s
NOTES
Possible integration with other frameworks via plugins
Create web applications using simple, POJO actions
Supports different types of templates and themes
Well-tested and Stable framework
Google Web Kit
Google Web Kit (GWT) is one of the most popular web framework, and it
is mainly used to develop client Java code and extend it to as JavaScript. It
is completely open-source. The popular Google applications such as
Adsense, Adwords, Google Wallet, and Blogger are built using GWT.
Apache Wicket
Wicket is also called as “Apache Wicket” because it is accessible through
Apache Software Foundation. It is a lightweight web framework and a
brilliant user interface. It is open-source and used to create server-side
web applications scripted in Java.
Everyone can easily integrate with the HTML language, which enables to
create simple Html pages, and which is going to decrease the complexity
of development. This framework contains powerful test applications to
enhance the productivity of development.
Highlights
Support HTML and Java languages
Easy to write and organize the code
Debug to test particular components of your code
Documentation and Support
JavaServer Faces
175 DDE SRMIST- MCA Self Learning Material
JavaServer Faces technology leverages existing, standard UI and web-tier
NOTES concepts without limiting developers to a particular mark-up language,
protocol, or client device.
The UI component classes included with JavaServer Faces technology
encapsulate the component functionality, not the client-specific
presentation, thus enabling JavaServer Faces UI components to be
rendered to various client devices.
5.8 Introduction to Struts
Struts in Java is an open-source framework that is made by Apache.
Apache provides a free source to download Struts for users. It follows
the MVC (Model View Controller) pattern. There are three models in
MVC – Model0, Model1, Model2.
It provides an implementation of MVC architecture. It gives us pre-
built classes for MVC that can be used/extended. Struts have their
custom tag libraries.
Struts in Java are used to develop web applications which are usually
based on servlet and JSP.
It simplifies the development and maintenance of web applications
by providing predefined functionality.
It is based on a front controller, which means it has a controller in
front of it which decides on which model request has to come or go.
Struts in Java are very helpful for us as MVC is a guideline followed by
all technologies in today’s world.
There is no better option to simplify web applications other than
MVC.
Struts are not distributed.
There are two versions of struts-
1.x(1.0,1.1,1.2)
2.x(2.0,2.1,2.2)
Struts 1.x
176 DDE SRMIST- MCA Self Learning Material
Server side validation
i18N
NOTES
Form backup Support
Exception Handling
Modularization
Multi button
Tiles Support
Plug-in support
Struts 2.x
It is a new framework by Apache software foundation. The following
facilities are available in struts 2.x-
Filter based controller
It uses both XML files and annotations for configuration.
It also supports zero configuration web application.
It also implements Aspect Oriented Programming (AOP) for cross-
cutting tasks with the help of interceptors.
Components of Struts
There are many components of struts and are given here,
Filter Dispatcher
Action
Result
Configuration file
Interceptors
Deployment descriptor
Tag Library
Filter Dispatcher
177 DDE SRMIST- MCA Self Learning Material
It is the controller component of Struts application. From a coding point of
NOTES view, the controller is represented by org.Apache.Struts2.filtered patcher
class, which is just a filter class.
A controller component is responsible for each incoming request and
identifies appropriate actions to process the request at outer processing.
The request is also responsible for identifying appropriate views to
display the result with the help of the result component.
Action
In Struts 2, the functionality of the model is represented by the action
component. From a coding point of view, an action is represented by a bean
class containing the state of an application and any business logic. This
component is developed by the programmer. An Action is a model in Struts
2 which is used to handle all the data.
Result
The result means view. In the Struts2 application, the functionality of view is
managed by the result component. That is, the result component is
responsible for the presentation logic of the Struts application.
A result is responsible for identifying JSP pages to display the results.
Configuration file
Struts 2 uses a configuration file to describe the action, result and other
resources. The name of this file is — struts.xml.
Interceptors
Interceptors are the helper components of the controller and are
responsible for applying cross-cutting concerns or other commonly used
logics. Wherever we want to use the logic in JSP or servlet, we use
interceptors. There are many interceptors in Struts.
Allows user code to inspect and/or change property values.
178 DDE SRMIST- MCA Self Learning Material
Inspection occurs before property values are written and after they
are read from the database.
NOTES
There might be a single instance of Interceptor for a SessionFactory,
or a new instance might be specified for each Session. Whichever
approach is used, the interceptor must be serializable if the Session is
to be serializable. This means that SessionFactory-scoped
interceptors should implement readResolve().
The Session may not be invoked from a callback (nor may a callback
cause a collection or proxy to be lazily initialized).
Instead of implementing this interface directly, it is usually better to
extend EmptyInterceptor and override only the callback methods of
interest.
Deployment Descriptor
This is the deployment descriptor of the Struts Application and contains the
information about controller web.xml. All information gathered in the
deployment descriptor, which is used in MVC. It stores information about
how many JSP and servlets used in this application. Basically, it is the XML
file.
Tag Library
Struts 2 provides a custom tag library to develop JSP pages and to
manipulate the data. The user can design the form or text using the tag
library.
Features of Struts
Param transfer to member variables.
Validation
It is easy to learn as it is very simple.
It provides good tag libraries.
It supports many convenient features.
It is extensible.
179 DDE SRMIST- MCA Self Learning Material
It is also flexible.
NOTES It is very well integrated with J2EE.
Advantages of Struts
An advanced framework with a lot of features.
Based on the MVC architecture.
Simple configuration.
Interceptors to reduce the cross-cutting functionality.
Object Graphics Notation Language (OGNL)
Pluggable with different Result types like Ajax, JSP, Free Marker,
Velocity etc.
Importance of Frameworks
Automates all tedious tasks of application.
Introduces an elegant architectural solution.
Uses the design patterns commonly agreed and that are standard in
the industry.
Why is Struts so useful?
Structural separation of data presentation and business logic
Easy separation of development tasks (web design, database…)
Increases maintainability and extensibility (new views!)
Increases reusability of code
Struts provides a controller that manages the control flow
Changes in the flow can all be done in struts-config.xml
Abstraction from (hard coded) filenames (forwards)
Easy localization (internationalization is more important than ever)
Based on standard Java technologies ( JSP, Servlets, Javabeans)
Thus running on all kinds of JSP/ Servlet containers
180 DDE SRMIST- MCA Self Learning Material
Open-source
Affordable
NOTES
No dependence on external companies
Robustness ( due to freely accessible source code)
Very vivid open-source project with growing developer community.
5.9 Hibernate
Hibernate is an open source object relational mapping (ORM) tool that
provides a framework to map object-oriented domain models to relational
databases for web applications.
Object relational mapping is based on the containerization of objects and
the abstraction that provides that capacity. Abstraction makes it possible
to address, access and manipulate objects without having to consider how
they are related to their data sources.
The Hibernate ORM framework guides mapping Java classes to database
tables and Java data types to SQL data types and provides querying and
retrieval.
Benefits of Hibernate
Any changes made are encapsulated in the data source itself, so that
when those sources or their Application Programming
Interfaces (APIs) change, the applications that use ORM don't have to make
changes or even be aware of that information. Similarly, programmers can
have a consistent view of objects over time, although the sources that
deliver them, the sinks that receive them and the applications that access
them may change.
How does Hibernate work?
Hibernate is an open-source Object-Relational Persistence and Query
service for any Java Application. Hibernate maps Java classes to database
tables and from Java data types to SQL data types and relieves the
developer from most common data persistence related programming
tasks.
181 DDE SRMIST- MCA Self Learning Material
Hibernate sits between traditional Java objects and database server to
NOTES handle all the works in persisting those objects based on the appropriate
O/R mechanisms and patterns.
Why use Hibernate?
Hibernate reduces lines of code by maintaining object-table mapping itself
and returns result to application in form of Java objects. It relieves
programmer from manual handling of persistent data, hence reducing the
development time and maintenance cost.
Hibernate and JPA vs. JDBC
Java Database Connectivity (JDBC) is an API packaged with the Java
SE edition that makes it possible to standardize and simplify the
process of connecting Java applications to external, relational
database management systems (RDBMS).
Hibernate and JDBC are two complimentary Java technologies for
database integration.
Fundamentally, applications written in Java perform logic.
The Java language provides facilities for performing iterative logic
with looks, conditional logic with if statements and object-oriented
analysis through the use of classes and interfaces. But Java
applications do not store data persistently.
Data persistence is typically delegated to NoSQL databases such as
MongoDB and Cassandra, or to relational databases such as IBM's
DB2 or Microsoft's SQL Server or the popular open source database
MySQL.
To help address the object-relational impedance mismatch, a number
of frameworks exist that simplify the task of moving data between a
relational database and a Java program.
Popular Object Relational Mapping (ORM) frameworks include
Hibernate, TopLink and DataNucleus. While each framework has its
182 DDE SRMIST- MCA Self Learning Material
own set of unique capabilities, all of them comply with the Java
Persistence API standard, which is now part of the Java EE/Jakarta
NOTES
EE specification.
Frequently Asked Questions
Module 1
1. Write brief on Swing Features
2. Write notes on Swing Components with respect to their
functionality
3. Discuss the Swing Containers and Frames with neat hierarchy
diagram
4. Discuss the various types of Layout Managers
5. Write the importance of using tab separators and describe
MenuBar,
6. Menu, MenuItem
7. Write the need for JToolbar as a container
8. Justify the importance of “callback” methods while handling
events
9. List down the event listeners and write the importance of abstract
10. methods (two from each listener)
Module 2
1. Write notes on advantages and disadvantages of J2EE technology
2. Discuss on the necessity of multi-tier distributed applications
183 DDE SRMIST- MCA Self Learning Material
3. Write brief notes on the technologies: Servlets, JSP and JSF
NOTES 4. Write notes on JNDI lookup services
5. Why J2EE container is important in web application development
6. Discuss your views on deployment descriptor, resource adapters
7. Illustrate the design pattern of MVC framework and brief the
responsibilities of the model, view and control layers
8. Write the need for build tool and list the features of your favorite
build tool
Module 3
1. RMI-architecture and the components
2. Steps to create RMI application
3. Justify the need for Remote objects in RMI application
4. Distinguish bind() and rebind() methods
5. The role of rmi registry in RMI framework
6. Distinguish active and passive objects
7. Feature of activation model and activation group
8. Serialization and deserialization
9. IIOP
10. CORBA and IDL
Module 4
1. Compare static and dynamic web pages
2. Client server communication
3. Servlet as a server-side component
4. JSP life cycle – methods/phases
5. Communication between applets
6. Communication between servlets and applets
7. Influence of multimedia applications and streaming
8. JDBC: Prepared statement interface
9. Java Media Framework
10. XML-features, advantages, disadvantages
Module 5
1. EJB architecture
2. Types of EJB
184 DDE SRMIST- MCA Self Learning Material
3. EJB container
4. Persistence management and EJB
NOTES
5. Lifecycle of stateful session bean
6. Lifecycle of stateless session bean
7. Lifecycle of entity bean
8. Lifecycle of message driven bean
9. Stateless and Stateful session bean
10. Container Managed Persistence and Bean Managed Persistence
11. Entity Bean and the support to access databases
12. Frameworks: Hibernate, Struts
13. Interceptors and session management
185 DDE SRMIST- MCA Self Learning Material