282
Chapter 8 Java Servlet and Java Bean: BonForumEngine and BonForumStore
method, as appropriate.That returns
actorKeys
, which is an array list of
nodeKey
s,
either for all host nodes or for all guest nodes in
bonForumXML
.
The
chatGuest
and
chatHost
session attribute values (
chatActor
strings) have the
following format, which depends upon the XSL document used in the XSLT process
that displays the lists of hosts and guests:
actorNickname age:actorAge rating:actorRating
Here is an example:
John Doe age:47 rating:11
The
actorNickname
is recovered from that string and is used as follows:
NodeKey actorNodeKey = getActorByNickname(actorKeys, actorNickname);
The
getActorByNickname()
method selects the correct actor
nodeKey
from the list for
1
or
–1
, in our case) to
get a new rating, which is converted to a string. Finally, the
actorRatingNodeKey
and
the new rating value for the
actorRating
node content are both passed to the
editBonNode()
method of the database object.That method takes care of updating the
actor rating in the XML data (we will spare you the details).
Accessing Bean Properties and Methods from JSP
You just saw a bean method,
changeChatActorRating()
, being called from a JSP.We
will now show several ways to access bean properties and to call bean methods from
JSP.The property examples will use two
BonForumStore
properties,
hitTimeMillis
and
initDate
, which are mostly useful for examples like this. For convenience, the method
examples will use the
get
and
set
property access methods of these same two proper-
initializeXML()
method. If the
bonForumXML
data object
is empty (normally true only after application startup), it will be filled with necessary
data.When that happens, the
setInitDate()
method of
BonForumStore
is called with a
null
argument, which puts a datestamp in the
initDate
property, which shows the
date and time that the database was initialized.The
getInitDate()
method is public,
but the
setInitDate()
method is protected. From JSP, therefore,
initDate
is a read-
only property.
One easy way to use a JavaBean from JSP is to use a
jsp:useBean
tag, as follows:
<jsp:useBean id=”bonForumStore”
class=”de.tarent.forum.BonForumStore”
scope=”application”/>
It is important to realize that
The
setInitDate()
method is protected, so attempts to set
initDate
from JSP will
cause a compile time error. Instead, let’s try to set the
hitTimeMillis
property value
from a JSP, using something like this example:
<jsp:setProperty name=”bonForumStore” property=”hitTimeMillis” value=”HELLO!”/>
Another way to set the same property is to use something like this:
<%
bonForumStore.setHitTimeMillis(“GOODBYE!”);
%>
Notice that this last example uses a scriptlet, not an expression, which would cause a
compilation error because the
set
method returns void.Also, as you can see, we
should have put some validation code in the
set
method.
These last examples illustrate some important points. Public access to a Web appli-
cation—through bean properties and methods, for example—can defeat one of the
08 1089-9 CH08 6/26/01 7:33 AM Page 283
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
284
Chapter 8 Java Servlet and Java Bean: BonForumEngine and BonForumStore
main goals of JSP, which is to separate the job of the page designer from the job of the
Java developer. Making writeable public properties (or readable ones with side effects)
and public methods available for JSP development can create possibilities for uninten-
).You must cast the object returned
from the attribute to the right class before assigning it to a variable, which can then be
used to access the bean and its methods, as in the JSP expression shown here:
<%
de.tarent.forum.BonForumStore bFS =
➥
(de.tarent.forum.BonForumStore)pageContext.getAttribute( “bonForumStore”, 4 );
%>
initDate: <%= bFS.getInitDate()%>
By the time you try using the XML versions for all the JSP tags used in the examples,
you will see that lots of variations are possible here. Depending on your point of view,
JSP is either a rich palette or a complicated mess!
08 1089-9 CH08 6/26/01 7:33 AM Page 284
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Java Applet Plugged In:
BonForumRobot
9
I
N THIS CHAPTER
,
WE DISCUSS THE
BonForumRobot applet, which is part of the
bonForum Web chat application. Here you learn how to create and deploy a Java
applet to control a Web application user interface.You also use the Sun Java plug-in to
support an applet on the client.
9.1 Hands-on with Java Applets
As you can see by searching in a bookstore or on the Internet, much information
about Java applets is available. Here we will be brief about topics that are well docu-
mented elsewhere.To find out more about applets, we suggest the Applet trail of the
Sun Java Tutorial, which you can find at the following URL:
Be sure to drag the mouse pointer around on the pictures of molecules to see them
from all angles.Try example2.html and example3.html as well.
9.1.2 Embedding Objects in HTML
You might be familiar with the now somewhat obsolete method of embedding an
applet in an HTML document using the
APPLET
element.
The group that creates the official recommendation for HTML thought that the
functionality of the Applet tag was better included into the new
Object
tag, which
allows embedding of more than just applets into a document. Look up the specifica-
tion for the embedded object tag in the HTML 4.01 specifications, which you can
find at the following URL:
/>09 1089-9 CH09 6/26/01 7:34 AM Page 286
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
287
9.1 Hands-on with Java Applets
9.1.3 Using Applets with Java Plug-in
First, just for fun, try using the Java plug-in to embed one of the Sun SDK demo
applets into a JSP document.You can get the details that you will need in your
jsp:plugin
element from the HTML file that is normally used to launch the applet
demo.
We did this with the demo called Fractal, which we can launch using the following
SDK document URL (yours may vary):
file://C:\jdk1.3\demo\applets\Fractal\example1.html
Put your new JSP document somewhere in the Tomcat Server document space. For
example, we saved a file as TOMCAT_HOME\webapps\examples\bonbook\
testFractal.jsp.
</jsp:params>
tags. Also, each parameter tag that you have needs a few changes, espe-
cially the following:
n
Change each
param
tag into a
jsp:param
tag.
n
Enclose the value of each attribute in double quotation marks.
n
Close the parameter tags correctly with a
/>
. (Note that the
</jsp:param>
clos-
ing tag throws a Jasper exception—you do need to use the trailing slash.)
n
Change the
codebase
parameter to point to the proper location of the applet
class file.
When you get done with the conversion, your JSP document will contain something
like this:
<html>
<table>
<tr>
<jsp:plugin type=”applet” code=”CLSFractal.class” codebase=”./applet”
jreversion=”1.3.0” width=”500” height=”120” >
things around, such as the
codebase
attribute value and corresponding location of the
applet
class files.You will find that you can put the
applet
class in a descendant folder
relative to the JSP document, but you cannot put it just anywhere at all on the system.
Debugging Applets Using the Java Console
When you deploy your applet on the browser using the Sun Java plug-in tags, you
should also be aware of the Java Console setting for the plug-in.The Control Panel
that comes with the Sun Java plug-in has a setting that enables or disables whether the
Java Console is displayed when your applet is first initialized.You can launch the Java
plug-in Control Panel by double-clicking its icon in the NT Control Panel. Make sure
that Show Java Console is checked on the Basic property tab.
Notice that you can disable the Java plug-in here as well, so if a plugged-in object
is not working, this is one place to troubleshoot.
Note that you can also turn on the Java Console using the Internet Properties icon
in the NT Control Panel and choosing the Advanced tab. Scroll down and check the
Java Console Enabled option in the Microsoft VM group.
Normally, you do not want the Java Console to appear on your system, especially
because it can take quite a while to appear. For development of an applet, however, at
times the Java Console will certainly help you to trace and debug your coding efforts.
Simply use the Java
System.out.println()
method in your applet code to print a
trace of the processing status.You can see that trace at runtime on the Java Console.
Here is an example that prints out the value of one of our applet parameters:
System.out.println(“refresh:” + this.refresh);
09 1089-9 CH09 6/26/01 7:34 AM Page 288
thisThread:Thread[963620229674,4,http://ginkgo:8080/bonForum/jsp/forum/applet/-
➥
threadGroup]
top stop
thisThread:Thread[963620229674,4,http://ginkgo:8080/bonForum/jsp/forum/applet/-
➥
threadGroup]
stop()
showDocument
thisThread:Thread[963620229674,4,http://ginkgo:8080/bonForum/jsp/forum/applet/-
➥
threadGroup]
MalformedURLException caught in
BonForumRobot/bonForum/jsp/forum/host_executes_chat.jsp963620229925.tfe
thisThread:Thread[963620229674,4,http://ginkgo:8080/bonForum/jsp/forum/applet/-
➥
threadGroup]
9.1.4 Converting Applet Tags to Object Tags
Because the object tags are now supposed to be used instead of applet tags, you might
want to convert existing applet tags into object tags. One way to do that is by using
the HTMLConverter utility from Sun.That will also mean, however, that your applets
will be embedded in Java plug-in elements, and thus will be executed by the Sun Java
JRE instead of the browser’s default Java runtime engine.
09 1089-9 CH09 6/26/01 7:34 AM Page 289
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
290
Chapter 9 Java Applet Plugged In: BonForumRobot
9.2 XSLTProcessor Applet
One of the classes that comes with the Apache Xalan XSLT processor packages is an
applet called XSLTProcessorApplet. As you might guess from its name, this applet
APPLET
element on the HTML page. Doing
that should allow the applet to find the Xalan and Xerces JAR files.That did not turn
out to be the case, though. As a further applet adventure, you could put the Xalan
XSLTProcessor applet into a
jsp:plugin
element on a JSP page. In this next section,
which is about the BonForumRobot applet, we will revisit the theme of plugging in
an applet.
9.3 BonForumRobot
The BonForumRobot applet is part of the bonForum Web chat application project.
How it is used in that application is discussed in Chapter 7, “JavaServer Pages:The
Browseable User Interface.”There you can find a description of how the applet is
embedded into the JSP pages that use it. In this chapter, we discuss the design and
inner workings of the applet.To follow the discussion, refer to the source code, either
in the back of this book or on the accompanying CD. Note that the Java source file is
09 1089-9 CH09 6/26/01 7:34 AM Page 290
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
291
9.3 BonForumRobot
not in the de.tarent.forum package.You should find the file BonForumRobot.java in
the top-level bonForum source folder.
9.3.1 Problems Solved Using This Applet
The making of this robot applet was undertaken for several reasons.The most practical
of these was to solve two or three problems encountered while creating the browser
user interface for the bonForum Web chat application.
n
Using the
jsp:forward tag
to get from one HTML frameset to another
.The
names are quite self-explanatory.You take advantage of this contract by overriding the
methods that you need in a subclass that you create of the
Applet
class. Here is the
brief applet storyline:
The
init()
method of the applet is first called by its applet context (a browser
or applet viewer) when the applet is loaded into that container system.
The
start()
method is automatically called after
init()
method and also each
time the HTML client containing the applet is visited.
The
stop()
method is automatically called when the HTML page containing
the applet has been replaced by another, as well as right before the
destroy()
method.
09 1089-9 CH09 6/26/01 7:34 AM Page 291
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
292
Chapter 9 Java Applet Plugged In: BonForumRobot
The
destroy()
method is called by the applet container right before it reclaims
the applet, giving it a chance to destroy resources that it has allocated.
an action one or more times in a timed loop.
For debugging purposes, we also give the thread a system-unique name using the
current time. Here is the code for the
start()
method:
public void start() {
setBackground(Color.cyan);
System.out.println(“start()”);
if (refresh) {
RefreshThread thread = new RefreshThread(
Long.toString(System.currentTimeMillis()));
thread.start();
}
}
We also set the background color to cyan, which matches the HTML page that con-
tains the applet. Otherwise, we might have a gray rectangle showing where the panel is
located.
9.3.6 The stop() Method
The
stop()
method of the bonForumRobot applet is quite simple. It breaks what
would otherwise be an endless loop, putting an end to the clocking action of the
timer loop in the thread
RefreshThread
instance.
public void stop() {
System.out.println(“stop()”);
continueRunning = false;
}
09 1089-9 CH09 6/26/01 7:34 AM Page 292
object tag that contains it.
If the message parameter is set to
debug
, then the applet will graphically display the
values of the current applet parameters.That is useful during development of both the
applet and its surrounding application.
9.3.8 The run() Method
This method of the inner
RefreshThread
class contains most of the code in this
applet. Much of the rest of this chapter discusses what is happening in this method. In
the
run()
method, the parameters that are passed to the applet by the
jsp:plugin
ele-
ment are utilized.You can find a discussion about these in Chapter 7. Here we discuss
what the parameter values are used for inside the BonForumRobot applet.
9.3.9 The jsp:plugin Parameters
The next excerpt from visitor_joins_chat_ready.jsp shows some code that sets up the
BonForumRobot applet parameters.The code then forwards the HTTP request to the
actor_leaves_frameset_robot.jsp page, which contains a
jsp:plugin
element referenc-
ing the BonForumRobot applet class.
<%--GOING THROUGH ROBOT TO GET TO NEXT JSP PAGE ALLOWS BREAKING OUT OF A FRAMESET
--%>
➥
<%
request.setAttribute(“target”, “_top”);
in a new frameset on the browser, the document with a URL something like this:
http://localhost:8080/bonForum/jsp/forum/guest_executes_chat.jsp
It should display this document only once. Of course, because displaying the docu-
ment in this case “jumps” out of the current frameset, there is no need to do that
more than once.
In other circumstances, the BonForumRobot applet is programmed by its parame-
ters to repeat its action of displaying a document.That periodically refreshes the infor-
mation displayed on the browser in one target frame.
The refresh Parameter
This is an example of a switch in the applet that is controllable using the
refresh
parameter.This switch is rather brutal—it turns the applet on or off. In fact, it is actu-
ally just a placeholder, already conveniently present in all the many JSPs that set up the
applet parameters. It is used to select the creation of different threads besides the one
RefreshThread
available now and thus will select different actions.That makes new
ideas easier to try out; if any turn out well, they could then be put in their own applet
class. However, to have the
refresh
parameter in the applet just to turn it on and off is
not good design.
09 1089-9 CH09 6/26/01 7:34 AM Page 294
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
295
9.3 bonForumRobot
The target Parameter
The
target
parameter tells the applet where to display its output in a browser’s
HTML frameset. For example, a value of
method of the
Applet
class. However, in the future, other actions could be added,
including communication to the host Web application.
The message Parameter
While doing its robotic action, the applet should display graphically the contents of
the
message
parameter. Obviously, by using a more complex object for this parameter,
we could create quite sophisticated displays, control panels, and more within the
applets display panel on the browser.
9.3.10 What the BonForumRobot Applet Does
In Section 9.3.1, “Problems Solved Using This Applet,” we listed the reasons why we
developed this applet for the bonForum project.These were also discussed in earlier
09 1089-9 CH09 6/26/01 7:34 AM Page 295
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
296
Chapter 9 Java Applet Plugged In: BonForumRobot
chapters and will be further discussed in later sections. Here we just want to emphasize
that this applet can have one of two possible behaviors. Which of the two happens
depends on the value of the
target
parameter.
When target Is _top
If the target value is
_top
, it means that we are using the applet to break out of a
frameset on the browser.The phrase “break out of a frameset” needs clarification.
Perhaps describing one example of this will help. Consider the HTML produced by
the JSP:
Like the problem of “breaking out of frameset,” this one seems like it should have a
simple, ready-made solution. In fact, we have been offered several suggestions. So far,
09 1089-9 CH09 6/26/01 7:34 AM Page 296
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
297
9.3 BonForumRobot
the only one that has worked is this bonForumRobot applet. Of course, we will not
consider having the applet directly create and refresh the displays for the chat, using
data from the server. After all, our whole point is to experiment with server-side tech-
nology for browser application.
9.3.11 Repeating an Applet Task
As discussed previously, this applet repeats an action. For the bonForum Web applica-
tion, that action is to invoke the
showDocument()
method of the
Applet
object.
The action repeats at increments that are set by the value of the
increment
parame-
ter of the applet.The maximum number of repetitions is controlled by the
limit
para-
meter.
However, note that if target is
_top
, no repetition of the
showDocument()
invocation
can occur if the robot applet is not in the top frame of the frameset displayed on the
Chapter 9 Java Applet Plugged In: BonForumRobot
9.3.12 Using AppletContext to Show Documents
Each applet running is provided with an AppletContext interface, which allows the
applet some functionality in its client-side runtime environment. For example, we use
AppletContext to put our message in the status line at the bottom on the browser dis-
play area:
getAppletContext().showStatus(message);
As another example, this is the code that makes the robot applet display a document:
getAppletContext().showDocument(new URL(uncachedDocument), target);
That looks like it may be simple, but things are never quite simple in a real software
project! That is why we created the variable named
uncachedDocument
, which you can
see is the argument to the
showDocument()
method. The next section explains what it
is for.
9.3.13 Circumventing Cached Documents
When we want to display a JSP page after having done it once already, its “contents”
could be entirely different than they were the previous time. JavaServer Pages are
dynamic. However, the name of the JSP document, its URL, can remain the same for
both requests.
This can cause a problem if the browser has cached the result that it got when it
first requested the JSP document.When the second request is made, the browser gets
the cached result from the first request out of its cache and effectively prevents JSP
from being dynamic!
We ran into this problem when we first got our robot applet working. It was mak-
ing the requests for the JSP repeatedly, but the display was not changing. It should
have been changing because part of it was a list of chat messages, and these were being
added to from another browser acting as a guest of the same chat.
generated by our JSP.We already discussed this problem enough (see Section 9.3.10,
“What the BonForumRobot Applet Does”). It is time to discuss what is working
instead.
In the bonForumRobot
run()
method, we fix up the JSP filename in the URL in
the
document
parameter.We do that to force it to be a unique filename. Because the
browser has not seen the resulting URL before, it does not look for it in its cache,
even though, as we shall see, the robot may actually be requesting the very same JSP
that it did the last time.
Here is an example of how the applet “fixes up” the URL for a JSP document.The
original URL is shown here:
http://localhost:8080/bonForum/jsp/forum/visitor_joins_chat.jsp
After being altered, that URL becomes something like this:
http://localhost:8080/bonForum/jsp/forum/visitor_joins_chat.jsp.962066767851.tfe
The 12-digit number added to the filename is the current time in milliseconds
obtained from the Java
System
object.That timestamp value creates a unique filename
within the context of this session.
The fake extension .tfe that is also added to the URL acts as a signal to the Tomcat
Server that it should send this request to the
bonForumEngine
object.That is because of
the servlet-mapping element that we added to the web.xml Tomcat Web application
deployment descriptor file.
The bonForumEngine servlet strips the timestamp and the fake extension off the
altered URL.Then that servlet simply forwards the request to the JSP document that
stop()
method of
the applet. In our applet code is a loop setup that begins with this:
while (continueRunning) {
Inside the loop, to stop it, we can use the following code:
// are all iterations done?
if(counter > limit) {
System.out.println(“counter:” + counter + “ over limit:” + limit);
stopRunning();
continue;
}
The
stopRunning()
method simply wraps the applet
stop()
method to makes things
clearer for humans:
public void stopRunning() {
stop();
}
The
stop()
method of the applet has been written to set the value of
continueRunning
to
false
:
public void stop() {
System.out.println(“stop()”);
continueRunning = false;
messages to the chat at any time, whether or not the applet was firing. In fact, the
problem turned out to be the flashing colors there in the corner of the screen—as our
traffic light cycled every 5 seconds through its colors!
Two-Phase Clock in Timer
To get the green light and yellow lights working, we put the thread to sleep twice
during each iteration of the timer loop. In effect, we have two phases in our clocks
ticking.That will come in handy in the future, when we need “on for X seconds, off
for Y seconds” types of robotic actions. However, the catch clauses for these two sleeps
should probably include
continue
statements because it’s possible at some point that
we might want to use an
InterruptedException
to stop the applet cold in the middle
of a sleep.We would not want it to go right back to sleep again after that exception,
but we would want it to do so before it gets back to the
while
and stops (that would
produce a weird delayed stop effect—we stopped the applet and, 3 seconds later, it
refreshed before finally stopping).
9.3.16 Implementing a Software Clock
The thread object in this applet is basically a timer. In embedded software systems that
are multithreaded, it has been popular to create a clocking action in the software by
putting a thread to sleep repeatedly in an endless loop. Java makes it easy to use this
technique in this applet, which needs a mechanism to repeat an action indefinitely.
09 1089-9 CH09 6/26/01 7:34 AM Page 301
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.