Sunteți pe pagina 1din 329

Java-Servlets-JSP

Visit www.bpbonline.com for more details on this book.

http://www.vijaymukhi.com/documents/books/javajsp/contents.html [5/2/2008 10:48:05 PM]


Java-Servlets-JSP

FOREWORD
- Tushar A. Gandhi

Since childhood Java has meant a lot of things to me, at first having been brought up
on an endless supply of Luis L'amour western paper backs Java was the cup of brew
over which cowboys swapped trail lore in the wild wild west, throwing the dredges of
Java into the camp fire was the ultimate symbol of machismo. Then one graduated to
the edge of the seat thrillers by Alistair McLean and java was part of the title of one of
his unputdownable chiller "South by Java Head", in the World War classics Java was
part of the exotic South East consisting of Java and Sumatra. "Java" was also the way
one was asked to leave in the Marathi language. So having come to grips with so many
uses of the word "Java" when "Oak" was rechristianed as Java one was pleasantly
reminded of the associations of the past with this one word having so many memories
attached to it.
That Java was first considered to be the language which would enable all the smart
house hold machines to talk across platforms, this was the strong point of Java it's
cross platform capabilities or rather platform independent character. This very ability
took this offspring of C and C++ away from its intended use to service the Internet
explosion. This was the golden age of Java working across networks and platforms.
Java thus was the language of the kitchen cabinet, which became the lingua franca of
the World Wide Web.
Java has been a boon for the software engineers who having learned it on the Windows
NT environment here are able to work in the US environment, which is predominantly
Unix, based since Java was the same on both the platforms. The InfoTech related boom
experienced by India is largely thankful to the versatility of Java.
If somebody talked to me about Java beans I would conjure up the image of shinny
rounded rich dark brown coffee beans and their rich aroma would fill the room, similar
to the aromas wafting from South Indian kitchens as freshly ground beans of Java were
brewed into the famous decoction of the Madras Coffee every day at breakfast time.
Who would know that Java beans would be far more recognizable as software plug ins.
The ease with which Java beans could be reused, as plug and play bits of software
pasted while writing programs, with out having to rewrite the entire code over and over
again every time a similar function had to be carried out.
On the "Mahatma on the World Wide Web Project" we are using the JDBC to handle the
vast database we are talking of over 250,000 printed pages of text, 15000
photographs, 5 hours of video and 48 hours of audio, all this will be managed and a
smart search engine also created using Java will enable our users to customize the
search according to their specific needs and thus explore the database. All this is made
possible because of the versatility of Java.
Java is human friendly technology which would have met with the approval of Mahatma
Gandhi since it is versatile, it takes care of many things without the need to become
over technological, two being platform independent it would work in all environments
just like Satyagraha and above all its simplicity the corner stone of the Mahatma's
philosophy.
When Scot McNealy of Sun put the animation of the steaming cup of coffee on
computer screens all over the world, be it the PC world or the Macintosh one, the world
woke up to the power of Java as its hot brew counter part wakes up the world every

http://www.vijaymukhi.com/documents/books/javajsp/foreword.html (1 of 2) [5/2/2008 10:48:15 PM]


Java-Servlets-JSP

day.
CAFEBABE dances on flirting with all, across the world of Information Technology and
Java and Java Beans take on a whole new meaning. Tomorrow's children are going to
react to "South by Java Head" as a software manual and Cowboys swapping tales over
a hot cuppa Java as engineers swapping trade secrets and the aromatic Java Bean is
going to be called a small software plug in.
When India's Computer Guru asked me to write a foreword for his book on Java I was
intimidated first by the fact that I was adding on to the writings of a master and second
by the fact that my association with the different meanings to the word Java had been
turned on their head. What you are about to read is a serious insight into what makes
the CAFEBABE swing so this is where the fun stops. As the cowboys would say to each
other as they swigged the last of the "Hot Cuppa" and threw the dredges on to a dying
fire "Lets catch some shut eye partner, cause tomorrow is another drive".

http://www.vijaymukhi.com/documents/books/javajsp/foreword.html (2 of 2) [5/2/2008 10:48:15 PM]


Java-Servlets-JSP

About the authors

Vijay Mukhi (vmukhi@vsnl.com) is one of the pioneers of the Indian Infotech Industry. For
years, he has been the first to teach the emerging technologies in India thus ensuring that India
always has people trained in technologies that the world requires. Vijay has written over 80
books on computers and programming over the last eight years on subjects ranging from C,
C++ (The Odyssey Series) to Animation and Networking to ERP. `marketing.com', his newly
released book has been widely acclaimed. Vijay is now focussing on Microsoft's .Net
technologies and aims at writing volumes on it.

Sonal Mukhi (svmukhi@yahoo.com) is a freelance programmer having a widespread


exposure to computer techniques and languages. Sonal has done groundbreaking work on
various Internet Technologies like Java, ActiveX, Perl and more. Her passion is programming
and some day she hopes to setup her own software firm.

Neha Kotecha (neha@personalfn.com) is a young bright girl who aspires to be a computer


professional. Being a Manager, Personal Finance, Neha dreams to head her company's
technology team some day. Her dedication to work and eagerness to learn newer things will
surely take her far in life.

http://www.vijaymukhi.com/documents/books/javajsp/about.html [5/2/2008 10:48:29 PM]


Java-Servlets-JSP

Introduction

Java, whether you love it, or hate it, it's here to stay. Like everyone's favorite language C, Java
has had a major impact on the computing scene. When the history of computers is written, its
name will be up there with the stars.

If you were to choose just one language to learn today, it should be Java. It's being pushed
aggressively by Sun and is growing by leaps and bounds. There are lots of Java programmers
out there and more join the party every day.

Java started out as a bit of an accident. A team under Bill Joy was working at Sun on a new
programming language for embedded applications. Java was originally expected to work in
toasters and fridges, not on modern computers! The initial prognosis for Java was not good
and it was only the rise of the Internet which saved Java from oblivion. Since then, neither the
Net nor Sun nor Java has looked back and all have grown from strength to strength.

In this book, we start off assuming that you know no programming language at all. We've
focussed on the place where Java is most prevalent, the server. We're going to be teaching you
Java one concept at a time and taking things real slow and easy. We believe that the best way
to learn is to try and absorb just one concept at a time. We're here to help you learn, not to
overwhelm you.

We like the concept of freedom, especially when it comes to information. We've occasionally
picked up ideas for our examples from programs we've found online or in the product
documentation. We've got information from so many sources, we can't credit them all, but we
are grateful to them. In turn, we'd like you to use the code you'll find within in any way you
wish.

Happy Learning!!!!

Acknowledgements:

Several key people are helpful in making this book become a reality and must be
acknowledged for their efforts - without them, this book would not exist.

Tushar Gandhi, the great grandson of Mahatma Gandhi and Managing Trustee of Mahatma
Gandhi Foundation.

Manish Jain, BPB, for working closely with us and publishing the book.

http://www.vijaymukhi.com/documents/books/javajsp/intro.html (1 of 2) [5/2/2008 10:48:39 PM]


Java-Servlets-JSP

Altaf Hemani and Kishore Rohra for the cover design.

Arsalan Zaidi for editing and proof reading the book.

Pradeep Mukhi and Shivanand Shetty for their motivation and support on this book.

Finally, we are grateful to our families and friends for their love, support and encouragement
while the book was being written.

Vijay Mukhi
Sonal Mukhi
Neha Kotecha

http://www.vijaymukhi.com/documents/books/javajsp/intro.html (2 of 2) [5/2/2008 10:48:39 PM]


Java-Servlets-JSP

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (1 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

Shlurrrpp......Java

Men are amused by anything. That is why professional ice hockey is so popular. That is why
Disneyland runs into lengthier balance sheets than the scientific museums. And that is why
something like Java is touted as the next Glasnost (well, unless you are a snoozebucket, you
are probably aware of Java, the language that is bowling the world over). Make way. Here
comes the stuff our forefathers warned us about. It is mightier than the sword, the pen and
usually, the programmer. A thousand and one news-breakers and articles have done their
rounds on how Java is invariably an isotope of C++ minus the warts and pimples, on how it is
going to give the Internet an upbeat facelift, on how......

But wait. The last thing you want to do is to sit back and worship the greatness of a language;
you want to use it. The one sad hitch with today's software is that the so-called tutorials and
manuals are scarcely meant for anyone to understand. Take the samples bundled with Java for
instance. How would you like the idea of brooding over a hundred-line sample code to begin
with? What these codes fail to do is spark an interest among the wide-eyed newbies. ( Between
you and me, I suspect that is the state-of-the-art way of doing graffitti on aspiring
programmers :) ).

That's precisely what we aim to do here - to give you the first few sips of Java (seasoned not to
burn your tongue). Our approach is simple. As far as possible, we will add a line at a time and

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (2 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

expect you to try it out (if we exceed that, we apologize). The worst thing that could happen by
trying to learn programming in this way is that we might lead to grazing down of a few more
trees (we will use more paper, right). But at least we can comprehend the language better.

Undoubtedly, Java has flung open a whole slew of possibilities to spruce up a page on the
Internet. Every little Johnny in the world, who has anything close to a GK, knows that Java
can change lives. How is the question. Before we begin, let us make a few things clear. First,
to learn programming in Java, it is undoubtedly a prerequisite to have a passing knowledge of
C++ or we'd rather you sit over the weekend with a load of beer and cheetos in the fridge and
atleast a dozen aspirins in the drawer :) . Secondly, the programs in Java here are explained in
a simple, understandable manner and hence anybody expecting a display of rhetorical caliber
is in for a disappointment of his lifetime. Just like an artist's potrait speaks for itself, we'd
rather have Java speak for itself too. Third, while each concept is clearly explained, we prefer
to keep our distance from the 'gears and cogs' of the language. And yes, it is also assumed you
have downloaded the Java Develoment Kit. (For those who came in late, the software can be
downloaded from the address http://www.javasoft.com )

Some Conventions that we swear by

" The essence of magic is simplicity "

We are not concerned with inculcating obedience or influencing the programming style of our
readers; quite the contrary, we intend the development of initiative. The simplicity that will
inevitably be exhibited in our code and explanation is merely a method to refrain from
pedantic. The idea is not to win a prize in computer literature but to shorten your learning
curve. The naming conventions that we will adhere to include:

The variables that we use will be of one letter, for instance i, j, g etc.
The functions will be of two letters, e.g., aa() , bb() etc.
The class names will be three letters, e.g., zzz etc.

When we started learning java 5 years ago, we made an attempt to put up tutorials relating to
different aspects of Java programming language on http://www.vijaymukhi.com. Since it was
ranked as one of the best online tutorials then, we have decided to add a few of these tutorials
to our very first book on Java. A lot has changed since then but most of the code written still
works. We would like to thank our writer then, 'Shashank Tripathi' for having used the best
langauge and vocabulory thereby making it an interesting readable literature.

PS: Some programs will repeat in a few chapters, but the explanation given here will give you
a different insight into this widely used language.

Applets
http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (3 of 46) [5/2/2008 10:52:14 PM]
Java-Servlets-JSP

A Tweak of Lemon...

"Ours is the age of substitutes; instead of principles, we have slogans; instead of genuine
ideas, bright ideas; instead of languages, jargon. "

When it comes to bright jargon, Sun Microsystems has left no stone unturned. And the
creative terminology goes a long way (if not all the way) in making it like the tidal wave it has
been. Java programs are called 'Applets'. In the directory in which the whole downloaded
software of Java is saved, there is a subdirectory called Bin. This is where we have the Java
compiler called 'Javac.exe'. The first thing we do is to create a subdirectory under the root
called, say, "xxx". Then set the path to \(javadirectory)\bin. We are going to write our Applets
here. Each applet or program has to be written in a file with the extension of .java. In keeping
with the ritual, let us consider this one-liner code first...

a1.java
class zzz
{
}

You'll agree that even an ice-hockey player or a visitor to Disneyland will love this sort of a
program because it is looks manageably concise and absolutely simple. Well, we do not expect
fireworks with that sort of a code, but let us compile it all the same. Save the file a1.java. It is
noteworthy to mention here that like C/C++, Java is case-sensitive too (and preposterously
so!). Type the command javac a1.java. The compiler gives no errors. If you key in the DIR
command now, you will see that after successful compilation, a file called zzz.class is made
automatically. That is because we specified zzz as the name of our class. This makes it
adequately clear that the name of the applet file (the .java file) and the class can very well be
different.

Now comes the question of viewing how our applet works. If it is a Java applet, you can call it
only from an HTML file (An HTML file, in case you don't know, is nothing but a text file with
tags that link it to other documents). Since all the documents on the Internet use this format, an
applet has to be specified in an HTML file. Consider the following HTML file.

aa.html
<applet code="zzz" width=120 height=120>
</applet>

As is evident, the .class file (zzz.class in our case) that is formed after successful compilation
of the .java file (a1.java) is specified in the HTML file alongwith the width and the height This
is the way in which you can incorporate an applet in the HTML format. The applet could be a

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (4 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

program to display animation or perform any other dynamic task and thus, enliven a page on
the net.

But it still remains to be seen how the applet works or what the output looks like. Towards this
end, we have a program called the appletviewer (in the same directory as javac). This is a
program that allows you to view how your applet works. Hence, we key in the command
appletviewer aa.html. Sorry folks, but there is no output (if your stars are not happy with you,
your machine might even hang!).

There are a hundred and sixty five things to be done in the background before our class begins
work (like the initialization routines et al). Our class does not have any property towards that
end. As one does not know what routines are to be initialized internally, the safest thing to do
is to derive a class from another class provided with the language. Now edit your a1.java file
in the following way.

a1.java
class zzz extends Applet
{
}

Applet is a class that has all the required functions necessary for this purpose, so we derive zzz
from Applet or extend zzz to Applet. This means, in plain English, that we can now use all the
functions and variables of the Applet class and also add our own ones. The only hitch now is
that compiler refuses to recognize Applet, unless we mention specifically the name of the class
library in which it is contained. So we now have to formally introduce the compiler to the
Applet class. We do this by inviting the Applet class into our program (how else?). Only, the
invitation here is in the form of importing a file called Applet.class from the classes.zip which
is within a java subdirectory.
a1.java
import java.applet.*
class zzz extends Applet
{
}

When we compile this program, however, we get some lines of dreadful errors, with only one
making any sort of horse-sense, " ; expected". Guess what, we missed out on the elusive
semicolon after the import statement! Remember, this is a sibling of C and C++ and the use of
semicolon is inevitable. And hence, our program now looks like this...
a1.java
import java.applet.*;
class zzz extends Applet
{

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (5 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

However, having put that necessary punctuation, when we compile and run the program again,
it gives the error that the 'class not public'. As a result, the applet is not initialized. That brings
us to another important feature of Java, as it stands today. All the classes that we define have
to be public, otherwise the class cannot be initialised by the Appletviewer. Not being the
arguing types, we make our class public in the following way...

a1.java
import java.applet.*;
public class zzz extends Applet
{
}

One snag with making a class public is that the name of your file and that of the class have to
be the same. So after adding the word public, rename a1.java to zzz.java.

> ren a1.java zzz.java

Before you begin to swear about this queue of unending snags, let us state that this is it. We
finally have what can be safely labeled as the smallest Java program. Now compile the new
java file using javac and when we key in the command appletviewer aa.html, a small window
appears to show the output. This is the first successful applet and all the economists out there
would love it. Because it is concise, precise and absolutely useless ( :-) ). As we are not
economists and expect our applet to do something, let us make some additions. But to continue
further, we have to quit from the appletviewer. For this, click on the Applet menu that you see
in the appletviewer window and select Quit.
zzz.java
import java.applet.*;
public class zzz extends Applet
{ public void init()
{ resize(300, 500);
}
}
All the functions in our class have to be public. The function init() gets called initially when
you run an applet. Whenever your applet begins and you need to do something put it in the
init(). Inside this, we have the resize() which is one of the many functions of the Applet class.
It is used to change the size of the area in which our applet can work. By default, a small area
is given to the applet but the resize() says "Give me two parameters, the width and the height
and I can increase or decrease the scope of your applet". We obediently pass two parameters to
this function, the width of the area(300) and the height(500). When we compile and run the
above program, we can see a rectangular box as an output. As yet, we have just plain specified

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (6 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

the area for the applet, now let us try displaying something inside it...
zzz.java
import java.applet.*;
import java.awt.* ;
public class zzz extends Applet
{ public void init()
{ resize(300, 500);
}
public void paint(Graphics g)
{ g.drawString("Hello", 10, 50);
}
}

As you must have realized, this program displays "Hello" at the coordinates 10, 50. As
mentioned earlier, the init () gets called first. The workarea is resized in the same way as
before. Everytime the screen or the window has to be displayed, the paint() gets called. You
cannot set your watch by it. An object g that looks like the class Graphics has to be tagged
along as a parameter. As Graphics is a predefined class, we require to import the Graphics
class, (which is in classes.zip ). The Graphics class has many functions including the
drawString(). Give this function its due in the form of three parameters, the string to be
displayed, and the x and the y coordinates and promises to display the string at that position.
So when the paint is called, "Hello" appears on the screen.

Now that we are aware of the method of displaying, let us write a program that is a little more
interesting. We propose to display a string and a value everytime the Mouse is clicked. Key in
the following code...
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ int i;
public void init()
{ resize(300, 500);
}
public void paint(Graphics g)
{ g.drawString("i....." + i, 10, 50);
}
public boolean mouseUp(Event e, int x, int y)
{ i++;
repaint();
return true;
}

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (7 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

When you compile this java file, you will get one warning. Warnings can be ignored for the
time being.

Let us start from the very beginning. A variable i is defined before any other function. This
make sure that the variable can be used in any function (for you C++ programmers out there, it
is similar to a public variable). A very interesting feature is the mouseUp(). Every time you
click with the mouse, the mouseUp() gets called. The mouseUp() is counted upon to return a
True or false. And that is the reason why that ugly word 'Boolean' comes into picture (which
will be explained at a later stage). Note that the mouseUp() accepts three parameters. The
Event is irrelevant to explain at this point of time and it will be explained later with a useful
example. The other parameters are x and y coordinates, which are internally calculated
everytime the mouse is clicked. That is, if i click at, say, the position (15, 20), then the value
of x will automatically become 15 and that of y will be 20. With every click the value of i is
increased by 1. Then the repaint() is called, which in turn calls the paint(). This way, with each
click we display the string "i...." followed by the value of i. The drawString() takes care of
that. Note the plus sign (+), it is used to concatenate or join two strings to be displayed.

They said programming in Java is object-oriented and event-driven. That sent my brains for a
toss when I first heard it, but the above program bears a glittering testimony to that. The
function mouseUp() gets activated everytime the mouse button is clicked, the paint() is called
whenever a window or a screen has to be redrawn etc.

Let us alter this code to display our usual "Hello", but now at the coordinates where the user
clicks. Change the code in zzz.java as the following..
zzz.java
import java.applet.*;
import java.awt.* ;
public class zzz extends Applet
{ int a; int b;
public void init()
{ resize(300, 500);
}
public void paint(Graphics g)
{ g.drawString("Hello", a, b);
}
public boolean mouseUp(Event evt, int x, int y)
{ a=x; b=y;
repaint();
return true;
}
}

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (8 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

Here, a and b are public variables as they are defined outside all the functions. When a
variable is public, it can be used inside any function. The logic to the above applet is pretty
simple. Everytime the mouse is clicked, the mouseUp() function is called. We can get to know
the coordinates where the user has clicked because the coordinates are stored automatically in
x and y. These values are assigned to a and b. Now when the repaint() is called, it calls the
paint(). Here, the drawString() will display "Hello" at the specified position. But since the
specified coordinates are nothing but the coordinates of the place where the user has clicked (a
and b), "Hello" will now be displayed at the position where the user clicks.

Our next program draws a line between two clicks of the mouse. That is, a line is drawn
between the first and the second click, the third and the fourth click and so on.
zzz.java
import java.applet.*;
import java.awt.* ;
public class zzz extends Applet
{ int a; int b; int c; int d; int e;
public void init()
{ resize(300, 500);
}
public void paint(Graphics g)
{ g.drawLine(a, b, d, e);
}
public boolean mouseUp(Event evt, int x, int y)
{ if (c==0)
{
a=x;
b=y;
c=1;
}
else
{
d=x;
e=y;
c=0;
repaint();
}
return true;
}
}

We define five public variables a, b, c, d and e. The paint() is called by default for the first

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (9 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

time. It is passed four parameters, the x and y coordinates of the points between which the line
has to be drawn, i.e. the two endpoints of the line. But since the four variables a, b, d and e are
currently zero, initially there is no line displayed. Whenever the user clicks with the mouse,
mouseUp() functions gets called. A variable c takes care of the fact whether the click is for the
first or the second time. If the click is for the first time (i.e if c is 0), a and b are given the
value of x and y. These are the points of the first end of the line. Then c is made 1. The second
time the user clicks, c is 1. Therefore, d and e given the values of x and y. c is made 0 again.
And the repaint() is called. Now when the paint() is called by the repaint(), the drawLine() will
draw a line from (a, b) - the position of the first click, to (c, d) - the position of the second
click. In this way, the value of c can be alternated and a line drawn between two successive
clicks.

Making the clouds look good - Images

Let us face it, drawing a line is too dry a thing to do; so let us move on to displaying an image
on the screen. And to write an applet that displays an image is simpler than you ever feared.
Consider this code...

zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Image n;
public void init()
{ n = getImage(getCodeBase(), "cow.gif");
resize(300, 500);
}
public void paint(Graphics g)
{ g.drawImage(n, 10, 15, this);
}
}

As is amply apparent, the basic structure of the program remains the same. An object n that
looks like the class Image is defined. Inside the init(), n is initialised to an image called
"cow.gif" which exists on our hard disk. (PS Check up the \demo directory for more .gif files;
gif files are nothing but images). This is done with the getImage() that is a member of the
Applet class. As n looks like the class Image, it can use the member functions of that class.
The getImage() accepts two parameters, the getCodeBase() and the name of the .gif file. Now,
n contains the image "cow.gif". So when the paint() is called using g (which looks like
Graphics), we can use n to display the image. The Graphics class has a member function called
drawImage(), which is used to actually draw the image (n) on to the screen. This takes four
parameters. First is the image that we wish to draw, as is n in our case. The second and the

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (10 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

third are the coordinates where we want the image to be displayed. The fourth parameter is
this. If you are a C/C++ programmer, you are well-versed with this, but for the rest it should
suffice right now to say that this refers to the current object ( pun unintended :-) ).

Now, the same image can be displayed at the coordinates where the user clicks by using the
mouseUp() and trapping the coordinates where the mouse was clicked. If you have not got it
already, the code for this will be..

zzz.java
import java.applet.*;
import java.awt.* ;
public class zzz extends Applet
{ Image n;
int a; int b;

public void init()


{ n = getImage(getCodeBase(), "cow.gif");
resize(300, 500);
}
public void paint(Graphics g)
{ g.drawImage(n, a, b, this);
}

public boolean mouseUp(Event e, int x, int y)


{ a=x;
b=y;
repaint();
return true;
}
}

At Work Then

Straight dope on The Abstract Windows Toolkit

If your most fiendish nightmare is drowning in a bowl of alphabet soup, maybe you'd better re-
think your Java-oriented strategies; because you are about to leap into a scaffold of functions
that come wrapped up, ribbon and all, to help you give that graphical look! And yep, from a
fairly prudent perspective, The Abstract Windows Toolkit as it is called, with its horde of
teeny-weeny functions, does indeed provide the underpinnings for the user-friendly Graphic
interface. In this section, we will tinker with these little widgets that come bunched up as the
AWT. Before embarking on any sort of coding, let us look at the following diagram...

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (11 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

Button
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ public void init()
{ add(new Button ("hell"));
}
}

In the init(), we add a button called "hell". When you run this program, you will see a button
with the name (or the label ) "hell" on the screen. That's not great shakes afterall, but you just
wrote your first AWT program!

TextField
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ public void init()
{ add(new TextField());
}
}

Like running the earlier program presented you with a button, this one will give you a text
field. That is nothing but a single line edit box on the screen. Well, I don't mind going on like
that for each and every wee feature, showing you one new thing at a time, but its the space that
counts (not to mention your patience). Hence, I guess it should suffice to say that like the
above objects,i.e, Button and Textfield, the following can also be created.

TextArea

add(new TextArea());

This is similar to a huge text field, that is, it covers a larger area than the Textfield. While
trying the text area, I'd rather you maximise the applet window because it comes like a
multiple line edit box on the screen.

Choice

add(new Choice());

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (12 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

Choice is a word straight out from the Jargon Dump (which, incidentally, is the favourite hang-
out of the techno-nerds!). A Choice() adds a drop down list box.

List
add(new List());

This will display a dry list box displayed on the screen. Dry because there will be no options
given. (Well you wouldn't want to use their options anyway).

Checkbox

add(new Checkbox());

Unless you bought your computer to serve as the world's most expensive doorstop, you are
well-versed with the check-boxes. In Java, this is the way you create your own checkboxes.
CheckboxGroup :The Windows aficionados know it as the radio-buttons.

Scrollbar

add(new Scrollbar());

Remember how you scroll through your love letters? Well, ulterior motives aside, you are well-
versed with the scrollbars (unless ofcourse, your fiancee is a DOS-diehard).

Label

add(new Label("Good"));

Here, let us meet the most drab member of the AWT family. Just plain text that drawls on the
screen whatever you pass it as a parameter.

Actually Getting down to work

Now that we are a little better than AWT-bumpkins, let us unwrap it all one by one and pick
up the pieces from the toolkit cornucopia...

Controls
The little yet useful underpinnings for the Graphical look

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (13 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

Buttons
We said a while ago that this tutorial was tailor-made for you. How in blazes could a tailor do
without buttons ? Try out the following code...
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button b;
public void init()
{ b = new Button("hell");
add(b);
}
}

Here we have a button b added, very much the same as our first AWT program but for one hair-
breadth difference. In this way, we have an object b that looks like a Button . Therefore, we
can also use the functions of the class Button . With this in mind, let us proceed to the next
one...

setLabel()
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button b;
int i=0;
public void init()
{ b=new Button("i..." + i);
add(b);
}
public boolean mouseUp(Event e, int x, int y)
{ i++;
b.setLabel("i..." + i);
return true;
}
}

Out here we first add the button b with the name of "i...0"(because i is 0 in the beginning).
Then we include the mouseUp() where we change the label or the name of the button with the
setLabel() . Meanwhile, we have a variable i which we increment everytime the user clicks
with the mouse. The increased value of i is displayed as the name of the button.

reshape()

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (14 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button b;
int i = 0;
public void init()
{ b = new Button("hell");
add(b);
}
public boolean mouseUp(Event e, int x, int y)
{ b.reshape(x, y, 30, 40);
return true;
}
}

This program demonstrates how the button or any other feature in the AWT like the text field,
list box etc can be moved to any coordinate and resized. For our button b , we use the
reshape() which means we want to change the shape and the position of our button. It is
apparent that the reshape() consumes four parameters. The coordinates of the position where
we want the button to be, and its width and height.

getLabel()
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button b;
int i = 0;
public void init()
{ b=new Button("hello");
add(b);
}
public boolean mouseUp(Event e,int x, int y)
{ showStatus(b.getLabel());
return true;
}
}

When we can set a label to a button, it ofcourse is possible to get the label of the button as
well. The above program explains how the getLabel() functions. It will become a little clearer
with the following program...
zzz.java

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (15 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button b;
public void init()
{ b=new Button("hello");
add(b);
}
public boolean mouseUp(Event e,int x, int y)
{ if(b.getLabel()=="hello")
b.setLabel("hi");
else
b.setLabel("hello");
return true;
}
}

When the user clicks with the mouse, it is checked if the label of the button is "hello" or "hi".
If it is "hello", the label is being changed to "hi" and vice versa. If a button is beginning to give
you the pips, let's move on to a little higher level.
Hide and seek
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button a, b, c;
public void init()
{ a = new Button("Hide");
b = new Button("Show");
c = new Button("Hello");
add(a);
add(b);
add(c);
}
public boolean action(Event e,Object o)
{ if("Hide".equals(o))
{ c.hide();
}
if("Show".equals(o))
{ c.show();
}
return true;
}

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (16 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

Three is a crowd. That's why we have three buttons here. The buttons a, b and c are assigned
the names "Hide", "Show" and "Hello" respectively. And then, for reasons other than
impressing you, we use the action() instead of the variety of mouse functions. The actions
function uses the parameters Event and Object . If clicked inside any of the button, the Object
o stores the string that is the label of that particular button. Inside the action() function, which
keeps a record of all the actions of the user, we have the condition. If the user clicks on the
button named "Hide", o will be "Hide" and in that case we are hiding the button. If, on the
other hand , the user has clicked on "Show", we show back the button.

zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button a, b, c;
public void init()
{ a = new Button("Enable");
b = new Button("Disable");
c = new Button("Hello");
add(a);
add(b);
add(c);
}
public boolean action(Event e,Object o)
{ if("Enable".equals(o))
{ c.enable();
}
if("Disable".equals(o))
{ c.disable();
}
return true;
}
}

This program works exactly like the previous one. But instead of hide() and the show() , we
have the enable() and the disable() . It is hard to find another program more self-explanatory.
Most of the functions that work with buttons also work with other members of the AWT, for
e.g., a textfield can be hidden/shown or disabled/enabled too.

TextField
zzz.java

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (17 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button b;
TextField t;
public void init()
{ b = new Button("click");
t = new TextField(60);
add(b);
add(t);
}
public boolean action (Event e, Object o)
{ if ("click".equals(o))
{ showStatus(t.getText());
t.setText("Hello how are you");
}
return true;
}
}

We create a TextField 60 characters long and a button to go along with it. When clicked on the
button, first the text already present in the TextField will be shown in the status bar. Then, its
text of is set to "Hello how are you". The programs here can be a little hard for the people not
really conversant with programming. It can be further simplified as follows...
public boolean action (Event e, Object o)
{ String s; boolean b;
s = "click";
b = s.equals(o);
if (b)
{ showStatus(t.getText());
t.setText("Hello how are you");
}
return true;
}

appendText()
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button b;
TextArea t;
public void init()

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (18 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

{ b = new Button("click");
t = new TextArea(5,60);
add(b);
add(t);
}
public boolean action (Event e, Object o)
{ if ("click".equals(o))
{ showStatus(t.getText());
t.appendText("Hello how are you");
}
return true;
}
}

We have a text field that has 5 lines and 60 columns. In the action() we don't say setText, but
appendText . This means that the text provided in this way will be added on to the text already
present in the text field.

CheckboxGroup
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ CheckboxGroup g;
Checkbox a, b, c;
public void init()
{ g = new CheckboxGroup();
add(a = new Checkbox("Good", g, false));
add(b = new Checkbox("Bad", g, false));
add(c = new Checkbox(null , g, true));
}
public boolean mouseUp(Event e, int x, int y)
{ showStatus("state of a..." + a.getState() + "
state of c..." +c.getState());
return true;
}
}

The CheckboxGroup is, in effect, a collection of checkboxes. But, too weirdly to be argued,
the CheckboxGroup looks like our usual radio buttons. Here we create an object g that looks
like a CheckboxGroup, and in the init function, we initialize it. We add to it three Checkboxes,
named "Good", "Bad" and null respectively (null is not a name, it means that no name has
been given). We also have to tell that the checkbox belongs to which CheckboxGroup, as in

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (19 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

our case is g . The third parameter tells which Checkbox will be currently active. In plain
English, this means that when we run the program, the third one will be active. After that if we
click in, say, the Checkbox a, and then clicked inside the window, the showStatus() will show
us that the "state of a..." is true and that of c is false.

Choice
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ List l;
Choice c;
public void init()
{ c=new Choice();
c.addItem("xxx");
c.addItem("yyy");
c.addItem("zzz");

l = new List();
l.addItem("a1");
l.addItem("a3");
l.addItem("a2");
add(l);
add(c);
}
}

We have a List l and a list box (or a Choice as it is called). To the Choice , we add three items
with addItem ... xxx, yyy and zzz . Likewise, to the List we add a1, a3 and a2 . We are not
really drunk to have the order as a1, a3, a2 and our basic arithmetic is not all that weak either.
It is plainly to demonstrate that the items do not get added in a sorted order. After adding the
items to the List and Choice , we add them to the Applet window with the add() . That, and a
little tinkering with the functions of the previous examples will have you deft in Lists and
choices in minutes.

delItem()
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ List l;
Button b;
public void init()

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (20 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

{ b = new Button("Remove");
l = new List(3, false);
l.addItem("aaa");
l.addItem("bbb");
l.addItem("ccc");
l.addItem("ddd");
l.addItem("eee");
add(l);
add(b);
}
public boolean action (Event e, Object o)
{ if("Remove".equals(o))
{ l.delItem(1);
}
return true;
}
}

First a list of 5 members is created (though only 3 will be visible because we specify so) and
added to the applet window. A button called "remove" is created. When the user clicks on this
button, we delete the item number 1 from the list using delItem() . Note that when we specify
1, the second item gets the scissors because the items start from 0 onwards. Also the 'false' that
we specify in the statement new List() (or for the C++ folks, in the constructor) means that
multiple selection will not be allowed from the list. If we want to allow multiple selection of
the items in a list, we have to specify it as true. consider the following code...

Multiple Selection
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ List l;
public void init()
{ l = new List(3,true);
l.addItem("aaa");
l.addItem("bbb");
l.addItem("ccc");
l.addItem("ddd");
l.addItem("eee");
add(l);
}
}

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (21 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

Now you can select more than one options of the list at the same time.
getSelectedIndex() and getSelectedItem()

zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ List l;
int i=0;
String s;
public void init()
{ l = new List(3,false);
l.addItem("aaa");
l.addItem("bbb");
l.addItem("ccc");
l.addItem("ddd");
l.addItem("eee");
add(l);
}
public boolean handleEvent(Event e)
{ if (e.target instanceof List)
{ i=l.getSelectedIndex();
s=l.getSelectedItem();
showStatus("Name.."+s+"..no.."+i);
}
return true;
}
}

When an item of the list is selected, the showStatus() will display the number of the item
selected and its name on the status line. The getSelectedIndex() returns the number of the item
that was selected, and the getSelectedItem returns a string that is the name of the item selected.

countItems()
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ List l;
public void init()
{ l = new List(3,false);
l.addItem("aaa");
l.addItem("bbb");

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (22 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

l.addItem("ccc");
l.addItem("ddd");
l.addItem("eee");
add(l);
}
public boolean mouseUp(Event e, int x, int y)
{ showStatus("Number of items.."+l.countItems());
l.clear();
return true;
}}
When clicked with the mouse, the countItems() will display the number of items in the list box
on the status line. The clear() should clear the list but for some old grudge, it does not. (Beta
version?)

Scrollbars
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Scrollbar s;
public void init()
{ setLayout(new BorderLayout());
s = new Scrollbar(Scrollbar.HORIZONTAL,10,5,1,100);
add("North",s);
}
public boolean mouseDown(Event e, int x,int y)
{ s.setValue(s.getValue()+5);
showStatus("value " + s.getValue());
return true;
}
}

The above program gives you a horizontal scrollbar with 1 as the minimum value for the scroll
bar and 100 as the maximum value/limit. The parameter 10 is the starting point. Everytime we
click, we increase the value of the scrollbar by 5. A noteworthy feature is that we'd rather have
the borderlayout because the scrollbars are better off in the corners. I still have to see a
scrollbar which reposes in the centre of a window.

Labels
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (23 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

{ public void init()


{ Label l=new Label("good");
add(l);
}
}

Inside the init(), we initialize a Label and call it "good". We add it to the current Applet
window. When you run the above code, you see a label on the screen.
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ public void init()
{ setLayout(new BorderLayout());
Label l=new Label("good");
add("North",l);
}
}

Here we explicitly state the layout we desire, viz., BorderLayout. Then we add the Label to the
North. In this way, we can control the positioning of a label.

Text Area
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ TextArea t;
public void init()
{ t=new TextArea();
add(t);
}
public boolean mouseMove(Event e, int x, int y)
{ t.setForeground(Color.blue);
if (t.inside(x,y))
{ showStatus("in");
setBackground(Color.red);
}
else
{ showStatus("out");
setBackground(Color.blue);
}
repaint();

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (24 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

return true; }
}

With the setForeground() function, the color of the TextArea is set to blue. The inside() , if fed
with two parameters, obediently tells us if the mouse is inside the scope of the text area or not.
Depending on whether the mouse is within the text region or outside it, we alternate
background colors. If inside, then red, if out, blue. Side by side, the showStatus also shows
whether the cursor is "in" the text area or not.

zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ TextArea t;
public void init()
{ t=new TextArea();
add(t);
}
public boolean handleEvent(Event e)
{ if(e.target instanceof TextArea)
{ t.setForeground(Color.blue);
setBackground(Color.red);
}
else
{ setBackground(Color.blue);
}
repaint();
return false;
}
}

With this porgram, we introduce the handleEvent() . If the user types inside the textarea or has
the mouse inside the region (this is determined through instanceof ), the foreground color is set
to blue and the background color to red.

getText()
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button b;
TextArea t,u;

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (25 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

public void init()


{ b = new Button("click");
t = new TextArea(10,50);
u = new TextArea("Hello ...",5,10);
add(b);
add(t);
add(u);
}
public boolean action (Event e, Object o)
{ if ("click".equals(o))
{ showStatus(t.getText()+"....."+u.getText());
}
return true;
}
}

We have a button and two text areas. The button is named "click". The text area called t is
placed at 10, 50 and the one called u is placed at 5, 10. But notice the difference. u is given a
text to be displayed as an initial text ("Hello ..."). Now, when the user clicks on the button, we
get the text of u and show it as the status. Therefore, the status will be "Hello ...".
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ List l;
TextArea t;
Button b;
int i=0;
public void init()
{ t = new TextArea(3,10);
l = new List(3,false);
b= new Button("click");
l.addItem("aaa");
l.addItem("bbb");
l.addItem("ccc");
l.addItem("ddd");
l.addItem("eee");
add(l);
add(t);
add(b);
}
public boolean action(Event e, Object o)
{ if("click".equals(o));

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (26 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

{ i = l.countItems();
for(int j = 0; j < i; j++)
t.appendText(l.getItem(j));
}
return true;
}
}

Quite a simpleton program, this one. We have a list with 5 items and a text area. Now the
names of all the items in the list are to be appended to the text area. Even a blonde could crack
this one :) But consider the following code and try to figure what it does...
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ List l, m;
Button a, b, c;
TextArea t;
int i = 0;
String s;
public void init()
{ l = new List(3, false);
m = new List(5, false);
a = new Button("Add");
b = new Button ("Del");
c = new Button("Go");
t = new TextArea(5,30);
l.addItem("aaa");
l.addItem("bbb");
l.addItem("ccc");
l.addItem("ddd");
l.addItem("eee");
add(l);add(a);add(b);add(c);
add(m);add(t);
}
public boolean action(Event e, Object o)
{ if("Add".equals(o))
{ s=l.getSelectedItem();
m.addItem(s);
}
if ("Del".equals(o))
{ if (m.countItems() > 0)
{ i=m.getSelectedIndex();

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (27 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

m.delItem(i);
}
}
if("Go".equals(o))
{ t.setText(" ");
for(int k = 0; k < m.countItems(); k++)
t.appendText(m.getItem(k)+"...");
}
return true;
}
}

Cryptic clues: Add will add to the other list box, delete will delete from the second list, go will
show the items in the second list on the text area

Or try another modified form of this one:

zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ List l,m;
Button a,b,c;
TextArea t;
int i=0;
String s;
public void init()
{ l = new List(3,false);
m = new List(5,false);
a = new Button("Add");
b = new Button ("Del");
c = new Button("Go");
t = new TextArea(5,30);
l.addItem("aaa");
l.addItem("bbb");
l.addItem("ccc");
l.addItem("ddd");
l.addItem("eee");
add(l);add(a);add(b);add(c);
add(m);add(t);
}
public boolean action(Event e, Object o)

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (28 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

{ if("Add".equals(o))
{ i=l.getSelectedIndex();
s=l.getSelectedItem();
m.addItem(s);
l.delItem(i);
}
if ("Del".equals(o))
{ if (m.countItems() > 0)
{ s=m.getSelectedItem();
i=m.getSelectedIndex();
m.delItem(i);
l.addItem(s);
}
}
if("Go".equals(o))
{ t.setText(" ");
for(int k = 0; k < m.countItems();k++)
t.appendText(m.getItem(k)+"...");
}
return true;
}

Threads: The stretchy skeins of possibilities

It is a poorly-kept secret how programmers quail at embarking on learning a new concept.


When they begin, they look like they were waiting for the dentist's drill and by the time they
wind up, they give the impression they just got trampled in a thousand-cow stampede! The
concept of threads, though relatively fresh, is by no means one of these gut-wrenching features
of Java. We will address threads very soon, but let us first consider the following code..
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{
Image m[];
int i=0;
int a=0, b=0;
int j = 1;
public void init()
{

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (29 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

m = new Image[10];
for (i = 0; i<10; i++)
{
m[i] = getImage(getCodeBase(), "T"+j+".gif");
j++;
}
i=0;
}
public void paint(Graphics g)
{
g.drawImage(m[i], a, b, this);
}
public boolean mouseUp(Event e, int x, int y)
{
repaint();
i++;
if (i == 10)
i = 0;
a = x;
b = y;
return true;
}
}

From the animator examples in the subdirectory demo, we picked up the ten *.gif files and this
is the way you can animate them.The above code is to display an image out of the 10 every
time you click. As seen in the earlier programs, an image was displayed wherever you clicked.
Here the concept is very much the same, only everytime a new image is displayed. From an
array of images, each image is picked up individually. After the 10th image is displayed, the
counter is set to 0 again. To acquaint you with these pictures well enough, so that you can
percieve the roots of animation clearly, we will now display 10 images at different
coordinates.

zzz.java
import java.applet.*;
import java.awt.*;

public class zzz extends Applet


{
Image m[];
int i, j = 1;
public void init()
{

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (30 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

resize(600, 400);
m = new Image[10];
for (i = 0; i<10; i++)
{
m[i] = getImage(getCodeBase(), "T"+j+".gif");
j++;
}
}
public void paint(Graphics g)
{
g.drawImage(m[0], 5, 10, this);
g.drawImage(m[1], 120, 30, this);
g.drawImage(m[2], 240, 50, this);
g.drawImage(m[3], 360, 70, this);
g.drawImage(m[5], 480, 100, this);

g.drawImage(m[6], 5, 130, this);


g.drawImage(m[7], 120, 170, this);
g.drawImage(m[8], 240, 200, this);
g.drawImage(m[9], 360, 230, this);

}
}

Now we will display the above-seen images at the same coordinates to get the effect of
animation.
zzz.java
import java.applet.*;
import java.awt.*;

public class zzz extends Applet


{
Image m[];
int i;
int j = 1;
public void init()
{
m = new Image[10];
for (i = 0; i<10; i++)
{
m[i] = getImage(getCodeBase(), "T"+j+".gif");
j++;
}

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (31 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

i = 0;
}
public void paint(Graphics g)
{
g.drawImage(m[i], 50, 100, this);
}
public boolean mouseUp(Event e, int x, int y)
{
repaint();
i++;
if (i == 10)
i = 0;
return true;
}
}

The next program demonstrates what necessiates the concept of threads.

zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{
int i=0;
public boolean mouseUp(Event e, int x, int y)
{
for(int k=0;k<10000;k++)
{
i++;
showStatus("i..."+i);
repaint();
}
return true;
}
public void paint(Graphics g)
{
g.drawString("i..."+i, 50, 100);
}
}

When you run the above program, a click of mouse will take us into the loop of 10000.
showStatus() does the work of displaying whatever is passed to it as a parameter.Therefore,
the value of i will continuously be incremented and shown as the status. Now, consider the

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (32 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

following code...

zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{
int i=0;
Button b;
public void init()
{
b=new Button("hell");
add(b);
}
public boolean mouseUp(Event e, int x, int y)
{
for(int k=0;k<1000;k++)
{
i++;
showStatus("i..."+i);
repaint();
}
return true;
}
public boolean action (Event e, Object o)
{
if("hell".equals(o))
showStatus("button clicked");
return true;
}
public void paint(Graphics g)
{
g.drawString("i..."+i, 50, 100);
}
}

Don't despair, the Button is introduced here, only to show that until the loop of incrementing i
does not get accomplished, you are hapless with the Button. As for now, rack your brains and
run the program.

While it is against our religious beliefs to cavil over trivia, it is also essential to know of some
Tid-bit functions that come along with threads. They might come in handy when threads try to
play hob with you. Let us check out the first one, which, infact, is the solution to an array of

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (33 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

problems.
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet implements Runnable
{
public void run()
{
}
public boolean mouseUp(Event e, int x, int y)
{
Thread t;
t = new Thread(this);
showStatus(t.toString());
return true;
}
}

The toString() does the work of converting the relevant details into a string form. Here we use
toString() with t, so the 'relevant details' are the details of the thread t. When this converted
string is specified as a parameter to the showStatus, the value is displayed on the show status.
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet implements Runnable
{
public void run()
{
}
public boolean mouseUp(Event e, int x, int y)
{
Thread t;
t = new Thread(this);
t.start();
list();
return true;
}
}

The list(), (which is the only new thing introduced here - in case you are wondering about the
necessity of the above program), tells you what are the components of the current window and
what are the threads currently executed.
zzz.java

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (34 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

import java.applet.*;
import java.awt.*;
public class zzz extends Applet implements Runnable
{
public void run()
{
}
public boolean mouseUp(Event e, int x, int y)
{
Thread t;
t = new Thread(this);
showStatus(t.getThreadGroup().toString());
t.getThreadGroup().list();
return true;
}
}

The ThreadGroup() will list the different threads executed at the moment when clicked with
the mouse. But the hitch is that this output is available only in the DOS shell,i.e., if you switch
to the DOS shell from the Windows environment.
zzz.java
import java.applet.*;
import java.awt.*;
class ttt extends Thread
{
zzz a;int i=0;
ttt( zzz z)
{
super("good");
a = z;
}
public void run()
{
while ( true)
{
i++;
a.repaint();
a.showStatus(getName());
}
}
}
class uuu extends Thread
{

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (35 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

zzz a;int j=0;


uuu(zzz z)
{
a = z;
}
public void run()
{
while ( true)
{
a.showStatus(getName());
j++;
a.repaint();
}
}
}
public class zzz extends Applet
{
uuu u;
ttt t;
public void init()
{
u = new uuu (this);
t = new ttt (this);
t.start();
u.start();
}
public boolean mouseDown(Event e, int x,int y)
{
u.setName("bad");
return true;
}
}

The super() will give a name to the thread (whatever provided as the parameter will be the
name given to the thread). In the ttt class, we name it as "good". In the mouseDown(), we set
the name of the thread u to "bad". So, now the run(), which is supposed to show the name of
the thread will alternate between "good" and "bad".

zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet implements Runnable
{

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (36 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

public void run()


{
}
public boolean mouseUp(Event e, int x, int y)
{
Thread t;
t = new Thread(this, "good");
showStatus(t.getName());
return true;
}
}

The yield()

As must be evident, while creating the new thread t, we are also giving it the name of "good".
This is another way of giving your thread a name. Now when we show the status of the thread,
the getName() will display "good".
zzz.java
import java.applet.*;
import java.awt.*;
class ttt extends Thread
{ zzz a;
int i=0;
ttt( zzz z)
{ a = z;
}
public void run()
{ while ( true)
{ yield();
i++;
a.repaint();
a.showStatus(getName());
}
}
}

class uuu extends Thread


{ zzz a;int j=0;
uuu( zzz z)
{ a = z;
}
public void run()
{ while ( true)

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (37 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

{ j++;
a.repaint();
a.showStatus(getName());
}
}
}
public class zzz extends Applet
{ uuu u;
ttt t;
public void start()
{ u = new uuu (this);
t = new ttt (this);
t.start();
u.start();
}
public void paint(Graphics g)
{ g.drawString("i .." + t.i,1,20);
g.drawString("j .." + u.j,1,60);
}
}

BREWING JAVA - THE FIRST SIP

Brrr....Its Hot : -

We briefed you on what the Java ballyhoo is all about. Bet you are throbbing for the innards of
Java programming by now. We will get down to that right off the bat.

Before we hop on to savor the wondercoffee, however, let up get clear on one thing. The Java
mug actually has two shades to it. For one. You can write applets , which will wriggle down
the cast skeins of Internet cables on to a user's terminal, with the browser picking up the
cudgels to execute them. As the other shade, you can write Java standalone programs, which
will compile and execute on the user's local machine. As promised, in this series, we will
master the techniques of creating such stand-alone Java programs and calling them your own
(though we really like calling internet-independent programs).

Owing to security reasons, there is an array of functionalities which the applets are denied by
the rather rigid duo of Java and the Java-enabled browser. On the other hand, the stand-alone
programs are, fortunately, spared from the security rigmarole. That gives us one good reason
to pursue such programs.

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (38 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

Unfortunately for the people who want to run without bothering to learn to walf first, we will
stick to our rituals, that is, a step-by-step approach to programming. As regards our naming
conventions, we do not intend to inculcate style-specific practices. Quite the contrary, we
intend development of initiative and understanding. Hence, the names of our classes, functions
and variables will not exceed three letters. In case you overlooked, the presence of classes etc.
Also presupposes the fact that the reader is versed to a reasonable extent with C/C++

With that widget of wisdom up our sleeve, let's take the first sip. Make sure you are in the
DOS mode and running a text editor of your choice. (According to our reliable astrologer, Edit
serves the purpose well enough).
zzz.java
class aaa
{
}

Well, that's admittedly a simple program. We define a class by the name of aaa. Mark that the
name of our java file is zzz.java, which implies that the names of the class and the .java file do
not matter so much now, though they will soon begin to. Hopefully, you know that the
program has to be compiled before it can be executed. The Java compiler is called javac. So
now we key in the following command at the DOS prompt.

javac zzz.java

The compilation process turns out to be comfortably peaceful and a file called aaa.class is
created by javac. Which indicates that Java makes .class files instead of the usual .obj (the
cheeky chappies at Sun were always creative with their names anyway). It is now a fair idea to
try and execute the program. For this, we have to type :

java aaa

Bet you have realized that this command would actually read : java aaa. Class since we are
trying to execute the .class file. But a period (.) is supposed to be a part of file path in Java, so
we'd rather you skip the .class part out. The program, though successfully compiled, refuses to
run without hassles. It flings the error message : In class aaa: vodi main(String argv[]) is
undefined. If anything, that error message smacks nostalgically of C - main() and all. So we
very willingly add the main() to our code. Consider the following code...

zzz.java
class aaa
{
void main( String s[] ) { }
}

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (39 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

Our main() has one argument - an array called s. This array will contain strings, hence the
String. It is similar to your argv in C, the only variation being, the number of parameters are
not specified. A point to be noted here is that arrays in Java and C differ slightly. C gave no
errors even if you tried to refer to an element outside the actual size of the array. That is,
assuming we have an array a[10]. The size of the array is 10. While using C, we could
cheerfully say a[11] in the program without any errors, though the output would be some out-
of-this-world junk. Java, however, has built-in error checks that keep a track of the number of
members and prevent us from going beyond the specified limit.

When we javac the above code, it compiles quite conveniently. However, it refuses to run.
This time the error shown is : In class aaa: main must be public and static. By default, the
main() is private and hence, the others cannot avail of it. The simple reason why it must be
public is that it should be visible to others (e.g., other classes, other programs and very
importantly, our own Java Run time system). In plain English, when we say java aaa, the Java
runtime system contacts the class aaa, looks for a function called main() init. But since the
function has not been declared as public, the system cannot look into it.

As regards static, a C++ programmer should be very well-versed with it. Ordinarily, to access
a function inside a class, we have to define an object that looks like that class and access the
function through the object. But by defining main() as static, we can access it directly, without
needing to create an object that looks like class aaa. So we modify the code as follows...

zzz.java
class aaa
{
public static void main( String s[] ) { }
}

After all those changes, the program finally works. But sadly, there is no attractive output
because we have admittedly done nothing in the main(). Let us go right ahead and add some
code. Retain the name of the java file.

zzz.java
class aaa
{
public static void main( String s[] )
{
System.out.println("in main");
}
}

Everytime we use java, we have a free reign to use the objects that are pre-created, so we are

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (40 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

spared the burden of creating our own objects. One very helpful of these objects is System
(and note the case because Java is pretty unforgiving with case-errors), which in turn has
various other objects in it. In our case, the object is called out. From out, w use a function or a
method called println, which can safely be likened to printf in C. Just like printf, whatever we
snuff inside the double quotes will be snuffed out on the screen. So when we run this program,
ofcourse after compiling, it will display the string "in main".

A program in any self-respecting language is virtually useless unless it makes use of variables.
Since Java is surely one of them, let us add a variable to the code...
zzz.java
class aaa
{
public static void main( String s[] )
{
int i = 0;
System.out.println( "in main.i.."+i );
}
}

We choose to call our variable i. It is of the type int, and it is inside main(). It is initialized to
0. That very eloquently shows that Java looks and feels like C/C++. However, the println
scores over the strict, old printf. Note that we are displaying a string - - "in main.i.." and the
variable i.Unlike C, Java figures out how to display two different data types at the same time,
chucking out the fuss involved in the cumbersome conversions.
The output of the above program will be...

in main i..0
The object String has a member called length. Since s (in the definition of the main()), looks
like a String, we can access length through s. That's what our next program speaks about.
zzz.java
class aaa
{
public static void main( String s[] )
{
int i;
i = s.length;
System.out.println("in main.i.."+i);
}
}

When you run the above program, with the command line being java aaa, you will see the
output:

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (41 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

in main.i...0

This is because the command line has to have some arguments besides the java aaa. For
instance, if you type out java aaa a b c, the output will be

in main.i...3

Which is to say that the object String works very much like argv[] of C, while the length can
be likened to argc. The array s stores the command line arguments (that is, whatever you type
besides java aaa) and length counts the number of extra arguments typed in. Now if we want to
display the actual elements, we can do that by saying s [0, s [1] and so on. In our case, for
example, when we say s[0] it will print the a, s[1] will print b and s[2], c). Let us see for
ourselves how...

zzz.java
class aaa
{
public static void main( String s[] )
{
int i;
i = s.length;
System.out.println("in main.i.."+i);
System.out.println("in main s[0] ..." + s[0]);
}
}

If you run the above program without any extra parameters, it will display the error..

java.lang.ArrayIndexOutOfBoundsException

To check for that, we can modify the program a little...

zzz.java
class aaa
{
public static void main( String s[] )
{
int i;
i = s.length;
System.out.println("in main.i.."+i);
if (i > 0)
System.out.println("in main s[0] ..." + s[0]);

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (42 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

else
System.out.println("no parameters");
}
}

In the above program, we check whether the user has entered anything other than java aaa with
the if condition. That is because i stores the number of these extra arguments. If the user has
entered nothing, we display "no parameters", otherwise we display the first additional
argument. All the arguments can be displayed inthe following way...

zzz.java
class aaa
{
public static void main( String s[] )
{
int i;
i = s.length;
System.out.println("in main.i.."+i);
if (i > 0)
for (int j = 0; j < i; j++ )
System.out.println("in main .."+ j +"..." + s[j]);
else
System.out.println("no parameters");
}
}

The above code checks for the presence of extra arguments, and if present, it displays all of
them.

Consider this code for another minor revelation...


zzz.java
class aaa
{
int i = 0;
public static void main( String s[] )
{
System.out.println( "i.." + i );
}
}

Here the compilation will give an error saying : can't make static reference to a nonstatic
variable i in class aaa. That is because main() is a static function and static functions cannot

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (43 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

refer to any variables outside their own body. Whereas, in the above program, our variable i is
a global variable, i.e., it is defined outside any function. So it cannot be referred by the
main() . The only way to access in a case as this is by making i static. This can be done by
rewriting the first line in the function as static int i = 0;

Before we bid adieu

We believe we have made our technique sufficiently clear by now. Ofcourse, with the kind of
programs illustrated here, we can not look forward to a prize in the field of computer sciences.
But yes, we make no compromises with our fundamentals. As regards the concepts of Java,
there are quite a few potatoes in the sack. We promise to bring you all of them in elaborate
detail and with a similar simple, step-by-step approach to programming. Whatever the
implications of how Java is being accepted as a popular language or how it is starting a whole
new revolution, one fact remains undeterred. It definitely is the harbinger of a dynamic future.
Sun Microsystems, by introducing the unprecedented concept, has planted a stake in the sand.
What we make out of it is in our hands.

With a little help from my friends

There are so many of us out there goofing up our programs trying hard to figure out the myriad
concepts of Java and so few who actually seem to be getting anywhere. The least we can do is
be together in cyberspace and share our experiences and knowledge. All your comments,
queries, headaches, suggestions and experiences, both of the moments of bright flashes of
understanding and the baffling times are welcome. You can reach us at : vmukhi@vsnl.com.
We might serve as Java Aspirins for your digital headaches :) .

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (44 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (45 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

Contents | Foreword | About the Authors | Introduction |


Appendix |Chapter 1 |Chapter 2 |Chapter 3 |Chapter 4 |Chapter 5 |Chapter 6 |
Chapter 7 |Chapter 8 |Chapter 9 |Chapter 10 |Chapter 11

http://www.vijaymukhi.com/documents/books/javajsp/chap0.htm (46 of 46) [5/2/2008 10:52:14 PM]


Java-Servlets-JSP

1. Evolution of Java

Things that you are aware of today haven't always existed nor have they suddenly emerged.
They have evolved over a period of time to fulfill our ever-growing needs. Similarly, Java has
evolved as the savior to meet the growing needs of the world. It incorporates useful elements
from languages like C and C++.

When you surf the Internet, you use a browser, which is also called a user agent, that enables
you to view web pages and transfer data over the Internet. The most familiar among the
browsers are Netscape Navigator and Internet Explorer. So what happens when you view a
web page? Technically speaking, you connect to a web server and download an html file. In
other words, this html file comes over onto your computer. Before Java, the downloaded file
contained no intelligence. In that sense, the web page was static. Sun Microsystems answered
our need for dynamism by developing Java. Java brought with it the ability to download an
actual program and at the same time execute it in our browser.

'Will Java save the world or not?' Inquisitive as you may be, wait a while and you will enjoy
the fruits of patience. The philosophy of Java and its history can be understood only gradually,
in light of the knowledge you will soon gain.

Having looked into the brief origin of Java let us start on our journey.

JAVA, The Programming Language

Let us begin with the basics. Every programming language has certain rules and programs
written in that language have to follow these rules. A similarity can be drawn to spoken
languages like English, French, etc. each of which has its own rules.

Given below is the smallest program written in the Java Programming language. To begin
writing your first program, you must click on the Start button, go to the dos prompt and type
edit z.java. But before typing in edit, create a sub directory called javaprg where you will save
all your files. We have called the sub directory javaprg but you can call it by any name you
like.
c:\javaprg>edit z.java

z.java
class zzz
{
}

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (1 of 39) [5/2/2008 10:53:54 PM]


Java-Servlets-JSP

Now, type the code given above. Once you have written the code, you must save the file. In
order to do so, activate the menu option File by pressing the keys Alt-F and then the menu
option Exit. Press Y at the MessageBox which asks you whether you want to save the file or
not.

We have done our coding under Windows but you can do the same under Linux or any other
Operating System, the results will be the same.

Let's understand the code.

This program begins with the word class. A class is a collection. Every class is identified by its
name. In this program, we have named the class zzz. In case you are sleepy, you might think
of it as a snore, in that case, change the name to awake. In other words, a class can be given
any name you like. But if you'd rather followed our naming conventions, then name it zzz.

A class being a collection obviously means you have to put something in it. In order to contain
something in a class use curly braces,'{' to indicate the start and '}' to indicate the end of a
collection.
The program must begin with the word class followed by '{' and '}'. This is what we mean by
programming language rules. Each programming language has its own grammar, its own
syntax for writing code.

Every Java program has to have at least one class and anything to do with Java has to be
placed in a class.

Now, something has to understand the code that you have just typed and that something is the
compiler. So you now need to run this, the smallest Java program, through a Java compiler and
execute it. The compiler in the Java programming language is called javac. Javac is part of
what is called the Java Development Kit or JDK in short. The JDK can be freely downloaded
from the Sun Microsystems site. In order to execute your program, give the command javac
z.java at the dos prompt.

C:\javaprg>javac z.java

No errors, Great!! Now execute the dir command.

( If you see any errors on your screen, set the path variable as c:\javaprg>set
PATH=c:\jdk1.2.2\bin;%PATH% )

C:\javaprg>dir

Volume in drive C is SONAL

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (2 of 39) [5/2/2008 10:53:54 PM]


Java-Servlets-JSP

Volume Serial Number is 0661-13EE


Directory of C:\javaprg

. <DIR> 04-26-00 4:11p .


.. <DIR> 04-26-00 4:11p ..
ZZZ~1 CLA 178 04-26-00 4:15p zzz.class
Z~1 JAV 17 04-26-00 4:12p z.java
2 file(s) 195 bytes
2 dir(s) 5,214.56 MB free

You will see two files listed. One is the .java file that you created and the other is a file with
the .class extension. Javac - the java compiler expects the java program to have a .java file
extension.

On closer observation, you will notice that the .class file is displayed as zzz.class. The name of
the .java file i.e. z.java is of little importance to the java compiler. The compiler gives weight
to the class name, which in our case is zzz. Thus, the file named zzz.class gets created. Had we
named the class xxx, the resultant file would have been xxx.class.

Applets

As mentioned earlier, one of the advantages of Java is that it enables you to create programs
that execute within a browser. Henceforth, we will call a java program an applet. Thus, an
applet is a java program which can be executed within a browser. It helps transform the static
HTML pages into documents full of life, interaction and vitality.

How can we execute an applet in a browser?

Browsers only understand html or html tags. Amongst these tags there is one by the name of
applet. You embed an applet in an HTML page using the applet tag. To understand this better,
create a file called a.html. This can be done using any word processor. Type the following
code:

a.html
<applet code=zzz.class></applet>

What does this mean? <applet> is a tag and </applet> indicates the end of the tag. The code
attribute is used to provide the name of the class file, which in our case is zzz.class.
Alternatively, you can simply write zzz. Our code resides in the class file. Now that you have
embedded the applet in an HTML file by the name of a.html, you will need to open a.html in a
browser.

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (3 of 39) [5/2/2008 10:53:54 PM]


Java-Servlets-JSP

You can use Internet Explorer or Netscape Navigator to open this file. However, there is a
possibility that you may have neither IE nor Netscape. Not only did Sun consider this
possibility but also when they first released java there were no browsers that supported it.
Hence they gave us a browser that understands only the applet tag, one that can run only java
applets. They called this browser the appletviewer.

We will use the appletviewer. At the command prompt type appletviewer a.html

C:\javaprg>appletviewer a.html

Warning: <applet> tag requires width attribute.


Warning: No Applets were started. Make sure the input contains an <applet> tag.
usage: appletviewer [-debug] [-J<javaflag>] [-encoding <character encoding type> ] url|file ...

What do these warnings mean? The appletviewer has come back with warnings saying that it
needs an attribute called width.

Since the applet will be shown in the browser window, it needs the width to ascertain how
large width-wise, the window should be. Add the width attribute in the html file as follows:
a.html
<applet code=zzz.class width=200></applet>

Now run the applet viewer by typing the following:


C:\javaprg>appletviewer a.html

Output
Warning: <applet> tag requires height attribute.Warning: No Applets were started. Make sure
the input contains an <applet> tag.usage: appletviewer [-debug] [-J<javaflag>] [-encoding
<character encoding type> ] url|file ...

The appletviewer comes back asking for another attribute called height. Java doesn't seem to
believe in the 'reveal all' concept, it divulges slowly. You have no choice but to add the height
attribute in a.html. The order here is not important, the attributes can be interchanged. A
browser would display the applet in its window. Thus, it wants to know the width and height
of the window it should give the applet.

Your code should resemble the following:

a.html
<applet code=zzz.class width=200 height=300></applet>

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (4 of 39) [5/2/2008 10:53:54 PM]


Java-Servlets-JSP

Run the appletviewer. It should run this time.

C:\javaprg>appletviewer a.html

Finally, the appletviewer seems to give no problems. You see a small window, at the bottom
of which, are displayed some messages and finally it says, Start: applet not initialized.

The above indicates that the applet didn't work. We have an error. Close the window and
return to dos. Here you will see the following error message or messages.

load: zzz.class is not public or has no public constructor.


java.lang.IllegalAccessException: zzz
at java.lang.Class.newInstance0(Native Method)
at java.lang.Class.newInstance(Class.java:241)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:508)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:444)
at sun.applet.AppletPanel.run(AppletPanel.java:282)
at java.lang.Thread.run(Thread.java:479)

The message says that zzz.class is not public. What does this message mean? Error messages
are rarely meant to be user friendly and can sometimes be difficult to decipher.
A Java program is executable code that comes across the net on to your computer. It could be
programmed to delete your entire hard disk. In that case, you would refrain from visiting sites
on the Internet due to lack of security. To prevent such hazards Java has a lot of inbuilt
security features.
The first form of security is that if you have a class and you don't put the word public in front
of it Java will make it private. Since it is private nobody cannot access it. Thus, by default,
every class is private. This is like security in many modern operating systems. You are not
allowed to access anything unless you are given explicit permissions to do so.

Having understood this, we can rectify the error by adding the word public in front of the
class.

z.java
public class zzz
{
}

Now say:

C:\javaprg>javac z.java

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (5 of 39) [5/2/2008 10:53:54 PM]


Java-Servlets-JSP

z.java:1: Public class zzz must be defined in a file called "zzz.java".


public class zzz
^
1 error

We still have an error. The program now wants the name of the Java file and the name of the
class file to be the same. Sounds stupid doesn't it! Once you create the .class file you don't
need the .java file. Don't abandon Java yet! We have an error only because we have not
followed the conventions, the rules of the language. After all, Rules are Rules! As
preposterous as they may be, they are not to be questioned.

Abiding by the rules, we rename this file to zzz.java.

c:\javaprg>ren z.java zzz.java

Now say:
C:\javaprg>javac zzz.java

Voila! No errors. Run appletviewer with a.html. Cross your fingers and hope that all works
well.

C:\javaprg>appletviewer a.html

As usual another error!!! The same window that we saw earlier ...Start:applet not initialized.

Close the window and get back to dos. You will see the following:

java.lang.ClassCastException: zzz
at sun.applet.AppletPanel.createApplet(AppletPanel.java:508)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:444)
at sun.applet.AppletPanel.run(AppletPanel.java:282)
at java.lang.Thread.run(Thread.java:479)

Here it shows you a different error, ClassCastException : zzz

Now you know why you bought this book.....these lines just don't make sense! You may read
from up or from bottom, it still looks like greek. We have learnt with experience that error
messages are not meant to be readable. If we knew what they meant, we wouldn't make any
mistakes.

Let's get back to some serious work. A class consists of functions. But what are functions? A
function is just program code. More on this just two programs later.

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (6 of 39) [5/2/2008 10:53:54 PM]


Java-Servlets-JSP

A class consists of functions. The appletviewer has been told to call certain functions in your
.class file. Appletviewer expects your applet to have some code or functions in it.
Unfortunately, these functions are not available in your file. Currently, the class in your
program is empty. To avoid adding all that code required by the appletviewer, we will use an
existing class supplied by Sun comprising of these functions. This existing class is called
Applet.

Sun documented the use of the word extends to inform the Java compiler to merge all the
functions or code from the Applet class to our class zzz. Have your code match the following:

zzz.java
public class zzz extends Applet
{
}

Extends simply means that if the class Applet contains 20 functions, then those functions get
added to zzz. It is like physically keying them in yourself. Now let's run javac once again.

C:\javaprg>javac zzz.java
zzz.java:1: Superclass Applet of class zzz not found.
public class zzz extends Applet
^
1 error

This time the error reads: 'Superclass Applet of class zzz is not found'. When you borrow
money from someone, he becomes the lender and you the borrower. In the same way,
whenever you take code from another class, in this case Applet, it becomes a super class or if
you like using new words Applet is the baseclass and zzz the derived class. We must
incorporate these words in our vocabulary to learn Java. The name of the super class is not
Applet; it is java.applet.Applet. In case you are wondering about the long names, let us remind
you that you can't argue with rules. Rewrite your code as given below and then run javac.
zzz.java
public class zzz extends java.applet.Applet
{
}
Run javac and you won't get any errors. Running appletviewer won't give errors either. But
you won't see anything other than 'Applet Started'. Finally, Mission Accomplished!!!

Some more java conventions

Let's be adventurous, put all the code on the same line. Remove the line-breaks and put no

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (7 of 39) [5/2/2008 10:53:54 PM]


Java-Servlets-JSP

spaces other than those between the words. You will find that everything works fine.

zzz.java
public class zzz extends java.applet.Applet{}

Thus, all that extra 'white space' doesn't bother the Java complier. You can use these to make
your program neater and thus more readable.

Java as a language is case-sensitive. If you replace the 'c' of class with a capital 'C', it will give
you errors. It will assume it to be something other than class. So, remember everything is case
sensitive except the {} ( ;-)) . Go ahead, make the change and see for yourself!

zzz.java
public Class zzz extends java.applet.Applet{}

C:\javaprg>javac zzz.java

zzz.java:1: 'class' or 'interface' keyword expected.


public Class zzz extends java.applet.Applet{}
^
zzz.java:1: '{' expected.
public Class zzz extends java.applet.Applet{}
^
zzz.java:1: Public class Class must be defined in a file called "Class.java".
public Class zzz extends java.applet.Applet{}
^
3 errors
You make one error and you get three errors instead! isn't that dumb!
So, be on your guard and don't say we didn't warn you.

Let's finally understand functions with the help of this program.


zzz.java
public class zzz extends java.applet.Applet
{
public void init()
{
resize(300,40)
}
}

What you are writing right now, these lines of code, is what is called a program. And a
function is nothing but program code. We know that there is a function called resize in the

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (8 of 39) [5/2/2008 10:53:54 PM]


Java-Servlets-JSP

class called Applet. In order to call a function, you need the function name. In this case, it is
resize. The resize function requires two values, the width and the height. This is because resize
changes the width and the height of the applet window.

Since we are learning to speak Java, let's call these 'values', 'parameters'. The first parameter is
the width and the second is the height. These values are passed to the function within the '('
and ')' brackets. Like Java, there are other programming languages like C and C++. Java is a
wholesale copy from C and C++. It retained the use of round brackets. We can't change it to
square brackets because that is not the syntax for functions. Consequently, C++ and Java are
similar. If you know one of them then moving on to the other is relatively simple. Compile the
above program using javac. More errors! The error says: ';' expected.

C:\javaprg>javac zzz.java
zzz.java:5: ';' expected.
resize(300,40)
^
1 error

When we see the ')' of the function, we know that the function is over. But nothing seems
obvious to the Java compiler. It requires us to put a semicolon at the end of the statement.
Carriage returns don't matter but semicolons are a must. But why semicolon, why not dots?
The developers of Java were asked to choose a character that would indicate the end of a
statement. Since they couldn't agree on a common character they decided to use their
grandma's recipie- They did "eenie,meenie,mina,mo" and their finger was pointing at the
semicolon and hence they decided on the semicolon! You see RULES are RULES... C
requires semicolons, so does C++ and Java uses them too.

Make your program error free by putting a semicolon after resize, just as we have done in the
following program. Execute it and see the window size change.

zzz.java
public class zzz extends java.applet.Applet
{
public void init()
{
resize(300,40);
}
}

All code in Java must be written within functions. Hence we say that a class is a collection of
functions. Here we haven't put the code of resize, instead we have given it the parameters it
requires and then put the semicolon. By doing so, we are calling the resize function. The code

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (9 of 39) [5/2/2008 10:53:54 PM]


Java-Servlets-JSP

within this function accepted the values and did the needful to resize the window.

Thus, you can call a function by specifying the function name, including the parameters and
ending it with a semicolon.

We didn't explain something in the earlier example and that is the function init. Now is the
time for it. We will also tell you what the words void and return mean. We created the function
by naming the function init and preceded it with the word void. Void means nothing. Here,
void is the return type. Return type indicates the type of value the function will return. That
means a function can return a number or a string or something else entirely. So, what we are
trying to say is that since the init function is preceded with the word void it is not returning
any value. It is of significance to note that functions may or may not return values.

In our program, we have the words public and void preceding the function name. To
understand this, delete the word public. Your program should look as follows:

zzz.java
public class zzz extends java.applet.Applet
{
void init()
{
resize(100,400);
}
}

Run it and you will surely see an error.

C:\javaprg>javac zzz.java

zzz.java:3: The method void init() declared in class zzz cannot override the method of the
same signature declared in class java.applet.Applet.The access modifier is made more
restrictive.
void init()
^
1 error

The error clearly indicates that there is a function/method called init in java.applet.Applet and
we haven't written it in the way it should have been in the class zzz. The init in Applet has the
word public and hence we have to make it public too. Rules... remember? Now, public has to
be called something, so why not call it a modifier. If there is a function with the same name in
the class from which you are borrowing, they both have to have the same modifiers, otherwise,
you can't override it.

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (10 of 39) [5/2/2008 10:53:54 PM]


Java-Servlets-JSP

Here, we have created a function called init. We've created it because we are using the open
and close curly braces {}. Then we are calling a function called resize(). The difference
between creating and calling a function is that you call a function using round brackets () and
end with a semicolon but you create a function using curly braces {}.

We must write the word public in front of init() or else others will not be able to use it or call it
and also because of the earlier error. You probably noticed that init(), though it is a function,
doesn't have a semi-colon(;) following it. This is because when we call a function we put a
semicolon whereas when we create a function we do not. Here we are creating a function
called init().

Why do we have to create a function called init? This is because when the appletviewer starts
up, it calls a function called init. If we have it in our code within the zzz class then our init()
gets called, otherwise, the one from java.applet.Applet gets executed. In our earlier program,
when we did not include 'extends java.applet.Applet' we got an error. This was because one of
the functions appletviewer calls is init().

If you were to replace the small 'i' in init() with a capital 'I', then the appletviewer will call the
init code in Applet and that code doesn't do anything. As you can see Case matters.

zzz.java
public class zzz extends java.applet.Applet
{
void Init()
{
resize(100,400);
}
}

We will now extend our definition of a class by saying that a class is a collection of functions
and within functions you can call other functions.

Let us quickly summarize what we have just learnt.

The appletviewer or any java enabled browser calls init(). Since we included the code of init()
in zzz, our function was called. From our function init(), we called another function, resize,
which changes the size of the window. The code of resize is in java.applet.Applet. So we now
know how to call and create a function.

Let's go one step further and take a look at the next program.

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (11 of 39) [5/2/2008 10:53:54 PM]


Java-Servlets-JSP

zzz.java
public class zzz extends java.applet.Applet
{
public void init ()
{
System.out.println("hi");
}
}

Delete the resize function and instead call another function System.out.println. This function
takes one parameter, which in this example is hi. Unlike numbers, strings must be enclosed
within double quotes.

On running this program neither javac nor the appletviewer will complain. But nothing gets
displayed in the applet window either. Close the window and go back to dos, you will see hi
displayed on the screen.

C:\javaprg>javac zzz.java

C:\javaprg>appletviewer a.html

hi

System.out.println is a function with a long name. It is like resize. The function ends with a
semicolon indicating that we are calling this function. The resize function can be called as it is
because it is found in java.applet.Applet which is a class made available to us.
System.out.println is also a function which is given to us by Java and hence using it will not
result in any error. This function takes a string as a parameter.

The next program says System.out.println ("bye"+ii); it gives you an error saying that it does
not know what ii is.

zzz.java
public class zzz extends java.applet.Applet
{
public void init ()
{
System.out.println("bye"+ii);
}
}

C:\javaprg>javac zzz.java

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (12 of 39) [5/2/2008 10:53:54 PM]


Java-Servlets-JSP

zzz.java:5: Undefined variable: ii


System.out.println("bye"+ii);
^
1 error

We will now introduce the concept of variables, an integral part of computer programming.
zzz.java
public class zzz extends java.applet.Applet
{
public void init()
{
int ii;
System.out.println("bye"+ii);
}
}
This program includes int ii; ii is a variable that looks like an int. int is the short form for
integer. int is a class just like Applet or zzz and is one which the java compiler knows. All
variables are stored in memory, they are words that hold or store a value. To be able to refer to
a vaiable, you have to give it a name. In our program, we have named the variable ii.

Now that the variable has been created it must be given a value otherwise you see the
following error..

C:\javaprg>javac zzz.java
zzz.java:6: Variable ii may not have been initialized.
System.out.println("bye"+ii);
^
1 error

So we give the variable ii a value, 10 .


zzz.java
public class zzz extends java.applet.Applet
{
public void init ()
{
int ii;
ii=10;
System.out.println("hi" + ii);
}
}
C:\javaprg>javac zzz.java

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (13 of 39) [5/2/2008 10:53:54 PM]


Java-Servlets-JSP

C:\javaprg>appletviewer a.html

hi10

What about the '+' sign? The '+' sign enables you to display the string 'hi' along with the value
of the variable ii. Hence the program displays hi10. The '+' here does not mean add, it means
concatenate. Have you been wondering why these named memory locations are called
variables? They are called variables because their values can vary.
The next program makes it clear as to why variables are called variables.

zzz.java
public class zzz extends java.applet.Applet
{
public void init ()
{
int ii;
ii=10;
System.out.println("hi" + ii);
ii=20;
System.out.println("hi" + ii);
}
}

C:\javaprg>javac zzz.java

C:\javaprg>appletviewer a.html

hi10
hi20

In this program, ii is assigned a value 10 initially. The first println displays hi10. Then the
value of ii is changed to 20. The second println prints out hi20.
zzz.java
public class zzz extends java.applet.Applet
{
public void init ()
{
int ii;
ii=10;
System.out.println(ii);
ii= ii +20;
System.out.println("hi" + ii);

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (14 of 39) [5/2/2008 10:53:54 PM]


Java-Servlets-JSP

}
}

C:\javaprg>javac zzz.java
C:\javaprg>appletviewer a.html
10
30

In the above program, initially ii has a value 10. println prints the value of ii ,which is 10.
Thereafter, we have ii= ii+20. Looks confusing, isn't it! Whenever you see '=', always start by
looking to the right of the sign. On the right we have ii+20. You know that ii has a value 10, so
this statement is read as 10+20. This evaluates to 30 and is given to the variable on the left
side of the '=' sign i.e. ii. So the value 30 is stored in ii. println will now display 30.

Thus, a variable is a word in which you store a value and its value can change. Where ever you
use a variable you can use a number and wherever you use a number you can replace it with a
variable.

int is commonly referred to as a datatype but in Java it is called a class. zzz is also a class. A
class can now be redefined as a collection of variables and functions.

Just as we had created our own function init, we create pqr. This function contains the line
System.out.println("hi"); Hence when pqr is called from init, hi is displayed.

zzz.java
public class zzz extends java.applet.Applet
{
public void init ()
{
pqr();
}
public void pqr()
{
System.out.println("hi");
}
}
C:\javaprg>javac zzz.java

C:\javaprg>appletviewer a.html

hi

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (15 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

We now create one more function named xyz. We are now calling the function xyz from the
function pqr.

zzz.java
public class zzz extends java.applet.Applet
{
public void init ()
{
pqr();
}

public void pqr()


{
xyz();
}
public void xyz()
{
System.out.println("In xyz");
}

C:\javaprg>javac zzz.java

C:\javaprg>appletviewer a.html

In xyz

In the above program, the pqr function is calling the function xyz. The xyz function has a
println, which displays "In xyz".

But you cannot have xyz call pqr as it will go into an indefinite loop .

Our next program passes a value to the function pqr.

zzz.java
public class zzz extends java.applet.Applet
{
public void init ()
{
pqr(200);
}
public void pqr(int z)
{

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (16 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

System.out.println("hi"+z);
}
}
C:\javaprg>appletviewer a.html

hi200

This program shows how parameters or values are passed to functions. Here, the value 200 is
being passed to the function pqr. The function pqr receives it in int z. What is z? It looks like
an int. Actually, we are creating a variable called z, which will store the value passed to pqr.
Variables can be called by any name. Earlier we used a variable ii and now we are using z.
You could have called it 'x', the choice is yours! z is also called a parameter.
System.out.println is used to display the value.

Our next program has a function called paint. It takes a value Graphics g. Just like the function
pqr had a parameter z that looked like int, here g is a parameter which looks like Graphics. To
put it a little more technically, we can say that paint and pqr are both called with one
parameter.

zzz.java
public class zzz extends java.applet.Applet
{
public void paint (Graphics g)
{

System.out.println("hi");
}
}

We did not create Graphics; it is available to us free. That's what we are assuming. Run javac
and you will get an error.
C:\javaprg>javac zzz.java

zzz.java:3: Class Graphics not found.


public void paint ( Graphics g)
^
1 error

You have already come across similar errors. The name is not Graphics; it is
java.awt.Graphics. The best way to learn a language is to speak it! Speak big names! Write big
names! Change Graphics to java.awt.Graphics and you don't get an error, everything seems
fine, but you don't see anything on the screen either.

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (17 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

zzz.java
public class zzz extends java.applet.Applet
{
public void paint ( java.awt.Graphics g)
{
}
}

When it comes to speaking, we do so readily but most of us shirk writing. Keeping that in
mind, we will use Graphics to make it concise but will also introduce a new statement as in
import java.awt.* with a semicolon
zzz.java
import java.awt.*;
public class zzz extends java.applet.Applet
{
public void paint ( Graphics g)
{
}
}
'*' implies everything. Note that the semicolon is a part of its syntax. Import does a search and
a replace. Since writing the entire class name is tedious, whenever it sees the name of a class it
adds java.awt. So it adds java.awt to every classname that gives an error. It will not add to
java.applet.Applet because it didn't give an error. So Graphics automatically becomes
java.awt.Graphics. Let's do the same thing for Applet. So we now have two imports.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void paint ( Graphics g)
{
}
}

The first thing that the compiler does is tries Applet as java.awt.Applet. It realizes that it still
gives an error. It then tries as java.applet.Applet and realizes that the error is removed.
Basically, the order doesn't matter. If you prefer using short names, then you will have to use
the import statements.

Thus, you could write the longest of programs without using the word import. But the only
problem is that your hands will get very tired. Java gave us a problem by giving us long names
but at the same time provided a solution to it by giving the import statement.

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (18 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

In the next example, we have included two import functions and a single paint function. The
paint function calls g.drawString.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void paint ( Graphics g)
{
g.drawString("Hi");
}
}

As of now, we will ignore what the dot in drawString really means. With the knowledge you
have already gathered, it must be clear to you that drawString is a function ( ) and ends with a
semicolon. Thus, in effect, we are calling a function. On running the program, you will get an
error saying 'drawString has wrong number of arguments'.

C:\javaprg>javac zzz.java

zzz.java:7: Wrong number of arguments in method.


g.drawString("Hi");
^
1 error

Arguments and parameters are words that can be used interchangeably. Similarly, functions
are analogous to methods.

This is why people like programming in Java. You are like a child and Java the mother. You
make a mistake and you get a spanking! Drawstring must be called with a certain number of
parameters. Goof up and you get errors!

If you are feeling sleepy and you are not drinking coffee, you can't write code in Java ;-)

Let's analyze the reason behind the error. In order to draw a string you must state at what
location on the screen the string is to be displayed. That would mean providing 3 parameters.
The first is the string followed by the x and the y coordinates. Rewrite this function with the
new set of parameters- "Hi", 5, 50. The x-coordinate and the y-coordinate are 5 and 50
respectively.

zzz.java

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (19 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void paint ( Graphics g)
{
g.drawString("Hi",5,50);
}
}

NOTE: In dos, the character-based screen is divided into 80 characters and 25 lines. In a
graphical user interface, the screen is divided into dots called pixels. It is commonly referred
to as resolutions. The costlier the monitor and the video card, the better the resolution!! The
resize function and the width and height attributes in the tag applet need their parameters to be
pixels .

Run the appletviewer. You will see Hi displayed at 5, 50 i.e. (x, y) in the applet window.

The paint function gets called every time Windows wants to redraw the screen and we can't
tell in advance how many times that is going to happen.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void paint ( Graphics g)
{
int ii;
ii=5;
g.drawString("Hi",ii,50);
}
}

Once again, just to revise the concept of variables, use int ii and initialize ii to 5. In the
drawString, instead of giving 5, put ii. This is the first use of a variable; you can place it
wherever there is a number.

In the next example, as a re-revision, we have put two drawStrings and changed ii by saying ii
= ii + 20 and given drawString again.
zzz.java
import java.awt.*;
import java.applet.*;

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (20 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

public class zzz extends Applet


{
public void paint ( Graphics g)
{
int ii;
ii=5;
g.drawString("Hi",ii,50);
ii=ii + 20;
g.drawString("Hi",ii,50);
}
}

The first drawString displays the string at 5 and the second at 5+20 ie 25.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
int ii;
}
public void paint ( Graphics g)
{
ii = 5;
g.drawString("Hi",ii,50);
}
}
In the init function we are creating a variable ii and in paint we are initializing it to 5. The Java
compiler, at this stage, will give an error.

C:\javaprg>javac zzz.java

zzz.java:11: Undefined variable: ii


ii = 5;
^
zzz.java:12: Undefined variable: ii
g.drawString("Hi",ii,50);
^
2 errors

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (21 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

You get these errors because variables in one function are not accessible in another function.
Variables, by default, are local. Local variables are only available to the function in which you
have created them. So ii is available only in init. It has a short life. It is alive only between the
'{' and the '}' brackets. If you want all functions in a class to access the variable, the only
option is to place it outside the function.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii;
public void init()
{
ii = 100;
}
public void paint ( Graphics g)
{
ii = 5;
g.drawString("Hi",ii,50);
}
}

A variable when placed outside the function is called a public variable. Every function in the
class can access a public variable. Hence we don't get any errors in the above program. The
init function changes the value of ii to 100. Paint changes it to 5. Finally, what gets displayed
is the last one and that is 5. So you see Hi on the top of the screen at 5,50 and not at 100,50. If
you remove the line ii=5 from paint then ii will retain the value 100.

There is a subtle difference between System.out.println and drawString in terms of displaying


a variable with a string. The only difference is that println draws in the dos box and drawString
writes in your graphics screen. In the following program, we have used the same '+' and
displayed the value of the variable with hi. A variable can be used constantly. That means you
can use it multiple times on the same line or in the same function. This program outputs Hi5
on top of the screen at 5,50.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii;
public void init()

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (22 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

{
ii = 200;
}
public void paint (Graphics g)
{
ii = 5;
g.drawString("Hi "+ii,ii,50);
}
}

The next example will strengthen your understanding of the concept of public variables.
Again, we have declared ii as a public variable.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii;
public void init()
{
ii = 20;
pqr();
}
public void paint (Graphics g)
{
g.drawString("Hi "+ii,ii,50);
}
public void pqr()
{
ii = 80;
}
}

In init, the variable ii is initialized to a value 20. Then the function pqr is called. pqr
reinitializes ii to 80. Hence in paint, the value displayed with Hi is 80.

In the next example, we will pass the public variable ii as a parameter to the function pqr()

zzz.java
import java.awt.*;
import java.applet.*;

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (23 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

public class zzz extends Applet


{
int ii;
public void init()
{
ii = 40;
pqr(ii);
}
public void paint (Graphics g)
{
g.drawString("Hi "+ii,ii,50);
}
public void pqr(int jj)
{
ii = jj + 20;
}
}

The public variable ii is initialized to 40 by init. Then pqr is called with one parameter i.e. ii.
In the pqr function, the value of ii, which is 40, is stored in jj. jj + 20 increases the value to 60
which is assigned to ii. In paint, ii will display its value as 60. A program can be made as
complicated as you like. But if we had replaced the line ii = jj + 20 with jj = ii + 50 , then
changing jj does not change ii.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii;
public void init()
{
ii = pqr();
}
public void paint (Graphics g)
{
g.drawString("Hi "+ii,ii,50);
}
public int pqr()
{
return 80;
}
}

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (24 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

This program is getting very interesting! ii is a public variable available to all. Instead of
passing ii as a parameter to the pqr function, we say ii=pqr();. Here pqr is a function, which is
public. If you notice, instead of void, this function returns an int. Previously, we used void,
implying that the function did not return a value. The pqr function now returns 80. The return
value of pqr is stored in ii. It returns a value using the statement return 80. 80 is the value that
will be given to ii. This is how functions return values. By saying return 80 all that happens is
that pqr() gets replaced by 80, the return value.

More on the return statement...

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii;
public void init()
{
ii = pqr();
}
public void paint (Graphics g)
{
g.drawString("Hi "+ii,ii,50);
}
public int pqr()
{
return 80;
ii = 200;
}
}

javac gives the following error.

C:\javaprg>javac zzz.java

zzz.java:14: Return required at end of int pqr().


public int pqr()
^
zzz.java:17: Statement not reached.
ii = 200;
^
2 errors

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (25 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

After the word return, we have included one more line i.e. ii=200. Return is an end to a piece
of code. No lines of code are executed after the return statement. Most of the other
programming languages don't give an error, but Java is different in its ways. In Java, you
cannot write any code after the return statement.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int x,y;
public void init()
{
x = 10 ; y = 20;
}
public void paint ( Graphics g)
{
g.drawString("Hi ", x , y);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
}
}

In the above program, we have added one more function named mouseDown. This function
returns a boolean value. Boolean is a logical value, either true or false. mouseDown is called
with 3 parameters; Event e, int x1 and int y1 are the three parameters. x1 and y1 are two
variables of type int and e looks like Event. On compiling the program, you will get the
following error:
C:\javaprg>javac zzz.java

zzz.java:14: Return required at end of boolean mouseDown(java.awt.Event, int, int).


public boolean mouseDown(Event e, int x1 , int y1)
^
Note: zzz.java uses or overrides a deprecated API. Recompile with "-deprecation " for details.
1 error, 1 warning

Here, mouseDown returns a boolean, but in our code we have no return statement with a true
or a false, hence the error. If a function has a return value other than void then it must return a
value. You can return either true or false, it doesn't really matter, as long as you return a
boolean value.

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (26 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

Let's look at another version of this example.


zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int x,y;
public void init()
{
x = 10 ; y = 20;
}
public void paint ( Graphics g)
{
g.drawString("Hi ", x , y);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
x = x1 ; y = y1;
return true;
}
}
In this example, the mouseDown function returns true. Alternatively, you can return false
instead of true. As long as you return a boolean value, your program will work fine. In this
program, it doesn't matter whether you return true or false but in other cases it may matter as
to what mouseDown returns. x and y are two public variables. You can create them separately
by saying int x; int y; But when you want to create 20 variables it is easier saying int
x,y,z,a,b,... all at a stretch. It is an alternative method, where we use ',' as a separator.

The compiler will display a warning which can be ignored.

The init function initializes x and y to 10 and 20 respectively. g.drawString takes the values 10
and 20 for x and y. Now run your program using the appletviewer.

Click with the mouse in the window. Stop clicking! As of now nothing happens. Now
minimize the window and then maximize it. Surprisingly, you see hi at the location where you
clicked or where you last clicked.

Let's understand what this means.

The mouseclick in the window was trapped by the mouseDown function. The parameters x1
and y1 tell you where the mouse was clicked. e, which is an object that looks like Event, tells
us how we clicked. How we clicked? Aren't all mouse clicks the same? Actually, they aren't

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (27 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

because not only can we click, but we can click with the control key or the shift key depressed
and so on. Event will give us information as to whether these keys were pressed while we
clicked. We will not go into further details regarding this as ours is but a simple click.

Before the mouseDown returns true, x and y are initialized to x1 and y1, which represent the
location where the mouse was clicked. They are public variables and are thus accessible from
within the mouseDown function too. On minimizing and maximizing the window, paint gets
called with the new values. Hence you see hi at a different position; the position where you
clicked.

Unless the window is not minimized and maximized, the paint function doesn't get called. It
gets called either at the start or when the window has to be redrawn. To demonstrate this, we
will now call paint through another function called repaint which exists in the Applet class.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int x,y;
public void init()
{
x = 10 ; y = 20;
}
public void paint ( Graphics g)
{
g.drawString("Hi ", x , y);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
x = x1 ; y = y1;
repaint();
return true;
}
}

The repaint function calls paint and hence the 'hi' follows the mouse click. Make sure that
every time you make changes to your code, you compile it again using javac, and then run the
appletviewer.

zzz.java
import java.awt.*;

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (28 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
ii++;
g.drawString("Hi "+ii,5,50);
}
}

In the above program, the value of ii increases every time the function paint gets called. i++
can also be written as i=i+1. When you run the program, initially the value of the variable will
be 1 because paint gets called once. When you minimize and maximize the window, paint gets
called. Now click the restore button to restore the window back to its original size. Now paint
gets called twice. We cannot really decide when and who calls paint. Whenever Microsoft
Windows realizes that your window needs to be redrawn, it calls paint. It can call paint once or
it can call paint 20 times. The important point to note is that it is only through paint that you
can write to the screen.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
g.drawString("Hi "+ii,5,50);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}

In the above program, each time you click in the window, repaint gets called. But before doing
that, the value of ii is incremented by 1. ii is a public variable hence you see the value change.

Every program should have some sort of intelligence built into it. A programming language
offers features that make the program more intelligent and more generic. Our program doesn't

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (29 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

have such features as yet. This is because we haven't given it the ability to decide whether a
certain piece of code should be executed or not. We will use the next program to demonstrate
this.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
if ( true )
g.drawString("Hi "+ii,5,50);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}

In this program, we have included the word 'if' followed by true in round brackets. When you
run this program, you realize that it's output is no different from that of the previous program.

Now change the 'true' to 'false' as shown below. You will observe that g.drawString doesn't get
called at all. You will see a blank screen.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
if ( false )
g.drawString("Hi "+ii,5,50);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (30 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

repaint();
return true;
}
}

Let's understand the reason behind it. The if statement lets you include decision making in
your program. It decides whether to execute the next line or not. When the if statement
evaluates to true, it executes the next line. When it evaluates to false, the next line is skipped.
This program now has the ability to either execute or not execute a piece of code.

The following program will make this concept clearer.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
if ( ii >= 3 )
g.drawString("Hi "+ii,5,50);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}

ii is a variable which increments by 1 when you click in the window. The mouseDown
function calls repaint which inturn calls paint. In paint, the if condition checks whether the
value of ii is greater than or equal to 3. When you click within the window for the first time,
the value of ii will be 1, so the if condition is now read as (1 >=3). Since the condition is false,
the if statement becomes if (false). As we have seen in the earlier program, if the if statement
evaluates to false, it ignores the next line. So hi is not displayed on the screen. The third click
will initialize ii to 3. Since 3 = 3, the if condition becomes true and hi is displayed along with
3 on the screen.

This is how, depending on certain conditions, you can decide whether code should be called or
not.

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (31 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

To understand > or < try out the next program. > and + - * are all called operators.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
Sysetm.ou.println(3>8);
Sysetm.ou.println(8>3);
}
}

In the next program, after the if statement, two drawString functions are called and passed Hi
and Bye respectively.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
if ( ii >= 3 )
g.drawString("Hi "+ii,5,50);
g.drawString("Bye "+ii,5,100);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}

Here, each time you click in the window Bye gets displayed on the screen but Hi gets
displayed only after the 3rd click. This implies that the if condition works only for the next
line i.e. it either ignores or executes the next line. The rest of the code is beyond its control. If
you want multiple statements to be affected by the if statement use curly braces '{}'. Now
include both the drawString functions within curly braces.
zzz.java
import java.awt.*;
import java.applet.*;

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (32 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

public class zzz extends Applet


{
int ii = 0;
public void paint (Graphics g)
{
if ( ii >= 3 )
{
g.drawString("Hi "+ii,5,50);
g.drawString("Bye "+ii,5,100);
}
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}

In this program, after the third click both the drawStrings get executed. Both 'Hi' and 'Bye' are
displayed only after the third click.

You can try the same code with different operators like <, >, <=, >=

Example:

if (i >3) , if (i<3), if(i <=3), if (i >=3)

Let's try this program using the '=' operator.

if( ii = 3 )

This will give you an error.

C:\javaprg>javac zzz.java

zzz.java:8: Incompatible type for if. Can't convert int to boolean.


if ( ii = 3 )
^
Note: zzz.java uses or overrides a deprecated API. Recompile with "-deprecation " for details.
1 error, 1 warning

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (33 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

This results in an error because a condition should result in a logical value i.e. it must be a
boolean value. Here '=' is assigning a value 3 to ii, it is not

asking whether ii is equal to 3 or not. The '=' attempts to assign ii a new value.

Using '==' solves this problem. The if statement now becomes if (ii == 3). When you run the
program, click slowly because the if condition will evaluate to true only once.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
if ( ii == 3 )
{
g.drawString("Hi "+ii,5,50);
g.drawString("Bye "+ii,5,100);
}
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}

The '==' compares ii with a certain value. You may not want a certain piece of code to be
executed if the variable meets a certain value. In such a case use !=, the 'not equal to' operator.
The following program supports this statement.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (34 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

if ( ii != 3 )
{
g.drawString("Hi "+ii,5,50);
g.drawString("Bye "+ii,5,100);
}
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}

The drawString functions are called for all values of ii except 3. The next program reveals how
a condition can be reversed.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
if ( ! ( ii >= 3) )
{
g.drawString("Hi "+ii,5,50);
g.drawString("Bye "+ii,5,100);
}
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}

'!' allows you to negate a condition. !( ii >= 3), is the same as (ii < 3). You can use two
different approaches to do the same thing, either say if (ii < 3) or if (! ( ii>=3)).

In the previous examples, if the condition was true, code was executed and when false, nothing

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (35 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

happened. You probably felt limited, because it only lets you execute a statement when the
condition is true. The next example takes care of this, showing us how to use an else with our
if. The additional else statement will execute the code following it only when the if condition
evaluates to false.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
if ( ii <= 3)
g.drawString("Hi "+ii,5,50);
else
g.drawString("Bye "+ii,5,20);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}
If the condition ii <= 3 evaluates to true then Hi will be displayed, otherwise, Bye will be
displayed.

The next program will show you how you can use the if statement intelligently.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;int a,b,c,d;
public void paint (Graphics g)
{
g.drawLine(a,b,c,d);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
if ( ii == 0)

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (36 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

{
a = x1; b = y1;
ii = 1;
}
else
{
c = x1 ; d = y1;
ii = 0;
repaint();
}
return true;
}
}

In this program, the variable ii is initialized to 0. The mouseDown function facilitates the
trapping of the mouse click. The if condition is used in the mouseDown function. If the
condition evaluates to true i.e. if ii is equal to 0, the click positions which are stored in x1 and
y1 are assigned to the public variables a and b respectively. After that, ii is initialized to 1.
With the second click the code for else is called. The click positions are given to a different set
of public variables i.e. c and d. ii is then reinitialized to 0. Then the repaint() indirectly calls
paint. The paint function calls the drawLine function which belongs to the Graphics class.
drawLine takes 4 parameters, the first two determine where the line begins and the next two
fix the end of the line.

In a nutshell, the first click calls code initializing the variables a and b. With the second click
the variables c and d are initialized. Thus, clicking twice draws a line between the two clicks.

Conclusion

In this chapter, we have seen how Java has taken the entire on-line world by storm. We have
seen how Java applets are embedded in the HTML pages. We showed you variations of
programs right from a simple Java applet to more complex ones. This was done using various
combinations of operators in the if statement and some basic functions. These together with
the concept of objects and classes were used to introduce to you the concept of object-oriented
programming and what Java as a programming language has in store for us.

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (37 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (38 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

Contents | Foreword | About the Authors | Introduction |


Appendix |Chapter 1 |Chapter 2 |Chapter 3 |Chapter 4 |Chapter 5 |Chapter 6 |
Chapter 7 |Chapter 8 |Chapter 9 |Chapter 10 |Chapter 11

http://www.vijaymukhi.com/documents/books/javajsp/chap1.html (39 of 39) [5/2/2008 10:53:55 PM]


Java-Servlets-JSP

2. Animation - Threads And Exceptions

Introduction

In the previous chapter, we introduced you to the methods paint() and repaint() which are the
foundation of graphical display in Java. These methods allow your Java programs to display
images, shapes, colors etc. We saw how it can be used to draw a simple line. In this chapter,
we will introduce you to Animation using Java. Animation has many uses, from dramatic web
pages to exciting games. Java animation is superior to things like animated GIF files because it
provides dynamic interaction instead of just a static performance. Here, you will learn how to
animate image files. This chapter also introduces the concept of threads and exceptions.

But before we get down to animation, there are a few more functions that you need to learn.

The following program introduces a new function called getCodeBase.

zzz.java
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
System.out.println(getCodeBase());
}
}

The init function calls System.out.println. Here, instead of passing a string we are giving a
function- getCodeBase as a parameter. getCodeBase already exists within the Applet class as a
function. getCodeBase returns the location of the applet class i.e. the sub directory which
contains the code of the applet.

C:\javaprg>javac zzz.java

C:\javaprg>appletviewer a.html

file:/C:/javaprg/

We once came across graffiti that said, "You can't fool me, I'm too stupid!!" But we intend no
folly here!

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (1 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

Let's understand the output.

Our applet is based on our local machine and hence it says file: We are on a windows machine
in C: drive within the javaprg subdirectory. This is the location from where the applet code has
been picked up. Had the applet been picked up from another site, getCodeBase would have
returned a url (uniform resource locater). A url or a uri (uniform resource identifier) identifies
some resource.

zzz.java
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
java.util.Date d;
d = new java.util.Date();
System.out.println(d);
}
}

In the previous programs, when we declared a variable int ii, we were actually creating an
object ii that looked like an int. In this program, java.util.Date d will create a variable called d
that looks like java.util.Date. We decided not to have the import statement for Date, hence the
longish name. You can rewrite the code with Date and the line import java.util.* on the top.

There is a difference between saying Date d and int i. A variable gets created as an object if its
data type is int, char or long. These data types are built into programming languages like C and
C++. In such a case the object is created at the time of its declaration. Anything other than the
basic data types must be explicitly created. Java implements the same rules.

Thus when we say d looks like Date, we are not creating an object that looks like Date. Here
the object is declared to be of Date type and will be created in the future.

Let's understand how we can create objects ourselves.

To create an object other than the basic types, languages like C++ utilized the word new. Java
follows the same route and uses new as well. The next line in our program uses new to create
the object d. The keyword new requires the name of the class which in this case is
java.util.Date.

d now becomes an instance or an occurrence of the class Date. Date is given with the round
brackets because that is part of Java's syntax. The println function with d as a parameter will

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (2 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

display the current date and time at which we ran the applet.

C:\javaprg>javac zzz.java

C:\javaprg>appletviewer a.html

Fri Apr 28 19:52:31 GMT+05:30 2000

In the previous chapter, we used the paint function extensively. We also had g that looked like
Graphics and if you recollect we did not use new Graphics() anywhere. The reason for this is
that whoever called paint had already created an instance of Graphics and passed it as a
parameter. Hence we were spared effort of doing so ourselves.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
Image n;
public void init()
{
n = getImage(getCodeBase(),"T1.gif");
}
public void paint(Graphics g)
{
g.drawImage(n,10,40,this);
}
}

This program introduces an additional class called Image. n looks like Image. Every class has
code as does Image which has its own code and its own set of variables. This class handles
images. getImage is a function that requires a location from where the image file can be picked
up. So the first parameter is the location and the second parameter is the name of the graphics
file. The function getCodeBase returns the location of the applet.

For this program, you need a gif file called T1.gif which must be placed in the same directory
as that of the applet. T1.gif comes with the Java development kit. T1.gif can be found by doing
the following: go to the jdk1.2.2 subdirectory, there you will find many directories one of
which is named demo. From demo, go to applets, which will take you to animator. One of the
subdirectories here is named images, which has beans and within beans lies T1.gif. The T
series starts from T1 and goes up to T10. We recommend you copy all of them to your current
directory, which in our case is c:\javaprg.
getImage returns an image which is stored in n. That means this function internally performs a

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (3 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

new Image and returns an object that looks like Image. In our current program, n represents an
image T1.gif. Just as drawLine and drawString are functions in the Graphics class and to call
them we say g.drawString and g.drawLine, the same applies to the drawImage function. It is
also to be found within the Graphics class. drawImage takes 4 parameters. The dot separates
the name of the object from the name of the function.

The first parameter to the drawImage function is an image, the second is the x coordinate, the
third is the y coordinate and the last one is a instance of an object. n in our program represents
the image T1.gif which is to be displayed. The next two are the locations on the screen where
we want the image to appear and finally we have the word 'this'.

'this' is a reserved word; it is a part of the Java programming language. In our code it stands for
two things, either zzz or applet. 'this' stands for the current class or the class that you are
extending from. So if Applet has been extended from two or three or more classes then it
stands for them too. drawImage requires an instance of a class i.e. an object and hence we
provide it as the last parameter by saying 'this'; which means zzz or Applet.

After running the applet you will see the image T1.gif displayed in the appletviewer.

The next program is similar to the earlier one. This program proves that strings and images are
all treated in the same manner. This may seem strange at first, but you'll soon get used to the
idea.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
Image n;int x = 19,y=76;
public void init()
{
n = getImage(getCodeBase(),"T1.gif");
}
public void paint(Graphics g)
{
g.drawImage(n,x,y,this);
}
public boolean mouseDown(Event e , int x1 ,int y1)
{
x = x1; y = y1;
repaint();
return true;
}

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (4 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

}
In this program, we have used drawImage instead of drawString. Whenever the mouse is
clicked in the window, x and y get initialized to the click position. repaint() calls the paint
function which in turn draws the image where the mouse is clicked. Thus the image follows
the mouse click.

Loops

The if statement is the bedrock of programming because it gives intelligence and decision
power to a language. The second major part of any programming language is a looping
construct. In Java, the for statement allows you to repeat computer programming statements.
However, you already know that we can enclose statements within a block, thus it also allows
repetition of multiple statements.

This next program should clarify this.


zzz.java
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
int i;
for ( i = 1; i<= 10; i = i + 1)
{
System.out.println("Hi "+i);
}
}
}

The for statement has 2 semicolons. The statement upto the first semicolon is executed only
once. For the first time i.e. only once is i initialized to 1. The statement enclosed within the
first and second semicolon is a condition. The condition checks whether i <= 10 evaluates to
true. Since this condition evaluates to true, the statements within the open and the close
brackets will be executed. If the condition evaluates to false, all these statements are skipped
and the loop terminates. Here, since the for loop is required to execute only a single statement,
the '{}' brackets are optional. This rule is applicable here too. The variable i has a value 1
which is less than 10, so System.out.println will be called and it will display hi 1. After all the
statements within the block are executed, the last part of the for is executed. i=i+1 will
increase the value of i by 1, making its new value 2. The condition is checked again, is 2 <=
10? The answer here is true so hi 2 is displayed. Now i is incremented once more and now
becomes 3. The condition 3 <= 10 is again evaluated to true or false and this goes on till the
condition is false. When i has the value 11, the condition checked is, 11 <= 10, which is false.
The for terminates and the remaining lines of the program after the for block are executed.

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (5 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

This is how the for statement enables the repetition of code. When we leave the for statement
the value of i will be 11.

The while lopp is similar to the for loop.


zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
int i;
i = 1;
while ( i<= 10 )
{
System.out.println("Hi "+i);
i = i + 1;
}
}
}

The while loop only takes a condition, hence the variable i is initialized to 1 before entering
the loop. The condition checks if i <= 10 evaluates to true. Currently the value of i is 1. The
condition evaluates to true and the statements within the curly braces are executed.
System.out.println is called with Hi and i. The next most important thing to do is increment the
value of i or else it will have the same value and the loop will go on indefinitely.

You may ponder over the question, "Should I use for or while?' After all, the for loop is
similar to the while loop. To answer your question is "On Mondays, Wednesdays, Fridays use
for and on Tuesdays, Thursdays, Saturdays use while. Take a break on Sundays; nobody
works on Sundays". Alternatively "Toss a coin. If it's heads use while and if it's tails, don't use
for" ;-)

This is the biggest problem regarding computer programming. There are multiple ways of
doing the same thing. Both while and for do the same thing. The middle parameter of the for
statement and the condition in while loop are basically the same. It is entirely up to you to
choose one.

The next program creates an infinite loop using the while statement.

The while condition simply says true. The condition will never evaluate to false and hence the
loop will go on indefinitely.

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (6 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
int i;
i = 1;
while ( true )
{
System.out.println("Hi "+i);
i = i + 1;
}
}
}

Arrays

All programming languages implement arrays. An array is just another entity. For e.g., all the
people born in India can be said to belong to a single array named India. They are all parts of a
single whole. The concept of an array is very flexible and like beauty, lies in the eyes of the
beholder.

Here is the simplest example on arrays.


zzz.java
import java.applet.*;
public class zzz extends Applet
{
int n[];
int i = 0;
public void init()
{
n = new int[4];
n[0] = 10;
n[1] = 20;
n[2] = 30;
n[3] = 40;
for (i=0; i < 4; i++)
System.out.println(n[i]);
}
}
C:\javaprg>javac zzz.java

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (7 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

C:\javaprg>appletviewer a.html

10
20
30
40

The init function contains int n[ ]. The [ ] tells us that the variable is an array. Here n is an
array of ints. int i is another variable. At this point it is not known how large the array will be.
So on the next line we give n = new int[4]. This will create 4 variables called n[0], n[1], n[2]
and n[3]. These variables now need to be initialized and we do this by giving every variable its
own value. n[0]is initialized to 10, n[1] to 20 and so on. The only change from earlier
programs is that we have created 4 int's in one step and they have names like n[0] and so on.

The for loop is used to display these variables. At first i is initialized to 0. The condition i<4
indicates that the loop will execute 4 times. System.out.println (n[i]), for the first time, will be
System.out.println(n[0]), hence it will display 10. In the next round, i will be 1 hence
System.out.println(n[1]) will display 20 and so on. In System.out.println, it is not specifically
stated which variable, instead we have said n[i]. There is no variable called n[i], but each time
the loop executes i gets a new value ranging from 0 to 3. Arrays are thus suited for loops as we
can use a variable i to decide the name of the array variable and thus its value. So one
variable's value decides the name of another variable. This extra layer of abstraction allows us
to create complex programs.

Doing this makes our programs more generic. We haven't specifically named each variable,
instead we're using another variable to form the name.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
Image n[]; int i = 0;
public void init()
{
n = new Image[4];
n[0] = getImage(getCodeBase(),"T1.gif");
n[1] = getImage(getCodeBase(),"T2.gif");
n[2] = getImage(getCodeBase(),"T3.gif");
n[3] = getImage(getCodeBase(),"T4.gif");
}

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (8 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

public void paint(Graphics g)


{
g.drawImage(n[i],1,10,this);
}
}

This program creates an array name n of type Image. n is an array of images. But how many
images? n= new Image[4] determines the number of images i.e. it creates an array 4 images.
They are initialized individually. drawImage is given the first parameter as n[i]. Remember,
the value of i is 0 thus we see the image which is stored in n[0]; in this case, T1.gif.

This goes to prove that what we did for ints is also applicable to images. The same rules apply.

In the following program, each time the mouse is clicked, i is incremented by 1 and then the
paint function is called.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
Image n[]; int i = 0;
public void init()
{
n = new Image[4];
n[0] = getImage(getCodeBase(),"T1.gif");
n[1] = getImage(getCodeBase(),"T2.gif");
n[2] = getImage(getCodeBase(),"T3.gif");
n[3] = getImage(getCodeBase(),"T4.gif");
}
public void paint(Graphics g)
{
g.drawImage(n[i],1,10,this);
}
public boolean mouseDown(Event e , int x1 ,int y1)
{
i++;
repaint();
return true;
}
}

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (9 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

The first time you see image n[0], then n[1], then n[2] and then n[3]. But the moment i
becomes 4, drawImage takes the first parameter as n[4]. Since our array is not large enough,
thus when you go back to the dos screen you will see a screen full of errors.

Let's see what we can do to prevent these errors.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
Image n[]; int i = 0;
public void init()
{
n = new Image[4];
n[0] = getImage(getCodeBase(),"T1.gif");
n[1] = getImage(getCodeBase(),"T2.gif");
n[2] = getImage(getCodeBase(),"T3.gif");
n[3] = getImage(getCodeBase(),"T4.gif");
}
public void paint(Graphics g)
{
g.drawImage(n[i],1,10,this);
}
public boolean mouseDown(Event e , int x1 ,int y1)
{
i++;
if ( i == 4)
i = 0;
repaint();
return true;
}
}

Here, we are making sure that when the variable i becomes 4, it is re-initialized to 0. Thus as
you keep clicking in the window, i gets a new value which is within the limits of the array size
and the images keep changing.

Using this concept, let's animate the 10 pictures that you copied into your current directory.
The pictures range from T1 to T10. Since there are 10 pictures, if you click in the window fast
enough you will see different pictures displayed each time, resulting in animation. The
following program demonstrates this.

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (10 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
Image n[]; int i = 0;int j = 1;
public void init()
{
n = new Image[10];
for ( i = 0; i <= 9 ; i++)
{
n[i] = getImage(getCodeBase(),"T"+j+".gif");
j++;
}
i = 0;
}
public void paint(Graphics g)
{
g.drawImage(n[i],1,10,this);
}
public boolean mouseDown(Event e , int x1 ,int y1)
{
i++;
if ( i == 10)
i = 0;
repaint();
return true;
}
}

At first, an array of 10 images is created and n now stands for the array of 10 images.
Initializing the variables individually is tedious, so we use a for statement. i is initialized to 0
at the start of the loop. The condition in the for statement evaluates to false when i becomes
10. Thus the value of i increases by 1 each time control enters the loop. There is no variable
called n[i], thus when i is 0 the variable becomes n[0] and when i is 9 the variable becomes
n[9].

Another variable called j is used to change the filenames. When the variable name is n[0] the
gif file will be T1.gif. Therefore, we initialize j to 1 and each time j++ is encountered, its value
is increased by 1. To give the filename, we simply use the + sign to add the different parts of
the name. So when j is 1, the filename given as "T"+j+".gif" will become T1.gif. We could
have avoided the use of j and simply used i by initializing it to 1 instead of 0, but that leads to
unnecessarily complicated code. Also remember that array variable names begin with 0 and

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (11 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

the images names start at 1. The rest of the code remains the same.

In a nutshell, within the for we have initialized 10 variables to 10 different images and
whenever we click with the mouse, paint is called with a new value in i. When i becomes 10, it
is reinitialized to 0. Thus any code that is repeated can be replaced by a for statement.

Interface

Let's get back to the basics of Java. The first program had public class zzz extends Applet.
Extends brings the existing code from Applet into zzz. zzz is called the derived class and
Applet the base class.

In the code given below we are saying zzz implements runnable. The minute we say
implements runnable and run javac, it comes back with an error saying 'class zzz must be
declared abstract'.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet implements Runnable
{
public void init()
{
}
}

C:\javaprg>javac zzz.java

zzz.java:3: class zzz must be declared abstract. It does not define void run() from interface
java.lang.Runnable.
public class zzz extends Applet implements Runnable
^
1 error

Let's keep this aside for the moment and create a new file yyy.java in the same sub directory.

yyy.java
public class yyy implements xxx
{
}

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (12 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

Here we have a class called yyy and we say implements xxx. Run the program by saying javac
yyy.java. It returns with an error saying that while it doesn't know what xxx is, it suspects that
xxx must be an interface.

C:\javaprg>javac yyy.java

yyy.java:1: Interface xxx of class yyy not found.


public class yyy implements xxx
^
1 error

So create xxx.java and write the following code. Don't put anything between the curly braces.

xxx.java
public interface xxx
{
}

Compile xxx.java. You won't see any errors. Now compile yyy.java. Surprisingly this time too
you get no errors. But this does not seem to make things any clearer, so lets go back to
xxx.java.

If you don't see the same output while trying out code, you will just have to set the classpath as
follows.

c:\javaprg>set classpath=.;%CLASSPATH%

The compiler looks into the directories specified in the classpath variable. The classpath tells
the compiler where to look for xxx. If it doesn't find xxx, it gives an error. Here, by saying '.'
we tell javac to look in the current directory. Classpath is an environmental variable which
informs the java compiler about either the sub directories within which it should search for
.class files or specifies the full names of the actual .class files.

In xxx.java, add public void abc(); within curly braces, just as we have done below.

xxx.java
public interface xxx
{
public void abc();
}

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (13 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

Note that function abc has public void in front of it and followed by a semicolon. This
indicates that we are neither creating a function nor calling a function. Then what is it? This is
a function prototype and we place them in interfaces, and elsewhere as well. When we compile
xxx.java, it won't show any errors. A function prototype contains no code whatsoever.
Compile xxx.java again.

Now go back to yyy.java and say javac yyy.java. This results in an error as shown before.

C:\javaprg>javac yyy.java

yyy.java:1: class yyy must be declared abstract. It does not define void abc() from interface
xxx.
public class yyy implements xxx
^
1 error

With implements runnable, the error message was

zzz.java:3: class zzz must be declared abstract. It does not define void run() from interface
java.lang.Runnable.

An interface only contains function prototypes. When we use extends, we are merging the
code of the extended class with the current class. With implements this does not happen. An
implemented class may have one or a hundred function prototypes. All these functions must be
included in the current class because it implements another class and if you don't do so, you
will get an error.

xxx has the prototype of the function abc, so you have to write this function within zzz. You
may or may not put any code in it. When you do so, the error vanishes.

yyy.java
public class yyy implements xxx
{
public void abc()
{
}
}

In the next program, xxx.java comprises of two function prototypes. The newly introduced
function pqr takes one parameter which is int i. If you don't give the variable a name it will
give an error. Compile the program and you will not get any errors.

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (14 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

yyy implements xxx hence pqr is included in yyy. But here the name of the variable can be
different, it doesn't have to be called i.
xxx.java
public interface xxx
{
public void abc();
public void pqr(int i);
}

yyy.java
public class yyy implements xxx
{
public void pqr(int j)
{
}
public void abc()
{
}
}

An interface must always be implemented and is thus different from a class. A class has
function code whereas interfaces contain only function prototypes. Any class implementing an
interface must have the code for the function whose prototype is specified in the interface.
This is to guarantee that code is present for the interfaced functions within a class. When you
extend a class you get stuff for free but when you use implements you have to write code
yourself. If a person is an engineer, we know exactly what his capabilities are and he knows
exactly what to do. Similarly, when you implement from a class it knows exactly what it has to
do.

An interface is like a contract. Hence if Runnable as an interface has a 100 functions then we
would have to write the code for all the 100 functions. If we do not, then the java compiler will
give us errors.

Constructors

Make sure that your program matches the following where the class zzz calls new xxx(). Also
create a public class called xxx in xxx.java

zzz.java
import java.applet.*;
public class zzz extends Applet
{

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (15 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

public void init()


{
new xxx();
}
}

xxx.java
public class xxx
{
}

Compile both, first obviously xxx and then zzz. You won't see any errors. At times, you don't
need to compile both the Java files. If you have the Java file then the compiler automatically
compiles xxx.java if it is present in the current directory; but it is advisable to compile both.

Now add a function name xxx to the class xxx as we have done below. Run the applet and
nothing spectacular will happen. However, when you close the window, "In const" is
displayed in the DOS box.

zzz.java
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
new xxx();
}
}

xxx.java
public class xxx
{
xxx()
{
System.out.println("In const");
}
}

The appletviewer calls init in zzz and executes new xxx( ). To execute this statement, it first
loads xxx.class and checks for a function with the same name as the name of the class, in this
case xxx. Since there is a function by that name, Java executes this function. So we see 'In
const' on the screen.

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (16 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

A constructor is a function whose name is the same as the name of the class. You can't call a
constructor; it is called when an instance of the class is created with the new command. If you
try to call the constructor directly, you will get an error.

Now rewrite the constructor as int xxx().


xxx.java
public class xxx
{
int xxx()
{
System.out.println("In const");
return 1;
}
}

C:\javaprg>javac xxx.java

xxx.java:6: 'return' with value from constructor: xxx()


return 1;
^
1 error

The program will now give an error because constructors can't return values. Ask yourself,
when is the constructor called? The constructor is called at the time the object is being created.
In our case it is called when we say new xxx. If the constructor is to return a value then to
whom should it return the value? The object after all has not yet been created. As such
constructors cannot return values.

Now within zzz.java, say new xxx(100), as we have done below. Don't make any changes to
xxx.java as yet.
zzz.java
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
new xxx(100);
}
}

xxx.java
public class xxx

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (17 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

{
xxx()
{
System.out.println("In const "+h);
}
}

C:\javaprg>javac zzz.java

zzz.java:7: Wrong number of arguments in constructor.


new xxx(100);
^
1 error

The constructor in class xxx takes no parameters. Hence we get an error. The only way to
eliminate the error is by saying xxx(int h) i.e. we are creating a constructor with one
parameter. We display the value of h by concatenating it with "In const ".
xxx.java
public class xxx
{
xxx(int h)
{
System.out.println("In const "+h);
}
}

C:\javaprg>appletviewer a.html

In const 100

Now go back to your program and say new xxx(); you will get an error.
zzz.java
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
new xxx();
}
}

xxx.java

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (18 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

public class xxx


{
xxx(int h)
{
System.out.println("In const "+h);
}
}

C:\javaprg>javac zzz.java
zzz.java:7: No constructor matching xxx() found in class xxx.
new xxx();
^
1 error

Bet you didn't expect this error! Earlier when you had new xxx() without the constructor, there
was no error triggered. In the second example, you added the constructor and the constructor
was called. Now however, when you say new xxx(), and within the class xxx you have a
constructor with one parameter, you get an error. The rule is that if you have no constructors
then you will receive one for free, the compiler within the xxx class will actually write xxx() {
} for you. But if you have even one constructor then the free one is taken away. In order to
remove the error you will now need two constructors. This is shown in the following program.

zzz.java
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
new xxx();
}
}

xxx.java
public class xxx
{
xxx()
{
}
xxx(int h)
{
}
}

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (19 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

zzz.java
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
xxx x;
System.out.println("No");
x=new xxx();
}
}

xxx.java
public class xxx
{
xxx()
{
System.out.println("In constructor");
}
}

Output
No
In constructor

In this program, we have an object x that looks like xxx. At this point, the constructor is not
being called. System.out.println displays 'No'. Now we have x=new xxx(); This is the point
where the constructor is called. It is only when we say new that the object is created. And only
when the object is created is the constructor called.

Constructors cannot be called directly. In the following program we try to call the constructor
by saying x.xxx(); This will give us an error.

zzz.java
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
xxx x;
System.out.println("No");
x=new xxx();

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (20 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

x.xxx();
}
}
xxx.java
public class xxx
{
xxx()
{
System.out.println("In constructor");
}
}
It says that Method xxx() is not found in class xxx. Thus you cannot explicitly call a
constructor.

The next program introduces threads. Here we have included Thread(this).

zzz.java
import java.applet.*;
public class zzz extends Applet
{
Thread t;
public void init()
{
t = new Thread(this);
}
}

t is a variable that looks like Thread. new Thread (this) will create an object that looks like
Thread and saves it in t. To create the object, the constructor with one parameter in the Thread
class is called. This constructor is being passed one parameter called 'this'. 'this' in this case
stands for zzz or Applet.

This program is similar to the earlier ones. On compiling, we get an error.

C:\javaprg>javac zzz.java

zzz.java:7: Incompatible type for constructor. Explicit cast needed to convert zzz to
java.lang.Runnable.
t = new Thread(this);
^
1 error

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (21 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

The thread constructor requires Runnable as a parameter. 'this' in our program represented zzz
or Applet, hence the error. The only option left is to extend the class from Applet and to
implement Runnable.

zzz.java
import java.applet.*;
public class zzz extends Applet implements Runnable
{
Thread t;
public void init()
{
t = new Thread(this);
}
}

C:\javaprg>javac zzz.java

zzz.java:2: class zzz must be declared abstract. It does not define void run() from interface
java.lang.Runnable.
public class zzz extends Applet implements Runnable
^
1 error

If you stop here you will get another error. Runnable is an interface and it has one function
called run, which hasn't been implemented in the class. In the next program, we have added
run and within it we are calling the System.out.println function.
zzz.java
import java.applet.*;
public class zzz extends Applet implements Runnable
{
Thread t;
public void init()
{
t = new Thread(this);
}
public void run()
{
System.out.println("hi");
}
}

This program doesn't give us any errors but when you run the program nothing happens either!

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (22 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

To call run, we have to say t.start() where start is a function in Thread. Add this function to
your program. Now when you run the program you will see hi displayed in the dos box.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet implements Runnable
{
Thread t;
public void init()
{
t = new Thread(this);
t.start();
}
public void run()
{
System.out.println("hi");
}
}

C:\javaprg>appletviewer a.html

hi

Here, the function run is called only once. If you use a while loop and give the condition as
true, the loop will go on infinitely. This is demonstrated in the following program.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet implements Runnable
{
Thread t;
public void init()
{
t = new Thread(this);
t.start();
}
public void run()
{
while ( true )
{

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (23 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

System.out.println("hi");
}
}
}

This also confirms that 'start' in the Thread class calls run().

You have used a class called Thread in your program but what is a Thread? The following
program will make this concept much clearer.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet implements Runnable
{
Thread t; int i = 0;Button b;
public void init()
{
t = new Thread(this);
t.start();
b = new Button("No");
add(b);
}
public void paint(Graphics g)
{
g.drawString("hi " + i,1,20);
}
public void run()
{
while ( true )
{
i++;
repaint();
}
}
public boolean mouseDown(Event e , int x , int y)
{
b.reshape(x,y,80,50);
return true;
}
}

Let's walk through this code and examine how it works.

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (24 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

A thread called t is created; t.start will call run. run contains an infinite while loop which
increments the value of i. The loop contains the repaint function and therefore the paint
function will be called. In paint, drawString will display the value of i. Now that we have
understood one part of the program, let's move onto the other.

Then we have b that looks like Button. We create this object by saying new Button ("no");
nothing happens here because we have simply created an object that looks like a button and
given it a parameter 'no'. The add function is a part of Applet and it takes one parameter. So
when you say add(b), you will see a button with the label 'no'.

Each time you click in the window, mouseDown will be called. This function calls reshape,
which is part of the button class and hence we can say b.reshape. reshape takes 4 parameters;
x,y is the location where the button will be drawn and the next two parameters, 80 and 50,
specify the width and height of the button. Thus the button obediently follows every click in
the window. Simultaneously, drawString also does its job of displaying the new value for i.

The crux of the program is that you can do two things at the same time and this is made
possible by using threads.

Today, any computer in the world is by far faster than a human being in terms of thinking as
well as work. It is a lot faster than a hard disk or a floppy disk.

Windows is said to be a multi-tasking operating system. In other words, it can handle multiple
jobs at the same time, allowing you to run more than one program at a time.

Let us assume you are using Microsoft Word and have given the save command to save a file.
If this file is a 50 megabytes large, Word will take a long time to save it. Assuming it takes
half an hour, what should you do in the meantime? While the file is being saved, you should
be able to run any other program.

To tackle these issues, every time you run a program under any operating system like
Windows or Linux, the operating system will run it in its own thread. A thread is an abstract
entity; it is code being executed. Let us assume that in one minute i.e. 60 seconds of time, and
you have 3 programs or 3 threads running simultaneously and each is allocated 20 seconds.
This is all hypothetical because in real life, no thread would be given 20 seconds at a stretch.
The OS switches between threads so fast that you won't notice it at all, nor would you believe
that the same computer is handling 3 different programs at the same time.

Thus when you save a file in Microsoft Word under MS Windows by clicking on File - Save,
Word starts a new thread. If you have 3 programs running concurrently with the save
command, there will now be 4 threads. Now the time slice will be 15 secs per minute to every

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (25 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

program/thread. So while the thread saves the file, the main thread in which Word operates too
can continue with its work. That is, you can use word as before.

Our Java program already operates in a thread. The mouseDown event is captured in this
thread. By creating an object that looks like Thread, a new thread is created which calls run.
run calls paint which displays the values. This is how two jobs can be done at the same time.
The run function is only called once, while the while loop will run on forever.

In the previous chapter, we had a program where the image followed the mouseclick. What we
did earlier in mouseDown, we can do in the run function too.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet implements Runnable
{
Image n[]; int i = 0;int j = 1;Thread t;
public void init()
{
n = new Image[10];
for ( i = 0; i <= 9 ; i++)
{
n[i] = getImage(getCodeBase(),"T"+j+".gif");
j++;
}
i = 0;
t = new Thread(this);
t.start();
}
public void paint(Graphics g)
{
g.drawImage(n[i],1,10,this);
}
public void run()
{
while ( true)
{
i++;
if ( i == 10)
i = 0;
repaint();
}

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (26 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

}
}

The code remains the same, the only difference being that this time we have put it in the run
function. When you run this program using the appletviewer, the code starts animating by
itself and at great speed. Amazing isn't it!!!

What we need to do is slow this down. Let's see how this can be done.
zzz.java
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
abc();
}
public void abc() throws InterruptedException
{
}
}
C:\javaprg>javac zzz.java
zzz.java:6: Exception java.lang.InterruptedException must be caught, or it must be declared in
the throws clause of this method.
abc();
^
1 error

Here, init calls the abc function. The function code has throws Interruped Exception added to
it.

Let us assume you opened a file and the operation returned an error. You then have to check
for the error and write code for error handling. Suppose you are opening files from 20 different
places in your program, you'll have to repeat the same error handling code 20 times. If you
have 6 different types of errors, you will have to check for all of them. That's a lot of code!

The second preoblem is with the constructor. If a constructor has an error, what should the
constructor do? The constructor cannot return an error because, as discussed earlier,
constructors do not return values.

The developers followed a new approach to error handling. This approach states that if a
function has a problem, it should throw an exception and a handler should catch it.

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (27 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

The abc function throws an exception called InterruptedException. This is a exception that
comes with java but you can create your own exceptions too. An exception is a class derived
from Exception. The abc function throws an exception, hence when you are calling abc you
have to catch it or else you will get an error.

The next program shows how you how to catch the error.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
try
{
abc();
}
catch (InterruptedException i) {}
catch (Exception i) {}
}
public void abc() throws InterruptedException
{
}
}
At first, we say 'try' and within this block we place the function that throws exceptions. At the
end of the block, we use catch along with the type of exception to handle the exception. So
within the {}'s we can put whatever code we want and it will be executed if that error occurs.

zzz.java
iimport java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
try
{
abc();
System.out.println("After abc");
}
catch (InterruptedException i) {System.out.println("I am Interrupted Exception");}
catch (Exception i) {System.out.println("I am Exception");}

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (28 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

System.out.println("After Exception");
}
public void abc() throws InterruptedException
{
throw new InterruptedException();
}
}
Output
I am Interrupted Exception
After Exception

In this program, we have throw new InterruptedException. throw is a reserved word in Java. It
is only when we use throw new InterruptedException that the exception is called. Within the
try-catch, we call abc. abc throws InterruptedException and thus the code in catch which deals
with InterruptedException is called. So println will display 'I am Interrupted Exception'. Once
an exception occurs all the remaining code in the try block is skipped. Thus you will not see
'After abc' displayed. After the catch is called, any code after catch will be executed. Since we
have a println statement after catch, it will display 'After Exception'.

In try, we can put as many functions as we want. We can also put as many catches as we like.
Here, we are catching two exceptions, InterruptedException and Exception. So depending
upon the exception that occurs, the relevant code is called.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
try
{
abc();
}
catch (Exception i)
{}
}
public void abc() throws InterruptedException{}
}

All code in the init function can be placed between the try and catch. We can be generic by
having only one catch with Exception. Exception is the mother of all exceptions. All other
exceptions are extended or derived from it, even InterruptedException. You decide the level of
sophistication you like in your program. A function can throw as many exceptions as it wants

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (29 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

using commas.

Similar to 'try-catch' is a throw. This entire exercise was conducted because our pictures were
being displayed too fast. To slow it down, we will now call a function called sleep, which is
part of thread. So we say t.sleep and then give 500, which is the time in milliseconds.

zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet implements Runnable
{
Image n[]; int i = 0;int j = 1;Thread t;
public void init()
{
n = new Image[10];
for ( i = 0; i <= 9 ; i++)
{
n[i] = getImage(getCodeBase(),"T"+j+".gif");
j++;
}
i = 0;
t = new Thread(this);
t.start();
}
public void paint(Graphics g)
{
g.drawImage(n[i],1,10,this);
}
public void run()
{
while ( true)
{
t.sleep(500);
i++;
if ( i == 10)
i = 0;
repaint();
}
}
}

'sleep' gives an error. This is because it throws an exception and we are not catching it.

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (30 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

C:\javaprg>javac zzz.java

zzz.java:26: Exception java.lang.InterruptedException must be caught, or it must


be declared in the throws clause of this method.
t.sleep(500);
^
1 error

Our next program is the last in this chapter; it is a working example showing animation. Here
the sleep function is put in 'try-catch'. We have no code for error handling so we'll leave it
blank.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet implements Runnable
{
Image n[]; int i = 0;int j = 1;Thread t;
public void init()
{
n = new Image[10];
for ( i = 0; i <= 9 ; i++)
{
n[i] = getImage(getCodeBase(),"T"+j+".gif");
j++;
}
i = 0;
t = new Thread(this);
t.start();
}
public void paint(Graphics g)
{
g.drawImage(n[i],1,10,this);
}
public void run()
{
while ( true)
{
try
{
t.sleep(500);
}
catch ( Exception e) {}

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (31 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

i++;
if ( i == 10)
i = 0;
repaint();
}
}
}

Conclusion

Thus, from this chapter it can be concluded that any program that displays animation
necessarily requires the use of threads. We saw how the applet begins the animation cycle
when it is activated and the animation is terminated when the applet is no longer active. But
when you want the applet to provide functionality beyond animation, then you'll have to use
threads. Often Animators are built within applets. Therefore, you need an interface. To
accomplish this we implemented the Runnable interface. In the process, we also learnt how
exceptions are handled with the help of the 'try-catch' statement. By now you are also well
versed with the concepts of loops, arrays and constructors.

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (32 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (33 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

Contents | Foreword | About the Authors | Introduction |


Appendix |Chapter 1 |Chapter 2 |Chapter 3 |Chapter 4 |Chapter 5 |Chapter 6 |
Chapter 7 |Chapter 8 |Chapter 9 |Chapter 10 |Chapter 11

http://www.vijaymukhi.com/documents/books/javajsp/chap2.html (34 of 34) [5/2/2008 10:56:45 PM]


Java-Servlets-JSP

3. Java Servlets

Introduction

Jakarta-Tomcat is the official reference implementation of the Java Servlet 2.2 and Java Server
Pages technologies. Developed under the Apache license in an open and participatory
environment, it is intended to be a collaboration of the best-of-breed developers from around
the world.

Jakarta-Tomcat is a servlet container. Servlets are memory-resident Java programs, running


inside a servlet container.

Installing Jakarta-Tomcat

Jakarta-Tomcat can be installed by downloading jakarta-tomcat-3.2.1.zip from the


jakarta.apache.org site. This zip file is approximately 3 MB large. On unzipping this file, it
will create a subdirectory called jakarta-tomcat-3.2.1, all the files will be installed in this
subdirectory. On our machine, we have extracted this file to the root i.e. C:\. This assumes that
you have downloaded version 3.2.1. By the time this you read this, version 4 will be out and
all subdirectory names will change accordingly. However, all the programs should work in the
same way.

Change to the bin directory in c:\jakarta-tomcat-3.2.1 and run the batch file 'startup'. This will
open up a window and on your dos screen you will see the following statements:
C:\jakarta-tomcat-3.2.1\bin>startup
Starting tomcat in new window
Using classpath:
c:\jakarta-tomcat-3.2.1\classes;c:\jakarta-tomcat-3.2.1\lib\webserver.jar;c:\jakarta-
tomcat\lib\jasper.jar;
c:\jakarta-tomcat-3.2.1\lib\xml.jar;c:\jakarta-tomcat-3.2.1\
lib\servlet.jar;c:\jdk1.2.2\lib\tools.jar;c:\jakarta-tomcat-3.2.1\lib\servlet.jar;c:\jswdk-
1.0.1\lib\jspengine.jar;.;
C:\jakarta-tomcat-3.2.1\bin>

If you donot see the output as shown above, edit the startup.bat file and add these two lines at
the beginning.
set JAVA_HOME=c:\jdk1.2.2
set TOMCAT_HOME=c:\jakarta-tomcat-3.2.1

In this chapter, we will build some simple servlets. This will help demonstrate the power and

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (1 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

flexibility of the Java platform.

Servlets are at the frontline of Java web application development. They provide an easy way
for server side code to communicate with web-based clients. In simple words, they are
programs that run on a Web server and build Web pages.

startup is a batch file that will start the Java Web server. Minimize the screen and activate
another DOS box. Change to the jakarta-tomcat-3.2.1 directory and then go to webapps. From
this directory go to examples, then web-inf and then go to classes.

C:\jakarta-tomcat-3.2.1> cd webapps\examples\web-inf\classes

All the programs that you key in will be stored in this subdirectory.

C:\jakarta-tomcat-3.2.1\webapps\ examples\web-inf\classes >

In this subdirectory, create a file called zzz.java containing the following 3 lines.
zzz.java
public class zzz extends HttpServlet
{
}

On compiling, javac gives an error because the extended class is javax.servlet.http.HttpServlet


and not HttpServlet.

C:\jakarta-tomcat-3.2.1\webapps\examples\web-inf\classes>javac zzz.java

zzz.java:1: Superclass HttpServlet of class zzz not found.


public class zzz extends HttpServlet
^
1 error

Since we don't want the name to be lengthy, we will use the import statement. Doing so will
get rid of the error.

If you do get an error, make sure the CLASSPATH variable has c:\jakarta-tomcat-
3.2.1\lib\servlet.jar as one of the directory paths.

The code for applet.class is in some jar file and by default javac looks for it. Unfortunately, it
could not find the code of javax.servlet.http.HtttpServlet and thus you got an error. The code
for javax.servlet.http.HttpServlet is in servlet.jar which is in the lib subdirectory. A jar file is
collection of .class files. Once you set the classpath correctly, javac looks at the jar file

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (2 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

specified to see if it contains the required .class file. ClASSPATH is an environmental variable
and it may have already been set to a certain path. To avoid overwritting the original
information, we say %CLASSPATH%. Our modifications will now be added to the begin of
the list.

We have given the CLASSPATH command as

C:\jakarta-tomcat-3.2.1\webapps\examples\WEB-INF\
classes>set CLASSPATH=c:\jakarta-tomcat-3.2.1\lib\servlet.jar;
%CLASSPATH%

zzz.java
import javax.servlet.http.*;
public class zzz extends HttpServlet
{
}

Start any browser, it can be Internet Explorer or Netscape, and give the address as
http://127.0.0.1:8080. First let's understand what this means. You are probably aware that
every phone has a unique phone number. Similarly, every computer on the Net has a unique
number. We can't just call it a number, so we call it an IP address. For example, the Microsoft
site, like all other sites, has a unique IP address. If each computer on the Net were not
identifiable by an IP address then we would not be able to connect to them. Each machine also
has a common IP address 127.0.0.1 and can be represented as 'localhost'. You use this number
to refer to your machine. Both 127.0.0.1 and localhost are the same. Since the address we're
typing in is 127.0.0.1, it means that both the client and the server are running on the same
machine.

Now, you may need to have ftp, email and http servers. That however, doesn't mean that you
need a separate machine for each of them. Each packet on the internet has a number. For
example, 25 is for email, 80 is for http. So, instead of separate machines, we have separate
ports. These packets can be intercepted at the respective ports and passed on to the relevant
server. Every server runs on a particular port. Just as the http server runs on port 80 and a smtp
server runs on port 21, the Java Web server runs on port 8080. In case you want to change the
port number or the original settings of the server, you can do so by giving various options to
startup. Since we are not interested in doing this, we will simply use 8080.

After giving address:port, give /examples/servlet/ followed by the name of the class file, which
is zzz. When you write /examples/servlet/, it is automatically converted to c:\jakarta-tomcat-
3.2.1\webapps\examples\web-inf\classes which is where Java will look for the zzz class file.
This is known as url mapping. In effect, you are mapping from a logical url to a physical
directory.

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (3 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

http://127.0.0.1:8080/examples/servlet/zzz

So when you say /examples/servlet/, the Java web server takes the /examples/servlet/ and maps
it to a path on the hard disk. Then it picks up the file zzz.class from the directory.
Unfortunately, you will see a screen with an error 'saying HTTP method GET is not supported
by this URL.

If you look at the server DOS box, it displays a similar error. This obviously implies that we
have done something wrong or a lot more must be added to get the servlet to work.

Add a function named doGet to zzz.java. This function receives two objects as parameters, req
and res. req looks like HttpServerRequest and res looks like HttpServerResponse. They are to
be found in HttpServlet.

zzz.java
import javax.servlet.http.*;
public class zzz extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
}
}

Compile this program and you will get no error. By merely adding this one line, you will find
that the error vanishes. Now we don't get an error because the server can now call the doGet
function. The server looks for a doGet function in the class file and since there was no such
function, we got the error. When zzz is loaded in the browser, it displays a blank screen (no
error). In Internet Explorer, click on View and select Source, you will see html tags.

View - Source
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META content="text/html; charset=windows-1252" http-equiv=Content-Type></HEAD>
<BODY><XMP></XMP></BODY></HTML>

We obviously didn't give these tags in our program. Hence it is assumed that the Java Web
server created these tags and gave it to the browser.

A small piece of advice: Create a new servlet each time i.e. give a new file/class otherwise the
browser takes it from the cache. Since the servlet is present in memory, even when you make
changes in your program file there is no effect as the program output is picked up from the
cache. Alternatively, you can use zzz for all your programs, but then after every change you

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (4 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

will have to stop the server and then restart it. We will stick to zzz.

The Web Server is another name for the File Server. The web server is expected to send an
html file over. Create an html file z.html in c:\jakarta-tomcat-3.2.1\webapps\root and type the
following.

c:\jakarta-tomcat-3.2.1\webapps\root>edit z.html
z.html
Hi
Bye

Now view it in the browser by typing

http://127.0.0.1:8080/z.html

You will see Hi and Bye displayed in the browser window. So the web server sends z.html
over to the browser. However, all of this is static. What we need are dynamic pages. We need
someone who will dynamically generate the html files. To do so, the web server calls another
program that processes the input and creates an html file. This is called CGI Programming.
The web server simply sends the generated html file across to the browser.

Let's look at the next program and see what it displays.


zzz.java
import javax.servlet.http.*;
public class zzz extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
System.out.println("<b>Bye");
}
}

In the earlier chapters, we learnt about System.out.println. Here we are giving <b>Bye as a
parameter to this function. When you run the servlet,(remember to stop the server and then
start it again) you will see a blank screen as before. View Source shows the same html file. But
if you look at the server dos box it will show you <b>Bye.

System.out.println prints in the dos box. This proves that the function doGet is indeed being
called by the web server.

We need to send an html file accross. Unfortunately, println displays its output in the dos box.
So, let's see how the servlet gives the web server an html file so that it can send it to the

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (5 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

browser.

zzz.java
import javax.servlet.http.*;
public class zzz extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
PrintWriter out;
out = res.getWriter();
out.println("<b>Bye");
}
}

C:\jakarta-tomcat-3.2.1\webapps\ WEB-INF \examples\web-inf\classes>javac zzz.java


zzz.java:6: Class PrintWriter not found.
PrintWriter out = res.getWriter();
^
zzz.java:6: Exception java.io.IOException must be caught, or it must be declared
in the throws clause of this method.
PrintWriter out = res.getWriter();
^
2 errors

This program creates a variable 'out' which looks like PrintWriter. It also uses res, a parameter
passed to doGet, which looks like HttpServletResponse. res has a member named getWriter
which returns an object that looks like PrintWriter. PrintWriter has a member named println
and hence the next line says out.println. This function is similar to System.out.println in terms
of syntax. With System.out.println, 'out' was a member of System, but here out is a member of
the PrintWriter class. The only problem here is that the name is not PrintWriter and hence we
get all these errors.

Printwriter is not part of javax.servlet.http.HttpServlet but of java.io. Its full name is


java.io.PrintWriter. So we add the import statement as shown below.
zzz.java
import java.io.*;
import javax.servlet.http.*;
public class zzz extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
PrintWriter out = res.getWriter();
out.println("<b>Bye");

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (6 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

}
}
Here, getWriter throws an IOException. This exception is thrown when it cannot create an
object like PrintWriter. The error is shown below. We won't talk about errors any more,
instead we'll say that an exception occurred. To handle the exception, we have to catch it.

C:\jakarta-tomcat-3.2.1\ webapps \examples\web-inf\classes>javac zzz.java

zzz.java:7: Exception java.io.IOException must be caught, or it must be declared in the throws


clause of this method.
PrintWriter out = res.getWriter();
^
1 error

We now have to use try and catch in order to handle the exception.

zzz.java
import java.io.*;
import javax.servlet.http.*;
public class zzz extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try
{
PrintWriter out = res.getWriter();
out.println("<b>Bye");
}
catch (Exception e){}
}
}

Note that we have given "<b>Bye" to out.println. This is because <b> in html means bold. We
want Bye to be displayed in bold letters and the <b> tag will allows us to do that.

We are not catching the IOException exception thrown by getWriter but instead are catching
Exception. We are using Exception because it catches all the exceptions that can ever occur.
There is a possibility that getWriter may throw two different exceptions; in that case you will
have to catch both of them with separate try-catchs. The right way to catch exceptions is to
have a separate try and catch for every function that throws an exception. We are however,
using a single try block for all the statements so that we don't have to worry about the
exceptions that occur.

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (7 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

Now, run the program from the browser. Great! Finally, you get to see Bye on the screen!
Click on View source and it will give you <b> and Bye.

View Source
<b>Bye

Let's say we have a file a.html. When the web server sends a file over, it actually first sends
some data and then the html file. This initial data is called a header. The first line of the header
in most cases is

HTTP/1.0 200 OK.

HTTP stands for the hyper text transfer protocol. A protocol is a set of rules. The http protocol
specifies how a browser communicates with a web server. It decides on issues like port nos to
be used for communication, the error codes and what they mean and so forth. All web servers
follow the http protocol.

zzz.java
import java.io.*;
import javax.servlet.http.*;
public class zzz extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try
{
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
out.println("<b>Bye");
}
catch (Exception e){}
}
}

View Source
<b>Bye

A header is always sent along with an html file. The browser knows about the type of the
document being received by looking at the header. Thus, if the browser finds that the header
says text/plain then it will display the text as it is. If it sees that the header has text/html then it
will display the text in the html format. Since we did not set the header for Content-Type
earlier, it was assumed to be text/html.

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (8 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

In this program, we have res and req. To receive something from the client we use req and to
send something to the browser we use res.

res has functions that lets you send something to the web server. That content then has to be
passed to the browser. res, that looks like HttpServletResponse, has a function named
ContentType which by default is set to text/html. Here we change it to text/plain. So we have
added res.SetContentType("text/plain") in the above program. The actual header that is
generated looks like this.

Content-Type: text/plain

A header is sent before the actual data and it consists of words which end in a colon. These
words describe the rest of the html file being sent across. Text/plain is called a mime type.
Content-Type is a header which tells the browser the nature of the file being sent across. If it
said image/gif, then the browser would know that it is receiving a picture file which has a gif
file format.
Even though, in the program, we did not specify any headers, the java web server sends a large
number of them over. We have the option of changing the values of these headers and to also
send our own.

Once the browser knows that the text coming in is an html file, it interprets <b> and displays
the remaining text in bold. It works perfectly and as advertised, hence the Bye becomes bold.

You can change it back to text/html if you like. But it is not necessary as the default is
text/html.

zzz.java
import java.io.*;
import javax.servlet.http.*;
public class zzz extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<b>Bye");
}
catch (Exception e){}
}
}

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (9 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

These programs that we have been writing so far are called Servlets. Why so? Well because
they are derived from HttpServlet. A servlet is a class which is derived from HttpServlet.

In chapter 2, we covered exception handling and learnt new words like try and catch. Most of
you may not like using try and catch, so Java gives us an option to use the 'throws' clause
instead. There are a number of ways of doing the same thing. Here, we have used throws as
part of the function syntax because you may see it in other books and it may confuse you. It is
just an alternative to try and catch.

To use the throws clause, use the word throws followed by the exception. The function doGet,
in the following example, says throws IOexception. Hence, you don't have to put a 'try-catch'
within the code for the functions throwing exceptions.

zzz.java
import javax.servlet.http.*;
import java.io.*;
public class zzz extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML> <b>hi </HTML>");
out.close();
}
}

Here, in out.println we have included the <HTML> </HTML> tag. Normally, html code is
written within the html tag. Since html is forgiving, it doesn't matter if you choose not to
include these tags. That's the reason we got away with it in our earlier program.

It is good programming practice to close a file and if you don't, it is closed by default.
out.close closes the newly generated file. If you run this from the browser, it will dispaly 'hi' in
the browser window.

View Source
<HTML> <b>hi </HTML>

When we want to dynamically generate html files, we use programs written in C, Perl, Java
etc. Perl is an interpreted language and so it is very slow. Java servlets stay in memory and are
thus quite fast. Perl as a program is called each time the program needs to be run. Perl runs,

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (10 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

generates a file and then quits. If a Perl program is required to connect to a database, maybe to
retrieve data and then disconnect, imagine the amount of time involved to complete the
transaction!. This CGI program is great if it is for a few connections but not for a million
connections.

Servlets are not removed from memory. To prove this, all that we do in the next program is,
display the value of i, which is a variable created outside a function.

zzz.java
import javax.servlet.http.*;
import java.io.*;
public class zzz extends HttpServlet
{
int i = 0;
public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
i++;
out.println("<HTML> hi " + i + " </HTML>");
out.close();
}
}

Here we are incrementing i by 1 in the function doGet. The first time that doGet gets called, i
will be incremented by 1, and then each time you click on Refresh, it will keep incrementing
by 1. This proves that the code is memory-resident. This is one of the reasons why you need to
stop your server and then restart it if you want to use the same servlet. Also try using a fresh
copy of IE or Netscape and you'll notice that the value of i is retained across browsers. Hence
if it is 3 in the first copy, clicking on Refresh in the second will make it 4 and then clicking on
Refresh in the first copy makes it 5. Thus, we can see that servlets never get removed from
memory.
The web server sent Content-Type as one of the headers to the web browser. Similarly, there
are headers that are sent by the web browser to the web server. To figure out what these
headers are, HttpServletRequest is given as a parameter to doGet.

zzz.java
import javax.servlet.http.*;
import java.io.*;
public class zzz extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException
{

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (11 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println( "Request method : " + req.getMethod()+"<p>");
out.println( "Request URI : "+ req.getRequestURI()+"<p>");
out.println( "Request protocol : "+ req.getProtocol()+"<p>");
out.println( "Servlet path : " + req.getServletPath()+"<p>");
out.println( "Path info : " + req.getPathInfo()+"<p>");
out.println( "Path translated : " + req.getPathTranslated()+"<p>");
out.println( "Query string : " + req.getQueryString()+"<p>");
out.println( "Content length : " + req.getContentLength()+"<p>");
out.println( "Content type : " + req.getContentType()+"<p>");
out.println( "Server name : " + req.getServerName()+"<p>");
out.println( "Server port : " + req.getServerPort()+"<p>");
out.println( "Remote user : " + req.getRemoteUser()+"<p>");
out.println( "Remote address : " + req.getRemoteAddr()+"<p>");
out.println( "Remote host : "+ req.getRemoteHost()+"<p>");
out.println( "Authorization scheme : " + req.getAuthType()+"<p>");
out.println("getCharacterEncoding:" + req.getCharacterEncoding()+"<p>");
out.println("getScheme: " + req.getScheme());
out.println("</HTML>");
out.close();
}
}

In Internet Explorer, the functions returned the following values:


Request method : GET
Request URI : /examples/servlet/zzz
Request protocol : HTTP/1.1
Servlet path : /servlet/zzz
Path info : null
Path translated : null
Query string : null
Content length : -1
Content type : null
Server name : 127.0.0.1
Server port : 8080
Remote user : null
Remote address : 127.0.0.1
Remote host : 127.0.0.1
Authorization scheme : null
getCharacterEncoding:null
getScheme: http

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (12 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

To understand all these headers, you have to go to the relevant RFC (Request For Comments).
RFC's are internet standards. The RFC will tell you what each one of the headers is all about.
There are thousands of RFCs on the net so you will have to find and read the RFC about the
HTTP protocol.

Thus, the servlet knows about the server and user's data from the headers sent in by the server.

Type in the next program as given and in the browser address bar type the url as:

http://127.0.0.1:8080/examples/servlet/zzz?pqr=abcd

zzz.java
import javax.servlet.http.*;
import java.io.*;
public class zzz extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String aa;
aa = req.getParameter("pqr");
out.println("<HTML>");
out.println( "pqr is " + aa);
out.println("</HTML>");
out.close();
}
}

getParameter is a function in HttpServletRequest. To this function, a parameter pqr is given.


req.getParameter removes the = sign and assigns the value of pqr ie abcd to aa. In the url,
we've given pqr=abcd, so the string aa becomes abcd.
pqr is abcd

This is how the servlet can figure out what the user has typed. If instead of abcd you had
initialized pqr to abcd xyz then aa would return abcd xyz.

Once you press enter, the screen will show pqr as abcd, but if you look at the address bar, it
will display %20 in the place of a space. At times instead of a '%' sign it may also show a '+'
sign. All the reserved characters get converted to ascii but in hexadecimal. The RFC forbids
you to use certain characters like spaces so they are encoded as '+' or '%'. Since we can't use

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (13 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

reserved characters in a url, they have to be replaced with their hexadecimal equivalent. To
sum up , if you use the reserved characters in a URL, then as specified in the RFC, they are
converted to hexadecimal characters.

Now, if you want to search for some word in a search engine, you will type that word in the
text box provided and press enter. The search engine will search its database for that word and
provide a list of all the sites that are related to it. This list will then be passed on to a program
which will generate an html file.

Let's create an html file where you can enter some text in a text box. Remember webapps\root
is where you create the file.

>edit a.html

a.html
<form action="http://127.0.0.1:8080/aa.html">
<input type=text name=pqr>
<input type=submit value=search>
</form>

Form is the tag used for creating a form in html. input type=text specifies that we want to
create a text box and the name of that text box is pqr. So, this will dispaly a simple text box.

Type the following in the address bar

http://127.0.0.1:8080/a.html

Now type 'abcd' in the text box and press enter or click on search. Take note of the url in the
address bar. It says

http://127.0.0.1:8080/aa.html?pqr=abcd

Earlier, we typed a similar url ourselves in the address bar. Now we are generating it through
the html file. Ignore the error that you see in the browser window.

Now edit your a.html file to match the following

a.html
<form action="http://127.0.0.1:8080/aa.html">
<input type=text name=pqr>
<input type=text name=aa>
<input type=submit value=search>

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (14 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

</form>

Here, we have an additional text box called aa and a button called submit.
Excecute it from the browser. Type abcd in the first text box and efgh in the second. Now click
on the submit button. It will display for you the following url

http://127.0.0.1:8080/aa.html?pqr=abcd&aa=efgh

Thus you can have many name value pairs in the url, each seperated by &, after the '?'.

In all these programs, we have been seeing the parameters in the url. We now have a servlet
which takes these values and displays them in the browser. So, lets rewrite the servlet and
compile it and then create a small html file that does this for us.

zzz.java
import javax.servlet.http.*;
import java.io.*;
public class zzz extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String aa,bb;
aa = req.getParameter("pqr");
bb = req.getParameter("xyz");
out.println("<HTML>");
out.println( "pqr is " + aa + " xyz " + bb);
out.println("</HTML>");
out.close();
}
}

If you are using many values in the address line, use getParameter as before. As long as you
know the name of the textbox, you can get the related value without a problem.

b.html
<html>
<b>Test</b>
<form action="http://127.0.0.1:8080/examples/servlet/zzz" method="get">
<input type=text name="pqr">
<input type=text name="xyz">

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (15 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

<input type=submit value="Click...">


</form>
</html>

Save the html file in c:\jakarta-tomcat-3.2.1\webapps\root. In the browser enter the url as
http://127.0.0.1:8080/b.html

In the text boxes, type in 'hi' in the first one and 'bye' in the second. When we click on the
button labeled Click, a new screen similar to the one seen before emerges in the window. Our
program, zzz, gets called. This is because we specified it in action. Also, we have specified
method=get. When we use get, whatever you type in the text box, along with its name,
becomes a part of the url. Give the method as post and you will see that the fields are not sent
as a part of the url. They are sent separately. We will explain get and post later.
Note the url in the address bar

http://127.0.0.1:8080/examples/servlet/zzz?pqr=hi&xyz=bye

zzz generates an html file depending on what we type in the text boxes. req.getParameter picks
up the values for the names specified.

pqr is hi xyz bye

What we have been trying to explain is called CGI Programming. CGI stands for Common
Gateway Interface. It specifies how data is transferred from the browser to the web server and
vice-versa. When we visit a site, it may ask us to fill up a form. The data we key in is sent to
the server as name value pairs. The name is the name of the text box and the value is what we
key in the text boxes.

The next program is a little lengthier.

zzz.java
import java.io.*;
import javax.servlet.http.*;
import java.util.Properties;
import java.util.Enumeration;
public class zzz extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException
{
res.setContentType("text/html");
Properties props;
props= System.getProperties();

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (16 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

PrintWriter out=res.getWriter();
Enumeration enprop= props.propertyNames();
String key="";
while (enprop.hasMoreElements())
{
key=(String)enprop.nextElement();
out.println("<p>");
out.println(key+"="+props.getProperty(key));
out.println("<p>");
}
out.println("<p>----------<p>");
props.list(out);
}
}

This program uses a function named System.getProperties. System is a class and it is


something that Java gives us for free. In our earlier programs, we worked with an object
named out. Here, we have getProperties which returns an object that looks like Properties. It is
similar to the 'out' object. This value is stored in a variable called props that looks like
Properties. The Java Web Server has a large number of properties. We intend to list all of
them.

A property is a name and an associated value.When you say aa=bb, aa is the name of the
property, bb its value.You can have hundreds of such properties. As the name of the property
changes, the value changes too. What you need to do for one, you need to do for all. Since we
want to access all properties and are not aware of the number, we use an Enumeration.

An Enumeration represents an array, enumeration means more than one of the same thing. Ten
people become an enumeration. What can be done with one can be repeated for all ten. So, an
enumeration is like a for statement where you simply repeat.

We need an object that looks like an Enumeration, props.propertyNames() returns a similar


object. This object is stored in a variable called enprop. enprop denotes all the property names.
Many functions return an Enumeration. Any Enumeration has a member function named
hasMoreElements.

Assuming there are ten property names, the while loop will go on ten times. The function will
return true when there are more elements, otherwise it will return false. nextElement will give
the next element. The variable named key, which looks like a string, will be equal to the return
value of enprop.nextElement. Note that nextElement may return a string or a number but key
is a string. We have given (String) so that no matter what nextElement returns it is cast to a
String and given to key. Remove (String) and you will get an error saying you need to cast it to

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (17 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

a String. But what does enprop.nextElement return? It returns the property name. We can
retrieve the property name only if the property exists. Hence the presence of the property is
checked first.

If the first property is named aaa, which has the value 'vijaymukhi', then enprops.nextElement
will return aaa which will be stored in key and getproperty("aaa") will be its value which is
vijaymukhi. So the Enumeration will give all the names and getProperty will get its value.

You may not want to get into all these details. Alternatively, props has a member called 'list' to
which you can give the variable 'out'. This will give you a similar listing. Thus in Java,
whenever there is a name=value pair and there are a number of such pairs, this method can be
used to access all of them.

Enter the url as http://127.0.0.1:8080/servlet/zzz and it will display an output which is too
large to be dispalyed.

In the following program we have used a function called getParameterNames which gives us
the names of the parameters.
Giving the url as http://127.0.0.1:8080/examples/servlet/zzz?aa=bb&cc=dd indicates that the
parameter names are aa and cc and the values are bb and cc respectively. It is similar to the
earlier examples. getParameterNames also returns an Enumeration. In our earlier program, we
used getProps. If you have ten words like aa=bb,cc=dd etc. you will have that many name and
value pairs. The while loop here remains the same.

zzz.java
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class zzz extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("Parameters:<p>");
Enumeration pNames = req.getParameterNames();
while (pNames.hasMoreElements()) {
String name = (String) pNames.nextElement();
String[] val = req.getParameterValues(name);
out.println(" " + name + ":");
for (int i = 0; i < val.length; i++) {

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (18 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

out.println(" " + val[i] + "<p>");


}
}
}
}

The req.getParameterNames returns a string. The value is not a single value but an array of
strings. Hence we have used val.length to find the number of members in the array. The for
loop allows us to display them.

Whenever we have more than one name/value pair, the function returns an enumeration which
then uses the same while loop to display all the multiple values. Enumeration makes the
programmers life easier.

In the same way, we can get the header names and cookies. Thus, even though you don't know
about cookies as yet you are able to do this.Cookies have been dealt with in one of our
chapters further on.

zzz.java
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class zzz extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("Request headers:");
Enumeration hNames = req.getHeaderNames();
while (hNames.hasMoreElements()) {
String name = (String) hNames.nextElement();
String value = req.getHeader(name);
out.println(" " + name + " : " + value);
out.println("<br>");
}
out.println();
out.println("Cookies:");
Cookie[] cookies = req.getCookies();
for (int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (19 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

String value = cookies[i].getValue();


out.println(" " + name + " : " + value);
}
}
}

Output
Request headers: Accept-Language : en-us
Connection : Keep-Alive
User-Agent : Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; COM+ 1.0.2204)
Host : 127.0.0.1:8080
Accept-Encoding : gzip, deflate
Accept : */*
Cookies:

Since we don't have any cookies at present, we don't see anything. If you have understood the
earlier example then this one will be a cake walk. It is basically for accessing multiple things
that are similar.

We also see the list of headers we are being sent by the browser.

In servlets, you can do anything you want. You can pick up an html file from your hard disk
and send it over or go to another site on the net, pick up an html file from there and send it
across. Let's see how the second method works.

zzz.java
import javax.servlet.http.*;
import java.io.*;
import java.net.*;
public class zzz extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException
{
URL u;URLConnection c;InputStream n;DataInputStream d;String s;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<head><title>Hello World</title></head>");
out.println("<body>");
out.println("<h1>Hello World</h1>");
try {
u=new URL("http://www.vijaymukhi.com");

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (20 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

c = u.openConnection();
n = c.getInputStream();
d=new DataInputStream(n);
while ((s=d.readLine()) != null )
out.println(s);
n.close();
}
catch(Exception x){}
out.println("</body></html>");
out.close();
}
}

This program retrieves a page from the net and sends it to the browser. Let's understand the
mechanics of it.

A url identifies a resource. So 'new URL' takes a string, a site address or a url and returns an
object that looks like URL. Here we have given our site address, so make sure that you are
connected to the Internet.

The object that looks like URL has a function named openConnection. 'u' is just the form of
the url. It is broken up into protocol, portno, address parameter and other things like that. It
actually uses the TCP protocol to physically connect to the webserver and returns an object
that stands for the connection. That is why c is not a URL, but an object that looks like a
URLConnection.

Now we need to read and write to this connection. The getInputStream function of
URLConnection returns an object that looks like InputStream from where you can read stuff.
The only problem is that the InputStream is too low level. To read data from this stream, an
object that looks like DataInputStream is created. The developers of Java could have stopped
at InputStream but they want us to use DataInputStream. You must be asking yourself useless
questions like 'Why'? Don't torture yourself with the unnecessary!

DataInputStream has functions like readLine, which returns data one line at a time. When
there are no more lines to return, it returns a null. Once some data is received, out.println is
used to display it in the browser and the stream is then closed. One of the functions throws an
exception and we catch the exception so that the program ends normally.

An applet is a Java program that runs within your browser. The browser has an applet engine
which executes the code coming in from across the net. A servlet is also a Java program but it
executes on the server. Unlike the browser, the server doesn't execute a servlet but instead
calls a program named the Servlet Engine. This program executes the Java code. Just as an

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (21 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

applet must be derived from Applet, a servlet must be derived from Servlet.

The whole idea behind servlets is that the Servlet Engine executes Java code, which creates the
html file and gives it to the web server. The web server then sends it across to the browser.

zzz.java
public class zzz extends Servlet
{
}

C:\jakarta-tomcat-3.2.1\webapps\examples\web-inf\classes>javac zzz.java

zzz.java:1: Superclass Servlet of class zzz not found.


public class zzz extends Servlet
^
1 error

In this program, zzz extends Servlet. HttpServlet, which we used earlier, too is derived from
Servlet. Had we derived from Servlet in the earlier programs, then our programming would
have been more tedious. So, to demonstrate and appreciate how HttpServlet makes life easier
for us, we will extend Servlet. We know that HttpServlet is derived from Servlet because we
looked at the source code. If you have downloaded Jakarta-Tomcat with the source code
option then you can edit the file HttpServlet.java and see for yourself.

Coming back to our program, let's compile it.

The compiler comes back with an error saying Servlet not found. We got an error because we
have not specified the full name. To remove the error, give an import statement because the
full name is javax.servlet.Servlet. We know that this is the full form becuase we looked at an
existing example. Also be sure to set the classpath as before.

zzz.java
import javax.servlet.*;
public class zzz extends Servlet
{
}

C:\jakarta-tomcat-3.2.1\webapps\examples\web-inf\classes>javac zzz.java

zzz.java:2: Can't subclass interfaces: interface javax.servlet.Servlet


public class zzz extends Servlet
^

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (22 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

1 error

Giving the full name does not seem enough! Javac comes back with an error because it knows
javax.servlet.Servlet to be an interface. An interface and a class look the same. The help files
will tell you that Servlet is an interface. You cannot distinguish between a interface and a class
using just the name.

zzz.java
import javax.servlet.*;
public class zzz implements Servlet
{
}

To use an interface, we write 'implements Servlet'. We've explained earlier that an interface is
a collection of function prototypes. Unfortunately, when we say implements Servlet, we get 5
errors. Runnable had only one function called run, this one has 5 functions. When you say
implements Servlet, it guarantees that it looks like a Servlet and that it defines all the five
functions. Because the Java Web server expects a class derived from Servlet, it expects your
program to have those same five functions.
C:\jakarta-tomcat-3.2.1\webapps\examples\web-inf\classes>javac zzz.java

zzz.java:2: class zzz must be declared abstract. It does not define void destroy() from interface
javax.servlet.Servlet.
public class zzz implements Servlet
^
zzz.java:2: class zzz must be declared abstract. It does not define void
service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) from interface
javax.servlet.Servlet.
public class zzz implements Servlet
^
zzz.java:2: class zzz must be declared abstract. It does not define void
init(javax.servlet.ServletConfig) from interface javax.servlet.Servlet.
public class zzz implements Servlet
^
zzz.java:2: class zzz must be declared abstract. It does not define java.lang.String
getServletInfo() from interface javax.servlet.Servlet.
public class zzz implements Servlet
^
zzz.java:2: class zzz must be declared abstract. It does not define javax.servlet.ServletConfig
getServletConfig() from interface javax.servlet.Servlet.
public class zzz implements Servlet
^
5 errors

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (23 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

We now need to create these five functions in zzz and the only statement included in these
functions is System.out.println. This is what the next program shows.

zzz.java
import javax.servlet.*;
public class zzz implements Servlet
{
ServletConfig a;
public void destroy()
{
System.out.println("destroy");
}
public String getServletInfo()
{
System.out.println("getServletInfo");
return "";
}
public void service(ServletRequest req,ServletResponse res)
{
System.out.println("service");
}
public void init(ServletConfig a)
{
System.out.println("init");
}
public ServletConfig getServletConfig()
{
System.out.println("getServletConfig");
return (ServletConfig) a;
}
}

When a function returns void it means you don't need to give a return value. But if it returns a
String, then either you must return a meaningful string or an empty string (which is two double
quotes). When the function returns a ServletConfig then we must return a ServletConfig. Let's
check that out! say return 0 like we have done in the following program.

zzz.java
import javax.servlet.*;
public class zzz implements Servlet
{
ServletConfig a;

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (24 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

public void destroy()


{
System.out.println("destroy");
}
public String getServletInfo()
{
System.out.println("getServletInfo");
return "";
}
public void service(ServletRequest req,ServletResponse res)
{
System.out.println("service");
}
public void init(ServletConfig a)
{
System.out.println("init");
}
public ServletConfig getServletConfig()
{
System.out.println("getServletConfig");
return 0;
}
}

C:\jakarta-tomcat-3.2.1\webapps\examples\web-inf\classes>javac zzz.java
zzz.java:29: Incompatible type for return. Can't convert int to javax.servlet.ServletConfig
return 0;
^
1 error

So, we must return a ServletConfig. In order to do that 'a' is made a public variable, which
looks like ServletConfig and is returned from getServletConfig. Now you're probably
wondering why we've made it public and haven't put it in the function itself. Well, in that case
you will have to use new. Let's see what happens. Make the changes in the program as shown
below.
zzz.java
import javax.servlet.*;
public class zzz implements Servlet
{
public void destroy()
{
System.out.println("destroy");
}

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (25 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

public String getServletInfo()


{
System.out.println("getServletInfo");
return "";
}
public void service(ServletRequest req,ServletResponse res)
{
System.out.println("service");
}
public void init(ServletConfig a)
{
System.out.println("init");
}
public ServletConfig getServletConfig()
{
ServletConfig a;
a=new ServletConfig();
System.out.println("getServletConfig");
return (ServletConfig)a;
}
}

C:\jakarta-tomcat-3.2.1\webapps\examples\web-inf\classes>javac zzz.java
zzz.java:27: interface javax.servlet.ServletConfig is an interface. It can't be instantiated.
a=new ServletConfig();
^ 1 error

You will now get an error saying you can't instantiate from an interface. There is no other way
out. We have to make it public. So zip back to the original program, the one where 'a' is public,
and run it. Javac will not complain. Move to the browser and check if the servlet works over
there.

Well, it does work! It shows a valid blank screen. But to actually confirm that the servlet has
worked, switch to the server dos box. Out of the 5 functions, only two of them get called, init
and service. init gets called once and service gets called each time refresh is clicked. So, click
on refresh and check the dos box.

Now let's do something smart. It may be too much to ask but we believe in making the
impossible possible! Put all the code that was in doGet into service within the try and the
catch. Everything works as advertised.
zzz.java
import java.io.*;
import javax.servlet.*;

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (26 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

public class zzz implements Servlet


{
ServletConfig a;
public void destroy()
{
System.out.println("destroy");
}
public String getServletInfo()
{
System.out.println("getServletInfo");
return "";
}
public void service(ServletRequest req,ServletResponse res)
{
try
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<b>Bye");
}
catch (Exception e){}
System.out.println("service");
}
public void init(ServletConfig a)
{
System.out.println("init");
}
public ServletConfig getServletConfig()
{
System.out.println("getServletConfig");
return (ServletConfig) a;
}
}

As before, init and service are called. Service takes the same parameters as doGet. So we
follow the same logic, that is, create a PrintWriter and write to the PrintWriter.

Earlier, we derived from HttpServlet. HttpServlet has the same five functions that we have in
zzz, so it's possible to replace HttpServlet with zzz. In either case, the Java Web server calls
init only once. If you have an init in your program then that's the one that's called, else, the init
in HttpServlet is called. Both init's don't do anything right now and it is upto you to decide if
you want init to do something. You can put code that is to be executed once in init.

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (27 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

The Java Web server calls service. Service has the getparameter function to figure out whether
the http method was 'post' or 'get'. It is called with the same parameters and it puts these on the
stack. It in turn calls doGet or doPost. The destroy gets called only at the end. Remember, with
get, the parameters are sent with the url as one packet, but with post, a seperate packet is sent.

We implement from Servlet because the Java Web server insists that we do so. If you remove
implements Servlet from zzz it will give you tons of errors. This shows that HttpServlet does
implement servlet. You must have the five functions, but the order of functions is not
important.

The Java developers realized that programmers would not like the idea of writing these
functions each time, so they created a class called GenericServlet containing these functions.

In the next program, zzz extends GenericServlet. On saying javac, it gives an error on service.

zzz.java
import javax.servlet.*;
public class zzz extends GenericServlet
{
}

C:\jakarta-tomcat-3.2.1\webapps\examples\web-inf\classes>javac zzz.java

zzz.java:3: class zzz must be declared abstract. It does not define void
service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) from class
javax.servlet.GenericServlet.
public class zzz extends GenericServlet
^
1 error

To understand this error let's look at a part of the GenericServlet file. We have printed a part of
this file relevant to our discussion.

GenericServlet.java
public abstract class GenericServlet
implements Servlet, ServletConfig, java.io.Serializable

You can search for this file with an extension of .java or .html in the jakart-tomcat
subdirectory

It contains the service function, but we will have to write our own service function because the
class GenericServlet is abstract. We will explain what we mean by that with the help of an

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (28 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

example.

yyy.java
public abstract class yyy implements xxx
{
public void aaa()
{
}
public abstract void bbb();
}

xxx.java
interface xxx
{
public void aaa();
public void bbb();
}

Now let's create ppp.java and extend from yyy.

ppp.java
import java.io.*;
public class ppp extends yyy
{
}

Run this and you get an error similair to the one we got when we tried to extend from
GenericServlet. That means when a function is declared as abstract in the class we are
extending from, we cannot directly use it. Instead we have to write our own function i.e we
have to override it. So make the following changes in ppp.java

The class yyy implements an interface xxx. xxx has 2 function prototypes. yyy decides to have
the code for only one function aaa and not bbb. Now if we compile yyy we will get an error.
Thus the only way to remove the errors is by making bbb abstract and also the class abstract.
Now if anybody wants to extend from the class yyy, he has to write the code of bbb.

ppp.java
import java.io.*;
public class ppp extends yyy
{
public void bbb()
{

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (29 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

System.out.println("hi");
}
}

Since bbb is abstract, you cannot call it directly. We are overriding bbb by giving our own
function. Now compile it and you will not get any errors.

Similarly, for our previous program we have to override service. So in the next program we
have added service and init.

zzz.java
import java.io.*;
import javax.servlet.*;
public class zzz extends GenericServlet
{
public void service(ServletRequest req,ServletResponse res)
{
try
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<b>Bye");
}
catch (Exception e){}
System.out.println("service");
}
public void init(ServletConfig a)
{
System.out.println("init");
}
}

Any servlet can be extended from GenericServlet. Even HttpServlet is derived from
GenericServlet. The service function in HttpServlet checks for the method and accordingly
calls doGet and DoPost. It also contains init. GenericServlet makes writing servlets much
easier.
The following html file will create a simple form where the method used is 'post'. So within
the servlet, function doPost will be called.

a.htm
<html>
<form action=/servlet/zzz method=post>

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (30 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

<input type=submit value="Click...">


</form>
</html>

zzz.java
import java.io.*;
import javax.servlet.http.*;
public class zzz extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<b>Get");
}
catch (Exception e){}
}
public void doPost(HttpServletRequest req,HttpServletResponse res)
{
try
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<b>Post");
}
catch (Exception e){}
}
}
When you change the method to 'get', doGet will be called, which will print get in the window.

Remember, the html file must be in c:\jakarta-tomcat-3.2.1\webapps\root. The only difference


between 'get' and 'post' is that in get, the query string is passed as a header value. So a header
called Query_String is created which contains all that we have keyed in. If you say
method=post then the data is sent separately. It is not a part of the header.

There is a finite amount of data that can be given to the environmental variable, so if you're
not going to be exceeding that, use 'get'. When you want to send a large chunk of data, then
use 'post'. Other methods are available too, but they are not used as frequently.

Conclusion

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (31 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

You have seen how the Java servlet is both simple and powerful. It allows us to extend the
functionality of any web server with just a few lines of code.

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (32 of 33) [5/2/2008 10:57:16 PM]


Java-Servlets-JSP

Contents | Foreword | About the Authors | Introduction |


Appendix |Chapter 1 |Chapter 2 |Chapter 3 |Chapter 4 |Chapter 5 |Chapter 6 |
Chapter 7 |Chapter 8 |Chapter 9 |Chapter 10 |Chapter 11

http://www.vijaymukhi.com/documents/books/javajsp/chap3.html (33 of 33) [5/2/2008 10:57:16 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

4. Files and Streams

Introduction

Now that we have laid the groundwork for developing servlets, let's get back to the basics.
This chapter carries on from where we left off in the first two chapters. It details a few more
features of the Java Programming language.

Let's understand the first program in this chapter, where we have two simple classes.
zzz.java
import java.applet.*;
public class zzz extends Applet {
public void init()
{
xxx a,b;
a = new xxx();
System.out.println(a.i);
b = new xxx();
System.out.println(b.i);
}
}
class xxx {
public int i = 6;
xxx()
{
i++;
System.out.println("In Const xxx " + i);
}
}
C:\javaprg>appletviewer a.html

In Const xxx 7
7
In Const xxx 7
7

You can have as many classes as you like in a file, but only one of them can be declared
public. You will get an error if you make more than one class public. Add public to the xxx
class as well and it will display an error as shown below.

C:\javaprg>javac zzz.java

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (1 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

zzz.java:14: Public class xxx must be defined in a file called "xxx.java".


public class xxx
^
1 error

In this program, class zzz is declared as public but class xxx is not. a and b are two objects that
look like xxx. Let us remind you that here you do not call the constructor; it is called by new at
the time the object is created. The next line is, a=new xxx(). In the constructor, i, which has
the value 6, will now become 7. The next line, System.out.println prints the value of i as 7.
Hence you see the output as
In Const xxx 7

C:\javaprg>appletviewer a.html

In Const xxx 7
7
In Const xxx 7
7

The statement b=new xxx() creates one more variable named i. This is because new creates the
variables again. a.i and b.i will both have the same value. A point to be noted here is that the
functions don't get created again. Functions can be shared but not variables.

The next example includes the word static which precedes the variable i.

zzz.java
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
xxx a,b;
a = new xxx();
System.out.println(a.i);
b = new xxx();
System.out.println(b.i);
}
}
class xxx
{
public static int i = 6;

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (2 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

xxx()
{
i++;
System.out.println("In Const xxx " + i);
}
}

C:\javaprg>appletviewer a.html

In Const xxx 7
7
In Const xxx 8
8

When you say static and run the program, you will notice that a.i displays 7 and b.i displays 8.
This means that i in xxx gets created only once. In the previous example, where the word
'static' was not included, if you had created 100 instances of xxx there would have been 100
i's. Remember, the code is not replicated each time you say new. It is only the variables that
get recreated.

Functions are stored in one area of memory and variables in another. Each time you say new,
it checks to see if the function exists in memory. If it exists, then the function isn't added. In
other words, functions are loaded into memory only once, but the variables within the class are
created afresh each time.

An object is an instance of a class and when a class is instantiated, the variables are created
afresh. i as a variable is now related to the object and not to the class. Whereas static variables
have nothing to do with the object, they go with the class. You don't have to say new to access
the static variable. This is shown in the next program.

zzz.java
import java.applet.*;
public class zzz extends Applet
{
xxx a;
public void init()
{
System.out.println(a.i);
}
}
class xxx
{

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (3 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

public static int i = 9;


}

C:\javaprg>appletviewer a.html

9
In this program, 'a' looks like xxx. We have not used new anywhere. We have a static variable
i in the class xxx. System.out.println with a.i will print 9 on the screen. Here, if we make 'a'
local, the compiler will return with an error saying that it has not been initialized.

public void init()


{
xxx a;
System.out.println(a.i);
}

The compiler error will be:

C:\javaprg>javac zzz.java

zzz.java:9: Variable a may not have been initialized.


System.out.println(a.i);
^
1 error

'a' was made global so it does not have to be initialized. a.i displays 9, which means that there
is one and only one i. We repeat, static variables can be accessed without creating the object.

Here's another example to prove the same point

zzz.java
import java.applet.*;
public class zzz extends Applet
{
xxx a,b;
public void init()
{
System.out.println(a.i);
b.i = 20;
System.out.println(a.i);
}
}

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (4 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

class xxx
{
public static int i = 9;
}

C:\javaprg>appletviewer a.html

9
20

At first a.i will print 9. Then b.i is initialized to 20. b.i and a.i are the same because i is a static
variable and is shared. So when you say a.i again, the value of i is 20. As you can see, you
don't have to create an object to use static variables.

The next program introduces the concept of a static function that returns void.

zzz.java
import java.applet.*;
public class zzz extends Applet
{
xxx a;
public void init()
{
a.abc();
}
}
class xxx
{
public static void abc()
{
System.out.println("hi");
}
}

Here a.abc calls the function abc in the class xxx. Once the function is called 'hi' is printed on
the screen.
c:\javaprg>appletviewer a.html

hi

The need for static functions will be discussed a little later in this chapter.

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (5 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

In the following program, the static variable 'i' is declared to be private.

zzz.java
import java.applet.*;
public class zzz extends Applet
{
xxx a,b;
public void init()
{
System.out.println(a.i);
b.i = 20;
System.out.println(a.i);
}
}
class xxx
{
private static int i=10;
}

C:\javaprg>javac zzz.java
zzz.java:7: Variable i in class xxx not accessible from class zzz.
System.out.println(a.i);
^
zzz.java:8: Variable i in class xxx not accessible from class zzz.
b.i = 20;
^
zzz.java:9: Variable i in class xxx not accessible from class zzz.
System.out.println(a.i);
^
3 errors
The default is private, which means that only the class members can access the variable.
"Outsiders are not allowed!" i.e. anyone outside the class is not allowed to access it. Try to
trespass and you will definitely see the watchdog, the error.

zzz.java
import java.applet.*;
public class zzz extends Applet
{
xxx a;
public void init()
{
a=new xxx();
}

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (6 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

}
class xxx
{
private static int i=10;
xxx()
{
i++;
System.out.println("In Const "+i);
}
}

C:\javaprg>appletviewer a.html

In Const 11

Here xxx increments the value of i by saying i++ and display its value. Only the constructors
and functions in xxx have access to i. The variables 'a' and 'b', though created in zzz and in the
very same file, are not allowed to access i.

zzz.java
import java.applet.*;
public class zzz extends Applet
{
}
class xxx
{
public void abc()
{
}
}
class yyy extends xxx
{
public void abc()
{
}
}

In the above program, apart from zzz there are two more classes, xxx and yyy. Class xxx has a
function called abc. Class yyy extends xxx and also has a function named abc. This will not
result in any compilation errors.

The next program introduces a small change. Here the word 'final' precedes void abc().

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (7 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

zzz.java
import java.applet.*;
public class zzz extends Applet
{
}
class xxx
{
public final void abc()
{
}
}
class yyy extends xxx
{
public void abc()
{
}
}
C:\javaprg>javac zzz.java

zzz.java:13: The method void abc() declared in class yyy cannot override the final method of
the same signature declared in class xxx. Final methods cannot be overridden.
public void abc()
^
1 error

Final methods cannot be changed or overrriden. Since abc has been made final, the class yyy
cannot have another function abc. The abc in xxx is final, thus you can't change it.

It is not without purpose that such a concept has been introduced in Java. Let's understand the
rationale behind it.

Let us assume that you have your own class with a final function. Others will derive from it,
but if they want to override the same function, they will not be allowed to do so. They will get
the error shown above. Without the use of final there is no guarantee that the function will not
be overridden. Thus to prevent the overriding of a function, it must be made final.

Now, in xxx, we are creating a function named abc.


zzz.java
import java.applet.*;
public class zzz extends Applet
{
}

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (8 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

class xxx
{
public void abc() throws IOException
{
}
}

C:\javaprg>javac zzz.java

zzz.java:7: Class IOException not found in throws.


public void abc() throws IOException
^
1 error

The function abc throws an exception, or to be more specific, it throws IOException. The full
name is java.io.IOException, hence we need to import java.io.*

zzz.java
import java.applet.*;
import java.io.*;
public class zzz extends Applet
{
public void init()
{
try
{
xxx x = new xxx();
x.abc();
}
catch (Exception e){System.out.println(e.getMessage());}
}
}
class xxx
{
public void abc() throws IOException
{
throw new IOException("hi");
}
}

C:\javaprg>appletviewer a.html

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (9 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

hi

A function takes parameters and along with it, it can also throw exceptions. This tells us more
about the function.

This program has x that looks like xxx and is created on the same line by saying new xxx().
This does not give us any problems at all. The next line has x.abc(), where we call this
function. abc returns a void and throws an IOException. Within the curly braces, the command
'throw' is used to actually throw the exception. Here, it throws the predefined exception, which
is IOException. Before the exception is thrown, it must be created. It is created with the help
of 'new'. We are calling the constructor, which takes one parameter, in this class. A couple of
lines later we will show you how to create your own exceptions.

Every exception thrown must be caught, so catch catches Exception, which is the base class
for all exceptions. System.out.println prints the return value of e.getMessage. e looks like
Exception and the getMessage function in e displays "hi". "hi" is displayed because this is
what was given in the constructor. You can have as many catches as you want for the different
exceptions you want to catch.

zzz.java
import java.applet.*;
import java.io.*;
public class zzz extends Applet
{
public void init()
{
try
{
xxx x = new xxx();
x.abc();
}
catch (IOException e){System.out.println("In IOException "+e.getMessage());}
catch (Exception e){System.out.println("In Exception " + e.getMessage());}

finally
{
System.out.println("All over");
}
}
}
class xxx
{

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (10 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

public void abc() throws IOException


{
throw new IOException("hi");
}
}

C:\javaprg>appletviewer a.html

In IOException hi
All over

Here's one more example where we catch IOException and then Exception e. Since abc throws
an IOException, the IOException will be called and not the second one. Once the first catch is
executed, the execution of the other catches stops.

Reversing the catch order will generate an error.

C:\javaprg>javac zzz.java

zzz.java:13: catch not reached.


catch (IOException e){System.out.println("In IOException "+e.getMessage());}
^
1 error

In the try and catch, we have introduced a new word 'finally'. The code in the curly braces,
which has been given after the word 'finally' is called when everything is over. Hence you see
'All over'. 'finally' gets called irrespective of the throws. To check this, comment out the throw
and you will still see 'All over'.

'finally' is used to execute code at the end of 'try' and 'catch' pair. It can be used to close a file
that was opened in the program. The file will be closed irrespective of whether the exception
takes place or not.

Ready for something interesting? We are now going to show you how to create your own
exception.
zzz.java
import java.applet.*;
import java.io.*;
public class zzz extends Applet
{
public void init()
{

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (11 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

try
{
xxx x = new xxx();
x.abc();
}
catch (Exception e){System.out.println(e.getMessage());}
}
}
class xxx
{
public void abc() throws ppp
{
throw new ppp("hi");
}
}
class ppp extends Exception
{
ppp(String p)
{
System.out.println("In const " + p);
}
}
C:\javaprg>appletviewer a.html

In const hi
null

Here we are calling our exception ppp which extends Exception, the base class of all
exceptions. Then we create a constructor, which accepts one parameter 'p'. This value is
displayed using System.out.println. There you go! Exception created.

When we say x.abc, at first abc in xxx gets called and it immediately throws an exception.
This will call the constructor in ppp. The p in the constructor has the value 'hi', hence we see
'In const hi'. But e.getMessage does not return any value, so we see null. Since we do not have
the getMessage function, the one in Exception is called and it returns a null.

In our next program, we have added the getMessage function in ppp and the statement
returned is "Sonal".

zzz.java
import java.applet.*;
import java.io.*;

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (12 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

public class zzz extends Applet


{
public void init()
{
try
{
xxx x = new xxx();
x.abc();
}
catch (Exception e){System.out.println(e.getMessage());}
}
}
class xxx
{
public void abc() throws ppp
{
throw new ppp("hi");
}
}
class ppp extends Exception
{
ppp(String p)
{
System.out.println("In const " + p);
}
public String getMessage()
{
return "Sonal";
}
}

C:\javaprg>appletviewer a.html

In const hi
Sonal

To print the value returned by e.getMessage, our getMessage will be called and thus you see
'Sonal'.

This is not the correct way to go about doing things, so we now set it in the right way.

When we create an object, our constructor is given 'hi' as a parameter. This constructor should

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (13 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

call the original constructor and give it the same string. Then, the getMessage function in our
code should receive the value returned by the original function, which will be the value to be
returned back.

The next program implements these two things.


zzz.java
import java.applet.*;
import java.io.*;
public class zzz extends Applet
{
public void init()
{
try
{
xxx x = new xxx();
x.abc();
}
catch (Exception e){System.out.println(e.getMessage());}
}
}
class xxx
{
public void abc() throws ppp
{
throw new ppp("hi");
}
}
class ppp extends Exception
{
ppp(String p)
{
super(p);
System.out.println("In const " + p);
}
public String getMessage()
{
String s;
s = super.getMessage();
return s;
}
}

C:\javaprg>appletviewer a.html

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (14 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

In const hi
hi

In ppp, we have super(p) which must be written on the very first line. It is used to call code in
the original. By original we mean the class that we have derived from. In our case, the
constructor in Exception will be called with one parameter p. This constructor stores the string.
In getMessage, we again have super.getMessage. super.getMessage will call getMessage from
the base class, which is Exception. The getMessage returns a string, which is stored in the
variable s and then we simply return s. Now the program will work in the required manner.

Our next example is slightly larger.

zzz.java
import java.applet.*;
import java.io.*;
public class zzz extends Applet
{
public void init()
{
try
{
xxx x = new xxx();
x.abc();
}
catch (Exception e){System.out.println(e.getMessage());}
finally
{
System.out.println("All over");
}
}
}
class xxx
{
public void abc() throws ppp
{
throw new ppp("hi");
}
}
class ppp extends Error
{
ppp(String p)
{

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (15 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

super(p);
System.out.println("In const " + p);
}
public String getMessage()
{
String s;
s = super.getMessage();
System.out.println("In getmessage "+s );
return s;
}
}

C:\javaprg>appletviewer a.html

In const hi
All over
In getmessage hi
In getmessage hi
In getmessage hi
ppp: hi
at xxx.abc(zzz.java:23)
at zzz.init(zzz.java:10)
at sun.applet.AppletPanel.run(AppletPanel.java:333)
at java.lang.Thread.run(Thread.java:479)

Class zzz has a variable x as an object that looks like xxx. The statement, x.abc, calls the
function abc which throws an exception called ppp. The constructor gets called, hence 'In
const hi' is displayed. This is the first line of output. Then 'finally' gets called because of which
'All over' is displayed. The catch code will be the next to be called and because we have
System.out.println, it will constantly print e.getMessage, which contains 'hi'. Once all this is
over, it will tell you that there was an error int xxx.abc at zzz.init.
The reason why all this happens is that we are not deriving ppp from Exception but instead we
are deriving from Error. The error messages are to be read in the reverse order: The error is in
xxx.abc, which has been called from zzz.init and AppletPanel.run calls init and so on.

Building Applications

So far you have been building Applets, now let's build Applications.

Applets and applications are very similar in appearance, with one key difference: A Java
application is an independent piece of software; an applet is not. The applet is loaded and run
by a browser or viewer. In fact, the HotJava browser is just a Java application.

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (16 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

qqq.java
public class qqq
{
}

Start by saying public class qqq { }. Here, no import statements are used. When you run the
program by saying javac, you get a file named qqq.class and no errors. To see the application
work, instead of appletviewer, run another program called java.

C:\javaprg>java qqq

Exception in thread "main" java.lang.NoSuchMethodError: main

This program gives an error saying that you don't have a function called main.

At times, you may get a different error that looks like the statement given below

Exception in thread "main" java.lang.NoClassDefFoundError: qqq


Then you must set the classpath to the current directory. In order to do so give the command

>set CLASSPATH=.;%CLASSPATH%

So far we have been using Java as a programming language. We have written code that
executes in a browser. Whenever code runs in a browser, it is called an applet. This time we
want our code to run as a standalone application. To do so, we require a program called Java,
also known as the Java Virtual Machine. We will go in depth into the differences between an
applet and an application just a little later. As of now, it is important to understand that a Java
applet can't read and write to a file on disk, whereas a Java application can do anything that
any executable can do.

In the next program, we have added a function named main.

qqq.java
public class qqq
{
public static void main(String a[])
{
System.out.println("Hi ");
}
}

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (17 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

Earlier, in this chapter, we discussed static variables and static functions where we explained
that we don't have to create an object to access them. main here is a function and it takes an
array of strings named a. You may choose to name the array as you please. main has been
declared public, otherwise, it won't be visible. main has also been made static so that it is
available to Java without creating the object that looks like qqq. Static functions are always
available irrespective of you using new or not. main returns void because it is not returning
anything here. The order is important, you cannot mess with it. First you must say public or
private, then static and then give the return value. Compile it and then say java qqq. It will
display 'hi'.
C:\javaprg>java qqq

hi

Now let's print out a[0] and a[1].

qqq.java
public class qqq
{
public static void main(String a[])
{
System.out.println(a[0]);
System.out.println(a[1]);
}
}

Run the compiler and then say java qqq. It will give an error saying,
ArrayIndexOutOfBoundsException.

C:\javaprg>java qqq

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0


at qqq.main(qqq.java:5)

Say java qqq one at the command prompt, this will first show one on the screen and then give
the same error.

C:\javaprg>java qqq one

one
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at qqq.main(qqq.java:6)

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (18 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

To eliminate the error, say java qqq one two.

C:\javaprg>java qqq one two

one
two

Simply saying java qqq does not create an array of strings because no parameters have been
given after qqq. java qqq one will create only one element in the array because only one
argument is specified. Hence printing the second member will give an error because the array
is limited to only one member. The last command that you tried, java qqq one two, creates two
elements and since you are displaying two members you see no errors. Elements in the array
are created with respect to the parameters specified. What we are trying to say here is that if
you go beyond the bounds of the array, an exception will be generated.

The next program is a generic one, which displays all the command line arguments without
showing any errors.

qqq.java
public class qqq
{
public static void main(String a[])
{
int i;
for ( i = 0 ; i < a.length ; i++)
System.out.println(a[i]);
}
}

C:\javaprg>java qqq one


one

C:\javaprg>java qqq one two three


one
two
three

In Java, an array class has a member called length. If you say java qqq one, a.length will be 1
because there is only one member. java qqq one two three will make a.length 3 as there are
three members. Since the condition is i< a.length, the value of i will start from 0 and keep
changing till it is less than 3 i.e. 2. System.out.println will therefore print a[0] ,a[1], a[2]. This
is how, depending on the parameters passed, all the members of the array can be displayed.

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (19 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

Now, let's try writting data to the disk.


qqq.java
import java.io.*;
public class qqq
{
public static void main(String argv[])
{
try
{
FileOutputStream fos = new FileOutputStream("c:\\javaprg\\z.ser");
}
catch (Exception e){e.getMessage();}
}
}

In this program, fos is an object that looks like FileOutputStream. We know how much
shortcuts are appreciated, so to avoid writing the full name the import statement has been used.
To create a new instance FileOutputStream requires one parameter, the name of the file. Our
subdirectory is c:\javaprg and the file name we want to use is z.ser. Similarly, make sure you
give the complete path to the constructor. fos is now an object that looks like
FileOutputStream. The name FileOutputStream itself suggests that the file will be in output
mode, i.e. we can write to the file. Stop here, compile the file and run it. You will find that
z.ser is created in the subdirectory but it's size is 0 bytes.

Now to write to this file.


To do that, another object is needed that looks like ObjectOutputStream. This class takes the
FileOutputStream variable as a parameter and so we pass fos to it. It is closed on the next line.

qqq.java
import java.io.*;
public class qqq
{
public static void main(String argv[])
{
try
{
FileOutputStream fos = new FileOutputStream("c:\\javaprg\\z.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.close();
}
catch (Exception e){e.getMessage();}
}

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (20 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

Compile this program and run it. A directory listing in the javaprg subdirectory will display
the file size as 4 bytes.

The bytes are shown in dec, char and hex below.

172 ac
237 í ed
00
5-5

Now we will actually write to this file.You may wish to write strings and many more things to
the file. oos is used to write to fos, fos stands for z.ser. In the program below, we are simply
writing AB.

qqq.java
import java.io.*;
public class qqq
{
public static void main(String argv[])
{
try
{
FileOutputStream fos = new FileOutputStream("c:\\javaprg\\z.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject("AB");
oos.close();
}
catch (Exception e){e.getMessage();}
}
}

Check the size of the file. It is a very small file and the size is 9 bytes. You can also see 2,
which is the length of the string and then AB.

172 ac
237 í ed
00
5-5
116 t 74
00

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (21 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

22
65 A 41
66 B 42

In the program below, we are writing two strings to the file. One string is AB and the other is
CDE. The output is shown below.

qqq.java
import java.io.*;
public class qqq
{
public static void main(String argv[])
{
try
{
FileOutputStream fos = new FileOutputStream("c:\\javaprg\\z.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject("AB");
oos.writeObject("CDE");
oos.close();
}
catch (Exception e){e.getMessage();}
}
}

You will notice that the string always starts with 116, followed by 0. After that, we have the
length of the string and then the string itself.

172 ac
237 í ed
00
5-5
116 t 74
00
22
65 A 41
66 B 42
116 t 74
00
33
67 C 43
68 D 44
69 E 45

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (22 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

You can't be satisfied with just this, can you? So let's write an entire object to a file in one
stroke.

qqq.java
import java.io.*;
public class qqq
{
public static void main(String argv[])
{
xxx x;
x = new xxx();
try
{
FileOutputStream fos = new FileOutputStream("c:\\javaprg\\z.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(x);
oos.close();
}
catch (Exception e){e.getMessage();}
}
}
class xxx implements Serializable
{
public int i=6;
String s = "hi";
}

In the above program, x is an object that looks like xxx. It has two members - int i and String
s. writeObject with x will write the entire object to the file.

Class xxx implements Serializable. This is an interface but it does not have any functions. So,it
is assumed that it only has variables. ObjectOutputStream is used to take the entire object and
write it to disk in one stroke.

qqq.java
import java.io.*;
public class qqq
{
public static void main(String argv[])
{
try

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (23 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

{
xxx x;
FileInputStream fos = new FileInputStream("c:\\javaprg\\z.ser");
ObjectInputStream oos = new ObjectInputStream(fos);
x = ( xxx ) oos.readObject();
System.out.println(x.i);
System.out.println(x.s);
}
catch (Exception e){System.out.println("bye");e.getMessage();}
}
}
class xxx implements Serializable
{
public int i=60;
String s = "Byes";
}

Instead of FileOutputStream and ObjectOutputStream, the above program uses


FileInputStream and ObjectInputStream. In the previous example, we had writeObject and
here we have readObject. We have to cast it to xxx. Now when you print x.i and x.n, the value
will be that of the earlier program, it doesn't take the new values.

C:\javaprg>java qqq
6
hi

Let's see how arrays can be saved to the disk.

qqq.java
import java.io.*;
public class qqq
{
public static void main(String argv[])
{
try
{
String a[];
a = new String[2];
a[0] = "hi";
a[1] = "Nono";
FileOutputStream fos = new FileOutputStream("c:\\javaprg\\z.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (24 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

oos.writeObject(a);
}
catch (Exception e){System.out.println("bye");e.getMessage();}
}
}

The concept of arrays has already been explained. Here 'a', an array of strings, is created. a[0]
is initialized to 'hi' and a[1] to 'Nono'. Using writeObject, the entire array is written to disk. 'a'
has the length of the array so it knows how much to write.

Thinking of taking a break? Great idea! But please do so after trying out the next program. The
next program will read from the same file into an array. So you need to try this right now.

qqq.java
import java.io.*;
public class qqq
{
public static void main(String argv[])
{
try
{
String a[];
FileInputStream fos = new FileInputStream("c:\\javaprg\\z.ser");
ObjectInputStream oos = new ObjectInputStream(fos);
a = (String [] ) oos.readObject();
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a.length);
}
catch (Exception e){System.out.println("bye");e.getMessage();}
}
}

C:\javaprg>java qqq

hi
Nono
2

First run the earlier program where you wrote the array to the disk and then the current one. In
this program, readobject will read from the file. Whatever is read in is assigned to a. Since we
have cast the output to an array of strings, 'a' now contains the data as Strings. Therefore, it

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (25 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

displays 'hi' and 'Nono' and the length is displayed as 2.

Multi-Dimensional Arrays

Let's understand multidimensional arrays. In Java, there is no such thing as a multidimensional


array. Arrays are limited to one dimension. But what if you need more complex data structures
such as two or three dimensions? For this you can fake multidimensional structures by
building arrays within arrays.

qqq.java
public class qqq
{
public static void main(String argv[])
{
String a[][] = {{ "a1","a2","a3"} , { "b1","b2","b3"} };
int i;
for ( i = 0 ; i<a.length ; i++)
{
System.out.println(a[i][0]);
}
}
}

C:\javaprg>java qqq

a1
b1

In order to create multidimensional arrays use two square brackets. In this program, the
multidimensional array is of strings, so it is declared as string a [ ] [ ]. At the same time, the
array is also being initialized using curly braces. Since there are two sets of curly brackets, we
can say that we have an array a[2],[3]. Each one of them is an array and each one has 3
members.

The for loop starts by initializing i to 0. a.length will give you 2 because the array only has two
members, each one of them in turn is an array, so their length should be three. When we say
println a[i][0], it is a[0][0]. This will print the first member of the first array, that is, a1. When i
becomes 1 we are printing a[1][0] and this will print b1.

The next program enables you to print all the members in the array.

qqq.java

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (26 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

public class qqq


{
public static void main(String argv[])
{
String a[][] = {{ "a1","a2","a3"} , { "b1","b2","b3"} };
int i,j;
for ( i = 0 ; i<a.length ; i++)
{
System.out.println(a[i][0]);
for ( j = 0 ; j < a[i].length ; j++)
{
System.out.println(a[i][j]);
}
}
}
}

C:\javaprg>java qqq

a1
a1
a2
a3
b1
b1
b2
b3

The objective here is to print all the members in the array. i in the for loop is initialized to 0;
the condition is i<a.length. a.length will give 2. So the println will print the value in a[0][0],
which is a1. Then we have another for loop within the earlier for. j in the loop gets initialized
to 0; the condition is j < a[i].length. The length here will be 3 because the first array has 3
members. Remember, a[0] and a[1] are both arrays. So j will be 0,1,2 and thus will print all
members of the array.

The same is applicable to ints also. The following program demonstrates this.

qqq.java
public class qqq
{
public static void main(String argv[])
{

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (27 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

int [][] m;
m = new int[3][];
int i;int k = 1;
for ( i = 0 ; i < m.length ; i++)
{
m[i] = new int[2];
m[i][0] = k++;
m[i][1] = k++;
}
for ( i = 0; i < m.length ; i++)
{
System.out.println(m[i][0]);
System.out.println(m[i][1]);
System.out.println("-");
}
}
}

C:\javaprg>java qqq

1
2
-
3
4
-
5
6
-

Here, the variable has been created in a slightly different manner. You can create it either by
saying int m[ ] [ ] or int [ ][ ]m. The square brackets can be put before or after the variable, it's
just a question of syntax. They both mean the same thing. m=new int[3][ ] will create 3 arrays
but how many members each of them will hold is not known. It has been left blank for the
moment. Then we have a for statement where m.length will be 3 because there are 3 arrays, so
the for will go on three times.

In the for, we say m[i] = new int[2]. This is how we initialize these arrays. Since i is 0, the 0th
member of the array will hold two values. m[i][0] is actually m[0][0], which we are initializing
to the value of k. k as of now is 0 which is the value given to m[0][0]. k++ will increment the
value by 1, so k becomes 1. This is given to m[0][1]. When the bracket is reached, i will be
incremented by 1, so it becomes 1. m[1] is now an array which will have 2 elements. And
m[i][0] is now m[1][0] which refers to the second array and the 0 th element in the array.

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (28 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

Since k has not been initialized again, k will retain its original value and will keep
incrementing.

qqq.java
import java.io.*;
public class qqq
{
public static void main(String argv[])
{
try
{
String a[][] = {
{ "a1","a2","a3" },{ "b1","b2","b3" }};
//a = new String[3][2];
FileOutputStream fos = new FileOutputStream("c:\\javaprg\\z.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(a);
oos.close();
}
catch (Exception e){System.out.println("bye");e.getMessage();}
}
}

In this program, the multidimensional array has 2 arrays each with 3 members. It could have
been created as shown in the comment and we could have initialized every member later. It
really doesn't make any difference. With writeObject, the entire object will be written to disk.

The next program reads from the file and prints it in the form of an array.
qqq.java
import java.io.*;
public class qqq
{
public static void main(String argv[])
{
try
{
String a[][];int i,j;
FileInputStream fos = new FileInputStream("c:\\javaprg\\z.ser");
ObjectInputStream oos = new ObjectInputStream(fos);
a = (String [][] ) oos.readObject();
System.out.println(a.length);
for ( i = 0 ; i < a.length ; i++)

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (29 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

{
for ( j = 0 ; j < a[i].length ; j++)
System.out.println(a[i][j]);
}
}
catch (Exception e){System.out.println("bye");e.getMessage();}
}
}

C:\javaprg>java qqq

2
a1
a2
a3
b1
b2
b3

Here, we want to read all the strings, so we read the object into a. The for statement initializes
i to 0 and it keeps incrementing i till it is less than the length, which is 2. This for will go on
twice, the second for is the one that prints a1, a2, a3 in the first round and b1, b2, b3 in the
second round.
See how easy it is to write and read an array of strings. Let's see if we can work with chars as
comfortably.

The difference between an array of chars and an array of strings is that a char holds a single
entity whereas a string holds multiple entities.

The following program has a multidimensional array with 2 arrays each 3 members large. The
values given are 'a' 'b' 'c' 'd' 'e' 'f'.

qqq.java
import java.io.*;
public class qqq
{
public static void main(String argv[])
{
try
{
char a[][] = {
{ 'a','b','c' },{ 'd','e','f' }};

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (30 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

FileOutputStream fos = new FileOutputStream("c:\\javaprg\\z.ser");


ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(a);
oos.close();
}
catch (Exception e){System.out.println("bye");e.getMessage();}
}
}

As previously, we are writing the object in one stroke to the file and in a similar way we are
reading it from the file.

qqq.java
import java.io.*;
public class qqq
{
public static void main(String argv[])
{
try
{
char a[][];
FileInputStream fos = new FileInputStream("c:\\javaprg\\z.ser");
ObjectInputStream oos = new ObjectInputStream(fos);
a = (char [][] ) oos.readObject();
System.out.println(a[0]);
System.out.println(a[0][0]);
System.out.println(a[1]);
}
catch (Exception e){System.out.println("bye");e.getMessage();}
}
}

C:\javaprg>java qqq

abc
a
def

a[0] within the println prints all the characters in one stroke. To print individual characters we
have to be specific, like a[0][0] is 'a' and so on. a[0] will print the entire string 'abc' and a[1]
will print out the entire string 'def'.

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (31 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

Thus the crux is that using ObjectInputStream and ObjectOutputStream you can read and write
arrays to the disk.

Conclusion

In this chapter, you learnt about static variables and static functions and gained some insight
into the concept of constructors.We also showed you how you can create your own exceptions.

Apart from the applets that you have been creating, you are now able to create applications.
Using ObjectInputStream and ObjectOutputStream you can read and write arrays to the disk.
After readig this hapter, we hope you are now well versed with the concept of
multidimensional arrays in connection with objects and classes.

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (32 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (33 of 34) [5/2/2008 10:57:56 PM]


http://www.vijaymukhi.com/documents/books/javajsp/chap4.html

Contents | Foreword | About the Authors | Introduction |


Appendix |Chapter 1 |Chapter 2 |Chapter 3 |Chapter 4 |Chapter 5 |Chapter 6 |
Chapter 7 |Chapter 8 |Chapter 9 |Chapter 10 |Chapter 11

http://www.vijaymukhi.com/documents/books/javajsp/chap4.html (34 of 34) [5/2/2008 10:57:56 PM]


Java-Servlets-JSP

5. Java Server Pages

Introduction

Based on servlet technology, Java Server Pages (JSP) is one of the most important elements of
Java server programming.

Java Server Pages combine HTML or XML with nuggets of Java code to produce dynamic
web pages. Each page is automatically compiled to a servlet by the JSP engine the first time it
is requested, and then executed. JSP provides a variety of ways to talk to Java classes, servlets,
applets and the web server.

NOTE: We'll be explaining JSP using the Java Server Development Kit or the JSWDK which
can be downloaded from Sun's site at www.javasoft.com. All new development on
JSP/servlets has been passed on to the apache team. The reason we are teaching you the older
version is because it is easier. There are cosmetic changes from the one we are doing to the
jakarta version which we will go back to in the last chapter.

Download the zip file from the Sun site on the Internet and unzip it. It will create a sub
directory jswdk-1.0.1. cd into this sub directory and then move into the bin sub directory. Here
run a batch file named startserver. If you get an error in the Java Web Server window and if
you are using jdk 1.2.2 like we are, add the following to the classpath variable.

set CLASSPATH=c:\jdk1.2.2\lib\tools.jar;%CLASSPATH%

A Simple Java Server Page

Let us begin by creating a simple jsp file. To do so, create a file that has a .jsp extension and
save this file to the examples\jsp subdirectory. You can save it in the examples subdirectory or
the jsp subdirectory, either is fine. We have named the file e1.jsp and it contains only one
word, 'hi'.
e1.jsp
hi

Open this file in the browser by giving the url as


http://127.0.0.1:8080/examples/jsp/e1.jsp

'hi' will now be displayed in your browser window.

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (1 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

Congratulations! You have written the world's smallest JSP program. The browser initially
takes a long time to show you the result but in future it will be very quick.

Now go to the subdirectory named work, where you will find a subdirectory ending with the
word examples. Change to this directory.

C:\jswdk-1.0.1\work>dir

Volume in drive C is SONAL


Volume Serial Number is 0661-13EE
Directory of C:\jswdk-1.0.1\work

. <DIR> 06-05-00 7:31p .


.. <DIR> 06-05-00 7:31p ..
%3A808~1 <DIR> 06-05-00 7:31p %3A8080%2Fexamples
%3A808~2 <DIR> 06-05-00 7:31p %3A8080%2F
0 file(s) 0 bytes
4 dir(s) 2,629.67 MB free

C:\jswdk-1.0.1\work>cd %3A808~1

This is your first JSP file. You will find 3 files there, one java file, one class file and one dat
file. If you look at their names, they are very long but they all contain e1.

C:\jswdk-1.0.1\work\%3A8080%2Fexamples>dir

Volume in drive C is SONAL


Volume Serial Number is 0661-13EE
Directory of C:\jswdk-1.0.1\work\%3A8080%2Fexamples

. <DIR> 06-05-00 7:31p .


.. <DIR> 06-05-00 7:31p ..
JSP_00~1 JAV 2,615 06-05-00 7:31p jsp_0005ce_00031_0002ejspe1_jsp_1.java

C_0003~1 DAT 59 06-05-00 7:31p C_0003a.


jswdk_0002d_00031_0005f_00030_0005f_00031.examples.jspe1.dat

C_0003A <DIR> 06-05-00 7:32p C_0003a

JSP_00~1 CLA 2,530 06-05-00 7:32p jsp_0005ce_00031_0002ejspe1.class

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (2 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

3 file(s) 5,204 bytes


3 dir(s) 2,629.66 MB free

C:\jswdk-1.0.1\work\%3A8080%2Fexamples>

Now open the java file by saying edit *.java

package C_0003a.jswdk_0002d_00031_0005f_00030_
0005f_00031.examples.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.Vector;
import com.sun.jsp.runtime.*;
import java.beans.*;
import com.sun.jsp.JspException;
public class jsp_0005ce_00031_0002ejspe1_jsp_1 extends HttpJspBase {

static char[][] _jspx_html_data = null;

public jsp_0005ce_00031_0002ejspe1_jsp_1( ) {
}

private static boolean _jspx_inited = false;

public final void _jspx_init() throws JspException {


ObjectInputStream oin = null;
int numStrings = 0;
try {
FileInputStream fin = new FileInputStream("work\\%3A8080%2Fexamples\\C_0003a.
jswdk_0002d_00031_0005f_00030_0005f_00031.
examples.jspe1.dat");
oin = new ObjectInputStream(fin);
_jspx_html_data = (char[][]) oin.readObject();
} catch (Exception ex) {
throw new JspException("Unable to open data file");
} finally {

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (3 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

if (oin != null)
try { oin.close(); } catch (IOException ignore) { }
}
}

public void _jspService(HttpServletRequest request, HttpServletResponse response)


throws IOException, ServletException {

JspFactory _jspxFactory = null;


PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
String _value = null;
try {

if (_jspx_inited == false) {
_jspx_init();
_jspx_inited = true;
}
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,"", true, 8192, true);
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();

out.print(_jspx_html_data[0]);

} catch (Throwable t) {
if (out.getBufferSize() != 0)
out.clear();
throw new JspException("Unknown exception: ", t);
} finally {
out.flush();
_jspxFactory.releasePageContext(pageContext);
}
}
}

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (4 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

Edit shows you a Java program which has been created by the Java Web Server. The JSP file
that you ran from the browser was converted into a servlet. The static data in the jsp file was
stored in a new file with the .dat extension in the subdirectory work. The JSP engine writes
this code for you. All your html code is stored in the file with the .dat extension. At first
_jspx_init is called which opens the .dat file with the static text. Then _jspService is called.
Now you know why it takes a long time for the output to show up in the browser. It takes
some time to convert the jsp file into a servlet and then compile the servlet to a .class file and
then run the servlet.

JSP Expressions

A JSP Expression is a great tool for embedding values within your HTML code. Anything
between <%= and %> tags will be evaluated, converted to a string, and then displayed.

Now let's create another file where we start with hi and then send %="bye" %.

e2.jsp
hi
<%= "bye" %>
no

Partial Output of the servlet code generated by the jsp engine for the .jsp file is enclosed with
the dotted lines..

----------------
out.print(_jspx_html_data[0]);
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\e2.jsp";from=(1,3);to=(1,10)]
out.print( "bye" );
// end
out.print(_jspx_html_data[1]);
--------------------

When you view this file in your browser, it will display hi, bye and no, all on the same line.

Note that you must save the file as e2.jsp and not e1.jsp.

Let's understand what we have just done. The JSP engine takes over and it saves hi to disk in
the .dat file. Then it sees the tag '<%'. It understands this character and for it anything within
<% %> is JSP. A tag is anything that starts with an angle bracket. '<%' is also used in Active
Server Pages. The '=' sign tells the engine to add the line 'out.print' in the Java program and
also whatever is given in double quotes as a parameter to print. It automatically puts the open
and close bracket and a semicolon at the end. The next line with 'no' is also saved to disk as

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (5 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

another array.

In effect, you have saved two arrays of chars on disk. If you look at the code, it all looks the
same. The only difference is that it says print the first array, then the newly added line,
out.print("bye"), and then it finally print the second array.

_jspx_init uses the function readObject to read the contents of the .dat file into an array
_jspx_html_data. Thus the array member _jspx_html_data[0] will contain hi and
_jspx_html_data[1] will contain bye. out looks like JspWriter and is initialized in _jspService.
It is used to create the html file which will be sent across.

e3.jsp
hi
<% out.println("no"); %>
bye

------------------
out.print(_jspx_html_data[0]);
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\e3.jsp";from=(1,2);to=(1,22)]
out.println("no");
// end
out.print(_jspx_html_data[1]);
------------------

Now remove the '=' sign in the JSP file and write out.println ("no"); Since there is no '=' sign,
the jspengine does not add its own out.print. This jsp statement gets added in as is. The JSP
engine assumes it to be Java code. This means that if you do not write good Java code here,
you will get horrible errors. This happens when javac compiles the Java program. They will be
displayed in your Java server window.

This implies that whenever you put an '=' sign, you must use something that will be converted
to a string in Java. This is because the out.print that is added takes only a single string as its
parameter.

Hence bye is enclosed within double quotes. Try giving it without quotes and you will be
presented with an error. The bye is assumed to be a variable. If you put a semicolon then it
takes the semicolon as a part of the double quotes. There is supposed to be no space between
the % and =. It must be typed in like this, <%=

In a nutshell, we have html code and then there are Java Server Pages, where we have html,
and Java code within that html. The html tags and text are saved to disk and the Java code
comes as is. Thus in a jsp program we get to mix html and java code. All the java code written

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (6 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

so far can be placed in a jsp program along with html but within the <% tag.

e4.jsp
hi
<%= bye %>
no

Output in Browser
Error: 500
Unable to compile class for JSP

Error message in the java server window.


com.sun.jsp.runtime.JspServlet: init
Scratch dir for the JSP engine is: work\%3A8080%2Fexamples
IMPORTANT: Do not modify the generated servlets
Unhandled error! You might want to consider having an error page to report such
errors more gracefully
com.sun.jsp.JspException: Compilation failed:work\%3A8080%2Fexamples\jsp_0005ce_
00032_0002ejspe2_jsp_2.java:69: Undefined variable: bye
out.print( bye );
^
1 error

at com.sun.jsp.compiler.Main.compile(Main.java:347)
at com.sun.jsp.runtime.JspLoader.loadJSP(JspLoader.java:135)
at com.sun.jsp.runtime.JspServlet$JspServletWrapper.loadIfNecessary(JspS
ervlet.java:77)
at com.sun.jsp.runtime.JspServlet$JspServletWrapper.service(JspServlet.j
ava:87)
at com.sun.jsp.runtime.JspServlet.serviceJspFile(JspServlet.java:218)
at com.sun.jsp.runtime.JspServlet.service(JspServlet.java:294)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:840)
at com.sun.web.core.ServletWrapper.handleRequest(ServletWrapper.java:155
)
at com.sun.web.core.Context.handleRequest(Context.java:414)
at com.sun.web.server.ConnectionHandler.run(ConnectionHandler.java:139)

Here it assumed that bye was a variable and the error is detected by javac on compiling the
servlet generated by the jsp engine.

Moving on to the next example, where we are now writing System.out.println("no") within the
% tag.

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (7 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

e5.jsp
hi
<% System.out.println("no"); %>
bye

----------------
out.print(_jspx_html_data[0]);
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\e5.jsp";from=(1,2);to=(1,29)]
System.out.println("no");
// end
out.print(_jspx_html_data[1]);
-----------------
Output in Server Window
no
There is no '=' following the %, so it is included as it is in the Java file. The 'no' will not be
shown on your screen but in the server's dos box. To display something on the screen, you
can't use System.out.println, instead you must use out.println.

If you carefully study the code, you will observe that there are seven variables created and one
of them is out. Hence in JSP you are allowed to use out and you can use any of these seven
variables in your program. These are the predefined objects available to you.
System.out.println can also be used anywhere in a jsp tag as it is a valid java statement. Do not
forget the terminating semicolon as java code written in a tag is added verbatim to the function
_jspx_service().

JSP Declarations

A JSP declaration can be thought of as the definition of class level variables and methods that
are to be used throughout the page.

In the next example, we have hi and then bye. The JSP code begins with int j preceded by an
exclamation, and thereafter it has int i with a semicolon.

e6.jsp
hi
<%! int j; %>
bye
<% int i; %>

--------------------
public class jsp_0005ce_00036_0002ejspe6_jsp_1 extends HttpJspBase {
static char[][] _jspx_html_data = null;

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (8 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\e6.jsp";from=(1,3);to=(1,11)]
int j;
// end

public jsp_0005ce_00036_0002ejspe6_jsp_1( ) {
}
-------------------
-------------------
out.print(_jspx_html_data[0]);
out.print(_jspx_html_data[1]);
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\e6.jsp";from=(3,2);to=(3,10)]
int i;
// end
out.print(_jspx_html_data[2]);
-----------------------

Whenever anything is put in an exclamation it is called a declaration. This is done outside any
function but within the class that is public. The line int j comes up when your class starts with
{. Whenever you put any statement in <%, it is placed in jspservice and becomes local. It is
visible from then onwards. If you want to make a variable global then use an exclamation. You
can create functions and global variables in a class. Unlike C, where 'global' is applicable to
the file, here it is limited to a class.

Now we will mix java with html code.


e7.jsp
hi
<% int i = 6;
if ( i == 6 ) %>
bye

---------------
out.print(_jspx_html_data[0]);
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\e7.jsp";from=(1,2);to=(2,14)]
int i = 6;
if ( i == 6 )
// end
out.print(_jspx_html_data[1]);
-------------
At first, the variable i which is of type int is initialized to the value 6. Then the if statement
checks to see if i == 6. The next line after the comments will print bye only if i holds the value
6, otherwise it will do nothing. Since the bye is pure html, we have to end the jsp tag and close
the JSP scriptlet. The final code looks like this, if (i == 6) out.println ("bye"); What ever is
given in <% %> is kept as it is while the html statements become part of the array of chars.

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (9 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

But what is the purpose of all this? This is a method of generating dynamic code. The Perl
family of scripting languages generates the entire page. The focus is on Perl writing the entire
html page whereas ASP, PHP, JSP opted to have an html page where the code would be
inserted. In the html page, you can put ASP, PHP or Java code to give the page dynamism and
free yourself of the tedium of trying to create every possible page the visitor must be shown by
hand. The file that you are writing is an html file, which means you can use an existing html
editor.

For Java Server Pages, servlets are the foundation. Normally, a web page has a static template
i.e. things which are permenant. With JSP, you separate the static and the dynamic, and insert
dynamism into a web page. We will also use beans extensively in the Java Server Pages and
one of the chapters will explain to you how you can create your own custom tags.

A JSP page is a text-based document that describes how to process a request and create a
response.

JSP pages in servlet classes are what Sun calls its web components and these pages are
delivered by a JSP container. When you look at a JSP page, you will see 3 classes of scripting
elements. These are declarations, scriptlets and expressions.

The following example has been taken from the Net from a great FAQ that we stumbled upon.
We don't mind if you take our programs too. We have not mentioned any names here because
there were too many brains behind it.
e8.jsp
<% for (int i = 1; i<= 4 ; i++) { %>
<H<%=i%>>Hello</H<%=i%>>
<% } %>
hi

The code looks complicated but you can easily understand it.

The for statement goes on four times. Since the for statement is not part of html, it is enclosed
within the % and the angle brackets. The '{' bracket starts the for loop. The set of statements to
be executed within the for is a combination of HTML and JSP. H is an html tag that stands for
heading. Along with H is a number that displays the heading in a different format. We have
not used a number directly because we want it to be the value of i. i is a variable initialized in
the for loop. The <%= is used to display the value of i which is 1 as of now. Hence the tag
becomes H1. Following this is Hello. To close the tag, the same rules are followed, the closing
tag becomes </H1>. The '}' bracket within the % and the angle brackets is used to close the for
loop. When i becomes 2, the statement will be <H2>Hello</H2> and the same follows for 3
and 4. This is how Hello can be seen in all 4 tags.

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (10 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

View the actual code in the Java file and you will realize that it is much easier to comprehend.

View Source

<H1>Hello</H1>

<H2>Hello</H2>

<H3>Hello</H3>

<H4>Hello</H4>

hi

-------------------
out.print(_jspx_html_data[0]);
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\e8.jsp";from=(0,2);to=(0,34)]
for (int i = 1; i<= 4 ; i++) {
// end
out.print(_jspx_html_data[1]);
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\e8.jsp";from=(1,5);to=(1,6)]
out.print(i);
// end
out.print(_jspx_html_data[2]);
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\e8.jsp";from=(1,20);to=(1,21)]
out.print(i);
// end
out.print(_jspx_html_data[3]);
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\e8.jsp";from=(2,2);to=(2,5)]
}
// end
out.print(_jspx_html_data[4]);

out.print(_jspx_html_data[0]);
for (int i = 1; i<= 4 ; i++) {
out.print(_jspx_html_data[1]);
out.print(i);
out.print(_jspx_html_data[2]);
out.print(i);
out.print(_jspx_html_data[3]);
}

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (11 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

out.print(_jspx_html_data[4]);
------------------

There are 5 sets of html data in the JSP file. The first one is blank, the second one is <h, the
next one is >hello</h, the third set is > and then finally, there is hi. These are the different
values assigned to the variables in the for loop.
_jspx_html_data[1] = <h
i 1,2,3,4
_jspx_html_data[2] = >hello</h
i 1,2,3,4
_jspx_html_data[3] = >
_jspx_html_data[4] = hi

If you look at e.dat, it shows data as 5.

dat file
5
-
<H
-
>Hello</H
-
>
-
-

Let's go one step further, give two hyphens after %. Whenever you start with a <%- and end it
with -%>, it signals a comment.

e9.jsp
hi
<%- vijay mukhi -%>
bye

The good thing about comments is that they soon disappear. They are present only in your JSP
file and will not be seen in the servlet. That's why we have written my name there, it doesn't
show up. So whenever you want to include comments but hide them from the client, this is
what you use. All this happens on the server, nothing comes over on to the client hence
nobody knows of it. If you want normal comments, use the html comments which are given as
<!- .

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (12 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

JSP Directives

A JSP Directive is a statement that gives the JSP engine information for the page that follows.
Anything with a <%@ sign is called a Directive. In the following program, we have used a
directive named page. The other possible directives in JSP1.0 are include and taglib.

e10.jsp
<%@ page info="vijay" %>

public String getServletInfo() {


return "vijay";
}

The compiler generates different kinds of code depending upon the directive you use. The
effects are global. Here we say page info=vijay. A page is a directive and info is an attribute.
The attribute is given a value; vijay in this case. On doing so, the JSP engine actually creates a
function named getServletinfo and this function returns the value given to info i.e. vijay.

e11.jsp
hi
<%@ page import="java.applet.*" %>

-----------------
package C_0003a.jswdk_0002d_00031_0005f_00030_0005f_00031.examples.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.Vector;
import com.sun.jsp.runtime.*;
import java.beans.*;
import com.sun.jsp.JspException;
import java.applet.*;
-------------

When you give import as an attribute and then look at the Java generated file, you will see that
at the end of the imports, there is import java.applet.*. You don't have to put a semicolon. This

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (13 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

means that if you are a referring to some Java code in some classes, you don't have to preface
them i.e. give full names, you just put imports. In case you have more than one import, then
separate them using commas, they will all be added at the end. If there are two similar imports,
it is not considered an error. A point to be noted here is that if the match is found earlier in the
file, then the import added by you is not used.

e12.jsp
hi
<%@ page extends="java.util.Dictionary" %>

--------------
public class jsp_0005ce_00031_00032_0002ejspe12_jsp_1 extends java.util.Dictionary {
---------------

Normally, extends is not used because by default every class extends HttpJspBase. But if you
do so then HttpJspBase is replaced with java.util.Dictionary. At times, when you want to write
complicated code then you can have a class that is derived from HttpJspBase, from which you
can further extend your classes. You must derive from HttpJspBase or else you will end up
with a load of errors.

e13.jsp
hi
<%@ page implements="java.util.Dictionary" %>

Implements follows the same rules as that of extends. The JSP engine adds a line to the class
with implements. It gives an error and no java file is generated as in this case as well,
Dictionary is a class not an interface.
e14.jsp
<%@ page buffer="1000" %>
hi

------------
pageContext = _jspxFactory.getPageContext(this, request, response,"",true,1024000, true);
---------

Since we have given the buffer as 1000, the getPageContext function makes the buffer
parameter 1000KB i.e. 1000 multiplied by 1024. This is the amount of buffering space
required. Buffering improves speed since its better to write a larger number of characters at
one go than a small number many times.

You will have multiple requests being sent to your web server. You may want either one

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (14 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

instance of the servlet or you may want 20 of them running at a time. If you want the servlet to
create multiple instances of itself then you must give isThreadsafe=false. The default is true.
e15.jsp
<%@ page isThreadSafe="false" %>
<b>hi

---------------
public class jsp_0005ce_00031_00035_0002ejspe15_jsp_1 extends HttpJspBase implements
SingleThreadModel
-----------------

By saying isThreadSafe=false, the JSP engine will implement SingleThreadModel and it can
load multiple instances of the servlet instead of one. This class in that sense doesn't have any
function prototypes and hence we don't have to add any code in the file. It can however, check
to see if we have implemented certain interfaces.

e16.jsp
<%@ page session="false" %>
Bye

Most of these attributes have a default value of true or false, so you don't need to specify them.
There is one more attribute named session. By default, session is true, so you see the session
object in _jspservice function.

The following are the variables that are created in the _jspservice function:

JspFactory _jspxFactory = null;


PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
String _value = null;

When you make the page session false, session that looks like HttpSession, is not created at
all.

The next script has the contentType initialized to text/plain. By default, the value assigned to
this attribute is text/html.

e17.jsp

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (15 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

<%@ page contentType="text/plain" %>


<b>Bye

----------
response.setContentType("text/plain");
----------

The tag b is not recognized by the browser anymore and thus we see <b> Bye in the browser.
The Content type depends upon the file being sent over.

If you initialize IsErrorPage to true, it will actually create an object called exception that looks
like Throwable. This is then initialized by the getAttribute function.

e18.jsp
<%@ page isErrorPage="true" %>
hi

-----------
Throwable exception=(Throwable) request.getAttribute("javax.servlet.jsp.jspException");
------------

The request variable is given to us as a parameter in the jspservice function. getAttribute takes
one parameter which is a variable and returns a value. Instead of a variable we call it an
attribute. This is used to initialize the new variable named exception which looks like
jspException. The concept of exceptions has already been discussed in one of the previous
chapters.

Import saves us the trouble of typing too much. Here we have a function named abc which has
been defined in the public area. Thus the declaration or the exclamation sign has been used.
Basically, it throws an IOException. The reason why we have page import=java.io* is because
it is easier to say IOException than java.io.IOException. The minute the function abc is called,
an exception will be thrown. Somebody has to be there to receive this exception.
e19.jsp
<%@ page errorPage="f1.jsp" %>
<%@ page import="java.io.*" %>
<html>
<%! void abc() throws IOException
{
throw new IOException("hi bye");
}
%>

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (16 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

<%
//try
//{
abc();
//}
//catch ( Exception e) {}
%>
</html>

If we stop here , in the browse we get the following error .


Error: 404
No detailed message

We start by using page directive errorPage, which is also an attribute and its value is a jsp file
f1.jsp. If you look at the code you will realize that it throws new HandleErrorPageException,
which has f1.jsp as a parameter. f1.jsp is your error page and because of this throw, it will now
go to f1.jsp. In abc we have a throw, we throw an IOException. Since an exception is thrown,
the catch in the servlet will catch it as the try and catch around abc have been commented out.
The servlet catch has HandleErrorPageException, where the first parameter is f1.jsp and the
last one is out. out is used to display output. t is throwable as a parameter to catch. If you look
at f1.jsp, it has to start with isErrorPage=true and we use exception.printStackTrace to print
where the exception took place.
f1.jsp
<%@ page isErrorPage="true" %>
<%
out.println("<pre>");
PrintWriter pw = response.getWriter();
exception.printStackTrace(pw);
out.println("</pre>");
%>

Output
java.io.IOException: hi bye
at C_0003a.jswdk_0002d_00031_0005f_00030_0005f_00031.
examples.jsp.jsp_0005ce_00031_00039_0002ejspe19_jsp_1.

abc(jsp_0005ce_00031_00039_0002ejspe19_jsp_1.java:23)
at C_0003a.jswdk_0002d_00031_0005f_00030_0005f_00031.
examples.jsp.jsp_0005ce_00031_00039_0002ejspe19_jsp_1.
_jspService(jsp_0005ce_00031_00039_0002ejspe19_jsp_1.java:82)
at com.sun.jsp.runtime.HttpJspBase.service(HttpJspBase.java:87)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:840)
at com.sun.jsp.runtime.JspServlet$JspServletWrapper.service(JspServlet.java:88)

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (17 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

at com.sun.jsp.runtime.JspServlet.serviceJspFile(JspServlet.java:218)
at com.sun.jsp.runtime.JspServlet.service(JspServlet.java:294)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:840)
at com.sun.web.core.ServletWrapper.handleRequest(ServletWrapper.java:155)
at com.sun.web.core.Context.handleRequest(Context.java:414)
at com.sun.web.server.ConnectionHandler.run(ConnectionHandler.java:139)

<pre>
</pre>

------------------
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\e19.jsp";from=(3,3);to=(7,0)]
void abc() throws IOException
{
throw new IOException("hi bye");
}
// end

In _jspservice
out.print(_jspx_html_data[0]);
out.print(_jspx_html_data[1]);
out.print(_jspx_html_data[2]);
out.print(_jspx_html_data[3]);
// begin [file="C:\\jswdk-.0.1\\examples\\jsp\\e19.jsp";from=(8,2);to=(14,0)]

//try
//{
abc();
//}
//catch ( Exception e) {}
// end
out.print(_jspx_html_data[4]);
} catch (Throwable t) {
if (out.getBufferSize() != 0)
out.clear();
throw new HandleErrorPageException("f1.jsp", t, out);
} finally {
out.flush();
_jspxFactory.releasePageContext(pageContext);
}
------------

f1.jsp error page

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (18 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

-----------
out.print(_jspx_html_data[0]);
out.print(_jspx_html_data[1]);
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\f1.jsp";from=(1,2);to=(6,0)]

out.println("<pre>");
PrintWriter pw = response.getWriter();
exception.printStackTrace(pw);
out.println("</pre>");
// end
out.print(_jspx_html_data[2]);
-------------

exception.printStackTrace prints out the text. In this way you can have a separate page for
error handling. All that you should do is create a page named anything.jsp and in every JSP
page redirect the errors to it.

Within the try and catch is abc, so the code of abc will be called. You can have a 'try' and
'catch' within another 'try' and 'catch' pair, nested as many levels deep as you want. abc throws
an IOException, so the exception will be called.
e19a.jsp
<%@ page errorPage="f1.jsp" %>
<%@ page import="java.io.*" %>
<html>
<%! void abc() throws IOException
{
throw new IOException("hi bye");
}
%>
<%
try
{
abc();
}
catch ( Exception e)
{
System.out.println("hi in exception");
}
%>
</html>

Now that we have uncommented the try and catch near abc, the earlier catch was not called
and down in the web server window we see hi in exception, which proves that only the inner

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (19 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

try catch was activated.

e20.jsp
hi
<%@ include file="aa.html" %>
Bye

C:\jswdk-1.0.1\examples\jsp>edit aa.html
in aa.html

-------------------
out.print(_jspx_html_data[0]);
out.print(_jspx_html_data[1]);
---------------
dat file
2
hi

Output in browser
hi in aa.html Bye

A @ in a JSP file signals a directive. The earlier examples had 'page', while in the program
shown above, we use include. include takes a string which has to be filename which is aa.html
here. e20.jsp contains hi, then the include and finally a bye. aa.html simply contains 'In
aa.html'.

As always, your entire JSP is converted into a .dat file. Since it is on two lines, you will see
only two prints in the Java file.

The point that we are trying to make is that the .dat file is made at the time of the creation of
the servlet. This is called the Translation Phase. You can change aa.html, add some more text
and then refresh the server. The new text within the html file will not be displayed because the
.dat file isn't created again.

The only way to incorporate the new changes is by either recompiling the Java file or stopping
and restarting the server.Stopserver deletes all the files in the work directory, so all the files
are created from scratch when you want to view them.

There are two phases in JSP. One of them is the Translation Phase, which it happens only
once. Then, the service function 'jspservice' is called for every request.

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (20 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

So far we have included a .html file, so now let's try it out with JSP.

e21.jsp
hi
<%@ include file="aa.jsp" %>
Bye
aa.jsp
no
<%= new java.util.Date() %>
lously

----------------
.java file for e21.jsp
out.print(_jspx_html_data[0]);
out.print(_jspx_html_data[1]);
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\aa.jsp";from=(1,3);to=(1,25)]
out.print( new java.util.Date() );
// end
out.print(_jspx_html_data[2]);
--------------------

There is no java file for aa.jsp.

dat file
3
hi
-
no
-
lousy

Bye

With this example you will realize that if you have JSP code in include, then all the JSP code
will be put in the service function. Thus whenever you want something dynamic, create a JSP
file and use it with the include directive. Now each time you click on refresh the date function
will be reexecuted, so you see a different date and time every time.

Let's go one step further.

e22.jsp

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (21 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

hi
<jsp:include page="zz.jsp" flush="true" />
bye

zz.jsp
no
bad

We now have 2 java files created for the 2 jsp files.


---------------------
The java file for e22.jsp

out.print(_jspx_html_data[0]);
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\e22.jsp";from=(1,0);to=(1,42)]
out.flush();
pageContext.include("zz.jsp");
// end
out.print(_jspx_html_data[1]);
-----------------
-----------------
The java file for zz.jsp
out.print(_jspx_html_data[0]);
-----------------

The first line in e22.jsp has hi and the second line is jsp:include page="zz.jsp" within angle
brackets. If you notice there is no % sign like we had earlier. Such a line is called an 'action'.
Each time you refresh the file, it gets the filename and requests the server for that file. Unlike
the earlier example, this is dynamic.

When you see the generated java code, there is no data stored anywhere, so you check the .dat
file. In the Java file, the array size is 2, for hi and bye, hence you see 0 and 1.
pageContext.include is what the jsp:include is converted to in the Java file. It is this
pageContext.include that regenerates the file each time. Now the problem with using include
as an action is that you cannot have Java code with it and in addition, you cannot change
headers and cookies.

e23.jsp
hi
<jsp:include page="a40.html" flush="true" />
bye

a40.html

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (22 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

bye

-----------------
out.print(_jspx_html_data[0]);
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\e23.jsp";from=(1,0);to=(1,44)]
out.flush();
pageContext.include("a40.html");
// end
out.print(_jspx_html_data[1]);
------------------

In e23.jsp, the first line is hi. Then a40.html, which contains bye, is included. Now change
'bye' in the html file to 'over' and click on refresh. This time you will see over instead of bye.
include here is an action.

In the next script, we have a new action called forward.

e24.jsp
hi
<jsp:forward page="cc.jsp" />
bye

cc.jsp
no
<%= new java.util.Date() %>
lousy

------------------
out.print(_jspx_html_data[0]);
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\e24.jsp";from=(1,0);to=(1,29)]
if (true) {
out.clear();
pageContext.forward("cc.jsp");
return;
}
// end
out.print(_jspx_html_data[1]);
------------------

This example introduces a new action named forward. page=cc.jsp implies that we are sending
a page with it. Hence every time you try to load e23.jsp, you will be forwarded to cc.jsp.
Forward becomes pagecontext.forward in the Java file. This will simply go to the page

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (23 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

mentioned. A valid question to ask here would be, 'will it come back to e23.jsp?' The answer is
no. That's because the last line before the closing brace is a return. So whenever you have
forward as an action, the file passed to pagecontext.forward becomes your active html file and
everything else is forgotten.

Bear in mind that the http protocol is a stateless protocol. Each time you connect to the web
server you are disconnected after you receive the page. So if you are on the Amazon.com site
and you buy 6 books, moving from one page to the other, it becomes a session and this session
has to be tracked. This is where the session object comes into use.

z.htm
<html>
<form action=e26.jsp>
<input type='text' name='aa'>
<input type='submit' value='click'>
</form>
</html>

e26.jsp
<%= request.getParameter("aa") %>

------------------
out.print(_jspx_html_data[0]);
// begin [file="C:\\jswdk-1.0.1\\webpages\\e26.jsp";from=(0,3);to=(0,31)]
out.print( request.getParameter("aa") );
// end
out.print(_jspx_html_data[1]);
--------------------

Run in browse is follows

http://127.0.0.1:8080/examples/jsp/z.html

If you write bye in the text box and click on the button you will see bye in the browser and in
the address bar of the browser

http://127.0.0.1:8080/examples/jsp/e26.jsp?aa=bye

If you want to read data from a form, you can say request.getParameter("aa") where aa is some
name that you have given in the form. This returns bye since that is what we typed in our text

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (24 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

box. The form has an action which will execute the JSP code on the server when the user
clicks on the submit button. This will bring up a new page with the url containing ?aa=bye.
The JSP engine then sends the value 'bye' to be displayed on the screen.

When the button named submit is clicked, the browser will look for a tag named form and
within that tag an attribute named action. It will then create a url with action and at the end add
a ?. Now it takes all the input statements, figures out what you have written in them and
converts then to a name value pair seperated by '=', like so
aa=bye

With JSP it is very easy to extract these values, thereby making it the preferred tool for Web
programmers.

In the following example we have created two functions, one named jspInit and the other
named jspDestroy.
e26.jsp
<%!
public void jspInit()
{
super.jspInit();
System.out.println("jspinit");
}
public void jspDestroy()
{
super.jspDestroy();
System.out.println("jspdestroy");
}
%>
hi

----------------
public class jsp_0005ce_00032_00036_0002ejspe26_jsp_1 extends HttpJspBase {
static char[][] _jspx_html_data = null;
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\e26.jsp";from=(0,3);to=(11,0)]
public void jspInit()
{
super.jspInit();
System.out.println("jspinit");
}
public void jspDestroy()
{
super.jspDestroy();
System.out.println("jspdestroy");

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (25 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

}
// end
---------------
Whenever a class extends HttpJspBase, the service function within HttpJspBase is called. This
service calls jspInit once and only once when the class is loaded or initialized. It is not like
_jspservice, which is called multiple times. jspDestroy is called when the servlet is destroyed.
We will need our own jspInit if we want to initialize our variables or if we want certain code
to be executed only once and similarly jspDestroy can be used to release the memory used by
variables or do anything at the end. But it is difficult to pin point as to when jspDestroy will be
called. Super is used to call the code in the original class.

In the next script, we have response.sendRedirect and within the round brackets a url has been
specified. The job of this function is to take you to the site that has been passed as a parameter.
This page then becomes the active Page.

e27.jsp
<% response.sendRedirect("http://127.0.0.1:8080/examples/jsp/e9.jsp"); %>

Normally, one is not supposed to write anything before or after sendRedirect. But if you do
write something, it will not be displayed.
e28.jsp
hi <p> bye
<% response.sendRedirect("http://127.0.0.1:8080/examples/jsp/e9.jsp"); %>
no <p> good

http://127.0.0.1:8080/examples/jsp/e9.jsp

The address bar in the browser also changes its url, which means that the browser asked for a
new url.

Every http page starts with a header. Normally, it will be 200 OK. 200 is called the http status
code. There are around 20 to 30 predefined status codes, where 200 means OK, 404 is file not
found and so on. Redirection has a status code of 304. In the next script, we have
response.setStatus.
e29.jsp
<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location","/examples/jsp/e9.jsp");
%>

SC_MOVED_PERMANENTLY is a status code informing the browser to read the next


header line because the file has been moved. The next line sets the header variable Location to

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (26 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

a location or a url from where the file is to be picked up. When you use response.sendRedirect
or you use setStatus the status code is sent over to the client with more information in the
header. When this reaches the browser, the browser asks for the new file, which in our case is
e9.jsp. Finally, the user sees e9.jsp.

Now let's take a case where we want the user to visit a certain page, barring which he will not
be allowed to browse our site. It's like a login page and unless the user doesn't go there first, he
can't browse through the rest of the site.
e30.jsp
<%@ page session="true" %>
login
<%
HttpSession s = request.getSession(true);
if ( s.getValue("EID") == null )
{
String s1 = (String ) response.encodeRedirectUrl("e31.jsp?Origin=e30.jsp");
System.out.println(s1);
response.sendRedirect(s1);
}
else
out.println("<h1>hi");
%>

e31.jsp
<%
session.putValue("EID","sonal");
String s1=(String)
response.encodeRedirectURL(request.getParameter("Origin"));
System.out.println("e31 " + s1);
response.sendRedirect(s1);
%>

Also see the output in the Java Web Server. In the browser it shows.
login
hi

Here we have two files, e30.jsp and e31.jsp. The directive, page session="true", is not required
but we will retain it. Then we have login as the text to be displayed. s is a variable that looks
like HttpSession and it is initialized to the return value of request.getSession. This function
returns details of the current session. getSession will either create a new session or will return
a handle to the current session. Of all the variables, we are currently interested in the value of
the variable EID which you must put in capital letters. Since we haven't declared a variable
named EID, it will be null for now.

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (27 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

response.encodeRedirectUrl will create a url of the string given within the brackets and return
a string. This is stored in s1. response.sendRedirect will take you straight to e31.jsp

In e31.jsp, session.putValue creates the variable EID and initializes it to 'sonal'.


request.getParameter will return the value of Origin, which is e30.jsp, and as previously
mentioned response.encodeRedirectUrl will convert this into a url. Finally, there is a
redirection to e30.jsp again. Within e30.jsp the value of EID is already set, which is why you
will not see login again. Instead you see hi. This proves that both s and the session are the
same.

What we are trying to say is that as long as it is the same user on the website, he will not have
to login again, but if the user shuts down the browser and starts another copy, the entire
process has to be repeated. The next program provides further insight into sessions.
e32.jsp
<%@ page session="true" %>
hi
<%
HttpSession s = request.getSession(true);
s.putValue("vij","sonal");
%>

e33.jsp
<%@ page session="true" %>
Bye
<%
HttpSession s = request.getSession(true);
%>
<%= s.getValue("vij") %>

In e32.jsp, we first write hi. request.getSession will return the current session handle which is
stored in s. Then s.putValue will create 'vij' if not present and initialize it to 'sonal'.

The next page where we have bye is along the same lines as earlier. s is a handle to
HttpSession. s.getValue of vij will return 'sonal'.

We first want you to run e33.jsp. Here, you will see bye and null because at the moment vij
has no value. After doing so, run e32.jsp. You will see hi on this page and now once again
reload e33.jsp. You will see 'sonal' displayed on your screen.

The point to be noted here is that there are two types of objects, implicit objects and explicit
objects. Session and out are examples of implicit objects; they are already created. The explicit

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (28 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

objects are not created by default, they have to be created and initialized. This is what you will
learn in the next chapter.

Applets are not allowed to write data to disk but with servlets no such rules apply. The next
example confirms this.
e34.jsp
<%@ page import="java.io.*" isErrorPage="true" %>
<%
try
{
PrintWriter p=new PrintWriter(new FileOutputStream("pp.txt"));
p.println("hi");
p.close();
}
catch ( Exception e) {
e.printStackTrace();
}
%>

C:\jswdk-1.0.1>dir pp.txt

Volume in drive C is SONAL


Volume Serial Number is 0661-13EE
Directory of C:\jswdk-1.0.1

PP TXT 4 06-13-00 3:15p pp.txt


1 file(s) 4 bytes
0 dir(s) 2,652.13 MB free

C:\jswdk-1.0.1>type pp.txt

hi

FileOutputStream is used when you want to open a particular file in output mode i.e. for
writing. Since the file named pp.txt is not present on the disk, it will first be created. To write
to this file you need a handle to it. new PrintWriter will return a handle to this file, so p now
becomes a pointer to pp.txt. We then say p.println ("hi") which will write the text 'hi' to the
file. You can give the complete path along with the filename, or use the default which is the
jswdk-1.0.1 subdirectory. If you want to read from a file then use FileInputStream instead of
FileOutputStream.
When you execute the command 'type pp.txt' in c:\jswdk-1.0.1, it will print hi on the screen.

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (29 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

For the grand finale of this chapter, we have one last example.

The web-inf directory has a file named servlet.properties. This example prints the properties
and their values within this file. We had done something similar in the servlet chapter. We
have not shown you the contents of this file as it will obviously differ on your machine.
e35.jsp
<%@ page import="java.util.*" %>
<%!
ServletConfig cfg;
public void jspInit()
{
cfg = getServletConfig();
for ( Enumeration e = cfg.getInitParameterNames(); e.hasMoreElements();){
String name = (String) e.nextElement();
String value = cfg.getInitParameter(name);
System.out.println(name+"="+value);
}
}
%>

keepgenerated=true

servlet.properties has things like keepgenerated=true. This property, if it is true, will not delete
the Java code from the work directory once it has been created and compiled.

Normally, when you have errors, you would like them to be displayed on your web page and
not on the console of the web server. To do so, you say setErrorToClient=true. The client will
now see the errors in his browser. They will now nolonger be displayed on the server console.

In our program, getServletConfig allows us to find the parameters that have been set by the
Java Web Server. This returns an object that looks like ServletConfig().
cfg.getInitParameterNames() returns an enumeration which in turn has a member
hasMoreElements. e.nextElement gives us the name of the element and getInitParameter along
with the name will tell us its value. Thus, they are all stored as a name-value pair. Since we
only have one property at the moment, it will display keepgenerated and its value true and then
the for loop will terminate.

Conclusion

Java Server Pages bring together the power of Java Servlets and HTML coding thereby give
the developers a powerful method to create Server-Side web applications. In this chapter, we
learnt the following:

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (30 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

A Java Server Page file consists of HTML tags, content, JSP directives, JSP declarations, JSP
scriptlets and action tags. Initially, the JSP engine parses the JSP file which then generates a
new servlet with the desired content. If the file changes, then a new servlet is generated;
otherwise, the compiled version is used.

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (31 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

Contents | Foreword | About the Authors | Introduction |


Appendix |Chapter 1 |Chapter 2 |Chapter 3 |Chapter 4 |Chapter 5 |Chapter 6 |
Chapter 7 |Chapter 8 |Chapter 9 |Chapter 10 |Chapter 11

http://www.vijaymukhi.com/documents/books/javajsp/chap5.html (32 of 32) [5/2/2008 10:58:31 PM]


Java-Servlets-JSP

6. JSP - Servlet Code


as generated by JSP Engine

Introduction

In the previous chapter we saw how the JSP engine first creates a servlet after adding the JSP
code, compiles it and then finally executes it. As we have already laid the foundation for
servlets, we will now try to gain in-depth knowledge of servlets, in the light of our newly
acquired knowledge.

Let's now understand servlets. To do so, we will refer to our first script in the previous chapter.

Open it in the browser by giving the url as


http://127.0.0.1:8080/examples/jsp/e1.jsp

You will see 'hi' displayed in your browser.

e1.jsp
hi

This Java file is located in one of the subdirectories of the work directory.
We explained the concept of servlets in one of the previous chapters. Let's understand the
servlet code generated by the JSP engine by looking at smaller examples.

p1.java
import com.sun.jsp.runtime.*;
public class p1 extends HttpJspBase {
}
Here, there is only one public class called p1 that extends HttpJspBase. Since the class is
called p1, you have no choice but to call the file p1.java. This program is in c:\jswdk-
1.0.1\webpages\web-inf\servlets. The name of the class is not HttpJspBase but
com.sun.jsp.runtime.HttpJspBase, therefore we have to use the import statement.

All code can be either in a .class file or in a .jar file. We have no choice but to point the
environmental variable named classpath to the jar file or jar subdirectory so the compiler looks
for the code there. A jar file is a collection of .class files. We have set the CLASSPATH to
servlet.jar and jspengine.jar which are in the lib subdirectory and the current directory. To
compile, we now say javac p1.java

Set CLASSPATH=c:\jswdk-1.0.1\lib\servlet.jar;c:\jswdk-

http://www.vijaymukhi.com/documents/books/javajsp/chap6.html (1 of 9) [5/2/2008 10:59:32 PM]


Java-Servlets-JSP

1.0.1\lib\jspengine.jar;.;%CLASSPATH%

C:\jswdk-1.0.1\webpages\WEB-INF\servlets>javac p1.java
p1.java:2: class p1 must be declared abstract. It does not define void
_jspService(javax.servlet.http.HttpServletRequest, avax.servlet.http.HttpServletResponse)
from class com.sun.jsp.runtime.HttpJspBase.
public class p1 extends HttpJspBase {
^
1 error

HttpJspBase is an abstract class and has one function named _jspService. Since p1 extends
HttpJspBase, p1 must define this class. Thus to eliminate the error, we must add this to our
next program.

p1.java
import com.sun.jsp.runtime.*;
public class p1 extends HttpJspBase {
public void _jspService(HttpServletRequest request,HttpServletResponse response) {
}
}
C:\jswdk-1.0.1\webpages\WEB-INF\servlets >javac p1.java
p1.java:2: class p1 must be declared abstract. It does not define void
_jspService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse
) from class com.sun.jsp.runtime.HttpJspBase.
public class p1 extends HttpJspBase {
^
p1.java:3: Class HttpServletResponse not found.
public void _jspService(HttpServletRequest request,HttpServletResponse response
){
^
p1.java:3: Class HttpServletRequest not found.
public void _jspService(HttpServletRequest request,HttpServletResponse response
){
^
3 errors

_jspService is the same service that we have been using all this time. doGet and service both
belong to the same category. This function takes two parameters, HttpServletRequest and
HttpServletResponse. Hence we import javax.servlet.http.* and since we will be using
PrintWriter in the program, we import java.io.* too. Now everything should work fine.

p1.java

http://www.vijaymukhi.com/documents/books/javajsp/chap6.html (2 of 9) [5/2/2008 10:59:32 PM]


Java-Servlets-JSP

import com.sun.jsp.runtime.*;
import javax.servlet.http.*;
import java.io.*;
public class p1 extends HttpJspBase {
public void _jspService(HttpServletRequest request,
HttpServletResponse response) {
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<b> Hi ");
out.close();
}
catch ( Exception e ) {System.out.println("bye");}
}
}

Run this program in the browser by typing


http://127.0.0.1:8080/servlet/p1

/servlet is converted to c:\jswdk-1.0.1\webpages\web-inf\servlets

This program now works like a servlet. A servlet will work in the same manner whether it is
derived from Servlet or GenericServlet or HttpServlet or from HttpJspBaseServlet.

Having understood this, let's check out a more complex program.

p2.java
import java.io.*;
public class p2
{
public static void main(String argv[])
{
try {
char a[][] = {
{ 'a','b','c' },{ 'd','e','f' }};
FileOutputStream fos =
new FileOutputStream("c:\\jswdk-1.0.1\\webpages\\web-inf\\servlets\\e.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(a);
oos.close();
}

http://www.vijaymukhi.com/documents/books/javajsp/chap6.html (3 of 9) [5/2/2008 10:59:32 PM]


Java-Servlets-JSP

catch (Exception e)
{System.out.println("bye");e.getMessage();
}
}
}
C:\jswdk-1.0.1\webpages\WEB-INF\servlets>javac p2.java

C:\jswdk-1.0.1\webpages\WEB-INF\servlets>java p2

C:\jswdk-1.0.1\webpages\WEB-INF\servlets>dir *.dat

Volume in drive C is SONAL


Volume Serial Number is 0661-13EE
Directory of C:\jswdk-1.0.1\webpages\WEB-INF\servlets

E DAT 73 06-13-00 8:28p e.dat


1 file(s) 73 bytes
0 dir(s) 2,651.09 MB free

C:\jswdk-1.0.1\webpages\WEB-INF\servlets>type e.dat
1/4_ -ur [[Cÿ2~+#i_- xp ur [C_&f__]ä1/4 xp a b cuq ~ d e f

Here, FileOutputStream creates a file named e.dat in the servlets subdirectory. Then we write
'abc' and 'def' in it. These two strings are written as chars to disk.

The next program follows up the previous one, which assumes that you have written an array
of chars to the file e.dat. So in our next program, we are merely picking them up and
displaying them. First we find out how many members are present in the file and then we
display each of them.

p3.java
import java.io.*;
public class p3
{
public static void main(String argv[])
{
try
{
char a[][];int i;
FileInputStream fos = new FileInputStream("c:\\jswdk-1.0.1\\webpages\\web-
inf\\servlets\\e.dat");
ObjectInputStream oos = new ObjectInputStream(fos);

http://www.vijaymukhi.com/documents/books/javajsp/chap6.html (4 of 9) [5/2/2008 10:59:32 PM]


Java-Servlets-JSP

a = (char [][] ) oos.readObject();


System.out.println(a.length);
for ( i=0; i<a.length;i++)
System.out.println(a[i]);
}
catch (Exception e){System.out.println("bye");e.getMessage();}
}
}

C:\jswdk-1.0.1\webpages\WEB-INF\servlets>javac p3.java

C:\jswdk-1.0.1\webpages\WEB-INF\servlets>java p3
2
abc
def

These small programs explain certain points required to understand the main program. So now
let's understand the servlet written by the JSP engine.
p4.java
import javax.servlet.jsp.*;
import com.sun.jsp.runtime.*;
import javax.servlet.http.*;
import java.io.*;
import com.sun.jsp.JspException;
public class p4 extends HttpJspBase {
public void _jspService(HttpServletRequest request,
HttpServletResponse response) throws IOException,JspException {
JspFactory _jspxFactory = null;
PageContext pageContext = null;
JspWriter out = null;
try
{
_jspxFactory = JspFactory.getDefaultFactory();
pageContext = _jspxFactory.getPageContext(this, request, response,"", true, 8192, true);
out = pageContext.getOut();
response.setContentType("text/html");
out.print("<b>Hie.... ");
out.print(out.getBufferSize());
} catch (Throwable t) {
if (out.getBufferSize() != 0)
out.clear();
throw new JspException("Unknown exception: ", t);
} finally {

http://www.vijaymukhi.com/documents/books/javajsp/chap6.html (5 of 9) [5/2/2008 10:59:32 PM]


Java-Servlets-JSP

out.flush();
_jspxFactory.releasePageContext(pageContext);
}
}
}

Output in browser
Hie.... 8192

Run the above as

http://127.0.0.1:8080/servlet/p4

and compare the above code with that generated by the jsp engine. They are identical.

The JSP engine calls the _jspService function in the servlet for any task that is to be
performed. Here, we first create an object _jspFactory that looks like JspFactory. JspFactory is
a class and to use it we add two imports statements.

It is important to know which import statements are required for the classes used in the
program. To avoid all these permutations and combinations, we have given all the imports that
we think are appropriate._jspFactory is initialized to the return value of getDefaultFactory.
JspFactory like System is a class. It has a static function getDefaultFactory, which returns an
object that looks like JspFactory.
JspFactory has a member named getPageContext that manages a page. For the moment, we
will leave the parameters aside. This function returns a pageContext which has a member
named getOut, used for writing purposes. getOut returns an object that looks like JspWriter,
which we store in out. Here, we have JspWriter instead of PrintWriter, but both are the same.
out.println is used to write text and out also has one more function named getBufferSize.
getBufferSize returns 8192 because that is the buffer size we have given in pageContent. If an
error is encountered at any point then catch will be called.

Exception is derived from Throwable. The base class is Throwable and all exceptions are
derived from it. We first check the buffer size and if it is not equal to 0, we clear the buffer.
Anything in the buffer will now be over-written. Then we throw the exception jspException
(we have imported com.sun.jsp.JspException.) After this has been done, out.flush will flush
the buffer and releasePageContext will release the pageContext.

Here, JspWriter is performing the job of PrintWriter. Effectively, they are the same; there is no
difference between them.

p5.java

http://www.vijaymukhi.com/documents/books/javajsp/chap6.html (6 of 9) [5/2/2008 10:59:32 PM]


Java-Servlets-JSP

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.Vector;
import com.sun.jsp.runtime.*;
import java.beans.*;
import com.sun.jsp.JspException;
public class p5 extends HttpJspBase {
static char[][] _jspx_html_data = null;
private static boolean _jspx_inited = false;
public final void _jspx_init() throws JspException {
ObjectInputStream oin = null;
int numStrings = 0;
try {
FileInputStream fin=new
FileInputStream("c:\\jswdk-1.0.1\\webpages\\web-inf\\servlets\\e.dat");
oin = new ObjectInputStream(fin);
_jspx_html_data = (char[][]) oin.readObject();
} catch (Exception ex) {
throw new JspException("Unable to open data file");
} finally {
if (oin != null)
try { oin.close(); } catch (IOException ignore) { }
}
}
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
JspFactory _jspxFactory = null;
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
String _value = null;
try {
if (_jspx_inited == false) {
_jspx_init();

http://www.vijaymukhi.com/documents/books/javajsp/chap6.html (7 of 9) [5/2/2008 10:59:32 PM]


Java-Servlets-JSP

_jspx_inited = true;
}
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,"", true, 8192, true);
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
out.print(_jspx_html_data[0]);
System.out.println(_jspx_html_data[0]);
} catch (Throwable t) {
if (out.getBufferSize() != 0)
out.clear();
throw new JspException("Unknown exception: ", t);
} finally {
out.flush();
_jspxFactory.releasePageContext(pageContext);
}
}
}

In this program, all that we have done is, within _jspService we have created 3 more objects,
session, application and config. Like the earlier program, getPageContext returns pageContext.
pageContext has a function which will create the respective object and then initialize session,
application and config.

Before all this is done, the if statement checks whether _jspx_inited, a static variable, holds a
true or false. The first time it holds false, so _jspx_init is called. This function has an object
that looks like ObjectInputStream. We now open a file named e.dat which we created a little
while ago. This entire file is read into _jspx_html_data, an array of chars, using
FileInputStream. In case an error is encountered, an exception is thrown and finally, the file is
closed. All this has been explained individually earlier, so we won't explain it again.

Once the function is called, _jspx_inited is made true so that the function is not called again.
In the main code, there is an out.print for _jspx_html_data[0]. This is the only new statement
added. This array had been initialized in _jspx_init with the contents of e.dat. So when you run
this servlet, it will show you abc in the browser because jspx_html_data [0] is the first array
and jspx_html_data [1] is the second array.

http://www.vijaymukhi.com/documents/books/javajsp/chap6.html (8 of 9) [5/2/2008 10:59:32 PM]


Java-Servlets-JSP

Contents | Foreword | About the Authors | Introduction |


Appendix |Chapter 1 |Chapter 2 |Chapter 3 |Chapter 4 |Chapter 5 |Chapter 6 |
Chapter 7 |Chapter 8 |Chapter 9 |Chapter 10 |Chapter 11

http://www.vijaymukhi.com/documents/books/javajsp/chap6.html (9 of 9) [5/2/2008 10:59:32 PM]


Java-Servlets-JSP

7. Java Beans

Beans in the Market

If you go to any marketplace and enquire about the types of beans available, you are bound to
get a variety of answers. There are french beans, large beans, small beans etc.,. and then some
intelligent friend of your's might say that Java Beans are available as well. We'll leave all the
other beans to the vegetable vendors and cooks to figure out and talk of Java Beans in this
chapter.

Before we try and figure out what a Java Bean is, let's explore the world of COMPONENTS
and CONTAINERS. Let's try and get the basics clear with a true to life example.

Suppose we had two programmers and a client. Programmer A has come out with the latest E-
MAIL program with a great user interface. The client hires A and is ready to buy his program,
but fortunately or unfortunately the client is weak in English, and sends programmer A a letter
saying

" I will take your prouduct only if you can inculude spelcheck in it."
Signed : client

Seeing the pitiable state of his client's English, A takes it to be his moral responsibility to
include spellcheck in his program. He neither has the time nor the patience to sit down and
write a speller-checker program. So, he goes to the market, buys a speller-checker from B and
includes it in his E-MAIL program. Now B's program is a component, which is added to A's
program(container). Not every programmer who wrote the speller-checker could get the sign
the deal with A(container). Only that program, which complied with, or followed all the set of
rules put forth by A got it.

We should drive home the fact that a COMPONENT must follow a certain set of rules given
by the CONTAINER. Sun Microsystems developed a set of rules to enable java programs to
be used as components, which they named 'Java Beans'. They also developed a reference
container for these Java Beans to show the world the rules to be followed while using them.

Create a subdirectory to work in. We have named our directory jb.

Bare Minimum Requirements for learning Java Beans


1. Windows Operating System (95/98/NT)
2. JDK 1.1.x

http://www.vijaymukhi.com/documents/books/javajsp/chap7.html (1 of 7) [5/2/2008 10:59:47 PM]


Java-Servlets-JSP

c:\jb\>edit zzz.java

zzz.java
import java.applet.* ;
import java.awt .* ;
public class zzz extends Applet
{
public void paint(Graphics g)
{
g.drawString("FrenchBean",10,10);
}
}

This Program ends here.!!!


We had this printed, just in case you were trying to turn pages, unable to believe that a Java
Bean (an eight lettered word ), can be such a simple program. Then, what was all the hype
about the technology we mentioned earlier ?

There is one thing every person must understand about any new technology. It always makes
life easier by doing all the complex jobs for us. So to succeed in the market it has to be very
simple to use.

Enough philosophy for now, let's get down to work . Java Bean is just another java program
which can be used as a component in a container.

An Ode to the Jars:

Bungee jumping, skiing, scuba diving and surfing the net are the hobbies of millions, the
world around, but did you ever try to think why surfing the net comes last on the list of
hobbies ? It's because of the amount of time you have to wait before things come to you.

When a person goes to a site on the Net and asks for some information, he is connected to the
site where this information is available. The required data is in the form of a html document
i.e. he first connects to the server, and gets the html document. Before being shown, the
application (let's suppose it is some animation software), might ask for some .gif files, or some
.class files etc. So, for retrieving each file, a special request has to be sent to the the server and
the bytes have to be transferred to the client. Moreover, there is a lot of congestion on the net
since the servers may be busy. Thus, the time taken for the transfer of the required bytes
depends on the quality of the line, congestion on the server (too many clients accessing the
same server) etc. Statistically speaking, even if we were to send you a message saying "Hello",
40 additional bytes of data (called as a TCP/IP header) would have to be transferred along with
this message. So the gist is that each time there is a transfer of actual meaningful data from or

http://www.vijaymukhi.com/documents/books/javajsp/chap7.html (2 of 7) [5/2/2008 10:59:47 PM]


Java-Servlets-JSP

to the client, there is a lot of over head involved.

Suppose your friend had given you a mystery novel. You start reading it and are interested. By
the time you reached the climax and the mystery situation, you find out that the second half of
the book is missing. Anxious to read the later chapters, you visit your friend, but in vain, as
he's left for some other place and wouldn't be returning until later the next day. As there is no
other alternative, you wait. Had you friend been thoughtful, he would have given you the other
part too!

Sun Microsystems has been thoughtful enough and they introduced the concept of JARS. All
the .class and other files relating to a particular application are compressed and put in the jar.
So when the client asks for the html program containing the bean, the server is kind enough to
send you the whole jar. Now you have all the information at one go. The client does not have
to connect to the server again and again for the files relating to the particular program. In this
way, both the server and the client save time. This has been done to make the life of net surfers
easier. Mind you, the previous program can be called as a Java Bean only when put in a jar
file.

To compile zzz.java , give the following command

c:\jb>javac zzz.java

In order to create the manifest file, create a file with .mf extension. Here we give the filename
as zzz.mf

c:\jb>edit zzz.mf // The manifest file

zzz.mf
Manifest-Version: 1.0
Name: zzz.class
Java-Bean: True

The jar program creates a .jar file. It is a utility provided by Sun which puts all the required
files of a particular application into the jar file.

c:\jb>jar cfm zzz.jar zzz.mf zzz.class

c:\jb>dir /w
Volume in drive C has no label.
Volume Serial Number is 1AD6-0B09

http://www.vijaymukhi.com/documents/books/javajsp/chap7.html (3 of 7) [5/2/2008 10:59:47 PM]


Java-Servlets-JSP

Directory of C:\jb

[.] [..] zzz.java zzz.class zzz.mf zzz.jar


4 File(s) 1,320 bytes
2 Dir(s) 545,153,024 bytes free

The cfm options to jar file mean the following.

-c create new archive


-f specify archive file name
-m include manifest information from specified manifest file

The new archive to be created is given first, then the manifest file which contains the bean
information and lastly the .class files which belong to the application. Note that only one class
can be called a bean. The other class files that you specify are more like supportive files that
contain code.

c:\jb>copy zzz.jar c:\progra~1\bdk1.1\jars

Sun Microsystem has a bean development kit which can be downloaded from their site. We
have installed bdk1.1 . Here they have created a reference container for Java Beans, called the
beanbox. The container looks at the jars subdirectory for all the jar files which have to be
implemented in the Bean Development Kit (BDK). Hence we copy our .jar file into this
subdirectory

Now to see our bean work, we change to the bdk subdirectory and run a batch file viz. run.bat

c:\jb>cd c:\progra~1\bdk1.1\beanbox
c:\Program Files\BDK1.1\beanbox>run

Voila! Our Java Bean - zzz is right there at the bottom of the Beanbox toolbar. Click and drag
zzz into the beanbox container and you'll see a "Frenchbean" on the screen. Now, to bring the
explicit button to the beanbox, we first click on the button and position the mouse on the
container and then we click. Now that we have both a button and our Java Bean (zzz)in the
beanbox container, let's learn how to connect both of them.
First, we click on the freshly brought button and then look into the various options in the EDIT
menuitem. Now, logically speaking, we want to see what the buttonpush can do for us, hence
we checkout the action performed in the buttonpush option of the Events submenuitem.

On clicking the action performed for a buttonpush, we find a jazzy red line with one end fixed
at the button and the other end, free to move with the mouse. Now position the mouse on zzz
and click on it. By doing this, we are actually connecting the button with our zzz Java Bean.

http://www.vijaymukhi.com/documents/books/javajsp/chap7.html (4 of 7) [5/2/2008 10:59:47 PM]


Java-Servlets-JSP

As soon as we click on the zzz Java Bean, an Event Target Dialog (a dialog box with this
heading) pops up. This dialog box has a big list of functions which can be assigned to our
pushbutton. Of the many functions in the dialog box only one seems to be both familiar and
mysterious i.e. hide. So we select it and click on OK.

Now let's emulate the disappearing act of Houdini. Press the pushbutton with a mouse click
and see the "Frenchbean" disappear i.e. the Java Bean (zzz) in the beanbox container
disappears.

The Fundamentals of a Property :

Now, it's time for some fun. To begin with, we first select the juggler icon from the toolbox
(beanbox frame) and bring it into our Container. Can we interact with the juggler? This is the
first question we should ask. The answer is, YES WE CAN !!

There is a small window named the property sheet next to the beanbox container. This window
has a property named animationrate which can be changed. By changing the value of the
property, you will see the juggler juggling either slower or faster than before.

What is a property?

It is a variable that can be changed by the user. Now, It is very easy to create a variable and
initialize it in the program itself. You can then have conditions and code that are executed
when the variable is greater than some value or less than a certain value. When you change the
value in the property sheet, a variable has to be created that accepts new values at run time and
shows the effect immediately. To incorporate this feature, every variable has to have two
functions that have to be preceded by either a get or a set. Such variables are called properties.

Only two things can be done to a variable. You can either 'get' it or 'set' it.

example :
When i is initialised to 10 by giving
i = 10
we are setting the variable i to 10 .

and when i is used on the right side of the equalto i.e.


something = i + 4, we are getting (returning) the value stored in variable i.

The function which has 'set' has to be given a value whereas the function which has 'get' has to
return some value.

zzz.java

http://www.vijaymukhi.com/documents/books/javajsp/chap7.html (5 of 7) [5/2/2008 10:59:47 PM]


Java-Servlets-JSP

import java.applet.* ;
import java.awt.* ;
public class zzz extends Applet
{
int aa =10 ;
public void paint (Graphics g)
{
g.drawString ("Great" + aa, 1, 1) ;
}
public void setxx(int i)
{
aa = i ;
}
public int getxx ( )
{
return aa ;
}
}

Create a batch file with the following commands and then execute it

a.bat
javac zzz.java
jar cfm zzz.jar zzz.mf zzz.class
cd c:\progra~1\bdk1.1\beanbox
run

Now when you bring in the bean into the container, you will see xx with the value 10 as a
property in the PropertySheet. You can change this value and the resultant value will then be
displayed in the Container.

When xx =10, we see " Great 10 " in the beanbox and if we change it to xx = 100, we see "
Great 100" in the beanbox .

Simulating our own function

Previously, to make something disappear, we clicked on action performed for a push button
and chose a target method ( assigned to the push button ) i.e . hide . We can now have our own
function in the Event Target Dialog. For this we make modifications to the previous program.

Remove the "getxx" and the "setxx" functions from the previous program, and put the

http://www.vijaymukhi.com/documents/books/javajsp/chap7.html (6 of 7) [5/2/2008 10:59:47 PM]


Java-Servlets-JSP

following function in the code

public void abc( )


{
aa = 1000;
repaint ();
}

Run the file a.bat. Bring the bean in the container and then the explicit button. Proceed to the
Event Target Dialog by clicking on action performed of a buttonpush as before. The function
abc() that we included in our code is up on the list. Select it and then click on OK. Now click
on the button and see the value change on the screen.

"Great 10 " now becomes " Great 1000"

We've chosen names like abc so that we can easily find them as the first entry on the list.

Contents | Foreword | About the Authors | Introduction |


Appendix |Chapter 1 |Chapter 2 |Chapter 3 |Chapter 4 |Chapter 5 |Chapter 6 |
Chapter 7 |Chapter 8 |Chapter 9 |Chapter 10 |Chapter 11

http://www.vijaymukhi.com/documents/books/javajsp/chap7.html (7 of 7) [5/2/2008 10:59:47 PM]


Java-Servlets-JSP

8. Java Beans and Java Server Pages

Introduction

The word Java Beans conjures up images of Coffee Beans or even Beanbags, but the Java
Beans that we are talking about are related to Java.

Java beans play a large role in JSP documents. A Java Bean is a Java component that works on
any Java Virtual Machine.

Packages

If you had a class called Applet and if another user also called his class Applet, then whose
Applet gets called, yours or his? To prevent a name clash, sun invented the concept of a
package. They said that all classes created by Sun would start with java. Unfortunately this
does nothing for a grouping. We would like all classes that deal with GUI issues to be grouped
together. Thus we have one more level i.e. all GUI classes are part of java.awt and applet
classes are a part of java.applet. Hence the full name of the class Applet is java.applet.Applet
and java.applet is the package name which can be part of the import statement.

Beans

Before we get down to telling you what beans are, we would like you to do the following:

We want you to change to c:\jswdk-1.0.1\examples\web-inf\jsp and there you will find a


subdirectory called beans. Within this directory, create a subdirectory called yyy. Now create a
file called zzz.java and enter the code given below.

C:\jswdk-1.0.1\examples\web-inf\jsp\beans\yyy>edit zzz.java

zzz.java
package yyy;
public class zzz {
private String username = "mukhi";
public zzz()
{
System.out.println("Constructor");
}

public void setusername(String name) {

http://www.vijaymukhi.com/documents/books/javajsp/chap8.html (1 of 9) [5/2/2008 10:59:56 PM]


Java-Servlets-JSP

username = name;
System.out.println("setusername " + username);
}
public String getusername() {
System.out.println("getusername" + username);
return username;
}
}

C:\jswdk-1.0.1\examples\web-inf\jsp\beans\yyy>javac zzz.java

Since the first line is package yyy, in the beans directory you must create a subdirectory
named yyy. The reason being, for the compiler to find packages, all the files that hold the
classes contained in a package must reside in a directory bearing the package name.

A Java Bean is a normal program. As we've seen in the previous chapter,it is a simple Java
program; an applet can also be called a Java Bean. The only difference is that in a Bean some
functions start with either a set or get, which is why we have setusername and getusername.
Whenever a function begins with set or get, it relates to a property. That's what a Java Bean is
made up of.
The property here is username and not setusername or getusername. A variable or a property
can either be used on the left or the right of the = sign. If it is on the left, then it gets a value,
hence it takes one string as a parameter. Once you receive the value, what you do with it is up
to you. In our program we store it in a public variable. Get is used with functions. When it is
on the right hand side of the = sign, it returns a value and hence we are returning a string.

C:\jswdk-1.0.1\examples\jsp>edit b1.jsp

b1.jsp
<jsp:useBean id="pp" scope="page" class="yyy.zzz" />
<html>
<body>
</body>
</html>

b1.jsp has an action called useBean followed by id=pp. pp is the id, we will use it to refer to
our bean in the future. The actual name can be anything and there is nothing special about pp
and class=yyy.zzz is because our bean zzz is in a package yyy. It is assumed that the bean will
be in the sub-directory C:\jswdk-1.0.1\examples\web-inf\jsp\beans\ and the package yyy starts
from this beans subdirectory onwards.

Run the jsp file in the browser as before.

http://www.vijaymukhi.com/documents/books/javajsp/chap8.html (2 of 9) [5/2/2008 10:59:56 PM]


Java-Servlets-JSP

You get no errors. Check the dos screen of the Java Web Server where it will print
'Constructor' and then let's look at the generated code.
-----------------
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\b1.jsp";from=(0,0);to=(0,52)]
// end

// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\b1.jsp";from=(0,0);to=(0,52)]
yyy.zzz pp = null;
boolean _jspx_specialpp = false;
synchronized (pageContext) {
pp= (yyy.zzz)pageContext.getAttribute("pp",PageContext.PAGE_SCOPE);
if ( pp == null ) {
_jspx_specialpp = true;
try {
pp = (yyy.zzz) Beans.instantiate(getClassLoader(), "yyy.zzz");
} catch (Exception exc) {
throw new ServletException (" Cannot create bean of class "+"yyy.zzz");
}
pageContext.setAttribute("pp", pp, PageContext.PAGE_SCOPE);
}
}
if(_jspx_specialpp == true) {
// end
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\b1.jsp";from=(0,0);to=(0,52)]
}
// end
out.print(_jspx_html_data[1]);
----------------------

pp looks like yyy.zzz where yyy is the name of the package and zzz the name of the class. This
is because in the JSP file the id was given as pp. pageContext has members like getAttribute,
setAttribute and so on. pp is initialized using the getAttribute function. The second parameter
is PageContext.PAGE_SCOPE, since that is what we had given in the JSP file. The next thing
that you do is check if pp has a value. If it is Null, then Beans.instantiate will instantiate or
create the bean. That means if the Bean is already loaded then you get a handle to it, if not then
it is created. Instantiate is a static member in the Beans class. One of the parameters is the
name of the Bean. We have given a very short explanation here; let's look at the next example
to understand a lot more on Beans with JSP.
zzz.java
package yyy;
public class zzz {
private String username = "mukhi";

http://www.vijaymukhi.com/documents/books/javajsp/chap8.html (3 of 9) [5/2/2008 10:59:56 PM]


Java-Servlets-JSP

public zzz()
{
System.out.println("Constructor");
}
public void setusername(String name) {
username = name;
System.out.println("setusername " + username);
}
public String getusername() {
System.out.println("getusername" + username);
return username;
}
}

b2.jsp
<jsp:useBean id="pp" scope="page" class="yyy.zzz" />
<html>
<body>
hello , <jsp:getProperty name="pp" property="username" />
</body>
<html>

Output in browser
hello , mukhi

In the next example, we have a new action named getProperty with a name and a property. In
our JSP file the property is username. This line will be replaced by the word mukhi. Look in
the dos window and you'll see that the function getusername is called. This function returns
the value of the variable username which is initialized to mukhi. Thus the tag <jsp:getProperty
name="pp" property="username" /> is replaced by the string mukhi.

--------------
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\b2.jsp";from=(3,8);to=(3,57)]
out.print(JspRuntimeLibrary.toString(pp.getusername()));
// end
----------------

getproperty in the java generated code will become pp.getusername. setproperty is a function
which is related to getproperty and is used in the next example.
b3.jsp
<%@ page import="yyy.zzz" %>
<jsp:useBean id="pp" scope="page" class="yyy.zzz" />

http://www.vijaymukhi.com/documents/books/javajsp/chap8.html (4 of 9) [5/2/2008 10:59:56 PM]


Java-Servlets-JSP

<html>
<body>
hello, <jsp:getProperty name="pp" property="username" />
<jsp:setProperty name="pp" property="username" value="no" />
<p> hi, <jsp:getProperty name="pp" property="username" />
</body>
</html>

Output in browser
hello, mukhi
hi, no

----------
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\b3.jsp";from=(5,0);to=(5,60)]
pp.setusername("no");
// end
out.print(_jspx_html_data[4]);
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\b3.jsp";from=(6,8);to=(6,57)]
out.print(JspRuntimeLibrary.toString(pp.getusername()));
// end
-----------
With setusername, you give the name of the property and then the value. The value given here
is 'no'. So you see mukhi and then no. The code is exactly the same. setusername is also called
with the parameter having a value no and we initialize username with it.

Scopes

Let's talk about scopes in greater detail.

There are four scopes, request, page, session and application. Each time you give the scope as
session or request, the PageContext variable changes.

b4.jsp
<jsp:useBean id="pp" scope="session" class="yyy.zzz" />

-------------
java file
synchronized (session) {
pp= (yyy.zzz)
pageContext.getAttribute("pp",PageContext.SESSION_SCOPE);
if ( pp == null ) {
_jspx_specialpp = true;

http://www.vijaymukhi.com/documents/books/javajsp/chap8.html (5 of 9) [5/2/2008 10:59:56 PM]


Java-Servlets-JSP

try {
pp = (yyy.zzz) Beans.instantiate(getClassLoader(), "yyy.zzz");
} catch (Exception exc) {
throw new ServletException (" Cannot create bean of class "+"yyy.zzz");
}
pageContext.setAttribute("pp", pp, PageContext.SESSION_SCOPE);
}
------------------

With scope as session, pageContext.getAttribute and setAttribute will have


PageContext.SESSION_SCOPE.
b5.jsp
<jsp:useBean id="pp" scope="request" class="yyy.zzz" />

-------------
java file
synchronized (request) {
pp= (yyy.zzz) pageContext.getAttribute("pp",PageContext.REQUEST_SCOPE);
if ( pp == null ) {
_jspx_specialpp = true;
try {
pp = (yyy.zzz) Beans.instantiate(getClassLoader(), "yyy.zzz");
} catch (Exception exc) {
throw new ServletException (" Cannot create bean of class "+"yyy.zzz");
}
pageContext.setAttribute("pp", pp, PageContext.REQUEST_SCOPE);
}
-----------

With the scope as request, pageContext.getAttribute and setAttribute will have


PageContext.REQUEST_SCOPE.

Now we will consider two programs at a time b6.jsp and b7.jsp.

b6.jsp
<%@ page import="yyy.zzz" %>
<jsp:useBean id="pp" scope="request" class="yyy.zzz" />
<html>
<body>
b6 , ello, <jsp:getProperty name="pp" property="username" />
<jsp:setProperty name="pp" property="username" value="no" />
<p> llo, <jsp:getProperty name="pp" property="username" />

http://www.vijaymukhi.com/documents/books/javajsp/chap8.html (6 of 9) [5/2/2008 10:59:56 PM]


Java-Servlets-JSP

<a href="b7.jsp"> click here </a>


</body>
</html>

b7.jsp
<%@ page import="yyy.zzz" %>
<jsp:useBean id="pp" scope="request" class="yyy.zzz" />
<html>
<body>
b7 , ello, <jsp:getProperty name="pp" property="username" />
<jsp:setProperty name="pp" property="username" value="no" />
<p> llo, <jsp:getProperty name="pp" property="username" />
</body>
</html>

Here, we have two JSP files, b6 and b7. We are using the same Bean in both of them and the
scope is request. The first file contains <a href="b7.jsp"> which will take us to the second
page i.e. b7.jsp.

When we click on the first page, yyy.zzz gets created, and the constructor is called. When we
click on href, we move to b7. Since the scope in both is request, the constructor is called once
more. The values are reinitialized and the variables are created from scratch.

In this case, the page behaves like request. The bean is created each time, which means that it
cannot remember its earlier values.

Let's see an example where we give the scope as session.


b8.jsp

<%@ page import="yyy.zzz" %>


<jsp:useBean id="pp" scope="session" class="yyy.zzz" />
<html>
<body>
b8 , <jsp:getProperty name="pp" property="username" />
<jsp:setProperty name="pp" property="username" value="no" />
<p> llo, <jsp:getProperty name="pp" property="username" />
<a href="b9.jsp"> click here </a>
</body>
</html>

b9.jsp
<%@ page import="yyy.zzz" %>

http://www.vijaymukhi.com/documents/books/javajsp/chap8.html (7 of 9) [5/2/2008 10:59:56 PM]


Java-Servlets-JSP

<jsp:useBean id="pp" scope="session" class="yyy.zzz" />


<html>
<body>
b9 , ello, <jsp:getProperty name="pp" property="username" />
<jsp:setProperty name="pp" property="username" value="no" />
<p> llo, <jsp:getProperty name="pp" property="username" />
</body>
</html>

Here, the constructor is called only once and that happens when the Bean is loaded for the first
time. When you click on the link, the constructor is not called. The Bean is not instantiated and
the variables are not created again. They are persistent for that entire session. If you start a
new browser, then a new session is created.

When you give the scope as application, then the Bean and the variables retain their values till
the server is shut down. Any client coming from any other site will see the values as they are
on the server. It's like a page counter that keeps increasing on every visit to the page.

Try it out with another copy of IE to understand it better.

pageContext.getAttribute decides, depending upon the scope, whether the Bean should be
instantiated or not. You decide on the scope depending upon the functionality of the JSP code.
If the page scope is application, then everybody will be able to use it forever, but in case of
session, it depends upon how you want to share the Bean.

Conclusion

In this chapter we have shown you how Java Server Pages receive from and send data to Java
Beans. At the same time we also showed you how to create your own package. You are now
also aware that setting the scope to the four different options will generate different results.

http://www.vijaymukhi.com/documents/books/javajsp/chap8.html (8 of 9) [5/2/2008 10:59:56 PM]


Java-Servlets-JSP

Contents | Foreword | About the Authors | Introduction |


Appendix |Chapter 1 |Chapter 2 |Chapter 3 |Chapter 4 |Chapter 5 |Chapter 6 |
Chapter 7 |Chapter 8 |Chapter 9 |Chapter 10 |Chapter 11

http://www.vijaymukhi.com/documents/books/javajsp/chap8.html (9 of 9) [5/2/2008 10:59:56 PM]


Java-Servlets-JSP

9. Cookies and a Shopping Cart

Introduction

Cookies have a number of uses for Web application developers and one of them is to track
user sessions. Cookies originate on the server, where they are sent as instructions in the header
of the HTTP response. In this chapter, we will see how Cookies are put to use in conjunction
with JSP. You will also be shown how a shopping cart can be created.

Remember that Java Server Pages are first turned into a servlet. In case there are any errors in
your JSP script then they too are seen in the servlet. You may not see any error messages at
this point but when you try to run the servlet and display the output in a browser, you will see
the errors. You may get two types of errors.

c1.jsp
<html>
<body>
<%! int i=62745435354354353454354353454354353453454353434543543534543; %>
<% out.println(i); %>
</body>
</html>

Consider this example where the variable i has been initialized to a very large number. The
question here is, will the JSP engine give an error while generating a servlet or will it show an
error while displaying the output?

---------------
public class jsp_0005cc_00031_0002ejspc1_jsp_1 extends HttpJspBase {
static char[][] _jspx_html_data = null;
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\c1.jsp";from=(2,3);to=(2,71)]
int i=62745435354354353454354353454354353453454353434543543534543;
// end
---------------

The browser shows you just a simple error whereas the web server DOS window tells you in
detail what the error is.

Whenever you have a page directive 'buffer=kb', it should be a number because kb will be
passed as a parameter, so when the servlet is compiled it gives an error.

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (1 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

c2.jsp
<%@ page buffer="kb" %>

This shows the same error as seen earlier. A bit of showing off now. Here we have a class
called JSPTest.

c3.jsp
<%! public class JSPTest {
public String getName()
{ return "JSPTest"; }
class Inner extends JSPTest {
public String getName()
{ return "Inner";
}
}
}
%>
<% JSPTest jspTest = new JSPTest();
JSPTest.Inner inn = jspTest.new Inner();
out.println(" Base name: " + jspTest.getName());
out.println(" Inner name: " + inn.getName());
%>
-----------------
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\c3.jsp";from=(0,3);to=(10,0)]
public class JSPTest {
public String getName() {
return "JSPTest";
}
class Inner extends JSPTest {
public String getName() {
return "Inner";
}
}
}
// end
out.print(_jspx_html_data[1]);
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\c3.jsp";from=(11,2);to=(15,0)]
JSPTest jt = new JSPTest();
JSPTest.Inner inn = jt.new Inner();
out.println(" Base name: " + jt.getName());
out.println(" Inner name: " + inn.getName());
// end
--------------

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (2 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

Output:
Base name: JSPTest Inner name: Inner

C3.jsp has a public class named JSPTest. This class has a function named getName that
returns a string. The string here is JSPTest. This class contains another class, which extends
the same class. Class Inner is within JSPTest and it extends JSPTest. This is all legal. These
types of classes are called inner classes. If Inner is an inner class then JSPTest should be an
outer class! This is in one block of the script. In the next block, 'jt' is a variable that looks like
JSPTest. 'inn' is another variable that looks like JSPTest.Inner. You can refer to this class
because inner is a class in JSPTest. In C++, they are called Nested Classes. jspTest.new inner()
is used to initialize inn.

It is of significance to note that instead of 'new' we have used 'jt.new'. new is now part of jt.
new ( ) is used to create the object and thus call the constructor. Therefore every time you have
a class within a class, the outer class has its own new to create the inner classes. The function
in the base class 'getName' returns JSPTest whereas the one in the inner class returns Inner.
This has nothing to do with JSP. All Java code that you write in a Java program can be written
in JSP too.

In one of the previous chapters, we tried the bean example where we clicked on a link and
went to another page. This can be done in another way by using jsp:forward. This will also
take us to another page and the same rules apply.

c4.jsp
<html>
<jsp:plugin type="applet" code="zzz.class" width="160" height="150"
codebase="/examples/jsp" jreversion="1.2" >
<jsp:fallback>
Hell
</jsp:fallback>
</jsp:plugin>
<p>
Bye
</body>
</html>

The code of zzz.java is in c:\jswdk-1.0.1\examples\jsp

zzz.java
import java.awt.*;
import java.applet.*;

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (3 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

public class zzz extends Applet


{
int x,y;
public void init()
{
x = 10 ; y = 20;
}
public void paint ( Graphics g)
{
g.drawString("Hi ", x , y);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
x = x1 ; y = y1;
return true;
}
}

>javac zzz.java

You can put any object you want along with jsp:plugin. A JSP page can have any plugin. Here
we are giving type=applet, code=zzz.class along with the width and the height. In order to
refresh your memory, the attribute width and height are given because the applet tag requires
us to do so. This has already been explained in the first chapter. The jreversion is the version
number of the Java runtime engine and the codebase attribute is the location from where the
class file is to be picked up. In our case '/' is the JavaWebserver root directory and from there
we are pointing to the examples/jsp subdirectory where the class file resides.

Jsp:fallback will be looked at only when the object or the plugin statement gives an error. This
is a lot like the 'try-catch' in Java. There are many types and applet is just one of them. A list of
all the types can be found in the documentation. Just another way to add more content to the
JSP page.
--------------------
// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\c4.jsp";from=(1,0);to=(6,13)]
/*Code generated for plugin*/
out.println ("<OBJECT classid=\"clsid:8AD9C840-044E-11D1-B3E9-00805F499D93\"
width=\"160\" height=\"150\" codebase=\"http://java.sun.com/products/plugin/1.2.2/jinstall-
1_2_2-win.cab#Version=1,2,2,0\">");
out.println ("<PARAM name=\"java_code\" value=\"zzz.class\">");
out.println ("<PARAM name=\"java_codebase\" value=\"/examples/jsp\">");
out.println ("<PARAM name=\"type\" value=\"application/x-java-applet;version=1.2\">");
out.println ("<COMMENT>");
out.print ("<EMBED type=\"application/x-java-applet;version=1.2\" width=\"160\"

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (4 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

height=\"150\" pluginspage=\"http://java.sun.com/products/plugin/\" java_code=\"zzz.class\"


java_codebase=\"/examples/jsp\" >");
out.println ("<NOEMBED>");
out.println ("</COMMENT>");
out.println ("Hell \r\n");
out.println ("</NOEMBED></EMBED>");
out.println ("</OBJECT>");
// end
------------------

The html file received by the browser is as follows

<html>
<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" width="160"
height="150" codebase="http://java.sun.com/products/plugin/1.2.2/jinstall-1_2_2-
win.cab#Version=1,2,2,0">
<PARAM name="java_code" value="zzz.class">
<PARAM name="java_codebase" value="/examples/jsp">
<PARAM name="type" value="application/x-java-applet;version=1.2">
<COMMENT>
<EMBED type="application/x-java-applet;version=1.2" width="160" height="150"
pluginspage="http://java.sun.com/products/plugin/" java_code="zzz.class"
java_codebase="/examples/jsp" ><NOEMBED>
</COMMENT>
Hell
</NOEMBED></EMBED>
</OBJECT>
<p>
Bye
</body>
</html>

Click anywhere and you will find the word 'hell' following the click. All that the servlet does
here is sends across the html file. Since this file has the applet tag, the browser asks for the
applet. So the JSP engine sends the tags across with the attributes. The browser receives it and
works as per the tags in the file.

c5.jsp
<html><jsp:forward page="e1.jsp" />
</html>

--------------------

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (5 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

// begin [file="C:\\jswdk-1.0.1\\examples\\jsp\\c5.jsp";from=(1,0);to=(1,29)]
if (true) {
out.clear();
pageContext.forward("e1.jsp");
return;
}
// end
------------------

You will directly come to another page, in this case you will come to e1.jsp.
Let's see how we can call a servlet from JSP and then have the servlet load another JSP file.
c.jsp
<html>
<jsp:forward page="/servlet/yyy" />
</html>
c.jsp is located in c:\jswdk-1.0.1\examples\jsp subdirectory. It forwards to another page that
the servlet yyy generates.

yyy.java is located in c:\jswdk-1.0.1\webpages\web-inf\servlets. To load this servlet the url


should be given as http://127.0.0.1:8080/examples/jsp/c.jsp.

yyy.java
import javax.servlet.*;
import javax.servlet.http.*;
public class yyy extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response)
{
try {
request.setAttribute ("servletName", "vijay");
ServletConfig a = getServletConfig();
ServletContext b = a.getServletContext();
RequestDispatcher c = b.getRequestDispatcher("/jsp/c6.jsp");
c.forward(request, response);
} catch (Exception ex) { ex.printStackTrace (); }
}
}

c6.jsp will be in the same directory as c.jsp i.e. c:\jswdk-1.0.1\examples\jsp.

c6.jsp
<html>
invoked by <% out.print (request.getAttribute("servletName").toString()); %>

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (6 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

</html>

c.jsp will load the servlet yyy, where the function doGet is called. request.setAttribute will set
the attribute named servletName to vijay. This is how we can create a variable within the
servlet. Now anyone who has access to the servlet can access this variable vijay. This implies
that any servlet can access the attribute 'servletName'. Instead of calling it 'servletName' you
could have called it aaa.

'a' is a servletconfig which is initialized to the return value of getServletConfig. It is a function


in HttpServlet. This has one member named ServletContext. The context in which the servlet
is acting is the ServletContext and this function's return value is stored in b. When we call
getRequestDispatcher from ServletContext, it will return a requestdispatcher and the
parameter passed to this function is the page we wish to view. Here, we give /jsp/c6.jsp, which
will load c6.jsp from the current directory-jsp and then finally, we say forward with our
request and response. Now c6.jsp will be called. This JSP file will be compiled on the fly i.e. it
will be converted into a servlet. In c6.jsp, we have request.getAttribute for servletName and
hence it will give us vijay. This is how servlets communicate internally.

In short, we have moved from one JSP page 'c.jsp', which became a servlet, to another servlet
yyy which called a third servlet of c6.jsp and finally you see vijay displayed on the screen.
Note that the first and the third servlet were originally JSP based

Let's consider a simple bean.

c7.jsp
<jsp:useBean id="cb" scope="session" class="yyy.zzz" />
<jsp:setProperty name="cb" property="*" />
hi

c7.jsp starts with jsp:usebean and the id is given as cb. The scope here is not important. The
name of the class is yyy.zzz.

Go to the web-inf directory and within the jsp\beans subdirectory create a new subdirectory
yyy. Create a Java file called zzz.java here. It must contain the following code:

c:\jswdk-1.0.1\examples\Web-inf\jsp\beans\yyy>edit zzz.java

zzz.java
package yyy;
public class zzz
{
public void setxx(String a)

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (7 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

{
System.out.println("setxx " + a);
}
public void setyy(String a)
{
System.out.println("setyy" + a);
}
public String getxx()
{
System.out.println("getxx");
return "";
}
public String getyy()
{
System.out.println("getyy");
return "";
}
}

run it in the browser as

http://127.0.0.1:8080/examples/jsp/c7.jsp?xx=hi&yy=bye

The property for the bean cb is set by giving property='*'. This refers to the properties that are
given in the form of name=value data in the url. Since the address given in the address bar has
a '?' followed by xx=aaa&yy=bbb, the properties to be set will be that of xx and yy. So the JSP
engine will call setxx and setyy with aaa and bbb in the Java Bean. If you had just given
xx=aaa then only setxx would be called. If you are a good Bean designer, you will first find
out the number of parameters you will be accepting and then accordingly create the properties
in the Bean. So if you are accepting 7 parameters, you must create 7 properties with the same
name in your Bean. Every property in the Bean will have get and set preceding the property
name. '*' in the property will initialize all the properties in the Bean. You don't have to set all
the properties yourself and this example proves that.

The next program has been taken directly from the examples provided by Sun Microsystems.
Here, we are considering an HTML file 'aa.html' within which there is code for creating a
listbox. This file is to be placed in the examples/jsp subdirectory of jswdk-1.0.1.

aa.html
<html>
<form method=POST action="http://127.0.0.1:8080/examples/jsp/c8.jsp">
Add Item:

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (8 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

<SELECT NAME="item">
<OPTION>Beavis & Butt-head Video collection
<OPTION>X-files movie
<OPTION>Twin peaks tapes
</SELECT>
<INPUT TYPE=submit name="submit" value="add">
<INPUT TYPE=submit name="submit" value="remove">
</form>
</html>

We are create one listbox with three options. The first one is shown by default but you are
allowed to choose any of them. When you click on the submit button the option selected will
be given to the name 'item'. You will notice that here we have two submit buttons here, with
the values add and remove respectively. Irrespective of the button clicked, the file that will be
called is c8.jsp, which for the moment is on the same hard disk that we are operating from.
The method given is post, items will be equal to the option selected and submit will be equal
to either add or remove, these will go as parameters to the JSP file.
Under normal circumstances submit isn't added as part of the parameter list, this happens only
when there are two submits in the form. Once you click on submit, c8.jsp will be called. c8.jsp
is stored in c:\jswdk-1.0.1\examples\jsp.

c8.jsp
<jsp:useBean id="cart" scope="session" class="ppp.qqq" />
<jsp:setProperty name="cart" property="*" />
<%
cart.processRequest(request);
%>
<FONT size = 5 COLOR="#CC0000">
<br> You have the following items in your cart:
<ol>
<%
String[] items = cart.getItems();
for (int i=0; i<items.length; i++) {
%>
<li> <%= items[i] %>
<%
}
%>
</ol>
</FONT>
<hr>
<%@ include file ="aa.html" %>
</html>

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (9 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

qqq.java
package ppp;
import javax.servlet.http.*;
import java.util.Vector;
import java.util.Enumeration;
public class qqq {
Vector v = new Vector();
String submit = null;
String item = null;
private void addItem(String name) {
v.addElement(name);
}
private void removeItem(String name) {
v.removeElement(name);
}
public void setItem(String name) {
item = name;
}
public void setSubmit(String s) {
submit = s;
}
public String[] getItems() {
String[] s = new String[v.size()];
v.copyInto(s);
return s;
}
public void processRequest(HttpServletRequest request) {
if (submit == null)
addItem(item);
if (submit.equals("add"))
addItem(item);
else if (submit.equals("remove"))
removeItem(item);
reset();
}
private void reset() {
submit = null;
item = null;
}
}

The bean that we are using is called ppp.qqq. At first the properties are set so setItem and

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (10 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

setSubmit are called which initialize item and submit to the values from the html file after the
user clicked on add. Then the cart.processRequest function in the bean is called with request as
a parameter. (Remember request, like 'out', is a predefined object)

If you click on add, then submit will have the value add. Hence the addItem function will be
called with item as a parameter. In addItem, we have only one line, which is v.addElement. v
is a vector and it has a function named addElement. A vector is like an array, made up of
similar objects. Using v.addElement we add the item name to the vector.

String[] items = cart.getItems();


for (int i=0; i<items.length; i++) {
%>
<li> <%= items[i] %>

In order to display the selected items, getItems in the Bean is called. This function copies
elements of the vector into a string array, which is then returned. Hence items in the JSP file
will now contain these elements. As you already know, every string contains a length, which
gives you the number of elements in the string. Thus items.length will now be the number of
elements in the vector. The for loop is used to display each member. In order to display it as a
bulleted list we have used li with <%=items[i]'. i is used along with the items to display every
element.

v.size represents the number of elements in the vector. For example, if you have 5 elements
then v.size will give the value 5. v.copyInto will copy from the vector into a string array
named s. Then s, an array of strings, is returned.

This is how you can build a shopping cart. The concept of keeping the connection alive with a
session in the servlet facilitates the creation of a virtual shopping mall.

At this point start afresh. There will be now two separate sessions. In case you had used
application instead of session, the process would have run forever for every new user. If the
session was request or page then this exercise would not have been valid. The best way to test
the Bean is by trying out these other scopes.

Cookies

The following example introduces the concept of Cookies.

e25.jsp
<%@ page session="true" %>
<%

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (11 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

Integer num = new Integer(100);


session.putValue("num",num);
String url = response.encodeURL("a1.jsp");
%>
<a href='<%=url%>'> a1.jsp </a>

a1.jsp
<%@ page session="true" %>
<%
Integer i = (Integer)session.getValue("num");
out.println("Num is " + i);
%>

In Internet Explorer, go to the menu option Tools and choose Internet Options. Then select the
tabbed dialog option Security and click on the button labelled Custom Level. Finally, select
prompt for the Cookie options. You must enable cookies in your browser. Also, select
'prompt'for the Cookies per-session option. You will now know when a cookie comes over
since the browser will ask you for confirmation.

A Cookie is stored as a file on disk. It contains a certain finite number of characters and is very
small in size. The second important point to remember is that the cookie is transferred as a
header. It is sent as the cookie name and it's value.

The first line in the example is page session=true. It is not necessary to include this line
because it is true by default. Then a variable named num is created which looks like integer.
While calling the constructor, 100 is passed as a parameter. So num now holds the number
100. The next line in the script is session.putValue. This function putValue will create a
variable named num and give it a value 100. Then we create a string variable called url that
will be assigned the absolute address of a1.jsp. Finally <a href='%url%'>a1.jsp</a> will be
evaluated to <a href='http://127.0.0.1:8080/examples/jsp/a1.jsp'>a1.jsp</a>" as it is pure html.

a1.jsp has a variable i of type integer. This variable is initialized to the return value of
session.getValue(num). Remember, num was a variable created by session.putValue and it
was initialized to 100. This object session remains active across the JSP pages and thus
getValue of num returns 100.

A user interacts with the web server in sessions. Thus, the session object allows you to create a
variable in one file using putValue. You can then use this variable on another page. This
method will work only if the page session is initialized to true.

This is how you can transfer values from one file to another. Hence a1.jsp will print the value
of i as 100.

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (12 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

What are Cookies and how do Cookies work? Aha! You all know what Cookies are and how
well they work for the stomach, but we are interested in a new type of Cookie, freshly baked
from the Java shelf! So far you've only smelt the Cookie, now you get to taste it!

The first time you connect to the web server, it will send you a cookie. As we have changed
our cookie option to prompt, we will see a message box where we will click on 'more info'.
Here we will be told that our cookie name is SESSIONID. It expires at the End of session and
also the Data is To1011mC8999595236320718At. The web server sends a header with Set-
Cookie: SESSIONID = To1011mC8999595236320718At. Now if you start another browser
session the cookie name will be the same but the data will be
To1012mC22314797589282154At i.e. it will be different. Each time a browser receives a
cookie, it sends a header to the server the next time it connects. This header contains Cookie:
SESSIONID = To1011mC8999595236320718At. This is how the web server can recognize
one browser instance from another. To sum up, the web server starts by sending a cookie and
the browser will send the same cookie back when it connects to the server again. The cookies
are stored on your hard disk.
Num is null

If you disable cookies then you will get the output shown above as there is no way to
distinguish one browser instance from another.

A Cookie is a small amount of information which is sent by a servlet to the web browser. The
browser saves this information on the hard disk and later on it can also be sent back to the
server. A Cookie's value can uniquely identify a client. Hence Cookies are commonly used for
session management. A Cookie has a name, a single value and it has attributes like comment,
path, domain qualifiers, maximum age and version number. A large number of web browsers
have bugs in how they handle the optional attributes, so please use them sparingly. They
improve the interoperability of the servlet.

Normally, a Cookie is sent to the browser one at a time and the browser is expected to support
20 Cookies for each web server, 300 Cookies in total and it may limit the Cookie size to 4k
each. The browser is sent Cookies in the header and it returns Cookies to the servlet by adding
fields to the http request header as mentioned earlier. Several Cookies might have the same
name but different path attributes. Cookies affect the caching of the web pages that use them
because HTTP 1.0 doesn't cache the pages with Cookies. There are two versions of the
Cookies, version 0 is by Netscape and version 1, which is documented in rfc2109, is the
original one. By default, Cookies are created in version 0 to ensure the best operability and the
Cookies class implements cloneable. By default, all Cookies are returned to the server that sent
them. A Cookie is sent to the browser by the servlet in the headers. That means that if the
browser ever receives a Cookie from the server then each time it connects to the server, it will
send the cookie in the header.

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (13 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

C:\jswdk-1.0.1\webpages\web-inf\servlets> edit c1.java

c1.java
import java.io.*;import javax.servlet.*;
import javax.servlet.http.*;
public class c1 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException,
ServletException
{
Cookie c;
c = new Cookie("zz7", "mukhi");
res.addCookie(c);
PrintWriter out = res.getWriter();
out.println("Hi");
}
}

Let's consider this example. Here, c is an object that looks like Cookie. When we say c=new
Cookie, we are passing two parameters to the constructor; one is a name 'zz7', which should be
the name our cookie and the other is a value 'mukhi' i.e. the value of the cookie. Basically,
we've created an object that looks like Cookie. res looks like HttpServletResponse and
addCookie will add this cookie. The servlet uses HttpServletResponse whenever it wants to
send some information to the server. All that the server does is, creates a header with the
header variable Set-Cookie: and the value is given as zz7=mukhi.

Set-Cookie: zz7=mukhi

If you haven't enabled the Cookies option in your browser to Prompt, we suggest you do it
now.

This program is called when you load it in the browser. Give the url as
http://127.0.0.1:8080/servlet/c1. On doing so, a message box will be displayed. Before
clicking on 'Yes' select 'More Info'. It will tell you that the Cookie name is zz7 and below that
it will show mukhi. This proves that your browser did receive a Cookie. Having understood
the above program, let's look at the next program.

c2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class c2 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException,

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (14 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

ServletException
{
PrintWriter out = res.getWriter();
Cookie[] c = req.getCookies();
for (int i = 0; i < c.length; i++)
out.println("cookie " + c[i].getName() + "=" + c[i].getValue());
out.println("Hi");
}
}

cookie zz7=mukhi Hi

We sent one cookie and we received one cookie.

Here, c is an array of Cookies. request.getCookies returns an array of Cookies. So, in the for
loop we have i=0; i < c.length and then i++. Using getName and getValue, the name of the
Cookie and the value given to it are printed. In our case c.length will be 1 because we have
sent only one Cookie from the server. You can also send two Cookies at the same time. The
next program demonstrates this.

c3.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class c3 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException,
ServletException
{
Cookie c;
c = new Cookie("zz9", "mukhi");
c.setComment("Will this get dropped?");
c.setMaxAge(100);
c.setPath(req.getServletPath());
c.setSecure(true);
res.addCookie(c);
c = new Cookie("zz10", "mukhi1");
c.setComment("Will this get dropped?1");
c.setMaxAge(10);
c.setPath(req.getServletPath());
res.addCookie(c);
PrintWriter out = res.getWriter();
out.println("H i" + req.getServletPath());

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (15 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

}
}

In this program we have included Comment, which are some lines of text that you may want to
add. setMaxAge decides how long the Cookie lives and setSecure is to use https - secure
sockets layer to send this Cookie across. setPath means you are sending your computer path
with your name and req.getServletPath will give the following : /examples/servlet/zzz.

Now click on 'More Info' and you will observe that the other values, which were not filled in
earlier, are now filled in. setMaxAge indicates the time period that the Cookie will be alive
for. setPath specifies the path for the cookie to which the client should return the cookie. A
cookie is visible to all pages in the directory you specify, and its subdirectorys. A Cookie's
path must include the servlet that sent the Cookie. For example, /catalog makes the Cookie
visible to all the Cookies on the server under /catalog.

As we set the setMaxAge, the cookies 'expires' property now gives you an actual date and
time. It is no longer a session cookie and netscape stores this information in a file named
cookies.txt. The header now has an Expires=date added to it.

In order to do so, use setPath and then use setVersion. If you specify the version as 0, the
Cookie should comply with the original Netscape specification, if it is 1, then it should comply
with rfc2109. Since Cookies are returned to a server, all servlets running within a server share
Cookies. The next program shows how the domain, the path and the version can be retrieved.

c4.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class c4 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException,
ServletException
{
PrintWriter out = res.getWriter();
Cookie[] d = req.getCookies();
for (int i = 0; i < d.length; i++)
{
Cookie c = d[i];
out.println("cookie " + c.getName() + "=" + c.getValue());
out.print(c.getComment() + " " + c.getDomain() + " " + c.getMaxAge());
out.println(" " + c.getPath() + " " + c.getSecure() + " " + c.getVersion());
}
out.println("Hi");

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (16 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

}
}

In this example, the first Cookie comes over because you didn't set the path, the next two
Cookies don't come over because you have set the path and the path is different.
But how can one write a program that determines whether the Cookies have been disabled or
enabled? Run the following program, c5.java.

c5.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class c5 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException,
ServletException
{
Cookie c;boolean h = false;
String p = req.getParameter("ppp");
if (p == null) {
c = new Cookie("vij4", "hi");
res.addCookie(c);
res.sendRedirect( "/servlet/c5?ppp=no" );
}
else if (p.equals("no")) {
h = false;
Cookie[] d = req.getCookies();
for (int i = 0; i < d.length; i++) {
if (d[i].getName().equals ("vij4")) {
if (d[i].getValue().equals("hi")) {
h = true;
break;
}
}
}
if ( h == true)
res.sendRedirect( "/servlet/c6?aa=yes" );
else
res.sendRedirect( "/servlet/c6?aa=no" );
}
}
}

c6.java

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (17 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class c6 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException,
ServletException
{
PrintWriter out = res.getWriter();
String s = (String ) req.getParameter("aa");
out.println(s);
}
}

c is a Cookie and h is a boolean with a value 'false'. p is a String that is initialized to the value
given to ppp. ppp gets a value only when the user sends the url as
http://127.0.0.1:8080/servlet/c5?ppp=xxx. Since we haven't given it in this manner, p will be
null. The if condition becomes true and the control passes to the if statement. c is a Cookie
where the variable vij4 is given the value 'hi'. This is added to the response and sendRedirect
will redirect the browser to pick up another file from the disk. In the meantime the server will
send the cookie to the browser and we can see that the value of the cookie vij4 is hi. The file is
c5, the same servlet, but now with ppp having a value 'no'. Remember, the cookie is sent to the
browser and redirect wrote the new url in the address bar of IE. The servlet gets called again
but now the else statements are executed. Here, it is first checked whether the value of p is 'no'.
This being true in our case, the statements within if are executed. The variable h is reinitialized
to false and d is now declared as an array of Cookies.

req.getCookies will return an array of Cookies. This is given to d. Within the for loop, it is
checked whether a Cookie named vij exists. If there is one, then we break from the loop after
initializing h to the value true. In our case with cookies off, the name 'vij4' does not exist, so h
remains false. When the loop terminates, it is checked whether the value of h is true or false. If
it is false, then the browser is redirected to another servlet c6 with the value 'no' given to aa.
The servlet c6 now prints the value 'no' on the screen. If the value is 'yes', then the browser
supports Cookies, because in that case it would already have a name 'vij4' stored.

c7.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class c7 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
{
res.setContentType("text/html");

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (18 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

PrintWriter out = res.getWriter();


out.println("<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>");
out.println("<BODY>");
String[] items = req.getParameterValues("item");
out.println("You currently have the following items in your cart:<BR>");
if (items == null) {
out.println("<B>None</B>");
}
else {
out.println("<UL>");
for (int i = 0; i < items.length; i++) {
out.println("<LI>" + items[i]);
}
out.println("</UL>");
}
out.println("<FORM ACTION=\"http://127.0.0.1:8080/servlet/c7\" METHOD=GET>");
if (items != null) {
for (int i = 0; i < items.length; i++) {
out.println("<INPUT TYPE=HIDDEN NAME=item VALUE=\"" + items[i] + "\">"); }
}
out.println("Would you like to<BR>");
out.println("<INPUT TYPE=SUBMIT VALUE=\" Add More Items \">");
out.println("<INPUT TYPE=TEXT NAME=item>");
out.println("</FORM>");
out.println("</BODY></HTML>");
}
}

In c7.java, we are first printing the values of the array 'items' of type String. This variable is
initialized to the value in the item parameter i.e. if the url contains ?item=hi , then the items
array will contain one member named hi. If after the ? we had item=hi&item=bye, then the
items array would have 2 members, hi and bye. A parameter in a url can have the same name
repeated multiple times. Since we have given the url as http://127.0.0.1:8080/servlet/c7 there is
no parameter value given to this servlet. Hence no items exist and we see 'None' displayed on
the screen. The else block isn't executed and hence no list is displayed. Then a form is
displayed on the screen. The for loop will not be executed as there are no items.

Now within the text box, we want you to write aa and then click on the 'Add More Items'
Button.

req.getParameterValue(item) will now have the value as item=aa. With Java servlets and the
HTTP protocol you can have items=hi&items=bye given along with the url. Note that you can
have as many values given to the same parameter. getParameterValue will now give you an

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (19 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

array of strings. You can then display all the strings.

The servlet creates an html file along with a form. We have the input tag with type=hidden
name =item and then the value of items. So if there are 6 items then we will have 6 input
statements and all of them will be hidden. Hidden inputs will not be displayed on the screen.
Now each time you say submit i.e. click on 'Add More Items' after writing in the text box, the
program specified by action is called. Finally, we are calling the same servlet c7 and thus you
see the same screen displayed again. This is one way of creating a shopping cart without using
sessions.
View Source

<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>


<BODY>
You currently have the following items in your cart:<BR>
<UL>
<LI>ggg
<LI>ttt
<LI>uuu
</UL>
<FORM ACTION="http://127.0.0.1:8080/servlet/c7" METHOD=GET>
<INPUT TYPE=HIDDEN NAME=item VALUE="ggg">
<INPUT TYPE=HIDDEN NAME=item VALUE="ttt">
<INPUT TYPE=HIDDEN NAME=item VALUE="uuu">
Would you like to<BR>
<INPUT TYPE=SUBMIT VALUE=" Add More Items ">
<INPUT TYPE=TEXT NAME=item>
</FORM>
</BODY></HTML>

URL
http://127.0.0.1:8080/servlet/c7?item=ggg&item=ttt&item=uuu

A little more on Sessions......

This example will explain sessions once more.

C:\jswdk-1.0.1\webpages\web-inf\servlets>edit xxx.java

xxx.java
import java.io.*;
import java.net.*;
import java.util.*;

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (20 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

import javax.servlet.*;
import javax.servlet.http.*;
public class xxx extends HttpServlet {
int i = 0;
public void doGet(HttpServletRequest
request,HttpServletResponse response) throws
ServletException, IOException {
HttpSession s = request.getSession();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String h=" ";
Integer o,o1;
if (s.isNew()) {
o = new Integer(0);
h = "First Time";
s.putValue("acc", o);
}
else {
h = "Once Again";
o = (Integer)s.getValue("acc");
o = new Integer(o.intValue() + 1);
s.putValue("acc", o);
}
out.println(h + "<p>");
out.println("id " + s.getId() + " <p>");
out.println("Creation Time "+new
Date(s.getCreationTime()) + " <p>");
out.println("Time of Last Access "+ new
Date(s.getLastAccessedTime())+"<p>");
out.println("Max Inactive Interval "+
s.getMaxInactiveInterval()+"<p>");
out.println("getValue "+ s.getValue("acc")+"<p>");
out.println("Number of Previous Accesses "+o+"<p>");
String e[];
e = s.getValueNames();
for(int i=0; i <e.length; i++)
out.println("Names "+e[i]+ "<p>");
}
}
Output
First Time
id To1015mC6692480998335292At
Creation Time Tue Dec 26 17:45:51 GMT+05:30 2000

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (21 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

Time of Last Access Tue Dec 26 17:45:51 GMT+05:30 2000


Max Inactive Interval -1
getValue 0
Number of Previous Accesses 0
Names acc

After clicking on the Refresh Button

Once Again
id To1015mC6692480998335292At
Creation Time Tue Dec 26 17:45:51 GMT+05:30 2000
Time of Last Access Tue Dec 26 17:45:51 GMT+05:30 2000
Max Inactive Interval -1
getValue 1
Number of Previous Accesses 1
Names acc

Once the servlet is loaded, the doGet function is called. A variable 's' that looks like
HttpSession is created. It is initialized to the session object returned by request.getsession.
response.setContentType will set the content type header to text/html. Now out is a variable
that will generate our html file. The variable 'h' is of type String and is initialized to a blank
space. Also, we have created two other variables o and o1 of type Integer.

Every object that looks like session has a function named isNew. This function checks whether
the session has been accessed in the past. At the moment, there has been no value given in this
session, so isNew returns true. When the control enters the if statement, the variable o is given
a value by calling the constructor with one parameter in Integer. Giving 0 as the value in the
constructor will initialize o to 0.

s.putvalue is one more function in HttpSession which takes the name of the variable and then
the value to be given to this variable. The variable or the word here is 'acc'. Indirectly, acc is
given the value 0. 'h', which is a string variable, is assigned the string 'First time'. At this point
the else block will not be executed.

The values of a few variables or properties in this session are then displayed.

out.println with h will display 'First time'. Then we have s.getId. Every session is given a
unique number. Thus, s.getId will display that unique id. The id is a number generated at
random and is assigned only by the servlet container. It is implementation dependent. Then
s.getCreationTime will return the time in milliseconds, i.e. the time when you last created the
session. This is given to the Date constructor. This in turn will return a Date object which
when displayed looks like the date format. The same rules apply for s.getLastAccessedTime.

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (22 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

In our case the creation time and the date of last access will be similar.

MaxInactiveInterval will tell you how much time has elapsed since you last accessed the
session. When a client doesn't access a running session within a certain period of time, the
session is invalidated. That means the servlet will discontinue the session. Here, if you say 10
minutes and do not access the session within 10 min, it will show a timeout. This is to make
sure that the session doesn't go on indefinitely. The reason being, a user may decide to visit the
Amazon site and not 'check out', he may simply disappear, or go to another site as he may
have changed his mind. Here, if you give -1, a negative time, then the session doesn't timeout.

s.getValue will give you the value of acc which is 0 at the moment. Thus it prints 0 along with
the number of previous accesses, which again is the value of o i.e. 0. Remember, both are the
same.

Session has a function named getValueNames, which returns an array of Strings for the
attributes or words present in the session. Since it is an array, we put it in a for loop. The
variable i is initialized to 0. The loop will go on till the value of i reaches the length of the
array. In our case, since we have only one attribute, the control will enter the loop only once,
display acc and then quit.

Now, when you click on the refresh button in IE, the session doesn't change but if you start a
new copy of the browser then things will change.

When doGet is called again i.e. when we press refresh, isNew returns false since acc is an
attribute with a value in the session. So now the else block of the if statement is called. Here
the current value of h is changed to 'Once again'. Then, the value of acc is retrieved using
getValue. The Integer class has a function named intValue which converts the value to an int.
o is reinitialized to a new value which is the old value plus 1. Finally, putValue sets acc to this
new value.

A session is an abstract entity created by the servlet. A servlet is loaded once and only once
into memory whereas a session is created each time a new instance of a browser accesses the
site. Thus a session is the same browser or the same user accessing different parts of the site. A
new copy of IE would mean a new user and hence implies a new session. It is the cookie
which distinguish one session from another.

Using this technique, you can now create a Shopping Cart. Remember, the servlet is loaded
only once in memory.

Consider the following illustration- Each time you vist the Amazon site, if there is a servlet
running on Amazon, you will be given a new session id. The session keeps track of what you
buy. This is very similar to the value of acc, which keeps incrementing and yet remains unique

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (23 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

to the current session. All the attributes are session wise, hence you can now store all the
books that you have purchased in the shopping cart.

The session provides a way to identify a user across more than one page or a visit to a website.
In effect, you can now store information about the user. Until a client joins a session isNew()
returns true and on joining the session a value is inserted in that session. The session
information is scoped only to the current copy of the browser. Therefore, the information
stored in one session will not be directly visible to another.

Conclusion

In this chapter, you have seen how a shopping cart can be created.

Contents | Foreword | About the Authors | Introduction |


Appendix |Chapter 1 |Chapter 2 |Chapter 3 |Chapter 4 |Chapter 5 |Chapter 6 |
Chapter 7 |Chapter 8 |Chapter 9 |Chapter 10 |Chapter 11

http://www.vijaymukhi.com/documents/books/javajsp/chap9.html (24 of 24) [5/2/2008 11:00:09 PM]


Java-Servlets-JSP

10. The Jakarta-Tomcat Project

Create a simple JSP file in any subdirectory. We have created a new directory 'myprg' in c:\jakarta-tomcat-
3.2.1\webapps\examples\jsp and written our programs there.

d1.jsp
<html>
<body>
<pp:log1>
Vijay Mukhi
</pp:log1>
</body>
</html>

Output in Browser
Vijay Mukhi

View Source
<html>
<body>
<pp:log1>
Vijay Mukhi
</pp:log1>
</body>
</html>

This program introduces the tag <pp:log1>. This tag is similar to the jsp:tag which you are already familiar
with. pp is not a predefined tag, it is our own custom tag. A custom tag allows you to extend a tag rather than
use an existing tag.
For those who need to have their memory refreshed, type in the following in the IE address bar.

http://127.0.0.1:8080/examples/jsp/myprg/d1.jsp

You will observe that the tag is ignored, since neither the browser nor the server understands <pp:log1>. All
that we see in IE or any browser is Vijay Mukhi and in View Source, we see the jsp file unchanged. The Java
Web Server ignored the tag. The Java Web Server takes a long time to send back any output but the important
thing to note is that the web server and the browser, both, ignored the tag as they don't understand it. There is
no output in tha Java Server window and it is the servlet generated which send the jsp file over unchanged.

Our next program includes minor changes.

d2.jsp
<html>

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (1 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

<body>
<%@ taglib uri="http://java.apache.org/tomcat/examples-taglib" prefix="pp" %>
<pp:log1>
Vijay Mukhi
</pp:log1>
</body>
</html>

Output in Browser

org.apache.jasper.JasperException: No such tag log1 in the tag library imported with prefix pp

It shows an error in the browser. The first statement within the body tag is a directive named taglib, followed
by uri, an attribute, which stands for 'universal resource identifier'. The uri attribute is given a specific url.
Another attribute required named prefix is initialized to pp, which is the name of our tag. When you try to
load this JSP file, the browser shows you an error. The error says that it is an internal server error which
means that we've upset the Java Web Server. The error clearly indicates that there is no tag log1 with the pp
prefix. It does not recognize pp as a valid tag.

In order to validate it, go to the following subdirectory- C:\jakarta-tomcat-3.2.1\webapps\examples\WEB-


INF. Here, you will find a file by the name of web.xml. The file web.xml and the WEB-INF subdirectory
have now been standardized by the java servlet specification. In the earlier days, you could put whatever you
wanted in whichever file and that could be located in any subdirectory. A major part of the Java servlet
specification deals with the directories, their names and the files they should contain.

web.xml talks about the web server. We have reproduced a part of the file that is relevant to our discussion.

web.xml
<taglib>
<taglib-uri>
http://java.apache.org/tomcat/examples-taglib
</taglib-uri>
<taglib-location>
/WEB-INF/jsp/example-taglib.tld
</taglib-location>
</taglib>

It starts with <taglib> within which is <taglib-uri>,this is the same url or name that we have given in the JSP
file. The location it points to is /WEB-INF/jsp/example-taglib.tld.

The uri is mapped to the location. The file example-taglib.tld contains the taglib description. Open this file by
giving the path as follows:

>edit C:\jakarta-tomcat-3.2.1\webapps\examples\WEB-INF\jsp\example-taglib.tld.

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (2 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

example-taglib.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<!- a tag library descriptor ->


<taglib>
<!- after this the default space is
"http://java.sun.com/j2ee/dtds/jsptaglibrary_1_2.dtd"
->
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>simple</shortname>
<uri></uri>
<info>
A simple tab library for the examples
</info>
<tag>
<name>ShowSource</name>
<tagclass>examples.ShowSource</tagclass>
<info> Display JSP sources </info>
<attribute>
<name>jspFile</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>

Since this file does not contain pp , we see an error. Now, we will add our own uri 'vijay' to the xml file and
the tag pp in a tld file.

d3.jsp
<html>
<body>
<%@ taglib uri="vijay" prefix="pp" %>
<pp:log1>
Vijay Mukhi
</pp:log1>
</body>
</html>

web.xml
..

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (3 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

..
<taglib>
< taglib-uri >
vijay
</taglib-uri>
< taglib-location >
/WEB-INF/jsp/ea.tld
</taglib-location>
</taglib>

Add the following lines in web.xml somewhere at the bottom. Now you must restart the web server because
web.xml is only read at startup time.

Truncated Output in Browser


org.apache.jasper.compiler.CompileException: C:\jakarta-tomcat-
3.2.1\webapps\examples\jsp\myprg\d3.jsp(2,0) Unable to open taglibrary vijay : C:\jakarta-tomcat-
3.2.1\webapps\examples\WEB-INF\jsp\ea.tld (The system cannot find the file specified)

The web server starts fine but when we load d3.jsp in the browser we get the error as shown above. When the
Java Web Server starts, it reads web.xml. There it meets a tag named taglib. Within that it finds a tag taglib-
uri which encloses a name, vijay. Then it looks at another tag taglib-location, which holds the name of the file
/WEB-INF/jsp/ea.tld. It looks for ea.tld as the details of vijay are stored in it.

When the server encounters a jsp tag starting with pp, it looks at one of the earlier lines to check for a uri
associated with this tag. This is done by using the taglib directive where we have given the uri as vijay and the
prefix as pp.
Vijay in web.xml points to a file named ea.tld. The file ea.tld is not present in the directory because we didn't
create it. Hence the error.

Create this file in the location specified in the web.xml file but leave it empty.

C:\jakarta-tomcat-3.2.1\webapps\examples\WEB-INF\jsp>copy con ea.tld

.............................................leave a blankline press {Enter}


^Z
1 file(s) copied

Shutdown and restart the Java Web Server. Once again, we get errors again.

Let's go back and load d3.jsp

Output in Browser
org.apache.jasper.compiler.CompileException: C:\jakarta-tomcat-
3.2.1\webapps\examples\jsp\myprg\d3.jsp(2,0) Unable to open taglibrary vijay : Parse Error in the tag library

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (4 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

descriptor: Document root element is missing.

You get the error since the file ea.tld is empty, although the error does say this. The tld extension is a short
form for tag library description. It is an xml file and every xml file must begin with xml version=1.0. As of
now the only version that xml understands is version 1.0 . Key in the following few lines in the tld file to have
this error disappear. What we are now learning are the rules of xml.

ea.tld
<?xml version="1.0" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag
Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

The second line that contains DOCTYPE taglib.... The word following DOCTYPE - taglib, is the starting tag
or the first tag or the document root. It indicates the beginning and an end of the xml document. In other
words it is the first tag we will encounter. PUBLIC is some sort of an identifier and the rules of this document
are stored in web-jsptaglibrary_1_1.dtd. These rules decide on the other tags to be allowed in the document,
their order and how many times they can appear. It is like a syntax check which HTML desn't have. This also
means that we can't write just anything in a tld file, it has to follow the rules which are specified in the dtd.
XML is called the eXtensible Markup Language because it is used to write other markup languages. These
rule are specified through the dtd which is also an xml file

Truncated Output in Browser


org.apache.jasper.compiler.CompileException: C:\jakarta-tomcat-
3.2.1\webapps\examples\jsp\myprg\d3.jsp(2,0) Unable to open taglibrary vijay : Parse Error in the tag library
descriptor: Element taglib requires additional elements

The error is now different from the earlier one where there was no mention of a tag taglib in the file. The
document type is taglib, but it needs more elements and one of them is a tag named pp.

ea.tld
<?xml version="1.0" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<shortname>pp</shortname>
<tag>
<name>log1</name>
<tagclass>examples.xxx</tagclass>
</tag>
</taglib>

Truncated Output in Browser

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (5 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

javax.servlet.ServletException: examples/xxx
Root Cause
java.lang.NoClassDefFoundError: examples/xxx

The error tells us that we need a class named examples.xxx.

The taglibrary is pp and has the version 1.0 which can be any number that we like. This library has a tag
named log1. The tagclass associated with this name will be loaded or called when some action has to be taken
on the tag. Since we do not have this class, we get the error.

tagclass refers to the Java file that contains the code. Since everything is bundled in a package, xxx.java is
included in the package 'examples; and hence the first line is package examples;

The directory where xxx.class would be searched for by default is C:\jakarta-tomcat-


3.2.1\webapps\examples\WEB-INF\classes and because of the package statement, we have to move down into
the examples sub-directory.

C:\jakarta-tomcat-3.2.1\webapps\examples\WEB-INF\classes >cd examples


C:\jakarta-tomcat-3.2.1\webapps\examples\WEB-INF\classes\examples>edit xxx.java

xxx.java
package examples;
public class xxx
{
public xxx()
{
System.out.println("In Constructor xxx");
}
}

The first line is package examples. This directory will be searched for from the classpath. The servlet
specification says that all your class files should be in web-inf\classes and all jar files in web-inf\jar. Hence
examples is created in web-inf\classes. Compile the java file and reload the jsp file in yur browswe. The java
file will give you an error.

Truncated Output in Browser


javax.servlet.ServletException: (class: jsp/myprg/_0002fjsp_0002fmyprg_0002fd_00033_0002ejspd3_jsp_0,
method: _jspService signature:
(Ljavax/servlet/http/HttpServletRequest;Ljavax/servlet/http/HttpServletResponse;)V) Incompatible object
argument for function call

In english, this error means that we have to derive xxx from some class as there are some functions which are
being called by the Java Web Server and they do not seem to exist in our servlet.

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (6 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

C:\jakarta-tomcat-3.2.1\webapps\examples\WEB-INF\classes\examples>javac xxx.java

xxx.java
package examples;
import javax.servlet.jsp.tagext.*;
public class xxx extends ExampleTagBase
{
public xxx()
{
System.out.println("In Constructor xxx");
}
}

We get 2 errors. The first one is at the import statement. Whenever we get an error at an import it means that
we have not specified a jar file in our classpath.

C:\jakarta-tomcat-3.2.1\webapps\examples\WEB-INF\classes\examples>set CLASSPATH=c:\jakarta-
tomcat.3.2.1\lib\servlet.jar;%CLASSPATH%

C:\jakarta-tomcat-3.2.1\webapps\examples\WEB-INF\classes\examples>javac xxx.java

Now the earlier import error disappears and we get another one stating that ExampleTagBase cannot be
found. Once again we have to set classpath to the sub directory before examples, i.e. upto classes.

Set classpath=C:\jakarta-tomcat-3.2.1\webapps\examples\WEB-INF\classes;%CLASSPATH%

Now javac does not give us any errors.

If our Java file or class file has to represent a tag, then it should extend a class that contains all the code to
represent a tag. Hence we have extended xxx from ExampleTagBase. This class is in the same subdirectory
but it in turn refers to other classes.

In case you don't see the same results as we do, then shutdown the server and restart it. Load d3.jsp in your
browser and the Java Web Server dos box will show 'In Constructor xxx'. This means that the JSP engine on
seeing pp:log1, instantiated xxx. Hence the constructor is called.

In addition, the View Source now shows us the following. This proves that the Java Web Server has now
changed the file and then sent it across.

View Source
<html>
<body>
</body>
</html>

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (7 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

A look at the next program


xxx.java
package examples;
import javax.servlet.jsp.tagext.*;
public class xxx extends ExampleTagBase
{
public xxx()
{
System.out.println("In Constructor xxx");
}
public int doStartTag() {
System.out.println("doStartTag1 " );
return SKIP_BODY;
}
}

This program implements a function named doStartTag. The return value is SKIP_BODY. This is a number
which we will concern ourselves with it a little later. In the web server console we will now see two lines of
output which tell us that the function doStartTag is called.

Let's add one more function named doEndTag.

xxx.java
package examples;
import javax.servlet.jsp.tagext.*;
public class xxx extends ExampleTagBase
{
public xxx()
{
System.out.println("In Constructor xxx");
}
public int doStartTag() {
System.out.println("doStartTag1 " );
return SKIP_BODY;
}
public int doEndTag() {
System.out.println("doEndTag");
return EVAL_PAGE;
}
}

The output in the dos box clearly tells us that at first the JSP engine calls doStartTag and then doEndTag. This
implies that the tags used in the JSP file are calling Java code in xxx. doStartTag returns SKIP_BODY

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (8 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

whereas doEndTag returns EVAL_PAGE. These return values are numbers or ints. We still do not see any
output in the IE window.

xxx.java
package examples;
import javax.servlet.jsp.tagext.*;
public class xxx extends ExampleTagBase
{
public xxx()
{
System.out.println("In Constructor xxx");
}
public int doStartTag() {
System.out.println("doStartTag1 " );
return EVAL_BODY_TAG;
}
public int doEndTag() {
System.out.println("doEndTag");
return EVAL_PAGE;
}
}

C:\jakarta-tomcat-3.2.1\webapps\examples\WEB-INF\classes\examples>javac xxx.java
xxx.java:11: Undefined variable: EVAL_BODY_TAG
return EVAL_BODY_TAG;
^
1 error

On compiling, we get an error. This is because we have used EVAL_BODY_TAG, a variable that the
compiler does not understand. We thought it would exist in ExampleTagBase but it is a member of BodyTag.
To get rid of this error we have to implement an interface named BodyTag. This is demonstrated in the next
example.
xxx.java
package examples;
import javax.servlet.jsp.tagext.*;
public class xxx extends ExampleTagBase implements BodyTag
{
public xxx()
{
System.out.println("In Constructor xxx");
}
public int doStartTag() {
System.out.println("doStartTag1 " );
return EVAL_BODY_TAG;
}

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (9 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

public int doEndTag() {


System.out.println("doEndTag");
return EVAL_PAGE;
}
}

When you implement from an interface, the interface either contains variables that have been given values or
it can contain function prototypes. Since the interface BodyTag also contains variables, the error disappears.
In IE, we see no errors provided we shutdown the server, move one directory up, deltree work, md work, go
back to bin and then run startup again.

In the next program, we have added a function named doAfterBody.

xxx.java
package examples;
import javax.servlet.jsp.tagext.*;
public class xxx
extends ExampleTagBase
implements BodyTag
{
public xxx()
{
System.out.println("In Constructor xxx");
}
public int doStartTag() {
System.out.println("doStartTag1 " );
return EVAL_BODY_TAG;
}
public int doAfterBody() {
System.out.println("doAfterBody1 " );
return SKIP_BODY;
}
}

At first doStartTag is called and because this function returns EVAL_BODY_TAG, the JSP engine will now
call doAfterBody. But if you replace EVAL_BODY_TAG with SKIP_BODY, the function doAfterBody will
not be called.

Thus the JSP engine/Java web server will first call doStartTag and depending on what it returns it will or will
not call doAfterBody.

Tags in html can either have some content or they can be empty. In our case we have vijay mukhi, which is
our body. This can be retrieved in doAfterBody. Let's understand how this is done.

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (10 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

xxx.java
package examples;
import javax.servlet.jsp.tagext.*;
public class xxx extends ExampleTagBase implements BodyTag
{
public xxx()
{
System.out.println("In Constructor xxx");
}
public int doStartTag() {
System.out.println("doStartTag1 " );
return EVAL_BODY_TAG;
}
public int doAfterBody() {
System.out.println("doAfterBody1 " );
String s = bodyOut.getString();
System.out.println(s);
return SKIP_BODY;
}
}

In order to do this, use bodyOut.getString in doAfterBody. bodyOut is an object in ExampleTagBase and


getString is a function in bodyOut which returns the string of the body, which in our case is Vijay Mukhi.

A quick look at d3.jsp in case you have forgotten

d3.jsp
<html>
<body>
<%@ taglib uri="vijay" prefix="pp" %>
<pp:log1>
Vijay Mukhi
</pp:log1>
</body>
</html>

BodyOut is an object which is an instance of BodyContent. This string will only be dispalyed in the web
server console window. To see it in the browser, we have to use some more functions like writeOut and
getEnclosingWriter() in bodyOut. These functions throw an exception. Merely saying 'doAfterBody throws
IOException' will not work because the signature changes. So, we must put the code of doAfterBody in a try
and catch.

xxx.java
package examples;

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (11 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

import javax.servlet.jsp.tagext.*;
public class xxx extends ExampleTagBase implements BodyTag {
public xxx() {
System.out.println("In Constructor xxx");
}
public int doStartTag() {
System.out.println("doStartTag1 " );
return EVAL_BODY_TAG;
}
public int doAfterBody() {
try {
System.out.println("doAfterBody1 " );
String s = bodyOut.getString();
System.out.println(s);
bodyOut.writeOut(bodyOut.getEnclosingWriter());
}
catch (Exception e) {}
return SKIP_BODY;
}
}

Output in Browser
<html>
<body>
Vijay Mukhi
</body>
</html>

The function bodyOut.getEnclosingWriter returns an object that looks like java.io.Writer and
bodyOut.writeOut requires a java.io.Writer. writeOut will write the entire body as an html page. In
doAfterBody, you can actually write into your html page which will then be sent over. Thus, writeOut will
actually send the contents between our tag log1 in our jsp file, which was Vijay Mukhi, over to the web
server.

xxx.java
package examples;
import javax.servlet.jsp.tagext.*;
public class xxx extends ExampleTagBase implements BodyTag {
public xxx() {
System.out.println("In Constructor xxx");
}
public int doStartTag() {
System.out.println("doStartTag1 " );
return EVAL_BODY_TAG;
}

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (12 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

public int doAfterBody() {


System.out.println("doAfterBody1 " );
return SKIP_BODY;
}
public void doInitBody() {
System.out.println("doInitBody " );
}
}

As you can see in your dos box, doStartTag is called first, then doInitBody is called and finally doAfterBody.
This happens because we return EVAL_BODY_TAG in doStartTag.

Since doAfterBody returns SKIP_BODY, the process terminates. If it were to return EVAL_BODY_TAG
then you would keep seeing Vijay Mukhi indefinitely.

xxx.java
package examples;
import javax.servlet.jsp.tagext.*;
public class xxx
extends ExampleTagBase
implements BodyTag
{
public xxx()
{
System.out.println("In Constructor xxx");
}
public int doStartTag() {
System.out.println("doStartTag1 " );
return EVAL_BODY_TAG;
}
public int doAfterBody () {
try
{
System.out.println("doAfterBody1 " );
String s = bodyOut.getString();
System.out.println(s);
bodyOut.writeOut(bodyOut.getEnclosingWriter());
}
catch (Exception e) {}
return EVAL_BODY_TAG;
}
public void doInitBody()
{
System.out.println("doInitBody " );
}

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (13 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

This means doAfterBody is invoked after each body evaluation. On returning EVAL_BODY_TAG, a new
evaluation of the body will start and it will follow the same procedure i.e. calling doAfterBody. The entire
roller coaster stops it sees get SKIP_BODY.

The JSP engine calls these function for us to execute certain tasks in them. doInitBody is called only once and
if we have any one time tasks to perform, we place them in doInitBody. In doAfterBody we receive the
content the tag encloses and can create an html file which will be sent across to the browser.

We have now learnt that when there is a tag in a JSP file, certain code in the class file gets called. Note that
these tags can also have attributes. The next example deals with an attribute in the tag.

C:\jakarta-tomcat-3.2.1\webapps\examples\jsp\myprg>edit d4.jsp

d4.jsp
<html>
<body>
<%@ taglib uri="vijay" prefix="pp" %>
<pp:log1 aa="hell">
Vijay Mukhi
</pp:log1>
</body>
</html>

xxx.java
package examples;
import javax.servlet.jsp.tagext.*;
public class xxx extends ExampleTagBase implements
BodyTag {
public xxx() {
System.out.println("In Constructor xxx");
}
public int doStartTag() {
System.out.println("doStartTag1 " );
return EVAL_BODY_TAG;
}
public int doAfterBody() {
try {
System.out.println("doAfterBody1 " );
String s = bodyOut.getString();
System.out.println(s);
bodyOut.writeOut(bodyOut.getEnclosingWriter());
}

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (14 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

catch (Exception e) {}
return SKIP_BODY;
}
public void doInitBody() {
System.out.println("doInitBody " );
}
public void setAa(String v) {
System.out.println("setaa " + v);
}
}

Here, we have an attribute named aa which is initialized to hell. If we stop here, we will not get an error even
though in ea.tld we have not specified the attributes that are allowed with our tag log1, and a prefix of pp. In
the browser run d4.jsp and not d3.jsp.

If we remove the function named setaa from xxx then we will get the following error in our browser.

Truncated Output in Browser


javax.servlet.ServletException: examples.xxx: method setAa(Ljava/lang/String;)V not found

So in ea.tld, we have to say attribute /attribute within the tag and within it we specify the name of our attribute
i.e. aa.

C:\jakarta-tomcat-3.2.1\webapps\examples\WEB-INF\jsp>edit ea.tld
ea.tld
<?xml version="1.0" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<shortname>pp</shortname>
<tag>
<name>log1</name>
<tagclass>examples.xxx</tagclass>
<attribute>
<name>aa</name>
</attribute>
</tag>
</taglib>

aa now becomes an attribute. For it to be an attribute, you need a function named setaa in xxx.java. This
function takes one string as a parameter, named v in this case. The value of v is hell.

C:\jakarta-tomcat-3.2.1\webapps\examples\WEB-INF\classes\examples>edit xxx.java

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (15 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

xxx.java
package examples;
import javax.servlet.jsp.tagext.*;
public class xxx extends ExampleTagBase implements BodyTag
{
public xxx()
{
System.out.println("In Constructor xxx");
}
public int doStartTag() {
System.out.println("doStartTag1 " );
return EVAL_BODY_TAG;
}
public int doAfterBody() {
try
{
System.out.println("doAfterBody1 " );
String s = bodyOut.getString();
System.out.println(s);
bodyOut.writeOut(bodyOut.getEnclosingWriter());
}
catch (Exception e) {}
return SKIP_BODY;
}
public void doInitBody()
{
System.out.println("doInitBody " );
}
public void setaa(String v) {
System.out.println("setaa " + v);
}
}

When you see the dos screen, you will realize that the attributes are called after the constructor. The value of
v is hell, the same value that the attribute had. There is no getaa in the class file. In a way, this class file
resembles a Java Bean that has a set and a get for the attributes.

A tag can have a subtag named required. When you say that the tag required encloses a value true, then you
have to have to have that attribute as part of the tag. It is mandatory and not having it present will get us an
error.

ea.tld
<?xml version="1.0" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (16 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

<taglib>
<tlibversion>1.0</tlibversion>
<shortname>pp</shortname>
<tag>
<name>log1</name>
<tagclass>examples.xxx</tagclass>
<attribute>
<name>aa</name>
<required>true</required>
</attribute>
</tag>
</taglib>

d5.jsp
<html>
<body>
<%@ taglib uri="vijay" prefix="pp" %>
<pp:log1 >
Vijay Mukhi
</pp:log1>
</body>
</html>

We do not have an attribute named aa which is mandatory in the ea.tld file.

The error is as follows

Truncated Output in Browser


org.apache.jasper.compiler.CompileException: C:\jakarta-tomcat-
3.2.1\webapps\examples\jsp\myprg\d4.jsp(3,0) According to the TLD attribute aa is mandatory for tag log1

Now that we have learnt how we can have tags and how a class file is loaded to work with tags, let's go back
to the basics again.

The class Tag is a base class. All the other tags are derived from Tag. The class BodyTag adds two more
methods. If you want support tags then you will have to implement Tag. Let's start with the smallest one. Here
we say public class xxx implements tag.

xxx.java
package examples;
import javax.servlet.jsp.tagext.*;
public class xxx implements Tag
{

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (17 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

>javac zzz.java
xxx.java:3: class examples.xxx must be declared
abstract. It does not define void release() from interface
javax.servlet.jsp.tagext.Tag.
public class xxx implements Tag
^
xxx.java:3: class examples.xxx must be declared
abstract. It does not define int doEndTag() from interface
javax.servlet.jsp.tagext.Tag.
public class xxx implements Tag
^
xxx.java:3: class examples.xxx must be declared
abstract. It does not define void setPageContext(javax.servlet.jsp.PageContext) from
interface javax.servlet.jsp
.tagext.Tag.
public class xxx implements Tag
^
xxx.java:3: class examples.xxx must be declared
abstract. It does not define javax.servlet.jsp.tagext.Tag getParent() from interface javax.servlet.jsp.tagext.Tag.
public class xxx implements Tag
^
xxx.java:3: class examples.xxx must be declared abstract. It does not define void
setParent(javax.servlet.jsp.tagext.Tag) from interface javax.servlet.jsp.tagext.Tag.
public class xxx implements Tag
^
6 errors

On compiling, you will get 6 errors. You can get rid of the errors by including the word abstract.

xxx.java
package examples;
import javax.servlet.jsp.tagext.*;
public abstract class xxx implements Tag
{
}

But if someone derives from xxx, he will get errors. Basically, there are 6 functions in tag that have to be
implemented. So, we remove abstract and place these 6 functions one by one. The 6 functions are: release,
doEndTag, setParent ,getParent, setPageContext and doStartTag.

d6.jsp
<html>
<body>

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (18 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

<%@ taglib uri="vijay" prefix="pp" %>


<pp:log1 >
Vijay Mukhi
</pp:log1>
</body>
</html>

ea.tld
<?xml version="1.0" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<shortname>pp</shortname>
<tag>
<name>log1</name>
<tagclass>examples.xxx</tagclass>
</tag>
</taglib>

xxx.java
package examples;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class xxx implements Tag
{
protected Tag parent;
public void release() {
System.out.println("release");
}
public int doEndTag() {
System.out.println("doEndTag");
return EVAL_PAGE;
}
public void setParent(Tag parent) {
System.out.println("setParent");
this.parent = parent;
}
public Tag getParent() {
System.out.println("getParent");
return this.parent;
}
public void setPageContext(PageContext pageContext) {
System.out.println("setPageContext");

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (19 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

}
public int doStartTag() {
System.out.println("doStartTag");
return SKIP_BODY;
}
}

When you open d6.jsp in the browser you will get the following error

Truncated Output in Browser


javax.servlet.ServletException: examples/xxx

The reason we get the error is because the jsp engine expects the class to implement from both Tag and
BodyTag.

C:\jakarta-tomcat-3.2.1\webapps\examples\WEB-INF\classes\examples>edit xxx.java

xxx.java
package examples;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class xxx implements Tag,BodyTag
{
protected Tag parent;
public void release() {
System.out.println("release");
}
public int doEndTag() {
System.out.println("doEndTag");
return EVAL_PAGE;
}
public void setParent(Tag parent) {
System.out.println("setParent");
this.parent = parent;
}
public Tag getParent() {
System.out.println("getParent");
return this.parent;
}
public void setPageContext(PageContext
pageContext) {
System.out.println("setPageContext");
}
public int doStartTag() {

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (20 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

System.out.println("doStartTag");
return SKIP_BODY;
}
}

C:\jakarta-tomcat-3.2.1\webapps\examples\WEB-INF\classes\examples>javac xxx.java

xxx.java:5: class examples.xxx must be declared


abstract. It does not define void setBodyContent(javax.servlet.jsp.tagext.BodyContent)
from interface javax.servlet.jsp.tagext.BodyTag.
public class xxx implements Tag,BodyTag
^
xxx.java:5: class examples.xxx must be declared
abstract. It does not define void doInitBody() from interface
javax.servlet.jsp.tagext.BodyTag.
public class xxx implements Tag,BodyTag
^
xxx.java:5: class examples.xxx must be declared abstract. It does not define int
doAfterBody() from interface javax.servlet.jsp.tagext.BodyTag.
public class xxx implements Tag,BodyTag
^
3 errors

Once again the error appears because of the interface.

xxx.java
package examples;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class xxx implements Tag,BodyTag
{
protected Tag parent;
protected BodyContent bodyOut;
protected PageContext pageContext;

public void release() {


System.out.println("release");
}
public int doEndTag() {
System.out.println("doEndTag");
return EVAL_PAGE;
}
public void setParent(Tag parent) {
System.out.println("setParent");

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (21 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

this.parent = parent;
}
public Tag getParent() {
System.out.println("getParent");
return this.parent;
}
public void setPageContext(PageContext pageContext) {
this.pageContext = pageContext;
System.out.println("setPageContext");
}
public int doStartTag() {
System.out.println("doStartTag");
return EVAL_BODY_TAG;
}
public void doInitBody() throws JspException {
System.out.println("doInitBody");
}
public int doAfterBody() throws JspException {
System.out.println("doAfterBody");
return SKIP_BODY;
}
public void setBodyContent(BodyContent bodyOut) {
System.out.println("setBodyContent");
this.bodyOut = bodyOut;
}
}

Output in Server window


setPageContext
setParent
doStartTag
setBodyContent
doInitBody
doAfterBody
doEndTag
release

8 functions are called in all. The first function that is called is setPageContext. This function receives a
parameter named pageContext. It takes this object that looks like PageContext and stores it in a public
variable of the same name i.e. pageContext. If we use this.pageContext we are referring to the public variable.
Without this, pageContext refers to the parameter passed to the function. This is how we initialize the first of
the three public variables in our class. Recall how we used bodyOut earlier.

The next function to be called is setParent, which as the name suggests, refers to the parent Tag which it is
passes as a parameter and initializes the public variable parent.

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (22 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

Thereafter, doStartTag and doEndTag are called and then finally, release is called. getParent doesn't ever get
called. This is the only function that isn't called and the order in which they are called remains constant. In
addition, three more functions which refer to the body are also called. They are doInitBody, doAfterBody and
setBodyContent.

The function setBodyContent is the one that initializes bodyOut, which we use to reference our tag. First
doStartTag is called and if we returns EVAL_BODY_TAG in this function, then SetBodyContent,
doInitBody and doAfterTag are called.

The exampleTagClass, which we derived from in the earlier examples has two to three variables - Parent,
bodyOut, pageContext. These were initialized in the functions and were mandatory in the required classes.

That means if you want to create your own class then you can name it anything you like. So you don't have to
use ExampleTagClass. All that you have to do is derive from Tag and BodyTag and make sure that the
functions do what we have done. ExampleTagClass is useful because we do not want to implement so many
functions and we can call it a helper class.

In doStartTag, if you return SKIP_BODY, then setBodyContent isn't called. so you don't require an object
that looks like BodyContent.

BodyContent is a subclass of jspwriter. If doStartTag returns SKIP_BODY then none of the tags from
BodyTag will ever be called. It is only if doStartTag returns EVAL_BODY_TAG that the rest of them are
called.

Let's consider another set of examples.

We will keep reminding you that attributes and methods are called before any other function.

Here, we have the same old tag pp:log1. A JSP tag starts with <% and here we use the same = with a name
memb.
d6.jsp
<html>
<body>
<%@ taglib uri="vijay" prefix="pp" %>
<pp:log1 >
Vijay <%= memb %>
</pp:log1>
</body>
</html>

On doing so, you will get the following error.

Output in Browser

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (23 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

org.apache.jasper.JasperException: Unable to compile class for JSPC:\jakarta-tomcat-


3.2.1\work\localhost_8080%2Fexamples\_0002fjsp_0002fmyprg_0002fd_00036_0002ejspd6_jsp_1.java:79:
Undefined variable: memb out.print( memb );

This is an error because the jsp engine cannot find a variable named memb.

In our next program, we have the same doStartTag, doAfterBody, doInitBody and are doing exactly the same
thing as earlier. But we have made an addition; we have added one more line where we are calling a function
pageContext.setAttribute(). So in other words, we are creating a variable named memb and initializing it to
Sonal.

xxx.java
package examples;
import javax.servlet.jsp.tagext.*;
public class xxx
extends ExampleTagBase
implements BodyTag
{
public xxx()
{
System.out.println("In Constructor xxx");
}
public int doStartTag() {
System.out.println("doStartTag1 " );
return EVAL_BODY_TAG;
}

public int doAfterBody() {


try
{
System.out.println("doAfterBody1 " );
String s = bodyOut.getString();
System.out.println(s);
bodyOut.writeOut(bodyOut.getEnclosingWriter());
}
catch (Exception e) {}
return SKIP_BODY;
}
public void doInitBody()
{
System.out.println("doInitBody " );
pageContext.setAttribute("memb", "Sonal");
}
}

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (24 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

You see the same error as before.

This means that we now have to go back to our ea.tld file, and introduce a new tag named a teiclass.

ea.tld
<?xml version="1.0" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>
<tlibversion>1.0</tlibversion>
<shortname>pp</shortname>
<tag>
<name>log1</name>
<tagclass>examples.xxx</tagclass>
<teiclass>examples.yyy</teiclass>
</tag>
</taglib>

yyy.java
package examples;
import javax.servlet.jsp.tagext.*;
public class yyy extends TagExtraInfo {
public VariableInfo[] getVariableInfo(TagData data) {
return new VariableInfo[]
{
new
VariableInfo("memb","String",true,VariableInfo.NESTED)
};
}
}
>javac yyy.java

In the yyy class, which is derived from the TagExtraInfo tag, we once again start with the package examples.
Class yyy extends TagExtraInfo. getVariableInfo is a member of this class, which returns an array of
VariableInfo. Here, we're returning an object that looks like an array of VariableInfo. Instead of giving a
semicolon to end the statement, we are giving an open curly bracket. At this point, we are creating the array
VariableInfo and initializing it at the same time. The syntax is important. Since it is an array, you can say new
as many times as you want, one below the other for each member of the array. Here, we are creating memb, a
variable of type string, and VariableInfo.NESTED indicates that it is nested one within the other. It will
display Vijay Sonal in the browser and in the Java Web Server, and of course no errors!

What if, in doStartTag, we give pageContext.setAttribute("memb", Sonal2") and in doAfterBody we give


pageContext.setAttribute("memb", Sonal3"), as shown below.

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (25 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

public int doStartTag() {


System.out.println("doStartTag2 " );
pageContext.setAttribute("memb", "Sonal2");
return EVAL_BODY_TAG;
}

public int doAfterBody() {


try
{
System.out.println("doAfterBody1 " );
pageContext.setAttribute("memb", "Sonal3");
String s = bodyOut.getString();
System.out.println(s);
bodyOut.writeOut(bodyOut.getEnclosingWriter());
}
catch (Exception e) {}
return SKIP_BODY;
}

We have initialized memb in three differnet places. Yet we see Sonal. The doStartTag function is called right
at the beginning. Here, memb should have been initialized to Sonal2, but it is in doAfterBody that we say
bodyout.write. doAfterBody has a setattribute too. In such a case, doAfterBody has no effect. Therefore, as
the setattribute in doafterbody is ignored, Sonal will be displayed. Hence you should not use setAttribute
everywhere as it will be ignored.

NESTED is the scope for the variable. If you say nested then the variable is available between the start and
the end tag. If you change nested to AT_BEGIN, then it is available from that tag to the end of the page. But
if you use AT_END, then it is available from the end of the tag to the end of the page.

In the following example, we have used memb twice.


d8.jsp
<html>
<body>
<%@ taglib uri="vijay" prefix="pp" %>
<pp:log1>
Vijay <%= memb %>
</pp:log1>
<p> Vijay1 <%=memb %>
</body>
</html>

xxx.java remains the same as before

yyy.java

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (26 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

package examples;
import javax.servlet.jsp.tagext.*;
public class yyy extends TagExtraInfo {
public VariableInfo[] getVariableInfo(TagData data) {
return new VariableInfo[]
{
new
VariableInfo("memb","String",true,VariableInfo.NESTED)
};
}
}

Truncated Output in Browser


org.apache.jasper.JasperException: Unable to compile class for JSPc:\jakarta-tomcat-
3.2.1\work\localhost_8080%2Fexamples\_0002fjsp_0002fmyprg_0002fd_00036_0002ejspd6_jsp_1.java:109:
Undefined variable: memb out.print( memb );

If you use NESTED, then you will get an error as shown above.

yyy.java
package examples;
import javax.servlet.jsp.tagext.*;
public class yyy extends TagExtraInfo {
public VariableInfo[] getVariableInfo(TagData data) {
return new VariableInfo[]
{
new
VariableInfo("memb","String",true,VariableInfo.AT_BEGIN)
};
}
}

Output in Browser
Vijay Mukhi Sonal
Vijay1 Sonal3

In the Server Window


Vijay Mukhi Sonal

AT_BEGIN means that they are now 2 different values to the same variable memb.

yyy.java
package examples;
import javax.servlet.jsp.tagext.*;

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (27 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

public class yyy extends TagExtraInfo


{
public VariableInfo[] getVariableInfo(TagData data)
{
return new VariableInfo[] {
new VariableInfo("memb","String",true,VariableInfo.AT_END)
};
}
}

When we use AT_END we will get the same error as before

The scope of a variable decides where the variable will be created and where it will be allowed.

Our next few examples will further expand on this concept.

d9.jsp
<html>
<body>
<%@ taglib uri="vijay" prefix="pp" %>
<ul>
<pp:log1 att1="98.5" att2="92.3" att3="107.7">
<li><%= memb %></li>
</pp:log1>
</ul>
</body>
</html>

ea.tld
<?xml version="1.0" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<shortname>pp</shortname>
<tag>
<name>log1</name>
<tagclass>examples.xxx</tagclass>
<teiclass>examples.yyy</teiclass>
<bodycontent>JSP</bodycontent>
<attribute>
<name>att1</name>
<required>true</required>
</attribute>

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (28 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

<attribute>
<name>att2</name>
<required>true</required>
</attribute>
<attribute>
<name>att3</name>
<required>true</required>
</attribute>
</tag>
</taglib>

xxx.java
package examples;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.util.Hashtable;
import java.io.Writer;
import java.io.IOException;
public class xxx extends ExampleTagBase implements
BodyTag
{
private String atts[] = new String[3];
int i = 0;
public void setAtt1(String value) {
System.out.println("setAtt1 " + value);
atts[0] = value;
}
public void setAtt2(String value) {
System.out.println("setAtt2 " + value);
atts[1] = value;
}
public void setAtt3(String value) {
System.out.println("setAtt3 " + value);
atts[2] = value;
}
public int doStartTag() throws JspException {
System.out.println("doStartTag ");
return EVAL_BODY_TAG;
}
public void doInitBody() throws JspException {
System.out.println("doInitBody ");
pageContext.setAttribute("memb", atts[i]);
i++;
}
public int doAfterBody() throws JspException {

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (29 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

System.out.println("doAfterBody " + i);


try {
if (i == 3) {
bodyOut.writeOut(bodyOut.getEnclosingWriter());
return SKIP_BODY;
} else
pageContext.setAttribute("memb", atts[i]);
i++;
return EVAL_BODY_TAG;
} catch (IOException ex) {
throw new JspTagException(ex.toString());
}
}
}

yyy.java
package examples;
import javax.servlet.jsp.tagext.*;
public class yyy extends TagExtraInfo {
public VariableInfo[] getVariableInfo(TagData data) {
return new VariableInfo[] {
new VariableInfo("memb","String",true,VariableInfo.AT_BEGIN)
};
}
}

Output in Browser Window

* 98.5
* 92.3
* 107.7

Lets sum up everything now. Nearly everything remains the same. At first, let's take a look at the jsp file. As
usual we have tags like html and then body. Here log1 has a prefix pp and it has three attributes; att1, att2 and
att3 with values 98.5, 92.3 and 107.7 respectively. The <ul> tag is to display an unordered list and it needs
<li> which stands for the start of the list and </li> means the end of the list. These tags i.e. ul and li are only
meant for ornamental purposes. Memb is a variable which is enclosed in % and angle brackets i.e. it is a jsp
tag.

As we have memb and 3 attributes, we should change the tld file to include these attributes. The attributes and
methods have the first preference. Hence the setAtt1, setAtt2 and setAtt3 functions will be called first. These
three functions accept only one string parameter. We have created an array atts of type String. In these
functions, we are initializing the array atts to the values passed on to the Java program by jsp. Since this is
done first, before any other function is called, you will see setAtt1, setAtt2 and setAtt3 with their values

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (30 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

displayed using System.out.println in you server dos screen.

Once this is done, the next function to be called is doStartTag. This function displays 'doStartTag' and then we
return EVAL_BODY_TAG. It is because of this return value that the JSP Engine now calls doInitBody.

In this function, the value of i is 0 and we then call pageContext.setAttribute. This creates memb as a variable
and initializes it to the value stored in atts[0]. The value of i is incremented by 1 and the next function to be
called is doAfterBody. Here, we check whether the value of i equals 3. As this condition evaluates to false,
the else is called. Now pageContext.setAttribute will initialize memb to the value in atts[1]. Again the value
of i is incremented but now we return EVAL_BODY_TAG. This will call doAfterBody once again and since
the if condition is false again, it will initialize memb to the value in atts[2]. On adding 1 to i, ii now becomes
3. EVAL_BODY_TAG will call doAfterBody once again. Now the value of i is 3, so the function
bodyOut.writeOut(bodyOut.getEnclosingWriter()) will write these values of memb on the browser screen and
return SKIP_BODY. Thus it will now skip the body functions.

In this example, comment out the i++ and then see the results. Remove the comments and you will understand
the flow of doAfterBody.

Contents | Foreword | About the Authors | Introduction |


Appendix |Chapter 1 |Chapter 2 |Chapter 3 |Chapter 4 |Chapter 5 |Chapter 6 |
Chapter 7 |Chapter 8 |Chapter 9 |Chapter 10 |Chapter 11

http://www.vijaymukhi.com/documents/books/javajsp/chap10.html (31 of 31) [5/2/2008 11:00:33 PM]


Java-Servlets-JSP

11. JAVA FOUNDATION CLASSES

All mothers of the world love to boast about their new babies to the entire world. Oh, what a
sweet child I have! At such a tender age, my child can do so many things! No other baby is as
good looking as my own! And they would go on and on. It was the same story when, about
five years ago, Sun Microsystems told us about their new baby, whom they had named Java.
Java, they told us, was better than anything, anyone in the software industry had ever
produced. The things it could do were absolutely incredible. Why, it could even work on any
platform! Have you ever heard of anything like it before? Write a program once and it would
work anywhere. And ofcourse, nothing looked as beautiful as Java.

We were hooked! We had heard other mothers boast about their babies but this seemed
different. We fell in love with Sun's baby for the promise it held of ushering in a new
paradigm in the world of Information technology. That promise, alas, remained just a promise.
Our relationship with Java turned into one with many ups and downs, with more downs than
ups. Simply because we realised there really wasn't a lot that we could do with Java. And as
far as the looks department was concerned, well, Cindy Crawford wasn't about to feel
threatened by Java. And that's probably one hell of an understatement. Because we actually
thought that the output we got from Java looked quite ordinary. We felt let down.

But all that was before the Java Foundation Classes or the JFCs were released. When we first
heard Sun talk about the JFCs, we wondered whether the people at Sun were referring to Jokes
For Crossplatform workability. To tell you the truth, earlier, we had been so disappointed with
Java that we defected to MicroSoft's ActiveX. We spent more than a year going ga-ga about
the brilliant features of ActiveX. It not only looked good but also could actually do really great
things. No longer. We are back home to where we belong. With Java. Infact, had Java been
like this since the beginning, we would have never gone astray.

So let's move onto looking at a couple of programs in the JFCs. We hope that you will be
convinced that this is definitely where our world is going to be heading.
program 0
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{
public void init()
{
Button b;
b = new Button("Hi");
add (b);

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (1 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

}
}

If you do not understand this program, then refer to the chapter titled 'Shlurrp Java'. We
compile this program using javac and then using Appletviewer we open a.html to run this file.
a.html
<applet code=zzz width=200 height=300></applet>

All that this program does is place a Button on our screen,which says 'Hi', This is the type of
output we get when we use the original JDK1.x. Not very impressive. Which is why we called
this program 0.

Another word for useless or dull. Time to get to the real thing.

zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{
public void init()
{
JButton b;
b = new JButton("Hi");
add (b);
}
}

In our first program, we have merely added a 'J' in front of Button to get the term JButton.
Now when we say 'JButton b; ', we are merely informing the compiler that b looks like a
JButton. Which means that it has all the properties and attributes of a JButton. We haven't as
yet created a JButton in our program.

To do that, we have to actually say that b=new JButton() or call a function that returns an
object that looks like a JButton. When we compile this program using the javac compiler, we
get an error message that says 'class JButton not found in type declaration'.

>javac zzz.java
zzz.java:7: Class JButton not found.
JButton b;
^
zzz.java:8: Class JButton not found.
b = new JButton("Hi");

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (2 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

There's a simple reason for this error. If you told me on the phone that your name is Bill, I
wouldn't know who you were. Bill Clinton? Bill Gates? Billy The Kid? I wouldn't know until
you told me your full name. I'd probably slam the phone down. But don't get depressed so
soon. Precisely, what the compiler is doing right now is saying 'give me your full name or else
how am I to know who you are?'.Write this full name and the compiler should be able to
recognize you. However an easier method of doing things is to write the statement
import javax.swing.*;
The terms after the word 'import' and before the '*' will automatically become a prefix to
JButton whenever needed. This is shown in the next program .

zzz.java
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class zzz extends Applet
{
public void init()
{
JButton b;
b = new JButton("Hi");
add (b);
}
}

You mean we went through that much trouble just to get something that looked as bad as the
best that JDK1.x could offer. Oh no! That's why we ran away from java in the first place! And
what about all those terms we kept on hearing about like ModelViewController, delegates,
etc? Things that were supposed to make java better looking?

In case you are wondering whether to go further in this chapter, let me assure you that we shall
get to all those terms at a relaxed pace. You probably won't even realise that we have run
programs using 'delegates', 'MVC', etc, until we actually point out to you that you have. And
we solemnly promise to create better looking buttons in the future.

zzz.java
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class zzz extends Applet
{
public void init()
{

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (3 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

JButton b;
ImageIcon i;
i = new ImageIcon("buttonImage3.gif");
b = new JButton(i);
add (b);
}
}

Before you run this program within your java subdirectory, move to demo\jfc\swingset\images
and copy all the 'gif' files into your current directory. A .gif file merely contains an image. In
this program we have the term ImageIcon. ImageIcon is an object that stands for an image. We
can use any .gif file but right now we are using the files that Sun has given us. When we run
this program, we see a button resembling a round circle with a bright green arrow in the
centre. If you had worked with java earlier, you would have realised that this button looks a lot
better than what buttons used to look like. And all that we have done is to create an ImageIcon
using our .gif file and adding this ImageIcon to our button. The image contained in
buttonImage3.gif file is pasted on to our button.

Earlier when we used button, all we could do was add text to it. Now in addition to plain text,
we can also add images to our buttons. In the good old days, if we wanted to paste on images
using java all we could do was to sit on our heads in some yoga style and meditate, waiting for
the JFCs to be released. But, right now, we can stop meditating because the JFCs are here, and
we have work to do. This is probably an easier way to paste an image onto the a button than
when using the JFCs. That's also one of the major reasons why we have come back to Java. It's
so simple to learn and work with.
zzz.java
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class zzz extends Applet
{
public void init()
{
JButton b;
ImageIcon i , j;
i = new ImageIcon ("buttonImage3.gif");
j = new ImageIcon ("duke2.gif");
b = new JButton (i);
b.setPressedIcon (j);
add (b);
}
}

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (4 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

In this program, we have created two ImageIcons. The only thing new in this program is the
line b.setPressedIcon(j). Here, we obviously mean that 'setPressedIcon' is a function in
JButton. When we run our program, we see our image, namely 'buttonImage3.gif' on our
button, as in our previous program. Now, due to this statement, when we keep the mouse
depressed on our button, the first image is replaced by the second. So as long as we keep the
mouse depressed, we see the image of a duke with a funny hat. When we release the mouse,
we once again see our original image, that is in buttonImage3.gif.
zzz.java
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class zzz extends Applet
{
public void init()
{
JButton b;
ImageIcon i , j;
i = new ImageIcon ("buttonImage3.gif");
j = new ImageIcon ("duke2.gif");
b = new JButton (i);
b.setRolloverIcon (j);
add (b);
}
}
This program is similar to the previous program, where we have two ImageIcons and want to
replace one with the other. By now, however, we must have become pretty lazy. I mean, why
take all the trouble to click on our JButton and keep it depressed to change the image, when
we can achieve our objective by merely positioning the mouse over our JButton? Fortunately,
we have some thing just for you . Something called setRolloverIcon( ) . So execute this
program and just place the mouse over the Button. You will notice the change immediately.
The first image has been replaced by the second. Move the mouse away from our JButton, and
once again, we see the original image.

A point to be remembered here is that when we say b.setRolloverIcon( ) ,we obviously mean
that the function setRolloverIcon is part of JButton. This may, however, not be the case, as
JButton itself may be derived from something else which contains this particular function.
Don't worry about this right now, as we shall be covering all this in greater detail later on.

zzz.java
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class zzz extends Applet

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (5 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

{
public void init()
{
JButton b;
ImageIcon i , j;
i = new ImageIcon ("buttonImage3.gif");
j = new ImageIcon ("duke2.gif");
b = new JButton (i);
b.setEnabled (false);
b.setDisabledIcon (j);
add (b);
}
}

In Java, most components, like JButtons, JCheckboxes,etc are all derived from the class,
JComponent. They therefore, can make use of all the functions of JComponent. One of these is
the function setEnabled(). This function requires a boolean as a parameter. When we say
b.setEnabled(false), all that we are doing is disabling b, which is our JButton. The next line
b.setDisabledIcon(j) simply says that when b has been disabled, replace the first ImageIcon
with the one in 'j'. When we execute this program, we don't see the first image at all, as the
button has been disabled immediately on execution. We directly get to see the second image.
zzz.java
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class zzz extends Applet
{
public void init()
{
JButton b;
b = new JButton ("Hello");
Font f=new Font ("Dialog",Font.BOLD,24);
b.setFont (f);
add (b);
}
}

Maybe, we do not like the look of the text that we have placed in our JButton. Or maybe we
just want to increase the size of the text to make it more prominent. All we have to do is to
change the font. We first create an object that looks like a Font. While doing this, we have to
give it three parameters.

The first is the name of the font. The second refers to the properties of the

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (6 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

font, that is, whether the font is bold, italic, or underline or strikethrough.
And finally we give the point size. We should know that 72 points make an inch. JButton has a
function setFont( ) to set a particular font for whatever we have written.
zzz.java
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class zzz extends Applet
{
public void init()
{
JButton b;
b = new JButton ("Hello");
b.add(Box.createRigidArea(new Dimension (100,50)));
add (b);
}
}

Sometimes, we might have too many buttons on a screen and they might appear too close to
each other. To avoid any cluttering of buttons, we need to separate our buttons. Box is a static
object. It has a static function called createRigidArea ( ). Due to this function, our JButton will
now be allocated some area on the screen. Of course, we still have to specify how large we
want this area to be. For this, we have to pass a Dimension function to it, which contains the
width and the the height . Once we have created this area around our box, nothing else besides
our JButton can occupy this area. Any new component will now be placed outside this area.
zzz.java
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class zzz extends Applet
{
public void init()
{
JCheckBox b;
b = new JCheckBox("hi");
add (b);
}
}
Now that we have done JButtons, we shall realize that JCheckBoxes are almost exactly the
same thing,except for the fact that the borders around a checkbox aren't clearly visible.
Compared to earlier checkboxes in Java, we can now add an ImageIcon to our JCheckBoxes.

zzz.java

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (7 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

import java.applet.*;
import java.awt.*;
import java. awt.event.*;
import javax.swing.*;
public class zzz extends Applet
{
public void init()
{
JCheckBox b;
ImageIcon a = new ImageIcon ("buttonImage3.gif");
b = new JCheckBox(a);
b.addItemListener (this);
add (b);
}
}

It is not sufficient to merely place a checkbox on our screen. When we click on our checkbox,
we want to know if we have actually clicked or not. We may find out whether we have clicked
by making use of the function addItemListener (), within which we pass the parameter 'this'.
When we compile our program, we get some strange error message that says 'Incompatible
type for method. Explicit cast needed...'. The parameter 'this' refers to our current object. In
our case, the current object is zzz as well as Applet. The function addItemListener however,
demands that it requires an object that is an ItemListener. This is now shown in the next
program.

zzz.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class zzz extends Applet implements ItemListener
{
public void init()
{
JCheckBox b;
ImageIcon a = new ImageIcon ("buttonImage3.gif");
b = new JCheckBox(a);
b.addItemListener(this);
add (b);
}
}

In this program we have to make sure that our current object is an ItemListener. ItemListener

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (8 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

is an interface so we use the term 'implements' to append ItemListener to our class. Now 'this'
in addItemListener( ) refers to zzz, Applet as well as ItemListener. On compilation, we still get
an error which tells us that we do not have some abstract function. This is because when we
say 'implements ', we can be sure that whatever follows this term is an Interface. Within an
Interface, all the functions are Virtual functions. These functions do not contain any code. To
remove the errors in our program, all we have to do is to add these functions to the class that
implements the interface. When we say our class extends another class, we mean that our class
contains all the code that was present in the base class, but when we say that our class
implements an interface, it means that our class will now contain all the functions that are
present in the interface. The interface in our program, namely ItemListener, has only one
virtual function 'itemStateChanged( )', which we have added in our next program.

zzz.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class zzz extends Applet implements ItemListener
{
public void init()
{
JCheckBox b;
ImageIcon a = new ImageIcon ("buttonImage3.gif");
b = new JCheckBox(a);
b.addItemListener(this);
add (b);
}
public void itemStateChanged(ItemEvent e)
{
System.out.println("function called");
}
}

When we now compile the program all the errors disappear, confirming that there is only one
virtual function in ItemListener. As we said earlier, the only prerequisite is that the function
must be present within our class. Within this function, we may add any code that we may
want. Here, we have placed the statement System.out.println( ). When this function gets
executed, whatever text we have written within the function appears at our dos prompt, for the
number of times that we have clicked on our JCheckBox. System, by the way, is a static
object. What we mean by that term is that we don't have to say 'new' to make use of it. At this
point, we must realise that we may have more than one checkbox in our program, which may
also call itemStateChanged. To distinguish between different components calling this
function,we use ItemEvent. We also note that addItemListener is one of the new concepts of

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (9 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

jdk1.x. Earlier, when we wanted to call a function we had to use handleEvent. Here, things
have been made much simpler, as we can now call our own code.

zzz.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class zzz extends Applet implements ActionListener
{
public void init()
{
JButton b;
ImageIcon a = new ImageIcon ("buttonImage3.gif");
b = new JButton(a);
b.addActionListener(this);
add (b);
}
public void actionPerformed(ActionEvent e)
{
System.out.println("function called");
}
}

An ItemListener is essentially meant for a JCheckbox. When we are working with buttons, we
would rather use an Action Listener. This Interface, as well, has only one virtual function
which we have to add within our class which implements ActionListener. This function is
called actionPerformed. Also we use ActionEvent to distinguish between different JButtons.
Now every time we click on JButton, our code which is in actionPerformed is called. This is
how we handle events in the Java Foundation Classes.
zzz.java
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class zzz extends Applet
{
public void init()
{
JLabel l=new JLabel("hi");
add( l);
}
}

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (10 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

If we want to print any text on to our screen, we normally make use of a label. Here we use
JLabel. The size of the label will vary according to the size of the text we have placed into it.
Here, we have only written the word 'hi'. Short and sweet. This now appears at the top of our
applet in the centre.
zzz.java
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class zzz extends Applet
{
public void init()
{
ImageIcon i=new ImageIcon("buttonImage3.gif");
JLabel l=new JLabel("hi");
l.setIcon( i);
add( l);
}
}

A JLabel, as with everything else in the JFCs, can have two entities within it. What we mean
to say is that within a JLabel, we can have an image as well as some text, both of which may
be independent of each other. Here, when we created our JLabel, we associated a text 'hi' with
it. We also create an ImageIcon. Every JLabel has a function setIcon( ). We place our Image
Icon within this function. When we execute this program, our label now contains an image as
well as the text, side by side.

zzz.java
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class zzz extends Applet
{
public void init()
{
setLayout(new BorderLayout());
ImageIcon i = new ImageIcon ("BigTiger.gif");
JLabel l=new JLabel(i);
add(l);
}
}

In this program, we have created an ImageIcon as we had done earlier. We have added this
ImageIcon to a JLabel. This JLabel has now been added to our screen. We have also created

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (11 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

the simplest of borders for our applet when we said setLayout(new BorderLayout( )). The
difference, in this program, is that the image we have in our .gif file is of a size much larger
than any image that we have used before. When we run this program, if we get the feeling that
we aren't really getting to see the entire image, we might probably just be right. Even if we
increase the size of our applet to it's full size, we may still not see the full image. After all, the
image in this .gif is probably larger than even our entire screen. Wouldn't it be great if we
could just scroll through the image, just as we use a scrollbar to view a large text document ?
Well, we are trying to do just that in our next program.

zzz.java
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class zzz extends Applet
{
public void init()
{
setLayout(new BorderLayout());
add("Center",new yyy());
}
}
class yyy extends JScrollPane
{
public yyy()
{
ImageIcon i = new ImageIcon ("BigTiger.gif");
JLabel l=new JLabel(i);
add(l);
}
}

We create a new class which can now extend the particular class that we require, namely
JScrollPane. JScrollPane contains functions that will enable us to create scrollbars within our
Applet. We call the constructor of this class when we say new yyy( ), from init( ). However,
when we now run this program, we find that only the border has been formed within our
applet. We don't get any image unlike in one of the earlier programs , here we at least got to
see half the image. We rectify this problem in the next program.

zzz.java
import java.applet.*;
import java.awt.*;
import javax.swing.*;

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (12 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

public class zzz extends Applet


{
public void init()
{
setLayout(new BorderLayout());
add("Center",new yyy());
}
}
class yyy extends JScrollPane
{
public yyy()
{
ImageIcon i = new ImageIcon ("BigTiger.gif");
JLabel l=new JLabel(i);
getViewport().add(l);
}
}

All that we have done out here is to write getViewport( ).add( l ) instead of
just add( l ). Here, we are saying that getViewport() is a function within
JScrollPane which ensures that scrollbars appear within our applet when we call the function
add() from it. When we have an image that is too large to fit onto our screen, we need to create
a smaller window to enable us to view just a portion of the image. This is done by
getViewport(). If we now use the scrollbar, we may see another part of the image. All this
assumes that the image within our gif file is large enough, otherwise we shall not see any
scrollbars.

zzz.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class zzz extends Applet implements ActionListener
{
JProgressBar p;
public void init()
{
JButton b;
b=new JButton("click");
p=new JProgressBar();
b.addActionListener(this);
p.setMinimum( 0);
p.setMaximum( 100);

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (13 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

p.setValue( 10);
add( b);
add( p);
}
public void actionPerformed( ActionEvent e)
{
int i=p.getValue()+10;
p.setValue( i);
System.out.println("hi");
}
}

Whenever software is in the process of being installed onto our computer, we see a progress
bar which tells us how much of the process has been completed. The problem with most
progressbars we have seen to date is that they are never accurate. Sometimes the pointer of the
progress bar will move slowly in the beginning and then in a flash of a second, will reach the
end. At other times, it moves quite fast, but stops just before the end of the bar for a time
period that seems like infinity. Anyway, let's see how the Java Foundation Classes have
implemented progressbars. We have added an ActionListener to the button in our program.
The bare minimum information we need to give our progressbar are the values at the extreme
left end and the extreme right end of the progressbar. For this we have two functions,
setMinimum() and setMaximum() respectively in JProgressBar. The function setValue() tells
the pointer of the progress bar where it should start from when it first starts executing. Here we
have placed the initial position at 10 using this function. Whenever we click on the button, the
current value of the progress bar is obtained by the function getValue(). We
add 10 to this value, and place it in a variable i. The current value of the
progressbar is now set to the the value in variable i. Thus each time we click on the button we
increment the value of the progressbar by 10.

When we click on the button for the first time, the initial value is 10, which is now
incremented by 10 to become 20. The pointer of the progressbar now points to this value. In a
practical progressbar, we may use something else besides a button to use the progressbar's
pointer to increment by a fixed amount, but the concept remains the same.

zzz.java
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class zzz extends Applet
{
public void init()
{
setLayout(new BorderLayout());

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (14 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

add("Center",new sss());
}
}
class sss extends JPanel
{
public sss()
{
JSlider s;
this.setLayout(new BorderLayout());
s=new JSlider(JSlider.HORIZONTAL,100,1000,400);
s.setPaintTicks(true);
s.setMajorTickSpacing(20);
this.add(s);
}
}

If you look at any music system, you'll notice that you can adjust the volume or the bass and
other functions using a slider. A slider is normally used when we have a wide range of values
and we want to choose a value within that range without typing in that value. When we have a
sliderpanel, all we do is to move the slider to the required value. Earlier, it was almost
impossible to obtain a slider in Java. In contrast, Windows allowed us to create a slider with
great ease. Now, using the JFCs, this is possible in Java as well. We first create an object that
looks like a JSlider. We have specified that it's alignment is horizontal. As we had done earlier
with our progressbar, we specify the minimum and maximum values of the slider, as well as
the value we want it to be set at initially. If we just write only the first three lines within the
constructor and then say add(s), we shall obtain a slider which we can drag with a mouse from
one end to another. The only problem is that we shall have difficulty placing the slider at any
particular value we want it at. For this, we enable markers between the two ends. We also
specify how much space should be there between each marker, using the function
setMajorTickSpacing(). Around our slider, we also want a border with some title. So, here, we
have put a border that looks like JTitledBorder(), with two parameters: s refers to our slider
around which we want our titled border and the second parameter now becomes the title of our
slider. If we say this.add() or this.setLayout(new BorderLayout()), 'this' merely refers to the
current class we are in. It doesn't make a difference if we do no write 'this' before add().

zzz.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class zzz extends Applet
{

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (15 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

public void init()


{
setLayout(new BorderLayout());
add("Center",new sss());
}
}
class sss extends JPanel implements ChangeListener
{
JLabel tf;
public sss()
{
JSlider s;
setLayout(new BorderLayout());
tf=new JLabel("Slider value: ");
add("South",tf);
s=new JSlider(JSlider.HORIZONTAL,100,1000,400);
s.setPaintTicks(true);
s.setMajorTickSpacing(20);
s.addChangeListener(this);
this.add(s);
}
public void stateChanged(ChangeEvent e)
{
JSlider s1 =(JSlider) e.getSource();
tf.setText("Slider Value: "+s1.getValue());
}
}

It's not possible for us to be totally satisfied by merely moving the slider from one end to
another. We would also like to know the current position of the slider. To do this , we have
created another JLabel and placed it in the south. Now all user interface tools have a listener
associated with them. A slider has a ChangeListener. Here we have written
s.addChangeListener(). The 'this' merely specifies that ChangeListener which is an interface is
in in the very same class. We have a function called StateChange within Change Listener
which will get called each time we move the slider up and down.

We have a parameter that looks like ChangeEvent that would allow us to distinguish between
different sliders calling the function stateChanged (). But right now we have only one slider so
that is not important. Here e.getSource will return the object that calls stateChanged(). In this
case, we know that it is a JSlider, so that is what we are casting it to. The getValue() function
will tell you the current position of the slider. Now setText() will allow this value to be seen
on our label at runtime.

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (16 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

zzz.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
public class zzz extends Applet
{
public void init()
{
JButton b=new JButton("Hello, how are you");
add(b);
DebugGraphics.setFlashTime(10);
b.setDebugGraphicsOptions(DebugGraphics.FLASH_OPTION);
}
}

To deal with problems that we may encounter with any graphics application in java, we have a
static object named DebugGraphics. This static object has a function named setFlashTime().
Our image will be drawn on screen within a time duration that depends on the value we pass to
this function. In the next statement, we have said
setDebugGraphicsOptions(DebugGraphics.FLASH_OPTION);

where FLASH_OPTION is another static variable in DebugGraphics. Each time a paint


message comes, this is the function that will cause our image to be redrawn. Since we are
redrawing our image very slowly, we can see, at what point in time, any errors in the drawing
of the image, occur. In this program, we have only used DebugGraphics to check whether a
button is being drawn properly. Normally, it is used for debugging complicated objects on
screen when we want to see in slow motion what is happening at every stage. We could try
this function with another component, or a User Interface.

zzz.java
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class zzz extends JPanel
{
static JFrame frame;
public static void main(String s[ ])
{
frame = new JFrame("zzz");
frame.getContentPane().add("Center", new zzz());
frame.pack();

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (17 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

frame.setVisible(true);
}
}

We now get down to working with applications in java. When we run such an application, we
don't use appletviewer, but instead say java zzz. All the
programs that we shall be doing after this will be applications and not applets.

In an application, the first function to be called is always main(). The reason we have made
main public is because we want every one to be able to access it. The function main() gets an
array of strings, which are the parameters we may pass after the name of the program. We
create a JFrame with the title zzz.

In this frame, we put all things together using the function pack(). Without
setVisible( true), we shall not be able to see anything. Notice that we have
declared frame to be of type static JFrame. We have to declare it as static to
be able to use it in another function, in this case main(). Alternately, we
could have put this statement within the function main(), in which case, we may avoid the use
of the term static.To learn more about applications in java, refer to one of the earlier chapters .

zzz.java
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class zzz extends JPanel
{
public zzz()
{
JRadioButton b;
b=new JRadioButton("hello");
add("Center",b);
}
public static void main(String s[])
{
JFrame f = new JFrame("hi");
f.getContentPane().add(new zzz());
f.pack();
f.setVisible(true);
}
}

A radiobutton functions in a manner similar to that of an ordinary button or a checkbox, only it

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (18 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

is smaller and round in appearance. Each and everyone of these components have a function
setKeyAccelerator(). Now when we write o in single quotes within this function, and now
execute this program, we shall notice that the first occurance of the letter we have placed
within this function is now underlined. If we now press the Alt key as well as the letter o, our
radio button which contains this text is activated. The function setKeyAccelerator() enables
Sun to implement, in part, a very crucial concept of almost all computers used today. A
concept that says that even if our mouse is not working properly, we must be able to operate
our computer using a keyboard. This is something of a standard across platforms and Sun has
made it very clear that we shall be able to use the Java Foundation Classes using only a
keyboard, without using a mouse. { Have you ever wondered what happens to a Mac user
when his mouse is giving him problems ? Don't even ask !

zzz.java
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class zzz extends JPanel
{
static JFrame frame;
public zzz()
{
JMenuBar m = new JMenuBar();
JMenu f = new JMenu ("File");
f.setIcon(new ImageIcon("folder.gif"));
m.add(f);
m.validate();
add(m);
}
public static void main(String s[ ]) {
frame = new JFrame("zzz");
frame.getContentPane().add("Center", new zzz());
frame.pack();
frame.setVisible(true);
}
}

As we said earlier, the first function to be called in an application is main().


When we say new zzz(), we are calling the constructor of the function zzz. Here, we have
created a menubar called m of type JMenuBar. Now to this menubar we are going to add our
menus. Our first menu has been called f and has a text 'File' associated with it. Also in this
menu, we have created an ImageIcon, which we add to our menu. When we say validate(),
what we are doing is forcing the menubar to redraw itself.

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (19 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

zzz.java
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class zzz extends JPanel
{
static JFrame frame;
public zzz()
{
JMenuBar m = new JMenuBar();
JMenu f = new JMenu ("File");
f.setIcon(new ImageIcon("folder.gif"));
f.setHorizontalTextPosition(JButton.RIGHT);
JMenuItem o=new JMenuItem("Open",new ImageIcon("open.gif"));
o.setHorizontalTextPosition(JButton.RIGHT);
f.add(o);
m.add(f);
JMenu gg = new JMenu ("Color");
gg.setHorizontalTextPosition(JButton.RIGHT);
JMenuItem red=new JMenuItem("Red");
gg.add(red);
red.setHorizontalTextPosition(JButton.RIGHT);
JMenuItem blue=new JMenuItem("Blue");
gg.add(blue);
blue.setHorizontalTextPosition(JButton.RIGHT);
m.add(gg);
m.validate();
add(m);
}
public static void main(String s[ ])
{
frame = new JFrame("hi");
frame.getContentPane().add("Center", new zzz());
frame.pack();
frame.setVisible(true);
}
}

While doing these programs, we have to remember the heirarchy of the terms involved. At the
top of this heirachy is the menubar. The menubar has to be filled with menus. There may be a
number of menus within a menubar and they will all appear in the same line on the screen.

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (20 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

Each menu may have a number of menu items which appear just below the menu, when we
click on the menu. Here, a single menuitem called 'Open' is added to our first menu, 'File'. For
our second menu 'Color', we have added two menuitems, namely red and blue. The entire
procedure is the same as in the previous program.

zzz.java
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class zzz extends JPanel {
static JFrame frame;
public zzz() {
JMenuBar m = new JMenuBar();
JMenu f = new JMenu ("File");
f.setIcon(new ImageIcon("folder.gif"));
f.setHorizontalTextPosition(JButton.RIGHT);
JMenuItem o=new JMenuItem("Open",new ImageIcon("open.gif"));
o.setHorizontalTextPosition(JButton.RIGHT);
f.add(o);
JMenuItem e=new JMenuItem("Exit");
e.setHorizontalTextPosition(JButton.RIGHT);
f.add(e);
e.addActionListener(new aa());
m.add(f);
add(m);
}
public static void main(String s[ ])
{
frame = new JFrame("hi");
frame.getContentPane().add("Center", new zzz());
frame.pack();
frame.setVisible(true);
}
}
class aa implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (21 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

As usual, we have a menubar to which we add menus. The menus themselves may consist of a
number of menuitems. Until now, we have been only displaying these menuitems. Wouldn't it
be useful if we were able to click on a menuitem and perform some task. For this, we shall
obviously need an ActionListener. With our menuitem 'Exit', we say addActionListener (new
aa()). aa has to implement ActionListener. This interface has one function, actionPerformed(),
which contains the code System.exit(0). This results in us getting out of this application. We
could, instead, have performed some other useful task using this function, with this type of an
application.

Listboxes are the kind of examples that we were talking a lot about. In the
previos program we only displayed numbers. However we have always said that the nice thing
about the Java Foundation Classes is that where ever we display numbers ,we may also display
pictures. Now, listbox has a function named setCellRenderer. Here, the statement, new te (),
will obviously call the constructor of class te. Within the class te, all that we have done is a
series of initialisations. Now te has to look like Renderer. Therefore we have said te
implements Renderer. Renderer have two virtual functions. One is setValue () and the other is
getComponent (). The first function to get called is getComponent(). The return value of
getComponent() is of type Component. When we say 'return this', it means that it can return
either a te or a JLabel or a Renderer. But here since we can return only a component, we return
a JLabel. Now, setValue() gets called. Here, the Object is what we have returned in the
function getComponent(), namely our JLabel. It is, however, not useful to us, as far as
processing data is concerned, if the object is a component. This is why we are casting it to an
Integer. The class Integer has a function, intValue(), which will return the object's value. .
Therefore i will now have the current value of the item or cell within the listbox. The boolean
parameter is used to find out whether we have selected that particular item or not. In case it
has been selected, we also print the price along with the picture, otherwise we only display the
picture. The actual displaying of the picture within each cell is done by setIcon(). We have to
call our renderer each time a cell has to be painted, which is why we may notice setValue()
and getComponent() being called a
number of times from whatever System.out.println() displays out at our DOS prompt.

Assume we are using an Operating System like Windows and we are in the main Window.
Take a case where a part of this window is overwritten by another window. At this point in
time, Windows will claim that it is not its responsibility to draw whatever is in that window.
Suppose we finish our work in the second window and if we come back to our original
window. Then the Windows operating system will tell our window that a part of it has been
dirtied. Therefore our window needs to be repainted. Windows does this by sending our
window a paint message. Suppose we had some text on our screen. A part of this text was in
the section that had been overwritten. Now we have to rewrite the text using the Windows
SDK command TextOut. This command has to be given within the function paint. Windows is
a very smart operating system and knows how to optimise time. This is, I suppose, for people
who are forced to run Windows on 486s, but it does save on time when a number of complex
items have

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (22 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

to be redrawn. Getting back to our textout command in paint, the complete text is not
rewriiten. Only the part of the text that had been overwritten is now redrawn. Notice that we
have said 'redrawn' and not 'rewritten'. As far as Windows is concerned, it treats everything
that has to go on to screen as a series of pixels. Therefore, text as well as images are treated the
same way. There are a few new things that the java foundation classes have provided us that
make our applets or applications better looking. Not only that, the way our applets look, can be
changed, depending on what the user wants it to look like.

Take for instance the case of a button. People who use Windows will want a button that looks
like a Windows button, while a person who is used to a Macintosh will want the same button
to be in the Mac style. This poses a dilemma. Should we keep the button looking the same
irrespective of the Operating System or should the button have the look and feel of the
particular operating System it is running under. The JDK1.0 used the second option and what
it did was to have the button drawn by the operating system itself. There was one problem with
this approach. Suppose you had earlier worked on an application on the Mac, and now you
switched on to say an Intel machine with Windows on it.

You will realise that the same application looks very different under your new operating
system. So what the JFCs decided to do was a very simple thing. They gave the user the option
of changing the look and feel. This was a very smart thing to do. After all, when we go to
work, our dress is very formal. However, if we have to attend a party with friends, we won't go
wearing the same clothes. We would rather change in to jeans and T-shirts. Something similar
can be done with the JFCs. If our application is running under Windows, but if we do not like
it's look and feel, we may change it to another look and feel that is either supplied by Sun or
has been created by us. This option is available to us at runtime, and enables us to decide how
our application will be displayed.

Earlier, if we were using Windows, we didn't have an option as to how our application would
be displayed. Windows itself decided how it would be displayed. Now with the JFCs we have
a very flexible look and feel. We call this the Plugable Look and Feel.

The Java Foundation Classes has the ability to change the look and feel of a component,
according to what the user desires. To achieve this change in the user interface, we make use
of a static object called UIManager. This has a static function called setLookAndFeel(). This
will set the look and feel within our frame, to whatever we have specified. There are classes
which refers to a Windows, Motif look and feel. Hence when we run the program, we see the
objects displayed as per the platform we have selected. You can have these components show
a neutral look too.

Now we come to the concept of 100% Pure Java. Right now we are using the JDK1.2.2 but
underneath it all, is the JDK1.2. All that JDK1.2.2 did was to call code. This code if it had to
run under Windows would have to be in a DLL. So that is where we call it from. This may

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (23 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

further call code in other Windows DLLs which will finally call code in VxDs. Now when we
say 100% Pure Java, we mean that our JFCs are basically .class files that are executed. In none
of these .class files do we call native code. In other words, we do not call any 'C' code. We can
however call code from the JDK1.2 which in turn may call native code. But the JFCs remain
100% Pure Java.

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (24 of 25) [5/2/2008 11:01:22 PM]


Java-Servlets-JSP

Contents | Foreword | About the Authors | Introduction |


Appendix |Chapter 1 |Chapter 2 |Chapter 3 |Chapter 4 |Chapter 5 |Chapter 6 |
Chapter 7 |Chapter 8 |Chapter 9 |Chapter 10 |Chapter 11

http://www.vijaymukhi.com/documents/books/javajsp/chap11.html (25 of 25) [5/2/2008 11:01:22 PM]

S-ar putea să vă placă și