Prog 732
Prog 732
Faculty of
Information Technology
PROGRAMMING 732
Year 3 Semester 6
TABLE OF CONTENTS
1. Welcome 4
2. Title of Modules 4
3. Purpose of Module 4
4. Learning Outcomes 5
5. Method of Study 5
7. Notices 5
4. Servlets 55-75
3
SECTION A: PREFACE
1. WELCOME
This section of the study guide is intended to orientate you to the module before the commencement of
formal lectures.
The following lectures will focus on the common study units described:
SECTION A: WELCOME & ORIENTATION
Study unit 3: Distribution and Orientation of JAVA 732 Learner Guides, Lecture 3
Textbooks and Prescribed Materials
Study unit 4: Discussion on the Objectives and Outcomes of JAVA 732 Lecture 4
Review and Recap of Study units 1-4 and special guideline to late registrations
2. TITLE OF MODULES, COURSE, CODE, NQF LEVEL, CREDITS & MODE OF DELIVERY
2nd Semester
4
3. PURPOSE OF MODULE
3.1 JAVA
Learners will be guided through the process of being able to solve real life problems sequentially as the
dynamics of this programming language will be put into play. Each and every chapter has a correlation
with the next chapter.
4. LEARNING OUTCOMES
On completion of these modules, learners should have a fundamental practical and theoretical knowledge
of:
5. METHOD OF STUDY
Only the key sections that have to be studied are indicated under each topic in this study guide are
expected to have a thorough working knowledge of the prescribed text book. These form the basis for
tests, assignments and examinations. To be able to do the activities and assignments for this module, and
to achieve the learning outcomes and ultimately to be successful in the tests and examination, you will
need an in-depth understanding of the the content of these sections in the learning guide and the
prescribed books. In order to master the learning material, you must accept responsibility for your own
studies. Learning is not the same as memorising. You are expected to show that you understand and are
able to apply the information. Use will also be made of lectures, tutorials, case studies and group
discussions to present this module.
Learners must refer to the notice boards on their respective campuses for details of the lecture and
tutorial time tables. The lecturer assigned to the module will also inform you of the number of lecture
periods and tutorials allocated to a particular module. Prior preparation is required for each lecture and
tutorial. Learners are encouraged to actively participate in lectures and tutorials in order to ensure success
in tests, assignments and examinations.
7. NOTICES
All information pertaining to these modules such as tests dates, lecture and tutorial time tables,
assignments, examinations etc will be displayed on the notice board located on your campus. Learners
5
must check the notice board on a daily basis. Should you require any clarity, please consult your lecturer,
or programme manager, or administrator on your respective campus.
8.1.1. JAVA Actually by Khalid A.Mughal, Torill Hamre, Rolf W.Rasmussem, 2008, ISBN 978-1-84480-
933-2
8.1.2. JAVA How to Program by Deitel, 6th Edition, 2005, ISBN 0-13-129014-2
The purchasing of prescribed books is for the learners own account and is compulsory for all learners. This
guide will have limited value if not accompanied by the prescribed text books.
8.2.1. Cay S. Horstmann, Gary Conell- Core Java 2 Volume 1- Fundamentals, 5th Edn. PHI,
2000.
8.2.2. P.Naughton and H.Schildt-Java 2 (The Complete Reference)-Third Edition, TMH, 1999.
8.2.3. K.Arnold and J.Gosling-The Java Programming Language- Second edition, Addison Wesley, 1996.
NB: Learners please note that there will be a limited number of copies of the recommended texts and
reference material that will be made available at your campus library. Learners are advised to make copies
or take notes of the relevant information, as the content matter is examinable.
8.4.1. Each campus keeps a limited quantity of the recommended reading titles and a larger variety of
similar titles which you may borrow. Please note that learners are required to purchase the
prescribed materials.
6
8.4.2. Arrangements have been made with municipal, state and other libraries to stock our
recommended reading and similar titles. You may use these on their premises or borrow them if
available. It is your responsibility to safe keep all library books.
8.4.3. RGI has also allocated one library period per week as to assist you with your formal research
under professional supervision.
8.4.4. The computers laboratories, when not in use for academic purposes, may also be used for research
purposes. Booking is essential for all electronic library usage.
9. ASSESSMENT
Final Assessment for this module will comprise two Continuous Assessment tests, an assignment and an
examination. Your lecturer will inform you of the dates, times and the venues for each of these. You may
also refer to the notice board on your campus or the Academic Calendar which is displayed in all lecture
rooms.
9.2. Assignment
There is one compulsory assignment for each module in each semester. Your lecturer will inform you of
the Assessment questions at the commencement of this module.
9.3. Examination
There is one two hour examination for each module. Make sure that you diarize the correct date, time
and venue. The examinations department will notify you of your results once all administrative matters
are cleared and fees are paid up.
The examination may consist of multiple choice questions, short questions and essay type questions.
This requires you to be thoroughly prepared as all the content matter of lectures, tutorials, all
references to the prescribed text and any other additional documentation/reference materials is
examinable in both your tests and the examinations.
The examination department will make available to you the details of the examination (date, time and
venue) in due course. You must be seated in the examination room 15 minutes before the commencement
of the examination. If you arrive late, you will not be allowed any extra time. Your learner registration
card must be in your possession at all times.
Understanding information
Grasp meaning
Translate knowledge into new context
Interpret facts, compare, contrast
Comprehension Order, group, infer causes predict
consequences
Question Cues
summarize, describe, interpret, contrast, predict, associate, distinguish,
estimate, differentiate, discuss, extend
Use information
Use methods, concepts, theories in new situations
Solve problems using required skills or knowledge
Application Questions Cues
apply, demonstrate, calculate, complete, illustrate, show, solve, examine,
modify, relate, change, classify, experiment, discover
8
Use old ideas to create new ones
Generalize from given facts
Relate knowledge from several areas
Synthesis Predict, draw conclusions
Question Cues
combine, integrate, modify, rearrange, substitute, plan, create, design, invent,
what if?, compose, formulate, prepare, generalize, rewrite
ASSESSMENT CRITERIA
(NB: The allocation of marks below may not apply to certain modules like EUC and Accounting) A.
Content- Relevance.
9
Mark Examiner’s Moderator’s
Question Number Remarks
Allocation Mark Marks
1
2
3
4
5
6
7
8
9
10
Sub Total 70 Marks
B. Research (A minimum of “TEN SOURCES” is recommended)
Library, EBSCO, Emerald Journals, Internet, Newspapers, Journals, Text Books, Harvard method of
referencing
Sub Total 15 Marks
C. Presentation
Introduction, Body, Conclusion, Paragraphs, Neatness, Integration, Grammar / Spelling, Margins on
every page, Page Numbering, Diagrams, Tables, Graphs, Bibliography
Sub Total 15 Marks
Grand Total 100Marks
NB: All Assignments are compulsory as it forms part of continuous assessment that goes towards the
final mark.
11. WORK READINESS PROGRAMME (WRP)
In order to prepare learners for the world of work, a series of interventions over and above the formal
curriculum, are concurrently implemented to prepare learners.
These include:
• Soft skills
• Employment skills
• Life skills
• End –User Computing (if not included in your curriculum)
The illustration below outlines some of the key concepts for Work Readiness that will be included in your
timetable.
10
SOFT SKILLS LIFE SKILLS
Time Management Manage Personal Finance
Working in Teams Driving Skills
Problem Solving Skills Basic Life Support & First
Attitude & Goal Setting Aid
Etiquettes & Ethics Entrepreneurial skills
Communication Skills Counselling skills
WORK
READINESS
PROGRAMM
EMPLOYMENT SKILLS
CV Writing
Interview Skills
Presentation Skills
Employer / Employee
Relationship
End User Computing
Email & E-Commerce
Spread Sheets
Data base
Presentation
Office Word
It is in your interest to attend these workshops, complete the Work Readiness Log Book and prepare for
the Working World.
Work Integrated Learning forms a core component of the curriculum for the completion of this
programme. All modules making of the Diploma/BSc in Information Technology will be assessed in an
integrated manner towards the end of the programme or after completion of all other modules.
11
The partners in Work Readiness Programme (WRP) include:
12
SECTION B
Registered with the Department of Higher Education as a Private Higher Education Institution under the Higher Education Act, 1997.
Registration Certificate No. 2000/HE07/008
LEARNER GUIDE
MODULE: JAVA 732 (2ND SEMESTER)
TOPIC 4 : SERVLETS
13
SECTION B: JAVA 732 (2ND SEMESTER) BSC IN IT
TOPIC 4: SERVLETS
14
TOPIC 1
__________________________________________________________________
LEARNING OUTCOMES
INTRODUCTION
You are already familiar with AWT (Abstract Window Toolkit) classes that help to build user interfaces.
Let’s look at a glance to its alternative called Swings. A set of classes that provides more powerful and
flexible components than AWT are called Swings Swing provides several citing components like tabbed
panes, Scroll panes, tree and tables in addition to the buttons, check boxes, and labels provided by AWT.
Swing components are written entirely in JAVA and, therefore, are platformindependent. Such
components are also called lightweight components. There is a substantial number of classes and
interfaces in the swing packages. We will provide an overview to just a few in this unit. You have to further
explore swings on your own.
15
(j) JRadio Button: The swing version of radio button.
(k) JScroll pane: Encapsulates a scroll bar window.
(l) JTabbed Pane: Encapsulates a tabbed window.
(m) JTable: Encapsulates a table-based control. (n) JText field: The swing version of a text field.
(o) JTree: Encapsulates a tree-based control.
All swing-related classes are contained in javax·swing and its sub packages like javax.swing.tree.
1.1.4 Panel
The Panel class is a concrete subclass of Container. It doesn’t add any new methods; it simply implements
Container. A Panel may be thought of as a recursively nestable, concrete screen component. Panel is the
superclass for Applet. When screen output is directed to an applet, it is drawn on the surface of Panel
object. In essence, a Panel is a window that does not contain a title bar, menu bar, or border. This is why
you don’t see these items when an applet is run inside a browser. When you run an applet using an applet
viewer, the applet viewer provides the title and border. Other components can be added to a Panel object
by its add( ) method (inherited from Container). Once these components have been added, you can
position and resize them manually using the setLocation( ), setSize( ), or setBounds( ) methods defined by
component.
1.1.5 Windows
The Window class creates top-level windows. A top level window is not contained within any other object;
it sits directly on the desktop. Generally, you won’t create Window objects directly. Instead, you will use
a subclass of Window called Frame, described next.
1.1.6 Frame
Frame encapsulates what is commonly thought of as a .window. It is a subclass of Window and has a title
bar, menu bar, borders, and resizing corners. If you create a Frame object from within an applet, it will
contain a warning message, such as .Java Applet Window,. to the user that an applet window has been
created. This message warns users that the window they see was started by an applet and not by software
running on their computer. (An applet that could masquerade as a hostbased application could be used
to obtained passwords and other sensitive information without the user’s knowledge). When a Frame
window is created by a program rather than an applet, a normal window is created.
16
1.1.7 Canvas
Although it is not part of the hierarchy for applet or frame windows, there is one other type of window
that you will find valuable: Canvas. Canvas encapsulates a blank window upon which you can draw. Refer
to Fig 1.1
1.2.1 JApplet
Japplet class is the fundamental to the swing. It extends applet class. It is the superclass of applets that
uses swings. Japplet supports those functionalities that are not found in Applet. One important difference
between Applet and Japplet is that while adding a component to an instance of Japplet, add( ) method of
the Applet should not be invoked. Instead, add( ) for the content pane of the Japplet object should be
called. The content pane can be obtained with the method shown below:
Container getcontentpane ( ) To add a component to the content pane, the add( ) method can be used as
follows:
Void add (comp)
17
The first form of constructor uses the image in the file named filename and the second form of constructor
uses the image in the resource identified by url. The Icon interface that declares the methods
implemented by the Image Icon class are as follows:
(a) int get Icon Height ( ) : Returns the icon.s height in pixels.
(b) int get Icon Width ( ) : Returns the width of the icon in pixels.
(c) Void paint Icon (component comp, Graphics g, int x, int y):
Paints the icon at position x, y on the graphics context g·Comp provides the additional information about
the paint operation. Instances of the Jlabel class, which extends Jcomponent are the swing labels. It can
display text and/or an icon. Some of its constructors are as follows:
Jlabel(Icon i)
Label (String s)
Jlabel (sring s, Icon i, int align)
Here s and I are the text and icon used for the label. The align attribute is LEFT, RIGHT, CENTRE, LEADING
or TRAILING. Swing constants interface defines these constants. To read icon and label associated with
the label, following methods are used:
Icon getIcon( )
String getText ( )
Void setIcon (Icon i)
Void setText (String s)
Let’s consider an example to create and display a label containing both an icon and a string:
Import java.awt.*;
Import javax.swing.*;
/* < applet code = “Jlabel Demo” width=250
height=200><lapplet*/
Public class Jlabel Demo extends Japplet
{
public void init ( )
{ // Get Context pane
container content Pane=getContentpane ( );
// Create an icon
ImageIcon ii = New ImageIcon (“Italy.gif”);
// Create a label
Jlabel jl = new Jlabel (“Italy, ii,
Jlabel.RIGHT);
// Add label to the content pane
contentPane.add (jl);
}
}
18
1.2.3 TextFields
JtextComponent class, which extends Jcomponent, encapsulats the swing textfield. The functionality
common to swing text components is provided by it. Jtextfield is one of its subclasses, which allows you
to edit one line of text. Some of its constructors are as follows:
JTextField ( )
JTextField (int cols) (Cols is the number of columns)
JText Field (string s,int cols)- s is the string to be presented)
JTextField (sring s)
Import java.awt.*;
Import javax.swing.*;
/*<applet code = “JtextFieldDemo” width = 250 height = 507
</applet> */
public class JtextFieldDemo extends Japplet
{
JTextField jtf;
Public void init ( )
{ // get content pane container contentPane =
get contentpane ( ); contentPane .
setlayout(new flowlayout ( ));
//Add text field to contentPane Jtf
= new JTextField (15);
contentpane·add(jtf);
} }
1.2.4 Buttons
Some features that are not found in the Button class defined by AWT are provided by the swing buttons.
For example, an icon can be associated with a swing button. Swing buttons are subclasses of the Abstract
Button class, which extends JComponent. The methods contained in the Abstract Button Class are as
under:
Here di, pi, si and ri are the icons to be used for these different conditions. The text associated with a
button can be read are written via the following methods:
String getText ( )
Void setText (string s)
Where s is the text to be associated with the button. Concrete subclasses of AbstractButton generate
action events when they are pressed. The methods used by listeners to register and unregister for these
events are:
19
Void addActionlistener (Actionlistener al)
Void removeActionlistener (Actionlistener al)
JButton(Icon i)
JButton(String s)
JButton (String s, Icon i)
Where s and I are the string and icon used for the button.
1.2.6 CheckBoxes
A concrete implementation of AbstractButton is the JcheckBox class. It provides the functionality of a
check box. Its constructors are:
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)
Where i is the icon for the button, s specifies the text. If state is true, the text box is initially selected.
Otherwise, it is not. To change the state of the checkbox, the following method is used:
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)
20
Where I is the icon for the button, the text is specified by s. If state is true, the button is initially selected.
Otherwise, it is not. The ButtonGroup class is instantiated to create a button group. Its default constructor
is involved for this purpose. The method used to add elements to the button group is:
Where ab is a reference to the button to be added to the group.Radio button presses generate action
events that are handled by actionPerformed (). The getActionCommand ( ) method gets the text that is
associated with a radio button and uses it to set the text field.
JcomboBox ( )
JcomboBox (Vector v)
Where v is a vector that initializes the combo box. Items can be added to the list of choices via the addItem
( ) method, whose signature is shown here:
21
JScrollPane (Component comp)
JScrollPane (int vsb, int hsb)
JScrollPane (Component comp, int vsb, int hsb)
Where comp is the component to be added to the scroll pane, vsb and hsb are int constants that define
when vertical and horizontal scroll bars for this scroll pane are shown. These constants are defined by the
ScrollPaneConstants interface. The steps that you should follow to use a scroll pane in an applet:
1.2.11 Trees
A tree is a component that presents a hierarchical view of data. A user has the ability to expand or collapse
individual subtrees in this display. Trees are implemented in swing by the Jtreeclass, which extends
Jcomponent. Some of its constructors are shown here:
JTree(Hashtable ht)
JTree ( Object obj [])
JTree (TreeNode tn)
JTree (Vector v)
The first form creates a tree in which each element of the hash table ht is a child node. Each element of
the array obj is a child node in the second form. The tree node tn is the root of the tree in the third form.
Finally, the last form uses the elements of vector v as child nodes.
1.2.12 Textfields
The Swing text fields 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, of its subclasses
is JtextField, which allows you to edit oneline of text. Some of its constructors are shown here:
JTextField( )
JTextField (int cols)
JTextField (String s, int cols)
JTextField (String s)
Here, s is the string to be presented and cols is the number of column in the text field. The following
example illustrates how to create a text field. The applet begins by getting its content pane, and then a
flow layout is assigned as its layout manager. Next a JTextField object is created and is added to the
content pane.
Import java.awt.*;
Import javax.swing.*;
/*
<applet codes = “JtextFieldDemo” width = 300 height
= 50>
</applet> */
22
public class JtextFieldDemo extends Japplet {
JTextField ( ) ; public void init( ) {
//Get content pane
Container content Pane, Document pane ();
Content pane.setLayout (new FlowLayout ());
//Add text field content pane jtf
= new JTextField (15);
content pane.odd(jtf);
1.2.13 TextArea
Sometimes a single line of text input is not enough for a given task. To handle these situations, the AWT
includes a simple multiline editor called TextArea. Following are the constructors for TextArea.
TextArea()
TextArea(int numLines, int numChars)
TextArea(String str)
TextArea(String str, int numLines, int numChars)
TexArea(String str, int numLines, int numChars, int sBars)
Here, numLines specifies the height, in lines, of the text area, and numChars specifies its width, in
characters. Initial text can be specified by str. In the fifth form you can specify the scroll bars that you want
the control to have sBars must be one of these values:
SCROLLBARS_BOTH SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY SCROLLBARS_VERTICAL_ONLY
TextArea is subclass of TextComponent. Therefore, it supports the getText(), set Text(), getSelectedText(),
select(), isEditable(), and setEditable() method described in the preceding section. TextArea adds the
following methods:
23
The append( ) method appends the string specified by str to the end of the current text. insert( ) inserts
the string passed in str at the specified index. To replace text, call replaceRange(). It replaces the
characters from startIndex to endIndex-1, with the replacement text passed in str.
Text areas are almost self-contained controls. You program incurs virtually no management overhead.
Text areas only generate got-focus and lost-focus events. Normally, your program simply obtains the
current text when it is needed.
Here, layoutObj is a reference to the desired layout manager. If you wish to disable the layout manager
and position components manually, pass null for layoutObj. If you do this, you will need to determine the
shape and position of each component manually, using the setBounds( ) method defined by Component
Normally, you will want to use a layout manger. Each layout manager keeps track of a list of components
that are stored by their names. The layout manager is notified each time you add a component to a
container. Whenever the container needs to be resized, the layout manager is consulted via its
minimumLayoutSize( ) and preferredLayoutSize( ) methods. Each component that is being managed by a
layout manager contains the getPreferredSize( ) and getMinimumSize( ) methods. These return the
preferred and minimum size required to display each component. The Layout manager will honor these
requests if at all possible, while maintaining the integrity of the layout policy. You may override these
methods for controls that you subclass. Default values are provided otherwise. Java has several
predefined LayoutManger classes, which are described next. You can use the layout manager that best
fits your application.
1.2.15 FlowLayout
FlowLayout is the default layout manager. This is the layout manager that the preceding examples have
used. FlowLayout implements a simple layout style, which is similar to how words flow in text editor.
Components are laid out from the upper-left corner, left to right and top to bottom. When no more
components fit on a line, the next one appears on the next line. A small space is left between each
component, above and below, as well as left and right. Here are the constructors for
24
FlowLayout.
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
The first form creates the default layout, which centers components and leaves five pixels of space
between each component. The second form lets you specify how each line is aligned. Valid values for how
are follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
These values specify left, center, and right alignment, respectively. The third form allows you to specify
the horizontal and vertical space left between components in horz nad vert, respectively.Here is a version
of the CheckboxDemo applet shown earlier in this unit, modified so that it used left-aligned flow layout.
//Use left-aligned flow Layout()
Import java.awt.*;
Import java.awt.event.*;
Import java.applet.*;
/*
<applet code = “FlowLayoutDemo” width = 250
height = 200>
</applet>
*/
public class FlowLayoutDemo extends Applet implements itemListener
{
String msg = “ “;
Checkbox Wind98, winNT, solaris, mac;
Public void init()
{
//set left-aligned flow layout setLayout (new
FlowLayout (FlowLayout.LEFT)); win98 = new
Checkbox (“windows 98”), null,true); winNT = New
Checkbox (“Windows NT/2000”); solaris = new
Checkbox (“Solaris”); mac = new Checkbox
(“MacOS”); add (Win98); add (winIT); add
(solaris); add (mac);
//register to receive item events
Win98.addItemListener (this);
WinNT.addItemListener (this);
Solaris.addItmeListener (this);
Mac.addItemListners (this);
}
//Repaint when status of a check box changes public
void itemStateChanged (ItemEvent ie)
{
repaint ();
}
25
//Display current state of the check boxes.
Public void paint (Graphics g)
{
Msg = “Current state:”;
g.drawstring (msg, 6, 80); msg =
“Windows 98: “+Win98.getState();
g.drawstring(msg, 6, 100);
msg = “Windows NT/2000;” +winNT.getState();
g.drawstring (msg, 6, 120); msg =
“Solaris:” + Solaris.getState();
g.drawstring (msg, 6, 140);
msg = “Mac: “ + mac.getState();
g.drawstring (msg, 6, 160);
}
}
Following is sample output generated by the FlowLayoutDemo applet (Figure 1.3).
Figure 1.3
BorderLayout()
BorderLayout(int horz, int vert)
26
Programming The first form creates a default border layout. The second allows you to specify the
horizontal and vertical space left between components in horz and vert, respectively. BorderLayout
defines the following constants the specify the regions:
BorderLayout.CENTER BorderLayout.SOUTH
BorderLayout.EAST BorderLayout.WEST
BorderLayout.NORTH
When adding components, you will use these constants with the following form of add(), which is defined
by Container.
Here, compObj is the component to be added, and region specifies where the component will be added.
Here is an example of a BorderLayout with a component in each layout area:
//Demonstrate
BorderLayout import
java.awt.*; import
java.applet.*; import
java.until.*;
/*
<applet code = “BorderLayoutDemo” width = 400 height
= 200>
</applet> */
public class BorderLayoutDemo extends Applet
{
public void init()
{ setLayout (new BorderLayout ());
add(new Button(“this is across the top”);
BorderLayout.NORTH);
Add(new Label (“The footer message might go here,”);
BorderLayout.SOUTH);
Add(new Button(“Right”), BorderLayout.EAST);
Add(new Button(“Left”), BorderLayout.WEST);
String msg = “the reasonable man adapts” +
“himself to the world;\n” +
“the unreasonable one persists in “ +
“trying to adapt the world to himself.\n” +
“Therefore all progress depends” +
“on the unreasonable man.\n\n” + “George
pernard shaw \n\n:;
add(new TextArea(msg), BorderLayout.CENTER);
} }
27
Figure 1.4
GridLayout()
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)
The first form creates a single column grid layout. The second form creates a grid layout with the specified
number of rows and columns. The third form allows you to specify the horizontal and vertical space left
between components in horz and vert, respectively. Either numRows ornumColumns can be zero.
Specifying numRows as zero allows for unlimited-length columns. Specifying numColumns as zero allows
for unlimited-length.
CardLayout()
CardLayout (int horz, int vert)
The first form creates a default card layout. The second form allows you to specify the horizontal and
vertical space left between components in horz and vert, respectively. Use of a card layout requires a bit
more work than the other layouts. The cards are typically held in an object of typePanel. This panel must
have CardLayout selected as its layout manager. The cards that form the deck are also typically objects of
type Panel. Thus, you must create a panel that contains the deck and a panel for each card in the deck.
Next, you add to the appropriate panel the components that form each card. You then add these panels
28
to the panel for which CardLayout is the layout manager. Finally, you add this panel to the main applet
panel. Once these steps are complete, you must provide some way for the user to select between cards.
One common approach is to include one push button for each card in the deck. When card panels are
added to a panel, they are usually given a name. Thus, most of the time, you will use this form of add()
when adding cards to a panel:
Void add(Component panelObj, Object name);
Here, name is a string that specifies the name of the card whose panel is specified by panelObj. After you
have created a deck, your program activates a card by calling one of the following methods defined by
CardLayout:
void first (Container deck)
void last (Container deck) void
next (Container deck) void
previous (Container deck)
void show (Container deck, String cardName)
Here, deck is a reference to the container (usually a panel) that holds the cards, and cardName is the name
of a card. Calling first() causes the first card in the deck to be shown. To show the last card, call last(). To
show the next card, call next(). To show the previous card, call previous(). Both next() and previous()
automatically cycle back to the top or bottom of the deck, respectively. The show() method displays the
card whose name is passed in cardName. The following example creates a tow-level card deck that allows
the user to select an operating system. Windows-based operating systems are displayed in one card.
Macintosh and Solaris are displayed in the other card.
//Demonstrate CardLayout
import java.awt.*; import
java.awt.event.*; import
java.applet.*;
/*
<applet code = “CardLayoutDemo” width = 300 height
= 100>
<applet> */
public class CardLayoutDemo extends Applet implements
ActionListener, MouseListener {
CheckBox Win98, WinNT, solaris, mac;
Panel osCards;
CardLayout cardLO;
Button Win, Other;
Public void init () {
Win = new Button(“Windows”);
Other = new Button(“Other”);
add(win); add(other);
cardLO = new CardLayout(); osCards
= new Panel();
osCards.SetLayout(CardLO); //set panel layout to
card layout
Win98 = new Checkbox (“Windows = 98”, null, true);
WinNT = new Checkbox (“Windows NT/2000”);
Solaris = new Checkbox(“Solaris”);
29
Mac = new Checkbox(“MacOS”); //add
Windows check boxes to a panel
panel winPan = new Panel();
WinPan.add(Win98);
WinPan.add(winNT);
//Add other OS check boxes to a panel
Panel otherPan = new Panel();
OtherPan.add(solaris);
OtherPan.add(mac);
//add panels to card deck panel
osCards.add(winPan, “windows”);
osCards.add(otherPan, “Other”); //add
cards to main applet panel
add(osCards);
//register to receive action events
Win.addActionListener(this);
Other.addActionListener (this);
//register mouse events
addMouseListener (this); //Cycle
through panels
public void mousePressed (MouseEvent me) { cardLO.next
(osCards);
}
//Provide empty implementations for the other MouseListener
Methods.
Public void mouseClicked (MouseEvent me) {
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
public void mouseReleased(MouseEvent me) {
}
public void actionPerformed(ActionEvent ae) { if
(ae.getSource() == Win) { cardLo.Show(osCards,
“Windows”);
} else
{
CardLo.show(osCards, “Other”);
}
}
}
Following is the output generated by the CardLayoutDemo applet. Each is activated by pushing is button.
You can also cycle through the cards by clicking the mouse (Figure 1.5).
30
Figure 1.5
TimerTask defines the methods shown in Table 9.1. Notice that run( ) is abstract, which means that it must
be overridden. The run( ) method, defined by the Runnable interface, contains the code that will be
executed. Thus, the easiest way to create a timer task is to extend TimerTask and override run( ).
Once a task has been created, it is scheduled for execution by an object of type Timer. The
constructors for Timer are shown here.
Timer( )
31
Timer(boolean DThread)
The first version creates a Timer object that runs as a normal thread. The second uses a daemon thread if
DThread is true. A daemon thread will execute only as long as the rest of the program continues to
execute. The methods defined by Timer are shown Table 1.2:
32
Figure 1.6: Sample output form the MenuDemo Applet
Here, parentWindow is the owner of the dialog box. If mode is true, the dialog box is modal. Otherwise, it
is modeless. The title of the dialog box can be passed in title. Generally, you will subclass Dialog, adding
the functionality required by your application.
1.2.21 Tables
A table is a component that displays rows and columns of data. You can drag the cursor on column
boundaries to resize column. You can also drag a column to a new position. Tables are implemented by
the JTable class, which extends Jcomponent. One of its constructors is shown here:
JTable(Object data[ ][ ], Object colHeads[ ])
Here, data is two-dimensional array information to be presented, and colHeads is a one-dimensional array
with the column headings. Here are the steps for using a table in an applet:
The following example illustrates how to create and use a table: The content pane of the JApplet object is
obtained and a border layout is assigned as its layout manager. A one-dimensional array of strings is
created for the column headings. This table has three columns. A twodimensional array of strings is
created for the table cells. You can see that each element in the array is an array of three strings. These
arrays are passed to the JTable constructor. The table is added to a scroll pane and then the scroll pane is
added to the content pane.
Import java.awt.*;
Import javax.swing.*;
/*
33
<applet code = “JtableDemo” width = 400 height
= 200>
</applet> */
public class JtableDemo extends JApplet
{
public void init()
{
//Get content pane
Container contentPlane = getContentPane();
//Set layout manager
ContentPane.setLayout (new BorderLayout());
//Initialize column headings
final String[] ColHeads = (“Name”, “Phone”,“Fax”);
//Initialize data final
object[][] data = {
{“Gail”, “4567”, “8675”
};
{“Ken”, “7566”, “5555” };
{“Viviane”, “5634”, “5887” };
{“Melanie”, “7345”, “9222” };
{“Anne”, “1237”, “4333” }; {John”,
“5656”, “3144” };
{“Matt”, “5672”, “2176” };
{“Claire”, “6741”, “4244” };
{“Erwin”, “9023”, “5159” };
{“Ellen”, “1134”, “5332” };
{“Jennifer”, “5689”, “1212” };
{“Ed”, “9030”, “1313” };
{“Helen”, “6751”, “1415” };
};
//Create the table
JTable table = new JTable (data, colHeads);
//Add tree to a scroll pane
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int
h =ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JscrollPane jsp = new JscrollPane(table, v,h);
//Add scroll pane to the content pane
ContentPane.add(jsp, BorderLayout.CENTER);
} }
Output from this applet is shown in Figure 1.7:
34
Figure 1.7
LEARNER ACTIVITY 1
_________________________________________________________ 1.
What are swings?
2. Describe various features of Swings.
3. Describe various Swing components.
4. Describe basic Swing containers.
5. Define Japplet.
6. Define Tables.
___________________________________________________________
35
TOPIC 2
__________________________________________________________________
LEARNING OUTCOMES
When two or more computers want to communicate with each other to share data or resources then the
communications among them can be done through networking.
36
Table 2.1 defines the standard TCP ports as follows:
Table 2.1
37
2.2 INET ADDRESS CLASS
As you know, when you want to establish a connection between two machines across the Internet or any
other kind of network, addresses are fundamental. The InetAddress class is used to convert the Domain
Name (or textual Internet address) of an Internet address into an object which represents the address.
The InetAddress class doesn’t have any constructors but it has three factory methods that can be used to
create instances of the InetAddress class. It is noted that according to Object Oriented Program, the term
factory applies to a class that can construct instances of that class without invoking constructors. The
instance of the class is constructed through static methods built into the class.
The getLocalHost() method returns the InetAddress object that represents the local host. The getByName
(String hostname) method takes the hostname as a parameterand returns the InetAddress object. The
getAllByName (String hostname) method returns an array of InetAddress objects that includes all the
addresses that a particular name (passed as a parameter to themethod) resolves to.
Program 1:
import java.net.*;
class uptecdemoInetAddress1
{
public static void main (String args[ ]) throws UnknownHostException
{
InetAddress idr;
idr = InetAddress.getLocalHost( );
System.out.println (idr);
}
}
38
The output produced by the program will be different from the one givenbelow :
tr 7comph/132 . 147 . 168 . 17
Program 2:
The following program displays the name and address of the machinewhose host name is given by the
user.
import java.io.*; import
java.net.*; class
DemoInetAddress2
{ public static void main (String args[ ])throws
UnknownHostException, IOException
{
InetAddress adr;
String host;
BufferedReader str = new BufferedReader
(new InputStreamReader (System.in));
System.out.print (“Enter the Machines | hostname:”);
host = str.readLine( );
adr = InetAddress.getByName (host);
System.out.println (adr);
}
}
BufferedReader and InputStreamReader are defined in the java.io package. The BufferedReader class
includes methods which allow you to read text lines from a character InputStream. Since the standard
input (System.in) is a byte stream, the Input StreamReader class converts the byte stream of the standard
input, System.in, into a character stream.The method readLine( ) allows you to read text lines from an
input stream. The output produced by this program is as follows (the output will vary according to the
input):
Enter the Machine.s host name : Machine1 Machine1/130. 130. 15. 24 Enter the Machine.s host
name : Uptec Uptec / 130. 130. 15. 25
InetAddress class also defines some non static methods which can be used on objects returned by the
factory methods (Table 2.2).
Table 2.2
39
2.2.2 Methods Purpose
String getHostName() Returns the string representation of the host name associated with the
InetAddressObject. byte[ ] getAddress() Returns an array of four bytes representing the numeric address
of the host.This array of bytes cannot be printed directly by caching them to int. They have to be copied
into an array of integers while ANDing with 255 to undo sign-extending. String toString( ) Returns a string
that consists of the host name and the IP Address, For example Uptec/130.130.15.25. This function can
be overridden. boolean equals(/InetAddress addr) Returns true if the invoking object has the same
Internet address as addr. Let us see an example which demonstrates the usage of the getAddress( )
method and overriding of the toString( ) method to display the Internet address.
Program 3:
import java.net.*; class
Uptec
{
static InetAddress adr;
byte[ ] numaddr;
byte[ ] numadr; String
Addrmsg;
Uptec( ) throws UnknownHostException
{ adr = InetAddress.getLocalHost( );
numadr = adr.getAddress( );
Addrmsg = adr.getHostName( ) +”/”;
}
public String toString( )
{ for (int i = 0; i < numadr.length; i++)
Addrmsg + = (Numadr[i] & 255) +”.”;
return “The local machine|’s address is :” +Addrmsg;
}
}
The java.net package provides two classes that allow you to create the two kinds of sockets. The classes
are Socket and Server Socket respectively. The Socket class, basically used to create client sockets, is
designed to connect to server sockets and initiate protocol exchanges.The Server Socket class, basically
used to create server sockets, is designed to be a listener, which waits for clients to Connect before doing
anything. When you create a Socket object, it implicitly establishes the connection between the client and
the server. The Socket class provides some constructors to create client sockets
40
Table 2.3
After you have created a socket, you can get the address and port details associated with the socket by
the use of the following methods (Table 2.4).
Table 2.4
Since TCP is a stream based protocol, every TCP socket is associated with input and output streams. It is
noted that Remember there should be two ports for all TCP connections, a port on the remote machine
and a port on the local machine, through which the client communicates. The local port number need not
be specified because the TCP/IP software allocates these ports dynamically. These ports are called
ephemeral ports because they exist only for the duration of a volatile client/server transaction. As
discussed earlier, Java defines another class that must be used to create server applications. The
ServerSocket class is used to create servers that listen for either local or remote client programs to connect
to them on standard ports
Table 2.5
Program 1:
For using TCP for a server program which sends the current data to the client upon its request and
terminates when the client wants to quit.
import java.io.*; import
java.net.*; import
java.util.*; class
TCPServer
{
public static void main (String args[ ])
{
ServerSocket server;
recSocket;
PrintWriter on;
BufferedReader i;
String msg;
server = new ServerSocket (8001); for
(; ;)
{
recSocket = Server.accept( );
i = new BufferedReader (new InputStreamReader
(recSocket.getInputStream( )));
on = new PrintWriter (new OutputStreamWriter
(recSocket.getOutputStream(
))); on.println (server); on
flush( ); msg = i.readline( );
if (msg.equals (“Date”))
msg = “Client asked for “+msg+” and the current date
is ”+ (new Date()).toString( ); else if (msg.equals
(“Quit”))
System.exit(1); else
msg = “Invalid Request”;
on.println (msg); on.flush(
);
i.close( ); on.close(
); recSocket.close(
);
}
} }
To write a Client Program:
Setp 1 : Create the Client Socket Connection.
Step 2 : Acquire read and write streams for the socket.
Step 3 : Use the streams according to the server.s protocol.
42
Step 4 : Close the streams.
Step 5 : Close the socket.
Table 2.6
43
DatagramPacket class does not provide the mechanism of sending and receiving datagrams. The
companion class DatagramSocket provides this functionality
Table 2.7.
Table 12.8.
2.4. NETWORK
Given the five classes, InetAddress, Socket, ServerSocket, DatagramSocket and DatagramPacket, you can
program any Internet protocol in existence. They also give you powerful low level control over Internet
connections.__ E V I E W QU E S T I O N S
___________________________________________________________
LEARNER ACTIVITY 2
1. What is networking?
2. Define the Networking Classes.
3. What is the Datagram Packet?
4. What is inetAddress Classes?
45
TOPIC 3
__________________________________________________________________
______
LEARNING OUTCOMES
INTRODUCTION
JDBC is not a derivative of Microsoft’s open Database Connectivity specification (ODBC). JDBC is written
entirely in java and ODBC is a C interface. While ODBC is usable by non C languages like Visual Basic, it has
the inherent development risks of C, like memory leaks. However, both JDBC and ODBC are based on the
X/oPen SQL command Level Interface (CLI). Having the same conceptual base allowes work on the API to
proceed quickly and makes acceptance and learning of the API easier. Sun provides a jdbcodbc bridge that
translates JDBC - ODBC. This implementation when done with native methods, is very small and efficient.
The JBDC API was first introduced with release 1.1. of the JDK. JDK 1.4 contains JDBC 3.0, which is
composed of the java.sql and javax.sql packages. JDBC provides application developers with a single API
that is uniform and database independent. The API provides a standard to write to, as well as a standard
that takes all of the various application designs into account. The API.s database independence is due to
a set of Java interfaces that are implemented by a driver. The driver takes care of translating the standard
JDBC calls into the specific calls required by the database it supports. The application is written once and
then moved to the various drivers. The application remains the same; the drivers change. Drivers may be
used to develop the middle tier of a multitier database design.
46
Figure 3.1: JDBC Database Designs
In addition to providing developers with a uniform and database independent framework, JDBC also
provides a means of allowing developers to retain the specific functionality that their database vendor
offers. JDBC drivers must support ANSI SQL- 2 Entry Level but JDBC allows developers to pass query strings
directly to the connected driver. These strings may or may not be ANSI SQL, or SQL at all. The user of these
strings is up to the underlying driver. (Of course, using this feature limits your freedom to change database
back ends.) Every Java client or J2EE application that uses JDBC must have at least one JDBC driver, and
each driver is specific to the type of DBMS used. A driver does not, however, need to be directly associated
with a database. JDBC is not a derivative of Microsoft’s Open Database Connectivity (ODBC) specification.
JDBC is written entirely in Java; ODBC is a C interface. Both JDBC and ODBC, however, are based on the
X/Open SQL Command Level Interface (CLI). JavaSoft provides a JDBCODBC bridge that translates JDBC to
ODBC. This implementation, done with native methods, is very small and efficient. The JDBCODBC bridge
is discussed later in the unit.
Fortunately, the application developer only needs to use the standard API interfaces to guarantee JDBC
compliance. The driver developer is responsible for developing code that interfaces to the database and
supports the JDBC application level calls. It is important, however, to understand the Driver layer, and
how some of the objects that are used at the Application layer are created by the driver. There are four
main interfaces that every driver layer must implement, and one class that bridges the Application and
Driver layers. The four interfaces are Driver, connection, Statement and ResultSet. The Driver interface
implementation is where the connection to the database is made. In most applications, the Driver is
accessed through the DriverManager class-providing one more layer of abstraction for the developer. The
Connection, Statement, and ResultSet interfaces are implemented by the driver vendor, but these
interfaces specify the methods that the application developer can use. They allow the developer to create
statements and retrieve results without having to think about where the objects are coming from or worry
about what specific driver the application will use. The following sections discuss the Driver and
Application layers in more detail.
The DriverManager Class is actually a utility class used to manage JDBC drivers. The class provides methods
to obtain a connection through a driver, register and deregister drivers, set up logging, and set login
timeouts for database access. The important DriveManager methods are listed below. Because they are
static, they may be referenced through the interface. SQL Exception is thrown if there is trouble with the
remote database.
a) Public Static Synchronized Connection getConnection (String url, properties info) throws
SQLException.
Attempts to return a reference to an object implemented from the Connection interface. The method
sweeps through a vector of stored Driver classes, passing the URL string and Properties object info to each
in turn. The first Driver class that returns a Connection is used, info are a reference to a Properties
48
container object of tags/value pairs typically username/password. The method allows several attempts to
make an authorized connection for each driver in the vector.
b) Public static synchronized Connection getConnection (String url) throws SQLException
Calls getConnection (url, info) with an empty Properties object (info). Public static synchronized
Connection getConnection (String url, String user, String password) Connectivity throws SQLException.
Creates a Properties object (info), stores the user and password strings into it, and then calls
getConnection (url, info).
Many J2EE servers support distributed transactions that involve multiple databases. For example, you
could run a SQL statement on a Connection from one DataSource for an Oracle database, and run a SQL
statement on a Connection from a DataSource for a SQL Server database. If your J2EE server supports
distributed transactions, you can specify that thosetwo SQL statements are in the same transaction, and
must commit or rollback together. JDBC 2.0 added an interface called XADataSource to allow JDBC drivers
to support distributed transactions. As with the ConnectionPoolData Source, you should not need to
directly use the DADataSource class. If your JDBC driver and J2EE server support distributed transactions,
they should use this interface behind the scenes. You don’t have to write any special code for this purpose.
49
portion of the connection interface definition follows. As usual, SQLException is thrown in case of trouble
with the remote database.
Connection conn;
Statement stmt;
conn = DriverManager.getConnection (url); Connectivity
stmt = c.createStatement ( );
This statement may be used to send SQL statements that return a single result set in a ResultSet object
reference. Statements that need to be called a number of times with slight variations may be executed
more efficiently using a PreparedStatement. The Connection interface is also used to create a
CallableStatement whose purpose is to execute stored procedures. Most of the time, the developer knows
the database schema before hand and creates the application based on the schema; however, JDBC
provides an interface that may be used to dynamically determine the schema of a database. The
Connection interface getMetaData ( ) method will return a DatabaseMetaData object. The instance of the
class that implements the interface provides information about the database as a whole, including access
information about tables and procedures, column names, data types, and so on. The implementation
details of DatabaseMetaData are dependent on the database vendor.s ability to return this type of
information.
50
3.4.3 The Statement Interface
A statement is the vehicle for sending SQL queries to the database and retrieving a set of results.
Statements can be SQL updates, inserts, deletes, or queries; statements may also create or drop tables.
The Statement interface provides a number of methods designed to ease the job of writing queries to the
database. The important Statement methods are listed below. As usual, SQLException is thrown if there
is a problem with the remote database.
g) ResultSet read.
Statement methods may or may not return a ResultSet object, depending on the Statement method used.
The executeUpdate ( ) method, for example, is used to execute SQL statements that do not expect a result
(except a row-count status); int rowCount;rowCount = stmt, executeUpdate (.DELETE FROM Customer
WHERE Custoer ID = .McG10233. .); SQL statements that return a single set of results can use the
executeQuery ( ) method. This method returns a single Result Set object. The object represents the row
information returned as a result of the query:
ResultSet results;
results = stmt.executeQuery (.SELECT * FROM Stock.);
51
SQL statements that execute stored procedures (or trigger a stored procedure) may return more than one
set of results. The execute ( ) method is a general-purpose method that can return either a single result
set or multiple result sets. The method returns a Boolean flag that is used to determine whether there are
more result sets. Because a result set could contain either data or the count of an operation that returns
a row count, the getResultSet 9 ), getMoreResults ( ), and getUpdateCount( ) methods are used. Here is
an example:
Parameters hold their current values until either a new setType method is called, or the method
clearParameters( ) is called for PreparedStatement object. In addition to the execute methods inherited
from Statement, PreparedStatement declares the setType methods listed in Table 3.1. Each method takes
two arguments a parameter index, and the primitive or class type, as shown in table 3.1.
53
Table 3.1: The Set Type Methods
54
cs.registerOutParameter(2, Types, FLOAT); cs.executeUpdate
();
float quote = cs.getFloat (2);
CallableStatement defines a set of get Type methods that convert the SQL types returned from the
database to Java types. These methods match the setType methods declared by Prepared Statement,
and are listed in Table 3.2
55
c) void close() throws SQLException
Normally a ResultSet is closed when another SQL statement is executed, but it may bedesirable to release
the resources earlier. As with the CallableStatement interface discussed earlier, the resulting data can be
read through getType () methods. Note, however, that values can be accessed either via volumn names
or column numbers; callable statements can use only column numbers. Recall that column numbers begin
at 1.
a) ResultSet.TYPE_SCROLL_INSENSITIVE
Creates a forward and backward scrollable ResultSet that will not reflect any changes to the database data
after the query data is returned.
b) ResultSet.TYPE_SCROLL_SENSITIVIES
Created a forward and backward scrollable ResultSet that will be updated if the database Connectivity
data changes even after the query data is returned. The resultSetConcurrency parameter can be one of
the following two values:
c) ResultSet.CONCUR_READ_ONLY
Creates an updatable ResultSet that allows updates insertions, and deletions, and backward scrollable
ResultSet:
Statement stmt;
stmt = conn.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,
56
ResultSet.CONCUR_READ_ONLY);
ResultSet results;
Results = stmt.executeQuery (“SELECT * FROM Stock”);
LEARNER ACTIVITY 3
___LLLLLO_________-_________ E V I E W QU E S T I O N S 1.
Define JDBC.
2. Describe JDBC/ODBC Bridge.
3. Describe the driver manager class.
4. Describe the connection Interface, Statement Interface and Resultset Interface.
5. Describe ResultSet Metadata Interface.
57
TOPIC 4
__________________________________________________________________
4. SERVLETS
__________________________________________________________________
LEARNING OUTCOMES
After studying this topic you should be able to understand:
• HTTP Servlets
• Servlet Life Cycle
• The Servlet API Packages
INTRODUCTION
One of the most essential technologies in J2EE is Servlets. Servlets provide the best mechanism for J2EE
applications to provide a web interface. This chapter about the essential concepts of developing servlets.
In 1993, messages sent is Hypertext Transfer Protocol (HTTP) format used by web servers were only a
minute portion of the traffic on the Internet. HTTP.S tremendous functionality led a rapid expansion in
both the number and capabilities of web server. Essentiality, it is web HTTP that made the world wide
web possible. Originally, a basic web server simply returned a text page when it got correctly formatted
request message; however it did not take the programmer long to discover that good things were possible
if some extra functionality was added, such an forms and graphics and capabilities. The Common Gateway
Interface (CGI) standard enables the user of a web browser to submit data from a web page to a sewer
for further processing programming with Java servlets and Java server pages builds on this universal
standard and makes it easier to me. To understand how this works, you must understand how a web
server processes. HTTP servlet Application programming Interface (API).
4.1 SERVLETS
A servlet is a Java component that can be plugged into a Java-enabled web server to provide custom
services. These services can include:
• New features
• Runtime changes to content
• Runtime changes to presentation
• New standard protocols (such as FTP)
• New custom protocols
Servlets are designed to work within a request/response processing model. In a request/response model,
a client sends a request message to a server and the server responds by sending back a reply message.
Requests can come in the form of an
• HTTP
• URL,
• FTP,
• URL,
or a custom protocol.
58
The request and the corresponding response reflect the state of the client and the server at the time of
the request. Normally, the state of the client/server connection cannot be maintained across different
request/response pairs. However, session information is maintainable with servlets through means to be
described later. The Java Servlet API includes several Java interfaces and fully defines the link between a
hosting server and servlets. The Servlet API is defined as an extension to the standard JDK. JDK extensions
are packaged under javax--the root of the Java extension library tree. The Java Servlet API contains the
following packages: Package javax.servlet
• Package javax.servlet.http
Servlets are a powerful addition to the Java environment. They are fast, safe, reliable, and 100% pure Java.
Because servlets plug into an existing server, they leverage a lot of existing code and technology. The
server handles the network connections, protocol negotiation, class loading, and more; all of this work
does not need to be replicated! And, because servlets are located at the middle tier, they are positioned
to add a lot of value and flexibility to a system. In this course you will learn about the Servlet API and you
will get a brief tour of the types of features servlets can implement.
59
any protocol that follows a request/response computing model can be implemented by a servlet. This
could include:
• SMTP
• POP
• FTP
Servlet support is currently available in several web servers, and will probably start appearing in other
types of application servers in the near future. You will use a web server to host the servlets in this class
and only deal with the HTTP protocol. Because HTTP is one of the most common protocols, and because
HTML can provide such a rich presentation of information, servlets probably contribute the most to
building HTTP based systems.
it would be detected by the web server as a request to perform an inline file include. While server side
includes are supported by most web servers, the SSI tags are not standardized.
Servlets are a great way to add server side include processing to a web server. With more and more web
servers supporting servlets, it would be possible to write a standard SSI processing servlet and use it on
different web servers.
60
Note that these servlets are not restricted to generating web pages; they can perform any other function,
such as storing and fetching database information, or opening a socket to another machine.
61
The most common way to run this utility is to move to the directory that contains your servlets and run
servletrunner from that location. However, that doesn't automatically configure the tool to load the
servlets from the current directory.
63
Sample Servlet
The code below implements a simple servlet that returns a static HTML page to a browser. This example
fully implements the Servlet interface.
import java.io.*; import
javax.servlet.*;
public class SampleServlet implements Servlet
{ private ServletConfig
config; public void init
(ServletConfig config)throws
ServletException
{ this.config =
config;
}
public void destroy() {} // do nothing
public ServletConfig getServletConfig()
{
return config;
}
public String getServletInfo()
{ return "A
Simple Servlet";
}
public void service (ServletRequest req,ServletResponse res)
throws ServletException, IOException
{ res.setContentType(
"text/html" ); PrintWriter out =
res.getWriter(); out.println(
"<html>" ); out.println( "<head>"
);
out.println( "<title>A Sample Servlet</title>"
); out.println( "</head>" ); out.println(
"<body>" );
out.println( "<h1>A Sample Servlet</h1>"
); out.println( "</body>" );
out.println( "</html>" ); out.close();
}
}
64
servlet class DatePrintServlet takes an initialization argument timezone, you would define the following
properties in a servlets.properties file:
servlet.dateprinter.code=DatePrinterServlet
servlet.dateprinter.timezone=PST
or this information could be supplied through a GUI administration tool. The timezone information would
be accessed by the servlet with the following code:
String timezone;
public void init(ServletConfig config) {
timeZone = config.getInitParameter("timezone");
}
An Enumeration of all initialization parameters is available to the servlet via the getInitParameterNames()
method.
65
}
The following Magercise shows you how to extract parameters from a service request.
66
4.1.18 Utility Classes
There are several utilities provided in the Servlet API. The first is the interface
javax.servlet.SingleThreadModel that can make it easier to write simple servlets. If a servlet implements
this marker interface, the hosting server knows that it should never call the servlet's service() method
while it is processing a request. That is, the server processes all service requests within a single thread.
While this makes it easier to write a servlet, this can impede performance. A full discussion of this issue is
located later in this course.
Two exception classes are included in the Servlet API. The exception javax.servlet.ServletException can be
used when there is a general failure in the servlet. This notifies the hosting server that there is a problem.
The exception javax.servlet.UnavailableException indicates that a servlet is unavailable. Servlets can
report this exception at any time. There are two types of unavailability:
Permanent. The servlet is unable to function until an administrator takes some action. In this state, a
servlet should write a log entry with a problem report and possible resolutions.
Temporary. The servlet encountered a (potentially) temporary problem, such as a full disk, failed server,
etc. The problem can correct itself with time or may require operator intervention.
GET / HTTP/1.1
Connection: Keep-Alive User-Agent: Mozilla/4.0 (compatible; MSIE 4.01;Windows NT)
Host: www.magelang.com Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg
67
On most web servers, servlets are accessed via URLs that start with /servlet/. The following HTTP GET
method is requesting the servlet MyServlet on the host www.magelang.com:
The URL in this GET request invokes the servlet called MyServlet and contains two parameters, name and
company. Each parameter is a name/value pair following the format name=value. The parameters are
specified by following the servlet name with a question mark ('?'), with each parameter separated by an
ampersand ('&').
Note the use of %20 in the company's value. A space would signal the end of the URL in the GET request
line, so it must be "URL encoded", or replaced with %20 instead. As you will see later, servlet developers
do not need to worry about this encoding as it will be automatically decoded by the HttpServletRequest
class.
HTTP GET requests have an important limitation. Most web servers limit how much data can be passed as
part of the URL name (usually a few hundred bytes.) If more data must be passed between the client and
the server, the HTTP POST method should be used instead. It is important to note that the server's
handling of a GET method is expected to be safe and idempotent. This means that a GET method will not
cause any side effects and that it can be executed repeatedly.
When a server replies to an HTTP GET request, it sends an HTTP response message back. The header of an
HTTP response looks like the following:
HTTP/1.1 200 Document follows Date: Tue, 14 Apr 1997 09:25:19 PST Server: JWS/1.1 Last-
modified: Mon, 17 Jun 1996 21:53:08 GMT Content-type: text/html Content-length: 4435
name=Scott&company=MageLang%20Institute
Note the blank line--this signals the end of the POST request header and the beginning of the extended
information.
Unlike the GET method, POST is not expected to be safe nor idempotent; it can perform modifications to
data, and it is not required to be repeatable.
69
The class HttpServlet is actually rather intelligent. Not only does it dispatch HTTP requests, it detects which
methods are overridden in a subclass and can report back to a client on the capabilities of the server.
(Simply by overriding the doGet() method causes the class to respond to an HTTP OPTIONS method with
information that GET, HEAD, TRACE, and OPTIONS are all supported. These capabilities are in fact all
supported by the class's code). In another example of the support HttpServlet provides, if the doGet()
method is overridden, there is an automatic response generated for the HTTP HEAD method. (Since the
response to an HTTP HEAD method is identical to an HTTP GET method--minus the body of the message-
-the HttpServlet class can generate an appropriate response to an HTTP HEAD request from the reply sent
back from the doGet() method). As you might expect, if you need more precise control, you can always
override the doHead() method and provide a custom response.
70
An interface that describes the configuration parameters for a servlet. This is
passed to the servlet when the web server calls its init() method. Note that the
servlet should save the reference to the ServletConfig object, and define a
ServletConfig
getServletConfig() method to return it when asked. This interface defines how to
get the initialization parameters for the servlet and the context under which the
servlet is running.
An interface that describes how a servlet can get information about the server in
ServletContext which it is running. It can be retrieved via the getServletContext() method of the
ServletConfig object.
ServletRequest An interface that describes how to get information about a client request.
ServletResponse An interface that describes how to pass information back to the client.
A base servlet implementation. It takes care of saving the ServletConfig object
reference, and provides several methods that delegate their functionality to the
GenericServlet
ServletConfig object. It also provides a dummy implementation for init() and
destroy().
A subclass of InputStream used for reading the data part of a client's request. It
ServletInputStream
adds a readLine() method for convenience.
ServletOutputStream An OutputStream to which responses for the client are written.
ServletException Should be thrown when a servlet problem is encountered.
UnavailableException Should be thrown when the servlet is unavailable for some reason.
Servlet Examples
Now for an in-depth look at several servlets. These examples include:
• Generating Inline Content
• Processing HTTP Post Requests
• Using Cookies
• Maintaining Session Information
• Connecting to Databases
71
4.1.25 Generating Inline Content
Sometimes a web page needs only a small piece of information that is customized at runtime. The
remainder of a page can be static information. To substitute only small amounts of information, some
web servers support a concept known as server-side includes, or SSI.
If it supports SSI, the web server designates a special file extension (usually .shtml) which tells the server
that it should look for SSI tags in the requested file. The JWS defines a special SSI tag called the <servlet>
tag, for example:
<servlet code="DatePrintServlet">
<param name=timezone value=pst>
</servlet>
This tag causes the invoking of a servlet named DatePrintServlet to generate some in-line content. SSI
and servlets allow an HTML page designer to write a skeleton for a page, using servlets to fill in sections
of it, rather than require the servlet to generate the entire page. This is very useful for features like page-
hit counters and other small pieces of functionality.
The DatePrintServlet servlet works just like a regular servlet except that it is designed to provide a very
small response and not a complete HTML page. The output MIME type gets set to "text/plain" and not
"text/html". Keep in mind that the syntax of server-side includes, if they are even supported, may vary
greatly from one web server to another. In the following Magercise you create the DatePrintServlet and
see how to use it in an HTML page.
72
as an editable HTML form. The structure of the data is kept separate from the actual data. This makes it
easy to modify this code to run against arbitrary tables from a JDBC-connected database.
4.2 COOKIES
For those unfamiliar with cookies, a cookie is a named piece of data maintained by a browser, normally
for session management. Since HTTP connections are stateless, you can use a cookie to store persistent
information accross multiple HTTP connections. The Cookie class is where all the "magic" is done. The
HttpSession class, described next, is actually easier to use. However, it doesn't support retaining the
information across multiple browser sessions.
To save cookie information you need to create a Cookie, set the content type of the HttpServletResponse
response, add the cookie to the response, and then send the output. You must add the cookie after setting
the content type, but before sending the output, as the cookie is sent back as part of the HTTP response
header.
private static final String SUM_KEY = "sum";
... int sum = ...; // get old value and
add to it
Cookie theCookie = new Cookie (SUM_KEY, Integer.toString(sum));
response.setContentType("text/html");
response.addCookie(theCookie);
It is necessary to remember that all cookie data are strings. You must convert information like int data to
a String object. By default, the cookie lives for the life of the browser session. To enable a cookie to live
longer, you must call the setMaxAge(interval) method. When positive, this allows you to set the number
of seconds a cookie exists. A negative setting is the default and destroys the cookie when the browser
exits. A zero setting immediately deletes the cookie.
Retrieving cookie data is a little awkward. You cannot ask for the cookie with a specific key. You must ask
for all cookies and find the specific one you are interested in. And, it is possible that multiple cookies could
have the same name, so just finding the first setting is not always sufficient. The following code finds the
setting of a single-valued cookie:
int sum = 0;
Cookie theCookie = null;
Cookie cookies[] = request.getCookies();
if (cookies != null)
{
for(int i=0, n=cookies.length; i < n; i++)
{
theCookie = cookies[i];
if (theCookie.getName().equals(SUM_KEY))
{
try
{
sum = Integer.parseInt(theCookie.getValue());
}
catch (NumberFormatException ignored)
{
sum = 0;
73
}
break;
}
}
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>" +
"<head><title>Session Information</title></head>" +
"<body bgcolor=\"#FFFFFF\">" +
"<h1>Session Information</h1><table>");
out.println ("<tr><td>Identifier</td>");
out.println ("<td>" + session.getId() +
"</td></tr>"); out.println ("<tr><td>Created</td>");
out.println ("<td>" + new Date(
session.getCreationTime()) + "</td></tr>");
out.println ("<tr><td>Last Accessed</td>");
out.println ("<td>" + new Date(
session.getLastAccessedTime()) + "</td></tr>");
out.println ("<tr><td>New Session?</td>");
out.println ("<td>" + session.isNew() + "</td></tr>");
String names[] = session.getValueNames(); for (int
i=0, n=names.length; i<n; i++) { out.println
("<tr><td>" + names[i] + "</td>"); out.println
("<td>" + session.getValue (names[i])
+ "</td></tr>");
}
out.println("</table></center></body></html>");
out.close();
The complete code example shown above is available for testing. One thing not demonstrated in the
example is the ability to end a session, where the next call to request.getSession(true) returns a different
session. This is done with a call to invalidate().
In the event a user has browser cookies disabled, you can encode the session ID within the
HttpServletResponse by calling its encodeUrl() method.
It is very common to have servlets connect to databases through JDBC. This allows you to better control
access to the database by only permitting the middle-tier to communicate with the database. If your
75
database server includes sufficient simultanious connection licenses, you can even setup database
connections once, when the servlet is initialized, and pool the connections between all the different
service requests.
The following demonstrates sharing a single Connection between all service requests. To find out how
many simultaneous connections the driver supports, you can ask its DatabaseMetaData and then create
a pool of Connection objects to share between service requests. In the init() method connect to the
database.
76
stmt.close();
} }
out.flush()
;
out.close()
;
}
It is not good practice to leave a database connection permanently open, so this servlet should not be
installed as a permanent servlet. Having it as a temporary servlet that closes itself down after a predefined
period of inactivity allows the sharing of the database connection with requests that coincide, reducing
the cost of each request. You can also save some information in the HttpSession to possible page through
the result set.
77
ACLs are extremely important, as some servlets can present or modify sensitive data and should be tightly
controlled, while others only present public knowledge and do not need to be controlled.
c) Threading Issues
A web server can call a servlet's service() method for several requests at once. This brings up the issue of
thread safety in servlets. But first consider what you do not need to worry about: a servlet's init() method.
The init() method will only be called once for the duration of the time that a servlet is loaded. The web
server calls init() when loading, and will not call it again unless the servlet has been unloaded and reloaded.
In addition, the service() method or destroy() method will not be called until the init() method has
completed its processing.
Things get more interesting when you consider the service() method. The service() method can be called
by the web server for multiple clients at the same time. (With the JSDK 2.0, you can tag a servlet with the
SingleThreadModel interface. This results in each call to service() being handled serially. Shared resources,
such as files and databases, can still have concurrency issues to handle.)
If your service() method uses outside resources, such as instance data from the servlet object, files, or
databases, you need to carefully examine what might happen if multiple calls are made to service() at the
same time. For example, suppose you had defined a counter in your servlet class that keeps track of how
many service() method invocations are currently running:
private int counter = 0;
Next, suppose that your service() method contained the following code:
For this situation, the answer might be to synchronize the access to the counter variable:
synchronized(this)
{
myNumber = counter + 1;
counter = myNumber;
}
// rest of code in the service() method
synchronized(this)
{
counter = counter - 1 ;
}
This ensures that the counter access code is executed only one thread at a time. There are several issues
that can arise with multi-threaded execution, such as deadlocks and coordinated interactions.
78
LEARNER ACTIVITY 4
79
ASSIGNMENT.GUIDELINES.....ATTENTION STUDENTS/STAFF
If you COPY AND OR REPRODUCE SOMEBODY ELSE’S WORK WITHOUT REFERENCING, your
assignment will be penalized by 30%.
TO AVOID BEING PENALISED IN YOUR ASSIGNMENTS DO NOT
Copy and paste information from the internet and on-line media, such as
encyclopedias or journal articles without acknowledging the source of
information (Referencing).
Use previous work for a new assignment without citing the original assignment
in your reference list.
Intention of student
Degree of plagiarism – how much of the assignment has been plagiarized
Previous offences by the student