0% found this document useful (0 votes)
113 views

Advanced Java Programming Notes

The document discusses the Java Abstract Window Toolkit (AWT) and Swing for developing graphical user interfaces (GUIs) in Java, including AWT components like containers, panels, frames, and applets as well as layout managers and event handling. It provides details on key classes in the AWT hierarchy and methods for working with common components like frames, panels, buttons, and text fields to build GUI applications and applets.

Uploaded by

Dhiraj Chaudhari
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
113 views

Advanced Java Programming Notes

The document discusses the Java Abstract Window Toolkit (AWT) and Swing for developing graphical user interfaces (GUIs) in Java, including AWT components like containers, panels, frames, and applets as well as layout managers and event handling. It provides details on key classes in the AWT hierarchy and methods for working with common components like frames, panels, buttons, and text fields to build GUI applications and applets.

Uploaded by

Dhiraj Chaudhari
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 315

Advanced Java

1
Programming: Subject Code:22517
 

Welcome To VCLIENT WORLD


Teaching and Examination Scheme
2

Teaching
Scheme     #Examination    
Scheme
Theory Practical
           
Credit
L T P (L+T+P) Paper
Hrs.
ESE PA Total ESE PA Total

Max Min M
Min Max Min Max Min Max M in Max Min
a
x

Welcome To VCLIENT WORLD


3 90
 1 2 6 min 70*# 28   30* 00 40  25# 10 25 10  50  20
AJP: Chapters 3

UNIT Chapter Name Marks (As per Remember Understand Apply


Syllabus)

01 Introduction to Abstract Windowing Toolkit(AWT) 12 02 04 06

02 Swings 10 02 02 06

03 Event Handling 12 02 02 08

04 Networking Basics 10 02 04 04

05 Interacting with Database 12 02 04 06

06 Servlets
Welcome To VCLIENT WORLD 14 04 04 06
Introduction to 12
Abstract Windowing Toolkit (AWT) 4
Marks

Welcome To VCLIENT WORLD


Specific Objectives 5

• To design and develop Graphical User Interface (GUI)


programs using AWT and Swing component.

• To arrange the GUI components using different layout.

Welcome To VCLIENT WORLD


GUI (Graphical User Interface) 6

• GUI offers user interaction via some graphical components


• Window, frame, Panel, Button, Textfield, TextArea, Listbox,
Combobox, Label, Checkbox etc.
• Using these components we can create an interactive user
interface for an application.
• GUI provides result to end user in response to raised event.
• GUI is entirely based event.

Welcome To VCLIENT WORLD


GUI (Graphical User Interface) 7

button menus title bar menu bar combo box

scroll
bars

Welcome To VCLIENT WORLD


AWT (Abstract Window Toolkit) 8

• AWT contains numerous classes and methods that allow you to create
and manage window.
• import java.awt.*;
• Java AWT is an API to develop GUI or windowbased application in
java.
• Java AWT components are platform-dependent
• i.e. components are displayed according to the view of operating
system.
• AWT is heavyweight i.e. its components uses the resources of system.
Welcome To VCLIENT WORLD
AWT Class Hierarchy 9

Welcome To VCLIENT WORLD


AWT Class Hierarchy : Detailed 10

Welcome To VCLIENT WORLD


AWT Class Hierarchy : Detailed 11

Welcome To VCLIENT WORLD


Component 12

• Component is an object having a graphical representation that can be displayed


on the screen and that can interact with the user.
• At the top of the AWT hierarchy is the Component class.
• It is abstract class that encapsulates all of the attributes of a visual component.
• It defines over a hundred public methods that are responsible for managing
events, such as mouse and keyboard input, positioning and sizing the window,
and repainting.
• Which object is responsible for remembering the current foreground and
background colors and the currently selected text font? (Answer: Componenet)
• It extends: Object Class
• Implements: ImageObserver, MenuContainer, Serializable
Welcome To VCLIENT WORLD
Container 13

• Container class is a subclass of Component.


• Provided additional methods that allow other Component to place on it.
• Which (Container) is responsible for laying out (that is, positioning) any
components that it contains.
• It does this through the use of various layout managers.
• Container is a component in AWT that can contain another components
like buttons, text fields, labels etc.
• The classes that extends Container class are known as container such as
Frame, Dialog and Panel.

Welcome To VCLIENT WORLD


Container Hierarchy: 14

• java.lang.Object
• java.awt. Component
• java.awt.Container
• The methods of the class Container are:

Component add (Component c) Adds the component to the end of


this container

void setLayout (LayoutManager m) Re-Sets the Container’s


LayoutManager
void
Welcome removeAll
To VCLIENT WORLD () Removes all Components
Containers and Components 15

• The job of a Container is to hold and displa.y Components.


• Some common subclasses of Component are Button, Checkbox,
Label, Scrollbar, TextField, and TextArea

• A Container is also a Component


• Some Container subclasses are Panel (and Applet, JApplet),
Window (Frame, JFrame)

Welcome To VCLIENT WORLD


Panel 16

• Panel is a concrete subclass of Container.


• It doesn’t add any new methods which simply implements Container.
• Panel is the immediate superclass of Applet. When screen output is
directed to an applet, it is drawn on the surface of a Panel object.
• Panel is one type of container that does not contain a title bar,
menu bar, or border.
• When you run an applet using an applet viewer, the applet viewer
provides the title and border.
• Uses add() to add component defined by container.
•Welcome
Uses setSize(),
To VCLIENT WORLD setLocation(), setBounds() defined by Component.
An Applet is Panel is a Container 17

• java.lang.Object
|
+----java.awt.Component
|
+----java.awt.Container
|
+----java.awt.Panel
|
+----java.applet.Applet

…so you
Welcome can WORLD
To VCLIENT display things in an Applet
Applets 18

• Applet is a public class which is predefined by java.applet.Applet.


• There is no main() method in Applet like Application program. The
main() method is defined by browser or Appletviewer for Applet.
• Life cycle methods: init, start, paint, stop, destroy
• Applet is one type of container and subclass of Panel. Applet is
superclass of JApplet

Welcome To VCLIENT WORLD


To create an applet 19

• import java.applet.*;
• Import java.awt.*;
• Applet code in comment
• Extends Applet class
• Life cycle method
• Class must be public

Welcome To VCLIENT WORLD


20

• Container (Applet)

• Containers (Panels)
• Component (Canvas)

• Components (Buttons)
• Components (TextFields)
• Components (Labels)
Welcome To VCLIENT WORLD
Window 21

• Creates top-level window means directly on the desktop.


• Don’t create Window objects directly.
• The window is the container that have no borders and menu bars.
• Uses Frame, Dialog class which is subclass of Window class for
creating window.

Welcome To VCLIENT WORLD


Frame 22

• It is subclass of Window and has a title bar, menu bar, borders,


and resizing corners.
• Frame object can be created from program or Applet.
• Through Applet: Warning message will display “Java Applet
Window”.
• Through Program or Application: Normal window is created.

Welcome To VCLIENT WORLD


Working with Frame Window 23

• Extends Frame class


• Constructor are:
• Frame()
• Frame(String title)
• Setting and Getting window size:
• void setSize(int width, int height)
• void setSize(Dimension newsize)
• Dimension getSize()
Welcome To VCLIENT WORLD
Working with Frame Window 24

• Showing and Hiding Frame


• void setVisible(boolean visibleFlag)
• Setting title to frame
• void setTitle(String title)
• Closing Frame: Four Ways
• Implements WindowListener interface.
• Extends WindowAdapter class.
• WindowAdapter Inner class.
• WindowAdapter anonymous inner classes.
Welcome To VCLIENT WORLD
AWT Controls and Layout Manager 25

• AWT Controls: Component which allows you to interact with


application.
• Labels
• Button
• Checkbox
• Checkbox group
• Scrollbars
• Text field
• Text
Welcome Area
To VCLIENT WORLD
AWT Controls View 26
Button Checkbox
Label

Choice Scrollbar

TextField List TextArea

Button

Welcome To VCLIENT WORLD

Checkbox
Layout Manager 27

• Layout Manager: Positioning the components in the container.


• Flow Layout
• Border Layout
• Grid Layout
• Card Layout
• Grid Bag Layout

• Menubars, menus, dialog boxes, file dialog.
Welcome To VCLIENT WORLD
AWT Controls: 28

• Allows user to interact with application.


• Adding the control in Window • First create instance of control.
• Call add() method defined by container.
• Component add(Component compObj)
• Removing the Control
• Call remove() method defined by container
• void remove(Component obj)
• For remove all: removeAll() method call.
Welcome To VCLIENT WORLD
AWT Control: Label 29

• Used to just display string on window. • Passive Components


• Constructors:
• Label( )
• Label(String str) //left – justified
• Label(String str, int how) // Label.LEFT, Label.RIGHT, Label.CENTER
• Methods to perform operation: Setter and Getter Method.
• About text:
• void setText(String str)
• String getText( )
• About Alighment
• void setAlignment(int how)
Welcome To VCLIENT WORLD

• int getAlignment( )
AWT Control: Button 30

• It contains a label and that generates an event when it is pressed.


• Active Components
• Constructors:
• Button( )
• Button(String str)
• Methods to perform operation: Setter and Getter Method.
• void setLabel(String str)
• String getLabel( )
Welcome To VCLIENT WORLD
AWT Control: Button Handling 31

• When Button pressed which generates an event when it is pressed.


• Implements ActionListener interface.
• Interface has defined actionPerformed() method, called when
event is generated.
• ActionEvent object is supplied as argument to the method.
• ActionEvent object refers both Button and Label of Button
• Label will get by using getActionCommand() from ActionEvent
which passed.
Welcome To VCLIENT WORLD
AWT Control: CheckBox 32

• Setter and Getter methods:


• boolean getState( )
• void setState(boolean on)
• String getLabel()
• void setLabel(String str)
• The value of on determine initial state (true/false).

Welcome To VCLIENT WORLD


AWT Control: CheckBox Handling 33

• Check box is selected or deselected, an item event is generated.


• For handling implements ItemListener interface
• ItemListener interface is defines itemStateChanged( ) method.
• ItemEvent object is supplied as the argument.
• getState() : Get Status about checkbox.
• Following methods determine and set status:
• Checkbox getSelectedCheckbox( )
• void setSelectedCheckbox(Checkbox which)

Welcome To VCLIENT WORLD


AWT Control: Choice Class 34
• Used to create a pop-up list items.
• Default constructor Choice() create empty list.
• For add item in list and select active item:
• void add(String name)
• void select(int index)
• void select(String name)
• Each item in the list is a string that appears as a left-justified label
in the order it is added to the Choice object.
• To determine selected item:
• String getSelectedItem( )
• int getSelectedIndex( )
Welcome To VCLIENT WORLD
• String getItem(int index)
AWT Control: Handling Choice 35

• When Choice selected, an item event is generated.


• Implements the ItemListener interface.
• Interface defines the itemStateChanged( ) method.
• ItemEvent object is supplied as the argument to this method.

Welcome To VCLIENT WORLD


AWT Control: List 36

• List class provides a compact, multiple-choice, scrolling selection list.


• List object can be constructed to show any number of choices in the
visible window.
• In Choice only one item is shown.
• Constructors
• List( )
• List(int numRows)
• List(int numRows, boolean multipleSelect)

Welcome To VCLIENT WORLD


AWT Control: List 37
• Following methods are used to add items:
• void add(String name)
• void add(String name, int index)
• For single selection items:
• String getSelectedItem( )
• int getSelectedIndex( )
• For Multi selection items:
• String[ ] getSelectedItems( )
• int[ ] getSelectedIndexes( )
• To retrieve item:
• String getItem(int index)
• To get Item Count
• int getItemCount( )
• Active
Welcome Item WORLD
To VCLIENT

• void select(int index)


AWT Control: List Handling 38

• Two types of event generated:


• For double clicked: ActionEvent generated.
• For select and deselect item: ItemEvent generated.
• Implements ActionListener interface and ItemListener.

Welcome To VCLIENT WORLD


AWT Control: Scrollbar 39

• Scrollbar control represents a scroll bar component in order to


enable user to select from range of values.
• Used to select continuous values between a specified minimum
and maximum.
• Scroll bars may be oriented horizontally or vertically.
• Each end has an arrow that you can click to move the current
value of the scroll bar one unit in the direction of the arrow.
• The current value of the scroll bar relative to its minimum and
maximum values is indicated by the slider box for the scroll bar.
• The
Welcome
slider box can be dragged by the user to a new position.
To VCLIENT WORLD
AWT Control: Scrollbar 40
• Constructors:
• Scrollbar( ) : construct new vertical scrollbar
• Scrollbar(int style) : : construct new scrollbar with style orientation
• Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
• style : Scrollbar.VERTICAL or Scrollbar.HORIZONTAL
• For set Values:
• void setValues(int initialValue, int thumbSize, int min, int max)
• For get and set current value:
• int getValue( )
• void setValue(int newValue)

Welcome To VCLIENT WORLD


AWT Control: Scrollbar 41

• For get Min and Max value:


• int getMinimum( )
• int getMaximum( )
• By default unit increment/decrement is 1 and Block page-up and
page-down increment/decrement is 10.
• For change increment and decrement:
• void setUnitIncrement(int newIncr)
• void setBlockIncrement(int newIncr)

Welcome To VCLIENT WORLD


AWT Control: Handling Scrollbar 42

• AdjustmentEvent is generated.
• Implement the AdjustmentListener interface.
• adjustmentValueChanged() method we have to override
• getAdjustmentType( ) method can be used to determine the type
of the adjustment.
• BLOCK_DECREMENT: A page-down event has been generated.
• BLOCK_INCREMENT: A page-up event has been generated.
• TRACK: An absolute tracking event has been generated.
• UNIT_DECREMENT: user clicks in the right arrow of a horizontal scroll bar,
or the bottom arrow of a vertical scroll bar
• UNIT_INCREMENT: User clicks in the left arrow of a horizontal scroll bar, or
Welcome To VCLIENT WORLD
the top arrow of a vertical scroll bar.
AWT Control: TextField 43

• TextField is subclass of TextComponent. TextComponent is


subclass of Component.
• TextField class implements a single-line text-entry area, usually
called an edit control.
• Text fields allow the user to enter strings and to edit the text
using the arrow keys, cut and paste keys, and mouse selections.
• Constructors:
• TextField( )
• TextField(int numChars)
• TextField(String str)
Welcome To VCLIENT WORLD
• TextField(String str, int numChars)
AWT Control: TextField 44

• Setter and Getter Method of TextField and TextComponent:


• String getText( )
• void setText(String str)
• Particular Text selection:
• String getSelectedText( )
• void select(int startIndex, int endIndex)
• About Modification of Text:
• boolean isEditable( )
• void setEditable(boolean canEdit)

Welcome To VCLIENT WORLD


AWT Control: TextField 45

• Setting echo character to text field and related methods:


• void setEchoChar(char ch)
• boolean echoCharIsSet( )
• char getEchoChar( )
• TextField can be used to Handling Event: ActionEvent generates.
• Implements ActionListener Class

Welcome To VCLIENT WORLD


AWT Control: TextArea 46

• Need ? Sometimes a single line of text input is not enough for a


given task.
• Subclass of TextComponent.
• Constructors:
• TextArea( )
• TextArea(int numLines, int numChars)
• TextArea(String str)
• TextArea(String str, int numLines, int numChars)
• TextArea(String str, int numLines, int numChars, int sBars)

Welcome To VCLIENT WORLD


AWT Control: TextArea 47

• The values of sbar:


• SCROLLBARS_BOTH
• SCROLLBARS_NONE
• SCROLLBARS_HORIZONTAL_ONLY
• SCROLLBARS_VERTICAL_ONLY
• It supports: getText( ), setText( ), getSelectedText( ), select( ),
isEditable( ), and setEditable( )
• Other some methods:
• void append(String str)
• void insert(String str, int index)
• void replaceRange(String str, int startIndex, int endIndex)
Welcome To VCLIENT WORLD
Arranging components : LM 48

• Layout means the arrangement of components within the


container.
• Layout manager automatically positions all the components within
the container.
• LayoutManager: Defines the interface for classes that know how to
layout Containers
• LayoutManager2:
• It is the sub-interface of the LayoutManager. This interface is for
those classes that know how to layout containers based on layout
constraint
Welcome To VCLIENT WORLDobject.
Arranging components : LM 49

• Every Container has a layout manager


• The default layout for a Panel and Applet is FlowLayout
• The default layout for a Window and Frame is a BorderLayout
• We could set it explicitly with: setLayout()
• setLayout (new FlowLayout( ));
• You could change it to some other layout manager

Welcome To VCLIENT WORLD


Different Layout Manager 50
• FlowLayout
• The FlowLayout is the default layout.It layouts the components in a directional/horizontally
flow.
• BorderLayout
• The borderlayout arranges the components to fit in the five regions: east, west, north,
south and center.
• GridLayout
• The GridLayout manages the components in form of a rectangular grid.
• CardLayout
• The CardLayout object treats each component in the container as a card. Only one card
is visible at a time.
• GridBagLayout
• This is the most flexible layout manager class. The object of GridBagLayout aligns the
Welcome To VCLIENT WORLD
component vertically, horizontally or along their baseline without requiring the components
of same size.
FlowLayout 51

• Use add(component); to add to a component when using a


FlowLayout
• Components are added left-to-right
• If no room, a new row is started
• Exact layout depends on size of Applet
• Components are made as small as possible
• FlowLayout is convenient but often not good

Welcome To VCLIENT WORLD


Complete example: FlowLayout 52

• import java.awt.*;
• import java.applet.*;
• public class FlowLayoutExample extends Applet {
• public void init () {
• setLayout (new FlowLayout ()); // default
• add (new Button ("One"));
• add (new Button ("Two"));
• add (new Button ("Three"));
• add (new Button ("Four"));
• add (new Button ("Five"));
•Welcome
addTo(new Button ("Six"));
VCLIENT WORLD

• }}
BorderLayout 53

• At most five components can be added


• If you want more components, add a Panel, then add components
to it.
• setLayout (new BorderLayout());
• add (new Button("NORTH"), BorderLayout.NORTH);

Welcome To VCLIENT WORLD


BorderLayout with five Buttons 54

• public void init() {


• setLayout (new BorderLayout ());
• add (new Button ("NORTH"), BorderLayout.NORTH);
• add (new Button ("SOUTH"), BorderLayout.SOUTH);
• add (new Button ("EAST"), BorderLayout.EAST);
• add (new Button ("WEST"), BorderLayout.WEST);
• add (new Button ("CENTER"), BorderLayout.CENTER);
• }
Welcome To VCLIENT WORLD
Complete example: BorderLayout 55
• import java.awt.*;
• import java.applet.*;
• public class BorderLayoutExample extends Applet {
• public void init () {
• setLayout (new BorderLayout());
• add(new Button("One"), BorderLayout.NORTH);
• add(new Button("Two"), BorderLayout.WEST);
• add(new Button("Three"), BorderLayout.CENTER);
• dd(new Button("Four"), BorderLayout.EAST);
• add(new Button("Five"), BorderLayout.SOUTH);
• add(new Button("Six"), BorderLayout.SOUTH);
Welcome To VCLIENT WORLD
• }
• }
Using a Panel 56

• Panel p = new Panel(); add (p, BorderLayout.SOUTH);


• p.add (new Button ("Button 1"));
• p.add (new Button ("Button 2"));

Welcome To VCLIENT WORLD


GridLayout 57

• The GridLayout manager divides the container up into a


given number of rows and columns:
• new GridLayout(rows, columns)

• All sections of the grid are equally sized and as large as


possible

Welcome To VCLIENT WORLD


Complete example: GridLayout 58

• import java.awt.*;
• import java.applet.*;
• public class GridLayoutExample extends Applet {
• public void init () {
• setLayout(new GridLayout(2, 3));
• add(new Button("One"));
• add(new Button("Two"));
• add(new Button("Three"));
• add(new Button("Four"));
• add(new Button("Five"));
•Welcome
} To VCLIENT WORLD
•}
CardLayout 59

• 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.
• Constructors:
• CardLayout()
• Creates a new card layout with gaps of size zero.
• CardLayout(int hgap, int vgap)
• Creates a new card layout with the specified horizontal and
vertical gaps.
Welcome To VCLIENT WORLD
CardLayout 60

• Cards are typically held in an object of type Panel.


• Panel must have CardLayout selected as its layout manager.
• For Add component:
• void add(Component panelObj, Object name);
• Methods:
• void first(Container deck)
• void last(Container deck)
• void next(Container deck)
• void previous(Container deck)
• void show(Container deck, String cardName)
Welcome To VCLIENT WORLD
GridBagLayout 61

• GridBagLayout arranges components in a horizontal and vertical


manner.
• GridBagLayout is the most complex and flexible of the standard
layout managers.
• GridBagLayout, elements can have different sizes and can occupy
multiple rows or columns.
• The position and behavior of each element is specified by an
instance of the GridBagConstraints class.
• The actual grid size is based upon the number of components
within the GridBagLayout and the GridBagConstraints of those
Welcome To VCLIENT WORLD
objects.
GridBagLayout 62

• Each GridBagLayout object maintains a dynamic rectangular grid of


cells, with each component occupying one or more cells, called its
display area.
• Each component managed by a grid bag layout is associated with an
instance of GridBagConstraints that specifies how the component is
laid out within its display area.
• Maximum capacity of a screen using GridBagLayout in
• Java 1.0 is 128 128 cells.
• Java 1.1 is 512 512 cells.
•Welcome
Constructor:
To VCLIENT WORLD

• GridBagLayout()
GridBagLayout 63

• For customize a GridBagConstraints object by setting one or more


of its instance variables:
• gridx, gridy: Specifies the cell at the upper left of the
component's display area, where the upper-left-most cell has
address gridx = 0, gridy = 0.
• gridwidth, gridheight: Specifies the number of cells in a row (for
gridwidth) or column (for gridheight) in the component's display
area. The default value is 1.
• fill:Used when the component's display area is larger than the
component's requested size to determine whether (and how) to
resize the component.
Welcome To VCLIENT WORLD
MenuBar and Menu 64

• Each menu title consists of exactly


one word.
• The menu titles fit in a single line in
the menu bar.
• The command name in each menu
item is a single word or a short
phrase, such as "Save As."
• No menu item has a command name
identical to the menu's title. (For
example, no item in the File menu is
labeled "File.")
Welcome To VCLIENT WORLD • All menu titles and menu items use
headline capitalization style.
65

Welcome To VCLIENT WORLD


MenuBar and Menu 66

Welcome To VCLIENT WORLD


MenuBar and Menu 67

• Top-level window can have a menu bar associated with it.


• A menu bar displays a list of top-level menu choices.
• Each choice is associated with a drop-down menu.
• Classes:
• MenuBar : Contains one or more Menu objects
• Menu : Contains one or more MenuItem objects
• MenuItem : Object something selected by user.
• It is also possible to include checkable menu items
• These are menu options of type CheckboxMenuItem and will have
a check mark next to them when they are selected.
Welcome To VCLIENT WORLD
MenuBar and Menu 68
• To create a menu bar, first create an instance of MenuBar.
• Set MenuBar using setMenuBar(MenuBarObject)
• Next, create instances of Menu that will define the selections
displayed on the bar.
• Constructors:
• Menu( )
• Menu(String optionName)
• Menu(String optionName, boolean removable)
• Individual menu items constructors:
• MenuItem( )
• ToMenuItem(String
Welcome VCLIENT WORLD itemName)
• MenuItem(String itemName, MenuShortcut keyAccel)
MenuBar and Menu 69

• Disable or enable a menu item by using:


• void setEnabled(boolean enabledFlag)
• boolean isEnabled( )
• Label set and get using:
• void setLabel(String newName)
• String getLabel( )
• Checkable menu item by using a subclass of MenuItem called
CheckboxMenuItem.
• CheckboxMenuItem( )
• CheckboxMenuItem(String itemName)
• CheckboxMenuItem(String itemName, boolean on)
Welcome To VCLIENT WORLD
MenuBar and Menu 70

• Status about checkable MenuItem:


• boolean getState( )
• void setState(boolean checked)
• For add MenuItem:
• MenuItem add(MenuItem item)
• For add MenuBar
• Menu add(Menu menu)
• To get Item from Menu:
• Object getItem( )
Welcome To VCLIENT WORLD
Dialog Box 71

• Dialog boxes are primarily used to obtain user input.


• They are similar to frame windows, except that dialog boxes are always child
windows of a top-level window.
• Dialog boxes don’t have menu bars.
• In other respects, dialog boxes function like frame windows.
• Dialog boxes may be modal or modeless.
• When a modal dialog box is active, all input is directed to it until it is closed.
• When a modeless dialog box is active, input focus can be directed to another
window in your program.

Welcome To VCLIENT WORLD


Dialog Box 72

• Constructors:.
• Dialog(Frame parentWindow, boolean mode)
• Dialog(Frame parentWindow, String title, boolean mode)
• To create Dialog Box:
• Create Frame or Applet
• Create another class which extends Dialog class.
• Call this new class from Frame/Applet class.
• In constructor of Extended Dialog class, use super method and pass
vales to constructor of Dialog
Welcome To VCLIENT WORLD
FileDialog 73
• Java provides a built-in dialog box that lets the user specify a file.
• To create a file dialog box, instantiate an object of type
FileDialog.
• Constructor:
• FileDialog(Frame parent, String boxName)
• FileDialog(Frame parent, String boxName, int how)
• FileDialog(Frame parent)
• Int how: FileDialog.LOAD, FileDialog.SAVE
• Methods:
• String getDirectory( )
Welcome To VCLIENT WORLD
• String getFile( )
UNIT –II SWINGS 10
2.1 Introduction to Swing 74
Marks
• Package : javax.swing.*
• Swing is set of classes which provides more powerful and flexible
components as compare to AWT.
• Swing supplies several exciting additions, including tabbed panes, scroll
panes, trees, and tables.
• Build on top of AWT API and acts as replacement of AWT API.
• Swing component follows a Model-View-Controller
• Swing Components are implemented using Java and so their LOOK & FEEL
is platform independent.
• Called
Welcome To VCLIENT lightweight
WORLD components
Introduction to Swing 75

Welcome To VCLIENT WORLD


Introduction to Swing 76

• 100 % Java implementations of components.


• Use MVC architecture.
• Model represents the data
• View as a visual representation of the data
• Controller takes input and translates it to changes in data

Welcome To VCLIENT WORLD


Difference Between AWT & Swing 77

• AWT uses Applet and Frame while Swing uses JApplet and JFrame
for GUI.
• AWT is platform dependent code while Swing code is platform
independent.
• Swing has bigger collection of classes and interfaces as compare to
AWT.
• In Swing extra feature to Button: Provide Image.
• Swing provides: Tree, Table, Scrollpanes, Tabbedpanes etc new
feature which not available in AWT.
Welcome To VCLIENT WORLD
Difference Between AWT & Swing 78
Awt Swing
Native component. Pure Java component.
Components are heavy weight. Components are light weight.
Native look and feel. Pure java component.
Does not have complex component. It has additional components like JTree, JTable, JProgressBar, and
JSlider ect.
Applet can not have menu. JApplet can contain menu.
Components like Button can not have images. Components like JButton can have images.
List has scrollbar. JList doesn’t support scrolling but this can be done using ScrollPane.
Components can be added directly on the Window While adding component to window or Frame, they have to be added
or Frame. on its ContentPane.
Does not have SplitPane or TabbedPane. Has SplitPane or TabbedPane.
Do not have MDI window. MDI can be achieved using JInternalFrame Object.
MenuWelcome To VCLIENT WORLD
item can not have images or radio button Menu item can have images or radio button or check boxes.
2.2 Swing Components : JApplet 79

• Fundamental to Swing is the JApplet class, which extends Applet.


• JApplet is rich with functionality that is not found in Applet.
• For example, JApplet supports various “panes,” such as the content pane, the
glass pane, and the root pane.
• Unlike Applet BorderLayout is default layout of JApplet.
• When adding a component to an instance of JApplet, do not invoke the add ( )
method of the applet.
• Instead, call add ( ) for the content pane of the JApplet object.
• The content pane can be obtained via the method shown here:
• Container getContentPane ( )
Welcome To VCLIENT WORLD
JApplet Hierarchy: 80

• java.lang.Object
+--- java.awt.Component
+----java.awt.Container
+--------java.awt.Panel
+--------java.applet.Applet
+-------javax.swing.JApplet

Welcome To VCLIENT WORLD


Difference between Applet and JApplet: 81

Applet JApplet

Applet doesn’t have rich JApplet is with rich functionality.


functionality as JApplet.

We add component to Applet. We add component to ContentPane.

We can not add MenuBar We can add JMenuBar to JApplet.

LayoutManager is set to Applet. LayoutManager is set to JApplet.

Default Layout is FlowLayout. Default Layout is BorderLayout.


Welcome To VCLIENT WORLD
JWindow: 82

• JWindow class is similar to the JFrame class.


• It uses a JRootPane for component management and implements
the RootPaneContainer.
• Basically it is top level window with no andorments.
• JWindow class adds no additional event handling capabilities
beyond those of the JFrame and Window Classes.

Welcome To VCLIENT WORLD


Jwindow Hierarchy 83

• java.lang.Object
• java.awt.Component
• java.awt.Container
• java.awt.Window
• java.swing.JWindow

Welcome To VCLIENT WORLD


Jwindow 84
• Constructor
• 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.
• Methods:
• setSize(int height, int width);
• setLocation(int x, int y);
• setVisible(boolean state);
Welcome To VCLIENT WORLD
JFrame 85
• Constructor:
• 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:
• setLayout(LayoutManager manager)
• setSize(int height, int width);
Welcome To VCLIENT WORLD
• setLocation(int x, int y);
• setVisible(boolean state);
JFrame Example: 86

• import javax.swing.*;
• public class JFrameDemo {
• public static void main(String[] args) {
• JFrame f = new JFrame("The Frame");
• f.setSize(300, 300);
• f.setLocation(100, 100);
• f.setVisible(true);
• }
• }
Welcome To VCLIENT WORLD

JApplet and JFrame 87

• Extends JApplet/JFrame class.


• Design UI in init() or Constructor method.
• Add all components on Container instead on JApplet/JFrame.
• getContentPane() method returns the container object.
• Call container add() method to add components.
• Guess default layout for JApplet/Jframe?
• For JFrame close operation: setDefaultCloseOperation()
• Parameters
• DISPOSE_ON_CLOSE
• EXIT_ON_CLOSE
• DO_NOTHING_ON_CLOSE
Welcome To VCLIENT WORLD
Important Classes by Swing 88

• Abstract Button • JRadioButton


• ButtonGroup • JScrollPane
• ImageIcon • JTabbedPane
• JApplet • JTable
• Jbutton • JTextField
• JCheckBox • JTree
• JComboBox
• JLabel
Welcome To VCLIENT WORLD
MVC Architecture 89

• Software design pattern for software development.


• Model:
• Major function of this layer to maintain the data.
• Database and logic
• View:
• Used to display full or partial data.
• User Interface
• Controller:
• Control the interaction and communication between Model and view.
• Communication logic/integration logic
Welcome To VCLIENT WORLD
MVC Architecture 90

Welcome To VCLIENT WORLD


Icons : 91

• In Swing, icons are encapsulated by the ImageIcon class, which


paints an icon from an image. Two of its constructors are shown
here:
• Constructors:
• ImageIcon(String filename)
• ImageIcon(URL url)
• The first form uses the image in the file named filename.
• The second form uses the image in the resource identified by url.
• Methods:
• int getIconHeight( )
Welcome To VCLIENT WORLD

• int getIconWidth( )
JLabel and ImageIcon 92

• Small display area for text, image or both.


• Extends JComponent.
• Constructors:
• JLabel ()
• Creates a JLabel instance with no image and with an empty string for the title.
• JLabel (Icon image)
• Creates a JLabel instance with the specified image.
• JLabel (String text)
• Creates a JLabel instance with the specified text.
• JLabel (String text, Icon icon)
• Creates a JLabel instance with the specified text and icon.
Welcome To VCLIENT WORLD
• JLabel(String s, Icon i, int align)
• align argument is either LEFT, RIGHT, CENTER,
JLabel and ImageIcon 93

• The ImageIcon class implements the Icon interface that declares the
methods
• int getIconHeight( )
• int getIconWidth( )
• Other methods:
• Icon getIcon( )
• String getText( )
• void setIcon(Icon i)
• void setText(String s)
Welcome To VCLIENT WORLD
JTextField 94

• The Swing text field is encapsulated by the JTextComponent class,


which extends JComponent.
• It provides functionality that is common to Swing text components.
• One of its subclasses is JTextField, which allows you to edit one
line of text.

• java.lang.Object
• java.awt.Component
• java.awt.Container
• javax.swing.JComponent
Welcome To VCLIENT WORLD
• javax.swing.text.JTextComponent
JTextField 95
• Constructors:
• JTextField ()
Constructs a new TextField.
• JTextField (int columns)
Constructs a new empty TextField with the specified number of columns.
• JTextField (String text)
Constructs a new TextField initialized with the specified text.
• JTextField (String text, int columns)
Constructs a new TextField initialized with the specified text and columns.
• Method:
• String getText ()
• Void setText (String s)
Welcome To VCLIENT WORLD
• int getColumns()
AbstractButton 96

• Swing provide Icon with Button text.

• Swing buttons are subclasses of the AbstractButton class, which extends


Jcomponent.
• AbstractButton contains many methods that allow you to control the
behavior of buttons, check boxes, and radio buttons.

• Setter and Getter:


• String getText( )
• void setText(String s)
Welcome To VCLIENT WORLD
JButton 97

• Constructors:
• JButton(Icon i)
• JButton(String s)
• JButton(String s, Icon i)

Welcome To VCLIENT WORLD


JCheckBox 98

• JCheckBox(Icon i)
• JCheckBox(Icon i, boolean state)
• JCheckBox(String s)
• JCheckBox(String s, boolean state)
• JCheckBox(String s, Icon i)
• JCheckBox(String s, Icon i, boolean state)

Welcome To VCLIENT WORLD


JCheckBox 99

• void setSelected(boolean state) n ItemEvent is generated.


• ItemListener interface is needed to handle ItemEvent.
• Public itemStateChnaged() used to override

Welcome To VCLIENT WORLD


JRadioButton 100

• JRadioButton(Icon i)
• JRadioButton(Icon i, boolean state)
• JRadioButton(String s)
• JRadioButton(String s, boolean state)
• JRadioButton(String s, Icon i)
• JRadioButton(String s, Icon i, boolean state)

Welcome To VCLIENT WORLD


JRadioButton 101

• ButtonGroup class is used to add radio button in group.


• ActionEvent is generated.
• ActionListener Listener interface is needed to handle ActionEvent.
• public void actionPerofrmed() used to override

Welcome To VCLIENT WORLD


JComboBox 102

• Combination of text field and drop down list.


• Subclass of JComponet
• Only one entry can view at a time.
• Constructor:
• JComboBox( )
• JComboBox(Vector v)
• void addItem(Object obj): Used to add object in Combobox

Welcome To VCLIENT WORLD


JComboBox: EventHandling 103

• ItemEvent is generated.
• Implements ItemListener interface
• Override: itemStateChnaged(ItemEvent ie) method defined by
ItemListener

Welcome To VCLIENT WORLD


JTabbedPane 104

• A tabbed pane is a component that appears as a group of folders in


a file cabinet.
• Each folder has a title.
• When a user selects a folder, its contents become visible
• Only one of the folders may be selected at a time.
• Tabbed panes are commonly used for setting configuration
options.
• Subclass of JComponent
Welcome To VCLIENT WORLD
JTabbedPane 105
• Constructors:
• JTabbedPane ()
Creates an empty TabbedPane with a default tab placement of JTabbedPane.TOP.
• JTabbedPane (int tabPlacement)
Creates an empty TabbedPane with the specified tab placement of either:
JTabbedPane.TOP,JTabbedPane.BOTTOM, JTabbedPane.LEFT, or JTabbedPane.RIGHT.
• JTabbedPane (int tabPlacement, int tabLayoutPolicy)
Creates an empty TabbedPane with the specified tab placement and tab layout
policy.
• Methods:
• void addTab(String title, Component component)
• void addTab(String title, Icon icon, Component component)
Welcome To VCLIENT WORLD
• void addTab(String title, Icon icon, Component component, String tip)
JTabbedPane 106

• Tabs are defined via the following method :


• void addTab(String str, Component comp)
• Str: title of pane
• Comp: component, it can be JPanel
• Steps to create JTabbedPane:
• Create a JTabbedPane object.
• Call addTab( ) to add a tab to the pane.
• Repeat step 2 for each tab.
• Add the tabbed pane to the content pane of the Japplet or JFrame

Welcome To VCLIENT WORLD


JScrollPane 107
• A scroll pane is a component that presents a rectangular area in which
a component may be viewed.
• Horizontal and/or vertical scroll bars may be provided if necessary.
• Subclass of JComponent n Constructor:
• JScrollPane(Component comp)
• JScrollPane(int vsb, int hsb)
• JScrollPane(Component comp, int vsb, int hsb) //Comp: Component,
vsb & hsb: Scrollbar constant
• HORIZONTAL_SCROLLBAR_ALWAYS
• HORIZONTAL_SCROLLBAR_AS_NEEDED
• VERTICAL_SCROLLBAR_ALWAYS
Welcome To VCLIENT WORLD
• VERTICAL_SCROLLBAR_AS_NEEDED
JTree 108

• A tree is a component that presents a hierarchical view of data.


• Trees are implemented in Swing by the JTree class, which extends
Jcomponent.
• Constructors:
• JTree(Hashtable ht)
• JTree(Object obj[ ])
• JTree(TreeNode tn)
• JTree(Vector v)

Welcome To VCLIENT WORLD


JTree 109

• TreePath object that encapsulates information about the tree node that
was selected by the user.
• The TreeNode interface declares methods that obtain information about
a tree node.
• The MutableTreeNode interface extends TreeNode. It declares methods
that can insert and remove child nodes or change the parent node.
• The DefaultMutableTreeNode class implements the MutableTreeNode
interface. It represents a node in a tree.
• Constructor: DefaultMutableTreeNode(Object obj)

Welcome To VCLIENT WORLD


JTree 110

• To create a hierarchy of tree nodes, the add( ) method of


DefaultMutableTreeNode can be used.
• void add(MutableTreeNode child)
• Tree Expansion event described by class:
• TreeExpansionEvent (Package: javax.swing.event)
• The getPath( ) method of this class returns a TreePath.
• TreePath getPath( )
• TreeExpansionListener interface provides the following two methods
• void treeCollapsed(TreeExpansionEvent tee)
• void treeExpanded(TreeExpansionEvent tee)
Welcome To VCLIENT WORLD
Jtree 111

• Steps to create Jtree:


• Create a JTree object.
• Create a JScrollPane object.
• Add the tree to the scroll pane.
• Add the scroll pane to the content pane of the applet.

Welcome To VCLIENT WORLD


JTable 112

• A table is a component that displays rows and columns of data.


• You can drag the cursor on column boundaries to resize columns.
• You can also drag a column to a new position.
• Subclass of JComponent
• Constructor:
• JTable(Object data[ ][ ], Object colHeads[ ])
• data is a two-dimensional array of the information
• colHeads is a one-dimensional array with the column headings.
Welcome To VCLIENT WORLD
JTable 113

• Steps to create Jtable


• Create a JTable object.
• Create a JScrollPane object.
• Add the table to the scroll pane.
• Add the scroll pane to the content pane of the JApplet or JFrame

Welcome To VCLIENT WORLD


Vocabulary 114

• AWT – The Abstract Window Toolkit provides basic graphics tools (tools for
putting information on the screen)
• Swing – A much better set of graphics tools
• Container – a graphic element that can hold other graphic elements (and is itself
a Component)
• Component – a graphic element (such as a Button or a TextArea) provided by a
graphics toolkit
• listener – A piece of code that is activated when a particular kind of event occurs
• layout manager – An object whose job it is to arrange
• Components in a Container

Welcome To VCLIENT WORLD


UNIT –III 12
Event Handling 115
Marks

• GUI components communicate with the rest of


the applications through events.
• The source of an event is the component that
causes that event to occur.
• The listener of an event is an object that receives
the event and processes it appropriately.

Welcome To VCLIENT WORLD


Specific Objectives 116

• To write event driven programs using the delegation event model.



• To write programs using adapter classes & the inner classes.

Welcome To VCLIENT WORLD


3.1 The Delegation Event Model 117

• Modern approach to handling events is based on the


“delegation event model”.

• Defines standard and consistent mechanisms to generate and


process event’s.

• “Source” generates an event and sends it to one or more listeners.

Welcome To VCLIENT WORLD


The Delegation Event Model : Event 118

• Event is an object that describes a state change in a


source.
• Some action we have to performed when it is generated.
• Generated when user is interacted with components.
• Example: Pressing Button, Selecting item from list etc.
• It can be also generated when timer expires, counter
value exceeds, software and hardware failure etc.
Welcome To VCLIENT WORLD
Event Source 119
• Source is an object that generates an event.
• This occurs when the internal state of that object changes.
• Sources may generate more than one type of event.
• Sources must be register listener so that listener will
receive notifications.
• For Register/add:
• public void addTypeListener(TypeListener el)
• For remove:
• public void removeTypeListener(TypeListener el)
Welcome To VCLIENT WORLD
Event Listener 120

• Listener is an object that is notified when an event


occurs.

• Two requirements:
• It must have been registered with one or more sources to
receive notifications.
• It must implement methods to receive and process these
notifications.
Welcome To VCLIENT WORLD
Event Classes 121
• Event Classes are core of Java’s event handling
mechanism.
• EventObject is the root of the Java event class hierarchy
which is present in java.util.
• It is the superclass for all events.
• Constructor:
• EventObject(Object src).
• EventObject class has defines two methods:
• Object getSource( ) : method returns the source of the event.
Welcome To VCLIENT WORLD
• String toString( ) : returns string equivalent of the event.
Event Classes : AWTEvent 122

• AWTEvent is defined in java.awt package.


• It is a subclass of EventObject.
• It is the superclass of all AWT-based events.

• Summarize:
• EventObject is a superclass of all events.
• AWTEvent is a superclass of all AWT events that are handled by
the delegation event model.
Welcome To VCLIENT WORLD
Summary 123

• Event Source – the class which


broadcasts the events
• Event Listeners – the classes
which receive notifications of
events
• Event Object – the class object
which describes the event.

Welcome To VCLIENT WORLD


3.2 Event Classes : Diff classes 124

• ActionEvent
• ComponentEvent
• ContainerEvent
• FocusEvent
• ItemEvent
• KeyEvent
• MouseEvent
• TextEvent
• WindowEvent
Welcome To VCLIENT WORLD
ActionEvent 125

• Generated when a button is pressed, a list item is double-clicked, or a menu


item is selected.
• ActionEvent class defines four integer constants that can be used to identify
any modifiers associated with an action event:
• ALT_MASK, (8)
• CTRL_MASK, (2)
• META_MASK, (4)
• SHIFT_MASK. (1)
• In addition, an integer constant, ACTION_PERFORMED (1001), which can be
used to identify action events
Welcome To VCLIENT WORLD
ActionEvent 126
• Constructors:
• ActionEvent(Object src, int type, String cmd)
• ActionEvent(Object src, int type, String cmd, int modifiers)
• ActionEvent(Object src, int type, String cmd, long when, int modifiers)
• src: object which generate event
• type: type of event
• cmd: Command string
• modifiers: which modifier key
• when: when the event occurred
• getActionCommand() used to get command name.
• int getModifiers() used to get modifier key.
Welcome To VCLIENT WORLD
• long getWhen( ) used to get when event generated.
ComponentEvent class 127

• A ComponentEvent is generated when the size, position, or


visibility of a component is changed.
• There are four types of component events
• COMPONENT_HIDDEN The component was hidden.
• COMPONENT_MOVED The component was moved.
• COMPONENT_RESIZED The component was resized.
• COMPONENT_SHOWN The component became visible.
• Constructor:
• ComponentEvent(Component src, int type)
Welcome To VCLIENT WORLD
ContainerEvent class 128

• ContainerEvent is generated when a component is added to or


removed from a container.
• Two Constants defined
• COMPONENT_ADDED and
• COMPONENT_REMOVED
• Subclass of ComponentEvent Class n Constructor:
• ContainerEvent(Component src, int type, Component comp)

Welcome To VCLIENT WORLD


FocusEvent class 129

• FocusEvent is generated when a component gains or loses input focus.


• Two constants defined:
• FOCUS_GAINED and FOCUS_LOST. n Constructors:
• FocusEvent(Component src, int type)
• FocusEvent(Component src, int type, boolean temporaryFlag)
• Focus Event(Component src, int type, boolean temporaryFlag,
Component other)
• isTemporary( ) method indicates if this focus change is temporary.

Welcome To VCLIENT WORLD


ItemEvent Class 130

• ItemEvent is generated when a check box or a list item is clicked


or when a checkable menu item is selected or deselected.
• Item events:
• DESELECTED The user deselected an item.
• SELECTED The user selected an item.
• ITEM_STATE_CHANGED that signifies a change of state. n
Constructor:
• ItemEvent(ItemSelectable src, int type, Object entry, int state)
Welcome To VCLIENT WORLD
KeyEvent Class 131

• KeyEvent is generated when keyboard input occurs.


• There are three types of key events:
• KEY_PRESSED,
• KEY_RELEASED, and
• KEY_TYPED
• Constructor:
• KeyEvent(Component src, int type, long when, int modifiers, int code)
• KeyEvent(Component src, int type, long when, int modifiers, int code,
char ch)
Welcome To VCLIENT WORLD
132

• There are many other integer constants that are defined by KeyEvent.

• VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents
of the numbers and letters.

• VK_ENTER VK_ESCAPE VK_CANCEL
• VK_UP VK_DOWN VK_LEFT VK_RIGHT
• VK_PAGE_DOWN VK_PAGE_UP VK_SHIFT
• VK_ALT VK_CONTROL
Welcome To VCLIENT WORLD
MouseEvent Class 133
• Eight types of mouse events.
• The MouseEvent class defines the following integer constants
• MOUSE_CLICKED The user clicked the mouse.
• MOUSE_DRAGGED The user dragged the mouse.
• MOUSE_ENTERED The mouse entered a component.
• MOUSE_EXITED The mouse exited from a component.
• MOUSE_MOVED The mouse moved.
• MOUSE_PRESSED The mouse was pressed.
• MOUSE_RELEASED The mouse was released.
• MOUSE_WHEEL The mouse wheel was moved

• MouseEvent is a subclass of InputEvent.


Welcome To VCLIENT WORLD
• Constructor:
• MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup)
TextEvent Class 134

• These are generated by text fields and text areas when characters
are entered by a user or program.
• TextEvent defines the integer constant
• TEXT_VALUE_CHANGED.
• Constructor:
• TextEvent(Object src, int type)

Welcome To VCLIENT WORLD


WindowEvent Class 135
• There are ten types of window events.
• WindowEvent class defines integer constants:
• WINDOW_ACTIVATED The window was activated.
• WINDOW_CLOSED The window has been closed.
• WINDOW_CLOSING The user requested that the window be closed.
• WINDOW_DEACTIVATED The window was deactivated.
• WINDOW_DEICONIFIED The window deiconified (min => Normal).
• WINDOW_GAINED_FOCUS The window gained input focus.
• WINDOW_ICONIFIED The window was iconified(Normal=>min)
• WINDOW_LOST_FOCUS The window lost input focus.
•Welcome
WINDOW_OPENED
To VCLIENT WORLD
The window was opened.
• WINDOW_STATE_CHANGED The state of the window changed.
WindowEvent Class 136

• WindowEvent is a subclass of ComponentEvent.



• WindowEvent(Window src, int type, Window other)
• WindowEvent(Window src, int type, int fromState, int toState)
• WindowEvent(Window src, int type, Window other, int fromState,
int toState)

Welcome To VCLIENT WORLD


3.3 Adapter Class 137

• Why do you need adapter classes?


 Implementing all the methods of an interface involves
a lot of work.
 If you are interested in only using some methods of the
interface.
• Adapter classes
 Built-in in JAVA
 Implement all the methods of each listener interface
with more than one method.
Welcome To VCLIENT WORLD
 Implementation of all empty methods
Adapter classes - an Illustration 138

• Consider, you create a class that implements a MouseListener


interface, where you require only a couple of methods to be
implemented. If your class directly implements the
MouseListener, you must implement all five methods of this
interface.
• Methods for those events you don't care about can have empty
bodies

Welcome To VCLIENT WORLD


Illustration (contd..) 139
public class MyClass implements MouseListener {
... someObject.addMouseListener(this);
/* Empty method definition. */
public void mousePressed(MouseEvent e) { }
/* Empty method definition. */
public void mouseReleased(MouseEvent e) { }
/* Empty method definition. */
public void mouseEntered(MouseEvent e) { }
/* Empty method definition. */
public void mouseExited(MouseEvent e) { }
public void mouseClicked(MouseEvent e) {
//Event listener implementation goes here...
} To VCLIENT WORLD
Welcome

}
Illustration (contd..) 140

• What is the result?


 The resulting collection of empty bodies can make
the code harder to read and maintain.
• To help you avoid implementing empty bodies, the API
generally includes an adapter class for each listener
interface with more than one method. For example,
the MouseAdapter class implements the MouseListener
interface.
Welcome To VCLIENT WORLD
How to use an Adapter class? 141

/* Using an adapter class */


public class MyClass extends MouseAdapter {
....
someObject.addMouseListener(this);
....
public void mouseClicked(MouseEvent e) {
...//Event listener implementation goes
// here
}
Welcome To VCLIENT WORLD

}
3.3 Adapter Class 142

• An adapter class provides an empty implementation of all methods


in an event listener interface.
• Adapter classes are useful when you want to receive and process
only some of the events that are handled by a particular event
listener interface.
• Example:

Welcome To VCLIENT WORLD


Adapter Class : Different Classes 143

ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter
Welcome To VCLIENT WORLD
WindowListener
3.4 Inner Class 144

• Inner class is class which defined in another class.


• In inner classes, the Adapter class will defined in same class.
• No need of passing reference of object as it is in same scope.
• Ex.

Welcome To VCLIENT WORLD


Using Inner classes for Event Handling 145
• Consider that you want to use an adapter class but you don’t want your public
class to inherit from the adapter class.
• For example, you write an applet with some code to handle mouse events. As
you know, JAVA does not permit multiple inheritance and hence your class
cannot extend both the Applet and MouseAdapter classes
• Use a class inside your Applet subclass that extends the MouseAdapter class.
public class MyClass extends Applet { ...
someObject.addMouseListener(new MyAdapter());
...
class MyAdapter extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
//Event listener implementation here... }
Welcome To VCLIENT WORLD
}
}
Anonymous Inner Class 146

• An anonymous inner class is one that is not assigned a name.


• Ex.

Welcome To VCLIENT WORLD


3.5 Event Listeners Interfaces 147

• Event Delegation Model has two parts: Sources and Listeners.


• When event generated, then event source invoked appropriate
method defined by interface.

Welcome To VCLIENT WORLD


Action Listener Interface 148

• Defines one method to receive action events.


• void actionPerformed(ActionEvent ae)

Welcome To VCLIENT WORLD


ComponentListener Interface 149

• Defines four methods to recognize when a component is hidden,


moved, resized, or shown.
• void componentResized(ComponentEvent ce)
• void componentMoved(ComponentEvent ce)
• void componentShown(ComponentEvent ce)
• void componentHidden(ComponentEvent ce)

Welcome To VCLIENT WORLD


ContainerListener Interface 150

• Defines two methods to recognize when a component is added to


or removed from a container.
• void componentAdded(ContainerEvent ce)
• void componentRemoved(ContainerEvent ce)

Welcome To VCLIENT WORLD


FocusListener Interface 151

• Defines two methods to recognize when a component gains or


loses keyboard focus.
• void focusGained(FocusEvent fe)
• void focusLost(FocusEvent fe)

Welcome To VCLIENT WORLD


ItemListener Interface 152

• Defines one method to recognize when the state of an item


changes.
• void itemStateChanged(ItemEvent ie)

Welcome To VCLIENT WORLD


KeyListener Interface 153

• Defines three methods to recognize when a key is pressed,


released, or typed.
• void keyPressed(KeyEvent ke)
• void keyReleased(KeyEvent ke)
• void keyTyped(KeyEvent ke)

Welcome To VCLIENT WORLD


MouseListener Interface 154
• Defines five methods to recognize when the mouse is clicked, enters a
component, exits a component, is pressed, or is released.
• Event handling when the mouse is clicked.
• void mouseClicked(MouseEvent me)
• Event handling when the mouse enters a component.
• void mouseEntered(MouseEvent me)
• Event handling when the mouse exits a component
• void mouseExited(MouseEvent me)
• Event handling when the mouse button is pressed on a component.
• void mousePressed(MouseEvent me)
• Event handling when the mouse button is released on a component.
Welcome To VCLIENT WORLD

• void mouseReleased(MouseEvent me)


MouseMotionListener Interface 155

• Defines two methods to recognize when the mouse is


dragged or moved.
• Invoked when the mouse button is pressed over a
component and dragged. Called several times as the mouse
is dragged
• void mouseDragged(MouseEvent me)
• Invoked when the mouse cursor has been moved onto a
component but no buttons have been pushed.
• void mouseMoved(MouseEvent me)
Welcome To VCLIENT WORLD
TextListener Interface 156

• Defines one method to recognize when a text value changes.


• void textValueChanged(TextEvent te)

Welcome To VCLIENT WORLD


WindowFocusListener Interface 157

• Defines two methods to recognize when a window gains or loses


input focus
• void windowGainedFocus(WindowEvent we)
• void windowLostFocus(WindowEvent we)

Welcome To VCLIENT WORLD


WindowListener Interface 158
Defines seven methods to recognize:

• Invoked when the window object is opened.


• void windowOpened(WindowEvent we)
• Invoked when the user attempts to close the window object from the object’s system menu.
• void windowClosing(WindowEvent we)
• Invoked when the window object is closed as a result of calling dispose (release of resources used by the source).
• void windowClosed(WindowEvent we)
• Invoked when the window is minimized.
• void windowIconified(WindowEvent we)
• Invoked when the window is changed from the minimized state to the normal state.
• void windowDeiconified(WindowEvent we)
• Invoked when the window is set to be the active window.
• void windowActivated(WindowEvent we)
•Welcome
Invoked when the window object is no longer the active window
To VCLIENT WORLD
• void windowDeactivated(WindowEvent we)
Hierarchy of event objects 159

Welcome To VCLIENT WORLD


Additional Listener Types 160

• Change Listener
• Container Listener
• Document Listener
• Focus Listener
• Internal Frame Listener
• ListSelectionListener
• Property Change Listener
• Table Model Listener
• TreeSelectionListener
• TreeWillExpandListener
• TreeExpansionListener
Welcome To VCLIENT WORLD
Common Event-Handling Issues 161
1. You are trying to handle certain events from a component, but it doesn’t generate
the events it should.
 Make sure you have registered the right kind of listener to detect the events.
 Make sure you have registered the listener on the right object.
 Make sure you have implemented the event handler correctly, especially, the
method signatures.
2. Your combo box isn’t generating low level events like focus events.
 Since combo boxes are compound components, i.e., components implemented
using multiple components, combo-boxes do not fire the low-level events that
simple components fire.
3. The document for an editor pane is not triggering document events.
 The document instance for an editor pane might change when loading text from
a URL. Thus your listeners might be listening for events on an unused document.
Welcome To VCLIENT WORLD
 Hence, make sure that the code adjusts for possible changes to the document if
your program dynamically loads text into an editor pane.
Networking and Security 162

• Chapter 04

Welcome To VCLIENT WORLD


TCP/IP reminder 163

• IP: network layer protocol


• unreliable datagram delivery between hosts.

• UDP: transport layer protocol


• unreliable datagram delivery between processes.

• TCP: transport layer protocol


• reliable, byte-stream delivery between processes.

Welcome To VCLIENT WORLD


Introduction 164

We will focus on these layers

java.net

Welcome To VCLIENT WORLD


Internet Protocol (IP) 165

• Packet oriented
• Packets routed between computers
• Unreliable

Welcome To VCLIENT WORLD


Internet Addressing 166

• Internet address is unique number, used to identify each


machine uniquely.
• IP address: 2 version
• IPv4 : 32–bits and in decimal (Now)
• IPv6 : 128-bits and in hexadecimal (Future)
• IPv4 : Divide 32 bits in 4 parts.
• Each part range from 0 to 255.

Welcome To VCLIENT WORLD


Internet Addressing 167

• Divided into 5 classes:


 Class A
 Class B
 Class C
 Class D
 Class E

Welcome To VCLIENT WORLD


IP - java.net.InetAddress 168

Represents a single IP address


• Factory class – no public constructor
• Performs transparent DNS lookups or reverse lookups
• java.net.UnkownHostException thrown if DNS system
can’t find IP address for specific host
. . .
//static methods
InetAddress address= InetAddress.getLocalHost()
InetAddress address=
InetAddress.getByAddress(‘’www.yahoo.com’’)
Welcome To VCLIENT WORLD
InetAddress class 169
•InetAddress class is encapsulate both numeric IP address ( eg
.74.125.236.88) and the domain name (eg. www.google.com) for the
address.
•Interaction with this class by using the Hostname rather than IP address,
more conveniently and understandable way.
•For example, mostly every internet user don't know IP address for
google.com.
•It has both Factory and Instance methods:
•Factory method: is a static method in a class return an instance of that
class.
Welcome To VCLIENT WORLD

•Instance Methods: is a non-static method.


About InetAddress class 170

• As we know, "new" Keyword is used to create object to that corresponding class.


• InetAddress Class has no visible constructors. to create a InetAddress object.
• Factory Method is used to create objects.
• Three factory methods:
 static InetAddress getLocalHost()
 static InetAddress getByName(String hostName)
 static InetAddress[] getAllByName(String hostName).
 All methods generate : UnknownHostException

Welcome To VCLIENT WORLD


Instance Methods 171

• boolean equals(Object other)


• byte[] getAddress(): Return four element of IP address.
• String getHostAddress(): Return host address associated with InetAddress.
• String getHostName(): Return host name.
• int hasCode() : return hashcode of invoking object.
• Boolean isMultiCastAddress()

Welcome To VCLIENT WORLD


Introduction 172

We will focus on these layers

java.net

Welcome To VCLIENT WORLD


User Datagram Protocol (UDP) 173

• Packet oriented
• Message split into datagrams
• Send datagrams as packets on network layer
• Unreliable but fast
• Application must deal with lost packets
• Examples
• Ping
• Streaming multimedia
• Online games
Welcome To VCLIENT WORLD
Transmission Control Protocol (TCP) 174

• Connection oriented
• Message split into datagrams
• Send datagrams as packets on network layer
• Provides illusion of reliable connection
• Extra messages between sender / recipient
• Resend packets if necessary
• Ensure all packets eventually arrive
• Store packets and process in order
Welcome To VCLIENT
Transmission Control Protocol (TCP) 175

• Reliable but slower


• Application can treat as reliable connection
• Despite unreliability of underlying IP (network)
• Examples
• ftp (file transfer) 20 and 21
• telnet (remote terminal) 23
• http (web) 80
• Email 25

Welcome To VCLIENT WORLD


Difference Between TCP & UDP 176

TCP UDP

Connection oriented Connectionless

Reliable Unreliable

Retransmit No retransmission

Slower data transmission Faster data transmission

Require most cost Less cost than TCP

Welcome To VCLIENT WORLD


Proxy Server 177

• It is mediator between real web server and a client applications


like web browser.
• Filter specific request and stored data in catch for future use.

Welcome To VCLIENT WORLD


Socket 178

• Network socket is an endpoint of an interprocess communication flow across a


computer network.
• Sockets provide the communication mechanism between two computers using
TCP/IP.
• IP (Internet Protocol): Low level routing protocol. Divides data into small
packets and send on given address. It does not guarantee to deliver the
packets.
• Transmission Control Protocol (TCP): Higher level protocol. Reliability to
deliver data.
• User Datagram Protocol (UDP): Next to TCP. It support fast, connectionless,
unreliable transport of data packets.
Welcome To VCLIENT WORLD
Reserved Sockets Ports 179

• Port number range : 0 to 65535


• 1 to 1024 are reserved.
• Examples:

• Client request for file from HTTP server, it is called hits.


Welcome To VCLIENT WORLD
Socket Programming 180

• A client program creates a socket on its end of the communication and


attempts to connect that socket to a server.
• When the connection is made, the server creates a socket object on its
end of the communication.
• The client and server can now communicate by writing to and reading
from the socket.
• The package java.net provides support for sockets programming.
• Typically you import everything defined in this package with:
• import java.net.*;
Welcome To VCLIENT WORLD
Socket Classes 181

• Provides interface to TCP, UDP sockets


• Socket
• TCP client sockets
• ServerSocket
• TCP server sockets
• DatagramSocket
• UDP sockets (server or client)

Welcome To VCLIENT WORLD


Socket I/O 182

• Socket I/O is based on the Java I/O support (in the package
java.io).

• InputStream and OutputStream are abstract classes


• common operations defined for all kinds of InputStreams, OutputStreams…

Welcome To VCLIENT WORLD


InputStream Basics 183
// reads some number of bytes and
// puts in buffer array b
int read(byte[] b);

// reads up to len bytes


int read(byte[] b, int off, int len);

Both methods can throw IOException.


Welcome To VCLIENT WORLD

Both return –1 on EOF.


OutputStream Basics 184

// writes b.length bytes


void write(byte[] b);

// writes len bytes starting


// at offset off
void write(byte[] b, int off, int len);

Both methods can throw IOException.


Welcome To VCLIENT WORLD
Socket Class 185

• Creates socket for client


• Constructor connects to
• Machine name or IP address
• Port number
• Transfer data via streams
• Similar to standard Java I/O streams

Welcome To VCLIENT WORLD


Socket Methods 186

• getInputStream()
• getOutputStream()
• close()
• getInetAddress()
• getPort()
• getLocalPort()

Welcome To VCLIENT WORLD


ServerSocket Class 187

• Create socket on server


• Constructor specifies local port
• Server listens to port
• Usage
• Begin waiting after invoking accept()
• Listen for connection (from client socket)
• Returns Socket for connection

Welcome To VCLIENT WORLD


ServerSocket Methods 188

• accept()
• close()
• getInetAddress()
• getLocalPort()

Welcome To VCLIENT WORLD


Client Programming 189

• Basic steps
1. Determine server location – IP address & port
2. Open network connection to server
3. Write data to server (request)
4. Read data from server (response)
5. Close network connection
6. Stop client

Welcome To VCLIENT WORLD


class TCPClient {
public static void main(String argv[]) throws Exception
{try{ String sentence;
BufferedReader inFromUser =
String modifiedSentence;
new BufferedReader(new InputStreamReader(System.in));
190
BufferedReader inFromUser =
Socket new clientSocket = new Socket(InetAddress.getLocalHost(),
BufferedReader(new InputStreamReader(System.in));
6789);Socket clientSocket = new Socket(InetAddress.getLocalHost(), 6789);
DataOutputStream outToServer =
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer =
BufferedReader inFromServer
new BufferedReader(new
=
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
sentence = inFromUser.readLine();
modifiedSentence = inFromServer.readLine();
outToServer.writeBytes(sentence + '\n');
System.out.println("FROM SERVER: " + modifiedSentence);
modifiedSentence = inFromServer.readLine();
clientSocket.close(); }catch(Exception e){
e.printStackTrace();
clientSocket.close();
}}
Welcome To VCLIENT} WORLD read
Get
Get data
Create
Get
user
socketfrom
socket
adata
new
output
and
input
send
Getrequest
response
user
Close
socket
stream
streamfrom server
socket
to server
Server Programming 191

• Basic steps
1. Determine server location - port (& IP address)
2. Create server to listen for connections
3. Open network connection to client
4. Read data from client (request)
5. Write data to client (response)
6. Close network connection to client
7. Stop server

Welcome To VCLIENT WORLD


Server Programming 192

• Can support multiple connections / clients


• Loop
• Handles multiple connections in order
• Multithreading
• Allows multiple simultaneous connections

Welcome To VCLIENT WORLD


Connection Oriented 193

• TCP Protocol

Welcome To VCLIENT WORLD


Client/server socket interaction:
Server (running on hostid)
TCP 194
Client
create socket,
port=x, for
incoming request:
Server Socket ss =new
ServerSocket(port)

TCP create socket,


wait for incoming
connection request connection setup connect to hostid, port=x
connectionSocket = clientSocket =
ss.accept() Socket()

send request using


read request from clientSocket
connectionSocket

write reply to
connectionSocket read reply from
connectionSocket
close
Welcome To VCLIENT WORLD connectionSocket close
clientSocket
Socket programming with TCP
195
Client must contact server • When client creates socket:
• server process must first client TCP establishes
connection to server TCP
be running
• When contacted by client,
• server must have created server TCP creates new socket
socket (door) that for server process to
welcomes client’s contact communicate with client
Client contacts server by: • allows server to talk with
multiple clients
• creating client-local TCP
socket application viewpoint
• specifying IP address, port TCP provides reliable, in-order
number of server process transfer of bytes (“pipe”)
Welcome To VCLIENT WORLD between client and server
TCP server 196
public static void main(String[] argv) throws IOException {
ServerSocket sock;
Socket clientSock;
try {
sock = new ServerSocket(PORT);
while ((clientSock = sock.accept( )) != null) {.
process(clientSock);
}
} catch (IOException e) {
System.err.println(e);
}
}
static void process(Socket s) throws IOException {
DataOutputStream os = new DataOutputStream(s.getOutputStream( ));
long time = System.currentTimeMillis( );
os.writeInt((int)time)
Welcome To VCLIENT WORLD
s.close( );
}
TCP server – multithreaded case 197
public class ServerThreaded {
public static final int PORT = 7;
public static void main(String[] av){
new ServerThreaded().runServer( );
}
public void runServer( ){
ServerSocket sock;
Socket clientSocket;
try {
sock = new ServerSocket(PORT);
System.out.println("ServerThreaded ready for connections.");
/* Wait for a connection */
while(true){
clientSocket = sock.accept( );
/* Create a thread to do the communication, and start it */
new Handler(clientSocket).start( );
Welcome To VCLIENT WORLD
}
} catch(IOException e) { System.exit(1); }
}
TCP server – multithreaded case 198
class Handler extends Thread {
Socket sock;
Handler(Socket s) {
sock = s;
}
public void run( ){
System.out.println("Socket starting: " + sock);
try { DataInputStream is = new DataInputStream(sock.getInputStream( ));
PrintStream os = new PrintStream(sock.getOutputStream( ), true);
String line;
while ((line = is.readLine( )) != null) {
os.print(line + "\r\n");
os.flush( );
}
sock.close( );
} catch (IOException e) {return;}
System.out.println("Socket
Welcome To VCLIENT WORLD ENDED: " + sock);
}
}
Classes 199

•InetAddress
•Socket
•URL
•URLConnection
•ServerSocket
•DatagramSocket
•DatagramPacket
Welcome To VCLIENT WORLD
Packet Oriented 200

• UDP Protocol

Welcome To VCLIENT WORLD


Socket programming with UDP 201
UDP: no “connection” between
client and server
• no handshaking application viewpoint
• sender explicitly attaches IP
address and port of UDP provides unreliable transfer
destination of groups of bytes (“datagrams”)
• server must extract IP between client and server
address, port of sender from
received datagram
UDP: transmitted data may be
received out of order, or lost
Welcome To VCLIENT WORLD
DatagramSocket Class 202

• Create UDP socket


• Does not distinguish server / client sockets
• Constructor specifies InetAddress, port
• Set up UPD socket connection
• Send / receive DatagramPacket

Welcome To VCLIENT WORLD


DatagramSocket Methods 203

• close()
• getLocalAddress()
• getLocalPort()
• receive(DatagramPacket p)
• send(DatagramPacket p)
• setSoTimeout(int t)
• getSoTimeout()

Welcome To VCLIENT WORLD


DatagramPacket Class 204

• Each packet contains


• InetAddress
• Port of destination
• Data (byte array)

Welcome To VCLIENT WORLD


DatagramPacket Methods 205

• getAddress()
• getData()
• getLength()
• getPort()
• setAddress()
• setData()
• setLength()
• setPort()
Welcome To VCLIENT WORLD
Client/server socket interaction: UDP 206
Server (running on hostid) Client
create socket, create socket,
port=x, for clientSocket =
incoming request: DatagramSocket()
serverSocket =
DatagramSocket()
Create, address (hostid, port=x),
send datagram request
using clientSocket
read request from
serverSocket

write reply to
serverSocket
specifying client read reply from
host address, clientSocket
port number close
clientSocket

Welcome To VCLIENT WORLD


class UDPClient {
BufferedReader inFromUser
public static void main(String =
args[]) throws Exception
{new BufferedReader(newInputStreamReader(System.in));
BufferedReader inFromUser =
DatagramSocket
InetAddress
clientSocket
new BufferedReader(new = new DatagramSocket();
InputStreamReader(System.in));
IPAddress = InetAddress.getLocalHost();
207
DatagramSocket clientSocket = new DatagramSocket();
byte[]InetAddress
sendData = new
IPAddress byte[1024];
= InetAddress.getLocalHost();
byte[]byte[]receiveData
sendData = new= byte[1024];
new byte[1024];
Stringbyte[] sentence = inFromUser.readLine();
receiveData = new byte[1024];
sendData = sentence.getBytes();
String sentence = inFromUser.readLine();
DatagramPacket sendPacket =
sendData = sentence.getBytes();

new DatagramPacket(sendData, sendData.length,


DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
IPAddress, 9876);
DatagramPacket receivePacket =
clientSocket.send(sendPacket);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
clientSocket.receive(receivePacket);
StringString modifiedSentence
modifiedSentence = new= new String(receivePacket.getData());
String(receivePacket.getData());
clientSocket.close();
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close(); Make preparations..
Closemessage
Receive socket from server
Welcome To VCLIENT WORLD
} CreateSend newmessage
Datagram to socket
Get local host IP, prepare Read data buffers
data from user
Introduction 208

We will focus on these layers

java.net

Welcome To VCLIENT WORLD


Whois 209

• The very simple example that follows opens a connection to a


"whois" port on the InterNIC server, sends the command-line
argument down the socket, and then prints the data that is
returned. InterNIC will try to look up the argument as a registered
Internet domain name, then send back the IP address and contact
information for that site.

Welcome To VCLIENT WORLD


Client Sever programming 210
• Client/server describes the relationship between
two computer programs in which one program,
the client, makes a service request from another
program, the server, which fulfills the request

Client- sends a Server- waits


request for requests
Server- returns
a replay
Welcome To VCLIENT WORLD
URL 211
•URL is Uniform Resource Locator.
•It is a formatted string used by email clients, web browsers and different
type of software recognize network resource on the internet.
•Network resource could be text, documents, plain web pages, programs or
graphics.
•URL string consist of following parts:
Network protocol
Host name or address
Port number
File or resource location.
•URL provides comprehensive form to uniquely identify or address
information
Welcome on the internet.
To VCLIENT WORLD
212
• Java has provided : URL class  http://www.msbte.com/index.html
• URL string consist of three parts: • URL class has some constructors and
it throws MalformedURLException
 Network protocol
• URL(String url)
 Host name or address
• URL(String protocol, String
 File or resource location. hostname, int port, String path)
• URL provides comprehensive form to • URL(URL obj, String url)
uniquely identify or address
information on the internet.
• Java has provided : URL class
•Welcome
ExTo VCLIENT WORLD
URLConnection 213

• URLConnection is a general-purpose class for accessing the


attributes of a remote resource.
• Once you make a connection to a remote server, you can use
URLConnection to inspect the properties of the remote object
before actually transporting it locally.
• These attributes are exposed by the HTTP protocol specification
and, as such, only make sense for URL objects that are using the
HTTP protocol.
• We'll examine the most useful elements of URLConnection here.
Welcome To VCLIENT WORLD
214
• // Demonstrate URLConnection. import java.net.*; import java.io.*; import
java.util.Date;
• class UCDemo {
• public static void main(String args[]) throws Exception {
• int c;
• URL hp = new URL("http://www.starwave.com/people/naughton/");
• URLConnection hpCon = hp.openConnection();
• System.out.println("Date: " + new Date(hpCon.getDate()));
• System.out.println("Content-Type: " + hpCon.getContentType());
• System.out.println("Expires: " + hpCon.getExpiration());
• System.out.println("Last-Modified: " + new Date(hpCon.getLastModified()));
• int len = hpCon.getContentLength();
Welcome To VCLIENT WORLD
• System.out.println("Content-Length: " + len);
Network Summary 215

• Internet
• Underlying medium is unreliable (IP), packet oriented
• Provides two views
• Reliable, connection oriented (TCP)
• Unreliable, packet oriented (UDP)
• Java
• Object-oriented classes & API
• IP – InetAddress
• TCP – Socket, ServerSocket
• UDP – DatagramSocket, DatagramPacket
Welcome To VCLIENT WORLD
Summary 216

• What is an IP address? To which layer in OSI model it


correlates? And to which Java class?
• What is the difference between a TCP and UDP? What is a
byte stream? Packet oriented? How is the difference
evident in the Java socket classes?
• what makes a server a server? How can a server handle
multiple requests?

Welcome To VCLIENT WORLD


217

Questions?

Welcome To VCLIENT WORLD


Chapter 5
Interacting With Database 218

Welcome To VCLIENT WORLD


Specific Objectives 219

• To create database driven business applications using the database


API’S two tier and three tier models and the Java.Sql package

Welcome To VCLIENT WORLD


Database Drivers 220

• Think of a database as just another device connected to your


computer
• Like other devices it has a driver program to relieves you of having
to do low level programming to use the database
• The driver provides you with a high level API to the database

Welcome To VCLIENT WORLD


ODBC 221

• Open Data Base Connectivity


• Developed by Microsoft for the Windows platform as the way for Windows
applications to access Microsoft databases (SQL Server, FoxPro, Access)
• Has become an industry standard
• Most data base vendors supply native, ODBC, and JDBC drivers for their
data base products .
• It was developed in C programming.
• It is low level, high performance interface that is designed specially for
relational data stores.

Welcome To VCLIENT WORLD


JDBC 222

• JDBC drivers implement the defined interfaces in the JDBC API for
interacting with your database server.
• Package: java.sql
• JDBC drivers enable you to open database connections and to
interact with it by sending SQL or database commands then
receiving results with Java.

Welcome To VCLIENT WORLD


JDBC API 223

• JDBC is a Java API that is used to connect and execute query for
the database.
• JDBC API uses jdbc drivers to connects to the database.

Welcome To VCLIENT WORLD


JDBC Arhitecture 224

Java
Application

JDBC API

Data Base Drivers

Access SQL DB2 Informix MySQL Sybase


Server
Welcome To VCLIENT WORLD
JDBC Driver Types 225

• JDBC driver implementation vary because of wide variety of OS,


hardware, databases in which Java operates. It divides into 4 types:
• Type 1
• JDBC-ODBC Bridge
• Type 2
• Native API, partially java
• Type 3
• JDBC Network Driver, partially java
• Type 4
• 100% Java
Welcome To VCLIENT WORLD
Type 1 Drivers 226

• The JDBC-ODBC bridge driver uses ODBC driver to connect to the


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

Welcome To VCLIENT WORLD


227

Welcome To VCLIENT WORLD


Type 1 Drivers 228

• • Advantages:
• easy to use.
• can be easily connected to any database.
• Disadvantages:
• Performance degraded because JDBC method call is converted into the
ODBC function calls.
• The ODBC driver needs to be installed on the client machine.

Welcome To VCLIENT WORLD


Type 2 Drivers 229

• The Native API driver uses the client-side libraries of the


database.
• The driver converts JDBC method calls into native (c/c++ API) calls
of the database API.
• If we change database, we have to change native API.
• It is not written entirely in java

Welcome To VCLIENT WORLD


Type 2 Drivers 230

Welcome To VCLIENT WORLD


Type 2 Drivers 231

• Advantage:
• performance upgraded than JDBC-ODBC bridge driver.
• Disadvantage:
• The Native driver needs to be installed on the each client
machine.
• The Vendor client library needs to be installed on client machine.

Welcome To VCLIENT WORLD


Type 3 Drivers 232

• The Network Protocol driver uses middleware (application server)


that converts JDBC calls directly or indirectly into the vendor-
specific database protocol.
• It is fully written in java

Welcome To VCLIENT WORLD


Type 3 Drivers(cont.) 233

Welcome To VCLIENT WORLD


Type 3 Drivers 234

• Advantage:
• No client side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.
• Disadvantages:
• Network support is required on client machine.
• Requires database-specific coding to be done in the middle tier.
• Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.

Welcome To VCLIENT WORLD
Type 4 Drivers 235

• The thin driver converts JDBC calls directly into the vendor-specific
database protocol. That is why it is known as thin driver.
• It is fully written in Java language.

Welcome To VCLIENT WORLD


Driver 4 Type 236

• Advantage:
• Better performance than all other drivers.
• No software is required at client side or server side.
• Disadvantage:
• Drivers depends on the Database.

Welcome To VCLIENT WORLD


Which Driver should I used? 237

• If you are accessing one type of database, such as Oracle, Sybase,


or IBM, the preferred driver type is 4.
• If your Java application is accessing multiple types of databases at
the same time, type 3 is the preferred driver.
• Type 2 drivers are useful in situations, where a type 3 or type 4
driver is not available yet for your database.
• The type 1 driver is not considered a deployment-level driver, and
is typically used for development and testing prposes only.

Welcome To VCLIENT WORLD


Steps to connect Database 238

• Register the driver class


• Creating connection
• Creating statement
• Executing queries
• Closing connection

Welcome To VCLIENT WORLD


Step 1 239

• The forName() method of Class class is used to register the driver


class.
• This method is used to dynamically load the driver class.
• public static void forName(String className)throws
ClassNotFoundException
• Example
• Class.forName("oracle.jdbc.driver.OracleDriver");

Welcome To VCLIENT WORLD


Step 2 240

• The getConnection() method of DriverManager class is used to


establish connection with the database.
• Syntax:
1) public static Connection getConnection(String url)th rows SQLException
2) public static Connection getConnection(String url,St ring name,String
password) throws SQLException
• Example
Connection con=DriverManager.getConnection("jdbc:o
racle:thin:@localhost:1521:xe","system","password");
Welcome To VCLIENT WORLD
Step 3 241

• The createStatement() method of Connection interface is used to


create statement.
• The object of statement is responsible to execute queries with the
database.
• Syntax:
• public Statement createStatement()throws SQLExc eption
• Ex:
• Statement stmt=con.createStatement();

Welcome To VCLIENT WORLD


Step 4 242
• The executeQuery() method of Statement interface is used to
execute queries to the database.
• This method returns the object of ResultSet that can be used to
get all the records of a table.
• Syntax:
• public ResultSet executeQuery(String sql)throws SQLEx ception
• Ex:
• ResultSet rs=stmt.executeQuery("select * from emp");
• while(rs.next()){
• System.out.println(rs.getInt(1)+" "+rs.getString(2));
• To}VCLIENT WORLD
Welcome
Step 5 243

• By closing connection object statement and ResultSet will be


closed automatically.
• The close() method of Connection interface is used to close the
connection.
• public void close()throws SQLException
• Ex:
• con.close();

Welcome To VCLIENT WORLD


Concrete Classes for Interfaces 244

• ResultSet interface: oracle.jdbc.driver.OracleResultSetImpl


• Statement: oracle.jdbc.driver.T4CStatement
• Connection: oracle.jdbc.driver.T4CConnection
• PreparedStatement: oracle.jdbc.driver.T4CPreparedStatement

Welcome To VCLIENT WORLD


Types of Architecture 245

• Two tire architecture • Three tire architecture

Welcome To VCLIENT WORLD


Statement Interface 246
• It is mainly used to execute queries.
• Few methods of Statement interface:
• public ResultSet executeQuery(String sql)
• Used to execute select query.
• public int executeUpdate(String sql)
• Used to execute create, insert, update, delete or drop etc
• public boolean execute(String sql)
• • Executes the given SQL statement, which may return multiple results.
• public int [] executeBatch()
• • Submits a batch of commands to the database for execution and if all
commands execute successfully, returns an array of update counts.
Welcome To VCLIENT WORLD
Statement Interface 247

• Insert Record:
• Statement st = con.createStatement();
• St.executeUpdate(“insert into dept values (‘comp’,101,’BVP’)”);
• Delete Record:
• Statement st = con.createStatement();
• St.executeUpdate(“delete from dept where deptno=101”);

Welcome To VCLIENT WORLD


PreparedStatement and CallableStatement
Interface 248

• Precompiled sql statement object.


• It can read runtime input parameters.
• Ex:
• PreparedStatement pstmt =
• con.prepareStatement(“update emp set salary = ? Where id = ?”)
• • CallableStatement interface used when Java interacting with database
using stored procedures.
• • Ex: • CallableStatement cstmt = null;
• String SQL = "{call getEmpName (?, ?)}";
• cstmt
Welcome = WORLD
To VCLIENT conn.prepareCall (SQL);
PreparedStatement Example 249

• String sql = "update DEPARTMENTS set DEPARTMENT_NAME = ?


where DEPARTMENT_ID = ?";
• PreparedStatement pst = con.prepareStatement(sql);
• pst.setString(1, "Information Technology");
• pst.setInt(2, 60);
• pst.executeUpdate();

Welcome To VCLIENT WORLD


Recommended Use 250

Interfaces Recommended Use


Statement Use the for general-purpose access to your database. Useful
when you are using static SQL statements at runtime. The
Statement interface cannot accept parameters.
Use the when you plan to use the SQL statements many
PreparedStatement times. The PreparedStatement interface accepts input
parameters at runtime.
CallableStatement Use the when you want to access the database stored
procedures. The CallableStatement interface can also
accept runtime input parameters.
Welcome To VCLIENT WORLD
Statement Interface Hierarchy 251

Welcome To VCLIENT WORLD


Batch Execute Example 252

• stmt.addBatch("update DEPARTMENTS set DEPT_NAME =


'Administrations' where DEPARTMENT_ID = 10");
• stmt.addBatch("update DEPARTMENTS set DEPT_NAME = 'Human
Resource' where DEPARTMENT_ID = 40");
• stmt.executeBatch();

Welcome To VCLIENT WORLD


ResultSet Interface 253

• ResultSet is table of data which represents a data from database.


• next() method is used to move cursor to next row.
• Type of ResultSet: Bydefault
• TYPE_FORWARD_ONLY
• ResultSet.TYPE_FORWARD_ONLY
• ResultSet.TYPE_SCROLL_INSENSITIVE
• ResultSet.TYPE_SCROLL_SENSITIVE

Welcome To VCLIENT WORLD


ResultSet Interface methods 254

• beforeFirst()
• afterLast()
• first()
• last()
• previous()
• next()
• getRow()

Welcome To VCLIENT WORLD


Transaction 255

• All action carried out or none of them.


• For AutoCommit
• connection.setAutoCommit(false);
• For Rollback:
• connection.rollback();
• For Commit:
• connection.commit();
Welcome To VCLIENT WORLD
DatabaseMetaData Interface 256
• Provide meta data about the database have connected to.
• For instance, you can see what tables are defined in the database,
and what columns each table has, whether given features are
supported etc.
• Obtaining a DatabaseMetaData Instance
• DatabaseMetaData databaseMetaData = connection.getMetaData();
• Database Product Name and Version
• int majorVersion = databaseMetaData.getDatabaseMajorVersion();
• int minorVersion = databaseMetaData.getDatabaseMinorVersion();
• String productName = databaseMetaData.getDatabaseProductName();
• ToString
Welcome productVersion = databaseMetaData.getDatabaseProductVersion();
VCLIENT WORLD
DatabaseMetaData 257
• Database Driver Version
• • int driverMajorVersion = databaseMetaData.getDriverMajorVersion();
• • int driverMinorVersion = databaseMetaData.getDriverMinorVersion();
• • Listing Tables
• String catalog = null;
• String schemaPattern = null;
• String tableNamePattern = null;
• String[] types = null;
• ResultSet result = databaseMetaData.getTables( catalog,
schemaPattern, tableNamePattern, types );
Welcome To VCLIENT WORLD

• while(result.next()) { String tableName = result.getString(3); }


Servlet 258

Welcome To VCLIENT WORLD


Servlet : Introduction 259

• Specific Objectives:
• To write web based applications using servlets
• To write servlet for cookies and session tracking.

Welcome To VCLIENT WORLD


Web and Web Application 260

• Web consists of billions of clients and server connected through


wires and wireless networks.
• The web clients make requests to web server. The web server
receives the request, finds the resources and return the response
to the client.

Welcome To VCLIENT WORLD


Web Application 261

• A web application is an application accessible from the web.


• A Web application is a web site with dynamic functionality on the
server. Google, Facebook, Twitter are examples of web
applications.
• A web application is composed of web components like Servlet,
JSP, Filter etc. and other components such as HTML.
• The web components typically execute in Web Server and respond
to HTTP request.

Welcome To VCLIENT WORLD


HTTP 262

• HTTP is a protocol that clients and servers use on the web to


communicate.
• It is similar to other internet protocols such as SMTP(Simple Mail
Transfer Protocol) and FTP(File Transfer Protocol) but there is one
fundamental difference.
• HTTP is a stateless protocol.
• The client sends an HTTP request and the server answers with an
HTML page to the client, using HTTP.

Welcome To VCLIENT WORLD


HTTP 263

Welcome To VCLIENT WORLD


HTTP methods 264
Method Name Description
OPTIONS Request for communication options that are available on the
request/response chain.

GET Request to retrieve information from server using a given URI.


HEAD Identical to GET except that it does not return a message-body, only the
headers and status line.
POST Request for server to accept the entity enclosed in the body of HTTP
method.
DELETE Request for the Server to delete the resource.
CONNECT Reserved for use with a proxy that can switch to being a tunnel.
PUT
This is same as POST, but POST is used to create, PUT can be used to
Welcome To VCLIENT WORLD create as well as update. It replaces all current representations of the
target resource with the uploaded content.
HTTP methods 265

GET Request POST Request

Data is sent in header to the server Data is sent in the request body

Get request can send only limited Large amount of data can be sent.
amount of data

Get request is not secured because Post request is secured because data is
data is exposed in URL not exposed in URL.

Get request can be bookmarked and Post request cannot be bookmarked.


is more efficient.
Welcome To VCLIENT WORLD
Anatomy of HTTP GET Request 266

• Get request contains path to server and the parameters added to it.

Welcome To VCLIENT WORLD


Anatomy of HTTP POST Request 267

• Post requests are used to make more complex requests on the server. For
instance, if a user has filled a form with multiple fields and the application
wants to save all the form data to the database. Then the form data will be
sent to the server in POST request body, which is also known as Message
body.

Welcome To VCLIENT WORLD


Servlet : Introduction 268

• Servlet technology is used to create web application (resides at


server side and generates dynamic web page).
• Servlet is Java program which run on web server and responding
to request of clients (Web browser).
• Servlet technology is robust and scalable because of java
language.

Welcome To VCLIENT WORLD


Servlet 269

• Web applications are helper applications that resides at web


server and build dynamic web pages. A dynamic page could be
anything like a page that randomly chooses picture to display or
even a page that displays the current time.

Welcome To VCLIENT WORLD


Servlet : Defined in many ways 270

• Servlet is a technology i.e. used to create web application.


• Servlet is an API that provides many interfaces and classes including
documentations.
• Servlet is an interface that must be implemented for creating any
servlet.
• Servlet is a class that extend the capabilities of the servers and respond
to the incoming request. It can respond to any type of requests.
• Servlet is a web component that is deployed on the server to create
dynamic web page.

Welcome To VCLIENT WORLD


Servlet : Defined 271

Welcome To VCLIENT WORLD


CGI(Common Gateway Interface) 272

• CGI(Common Gateway Interface) programming was used to create web


applications.
• Here's how a CGI program works :
User clicks a link that has URL to a dynamic page instead of a static page.
The URL decides which CGI program to execute.
Web Servers run the CGI program in seperate OS shell. The shell includes OS
enviroment and the process to execute code of the CGI program.
The CGI response is sent back to the Web Server, which wraps the response in an HTTP
response and send it back to the web browser.
Welcome To VCLIENT WORLD
273

Welcome To VCLIENT WORLD


CGI(Common Gateway Interface) 274

• For each request, it starts a new process.


• Disadvantages:
 If number of clients increases, it takes more time for sending response.
 For each request, it starts a process and Web server is limited to start
processes.
 It uses platform dependent language e.g. C, C++, perl.
 High response time because CGI programs execute in their own OS shell.
 CGI is not scalable.
 CGI programs are not always secure or object-oriented.
 It is Platform dependent.
Welcome To VCLIENT WORLD
Contrast of process vs. thread 275

Process Thread
Takes more time to create Takes less time to create
More secure Offers multiple threads of execution
More fault tolerant Share information with other threads
Less secure
More vulnerable to crashes

Welcome To VCLIENT WORLD


Servlet: Advantages over CGI 276

Welcome To VCLIENT WORLD


Servlet: Advantages over CGI 277

• Less response time because each request runs in a separate


thread.
• Servlets are scalable.
• Servlets are robust and object oriented.
• Servlets are platform independent.

Welcome To VCLIENT WORLD


Servlet Terminologies 278

• HTTP:
Http is the protocol that allows web servers and browsers to
exchange data over the web.
It is a request response protocol.
Http uses reliable TCP connections by default on TCP port 80.
It is stateless means each request is considered as the new
request. In other words, server doesn't recognize the user by
default.

Welcome To VCLIENT WORLD


Servlet 279

• A Java Servlet is a Java object that responds to HTTP requests. It


runs inside a Servlet container.

Welcome To VCLIENT WORLD


280

• A Servlet is part of a Java web application.  A Servlet container


may run multiple web applications at the same time, each having
multiple servlets running inside.

Welcome To VCLIENT WORLD


Servlet 281

• A Java web application can contain other components than


servlets.
• It can also contain Java Server Pages (JSP), images, text files,
documents, Web Services etc.

Welcome To VCLIENT WORLD


HTTP Request and Response 282

• The browser sends an HTTP request to the Java web server.  The
web server checks if the request is for a servlet. If it is, the
servlet container is passed the request.
• The servlet container will then find out which servlet the request
is for, and activate that servlet.
• The servlet is activated by calling the Servlet.service()method.
• Once the servlet has been activated via the service() method the
servlet processes the request, and generates a response. The
response is then sent back to the browser.
Welcome To VCLIENT WORLD
Servlet Containers 283

• Java servlet containers are usually running inside a Java web


server.
• Example: Tomcat, GlasssFish, Jboss etc.
• Container:
• It provides runtime environment for JavaEE (j2ee) applications.
• It performs many operations that are given below:
• Life Cycle Management
• Multithreaded support
• Security etc.

Welcome To VCLIENT WORLD


Server 284

• Server:
• It is a running program or software that provides services.
•  Two types
•  Web Server:
• Web server contains only web or servlet container. It can be used for servlet, jsp,
struts, jsf etc. It can't be used for EJB.
• Example of Web Servers are: Apache Tomcat and Resin.
•  Application Server:
• Application server contains Web and EJB containers. It can be used for servlet, jsp,
struts, jsf, ejb etc.
• Ex: Jboss, Glassfish, Weblogic, Websphere
Welcome To VCLIENT WORLD
Content Type 285
• Content Type:
• Content Type is also known as MIME (Multipurpose internet Mail Extension) Type.
• It is a HTTP header that provides the description about what are you sending to the
browser.
• text/html
• text/plain
• application/msword
• application/vnd.ms-excel
• application/jar
• application/pdf
• application/octet-stream
• application/x-zip
• images/jpeg
• video/quicktime
Welcome To VCLIENT WORLD
Types of Servlet 286

• Generic Servlet:
• It is in javax.servlet.GenericServlet package
• It is protocol independent.
•  HTTP Servlet
• It is in javax.servlet.HTTPServlet package
• Built-in HTTP protocol support.

Welcome To VCLIENT WORLD


Types of Servlet 287

Generic Servlet HTTP Servlet


Package: javax.servlet Package: javax.servlet.http

It is protocol independent servlet It is protocol dependent


specifically
only HTTP protocol
requestresponse handle.
It uses service() method for It uses methods like doPost(),
handling request-response. doGet()
Welcome To VCLIENT WORLD
Servlet life cycle 288

• Managed by :____________.
• Each servlet instance is loaded once.
• Each execution happens in a separate thread
• Three methods:
• init() : call only once to initialize servlet.
• service() : Call for every request.
• destroy() : call only once
•  Method service() is invoked every time a request comes it. It spawns
off threads to perform doGet or doPost based on the method invoked.
Welcome To VCLIENT WORLD
Servlet life cycle 289

1. Load Servlet Class.


2. Create Instance of Servlet.
3. Call the servlets init() method.
4. Call the servlets service() method.
5. Call the servlets destroy() method.
 Note: Step 1,2,3 executed only once when servlet is initially loaded. By
default servlet is not loaded until first request is received for it.
 Step 4 executed ‘N’-times whenever http request comes
 Step 5 executed to destroy servlet means unload servlet class
Welcome To VCLIENT WORLD
Servlet life cycle 290

Welcome To VCLIENT WORLD


291

Welcome To VCLIENT WORLD


Servlet API 292

• Servlet API consists of two important packages that encapsulates


all the important classes and interface, namely :
•  javax.servlet
•  javax.servlet.http
•  javax.servlet and javax.servlet.http packages represent
interfaces and classes for servlet API.

Welcome To VCLIENT WORLD


Servlet Interface: javax.servlet 293

Interfaces Description
Servlet Declare life cycle methods for servlet. To implement
this interface we have to extends GenericServlet or
HttpServlet classes.

ServletConfig Helps servlet to get initialization parameter means


startup information, basic information about servlet.

ServletContext Allows servlet to log events and access information


about their environment

ServletRequest Used to read data from client


ServletResponse Used to sent data to client
Welcome To VCLIENT WORLD
Servlet Classes: javax.servlet 294

Classes Description
GenericServlet Used to create servlet (Protocol independent)

ServletInputStream Provides an input stream for reading requests


from client.
ServletOutputStream This class supports an output stream for writing
responses to a client

ServletException For handling exception: Error Occurred

UnavailableException For handling exception: generate when servlet


not available
Welcome To VCLIENT WORLD
Servlet Interface: javax.servlet.http 295

Classes Description
HttpServlet Used to create http servlet (Protocol
dependent)
HttpServletRequest It enables servlets to read data from
an HTTP request
HttpServletResponse It enables servlets to write data to an
HTTP response
HttpSession It allows to read and write session
data.

Cookie Cookie class allows state information


to be stored on a client machine

Welcome To VCLIENT WORLD


296

Welcome To VCLIENT WORLD


GenericServlet class 297

• It implements Servlet, ServletConfig and Serializable interfaces.


•  It provides the implementation of all the methods of these
interfaces except the service method(You have to write code in
your servlet class for this method).
•  GenericServlet class can handle any type of request so it is
protocol-independent.

Welcome To VCLIENT WORLD


ServletConfig interface 298

• Object of ServletConfig created by the web container for each servlet.


•  This object can be used to get configuration information from web.xml file.
•  Advantage: No need to edit the servlet file if information is modified from the
web.xml file.
• public String getInitParameter(String name):
• Returns the parameter value for the specified parameter name.
•  public Enumeration getInitParameterNames():
• Returns an enumeration of all the initialization parameter names.
•  public String getServletName():Returns the name of the servlet.
•  public ServletContext getServletContext():Returns an object of ServletContext.
Welcome To VCLIENT WORLD
ServletConfig interface 299

Welcome To VCLIENT WORLD


ServletContext interface 300

• An object of ServletContext is created by the web container at


time of deploying the project (web application).
•  This object can be used to get configuration information from
web.xml file.
•  There is only one ServletContext object per web application.

Welcome To VCLIENT WORLD


ServletContext interface 301

• If any information is shared to many servlet, it is better to provide


it from the web.xml file using the element.
•  Usage:
•  The object of ServletContext provides an interface between the container
and servlet.
•  The ServletContext object can be used to get configuration information
from the web.xml file.
•  The ServletContext object can be used to set, get or remove attribute from
the web.xml file.
•  The ServletContext object can be used to provide inter-application
communication.
Welcome To VCLIENT WORLD
ServletContext interface 302

•<context-param>

• <param-name>dname</param-name>

• <param-value> sun.jdbc.odbc.JdbcOdbcDriver</param-value>
• </context-param>

Welcome To VCLIENT WORLD


ServletConfig Vs ServletContext 303

Config Context
One object per servlet Object is global to entire web application

Object is created when servlet class is Object is created when web application
loaded deployed
It destroy when servlet is destroyed or It will destroyed when web application is
upload the class. un-deployed or removed.

Config object is public to particular It can share information between the


servlet only. servlet
Welcome To VCLIENT WORLD
HttpServlet 304

• It extends GenericServlet class and implements Servlet,


ServletConfig and Serializable interface.
•  It provides http specific methods such as doGet, doPost,
doHead, doTrace etc.

Welcome To VCLIENT WORLD


305

Welcome To VCLIENT WORLD


Implementation 306

• A Java Servlet is just an ordinary Java class which implements the


interface
•  javax.servlet.Servlet;
• The easiest way to implement this interface is to extend either
the class GenericServlet or HttpServlet.
• When an HTTP request arrives at the web server, targeted for your
Servlet, the web server calls your Servlet's service() method.
• The service() method then reads the request, and generates a
esponse which is sent back to the client (e.g. a browser).
Welcome To VCLIENT WORLD
307

Welcome To VCLIENT WORLD


Implementation:HTTP 308

• The javax.servlet.http.HttpServlet class is a slightly more


advanced base class than the GenericServlet
• The HttpServlet class reads the HTTP request, and determines if
the request is an HTTP GET, POST, PUT, DELETE, HEAD etc. and
calls one the corresponding method.

Welcome To VCLIENT WORLD


309

Welcome To VCLIENT WORLD


HttpRequest: Interface 310

• This interface present in javax.servlet.http.HttpRequest

• The purpose of the HttpRequest object is to represent the HTTP


request a browser sends to your web application.
• Thus, anything the browser may send, is accessible via the
HttpRequest
• We can read initialization parameters also using
HttpServletRequest
Welcome To VCLIENT WORLD object with getInitParameter method.
HttpRequest: Parameters 311

• Also we can use same (following) code if request parameters is send through body part
of the Http request.

•  If the browser sends an HTTP GET request, the parameters are included in the query
string in the URL.
•  If the browser sends an HTTP POST request, the parameters are included in the body
part of the HTTP request.h body part of the Http request.
Welcome To VCLIENT WORLD
HttpRequest: Header 312

• The request headers are name, value pairs sent by the browser along
with the HTTP request.
•  The request headers contain information about e.g. what browser
software is being used, what file types the browser is capable of
receiving etc. In short, at lot of meta data around the HTTP request

• Above example reads the Content-Length header sent by the browser.


Welcome To VCLIENT WORLD
HttpRequest: InputStream 313

• If the browser sends an HTTP POST request, request parameters


and other potential data is sent to the server in the HTTP request
body.
•  If does not have sent data in parameters means may be binary
data, that time we will require InputStream for accessing request
body come from client.
•  InputStream requestBodyInput = request.getInputStream();
•  NOTE: You will have to call this method before calling any
getParameter() method
Welcome To VCLIENT WORLD
HttpRequest: Session 314

• It is possible to obtain the session object from the HttpRequest


object too.
•  The session object can hold information about a given user,
between requests.
•  So, if you set an object into the session object during one
request, it will be available for you to read during any subsequent
requests within the same session time scope.

Welcome To VCLIENT WORLD


HttpResponse: Interface 315

• This interface is present in java.servlet.http package.


•  The purpose of the HttpResponse object is to represent the
HTTP response of web application sends back to the browser.

Welcome To VCLIENT WORLD

You might also like