module 4_2
module 4_2
The
Coinplete
Re erence
Optional Nasamajh
Optional Nasamajh
. 380. J 2 EE: Th e Co mp I e t e Re f e r e n c e
A JSP is simpler to create than a Java servlet because a JSP is written in HTML rather
than with the Java programming language. This means that the JSP isn't cluttered with
many println() methods as found in a Java servlet. However, a JSP offers basically the
same features found in a Java servlet because a JSP is converted to a Java servlet the
first time that 3. client requests the JSP.
Th~ -e-are three methods that are automatically called when a JSP is requested and
when the JSP terminates normally. These are the jsplnt() method, the jspDestroy()
method, and the service() method. These methods can be overridden, although the
jsplnt() method and jspDestroy() methods are commonly overridden in a JSP to
provide customized functionality when the JSP is called and terminates.
The jsplnt() method is identical the _init() method in a Java servlet and in an applet.
The jsplnt() method is called first when the JSP is requested and is used to initialize
objects and variables that are used throughout the life of the JSP.
The jspDestToy() method is identical to the destroy() method in a Java servlet. The
destroy() method is automatically called when the JSP terminates normally. It isn't
called if the JSP abruptly terminates such as when the server crashes. The destroy()
method is used for cleanup where resources.used during the execution of the JSP are
released, such as disconnecting from a database.
The service() method is automatically called and retrieves a connection to HTTP.
Installation
Once a JSP is created, you place the JSP in the same directory as HTML pages. This differs
from a Java servlet, which must be placed in a particular directory that is included in the
CLASSPATH. You don't need to set the CLASSPATH to reference a JSP.
Optional Nasamajh
Optional Nasamajh
However, there are three factors tJ:1.at you must address w hen in tallin° a J P.
First, web servjces called by a JSP must be installed properly. For example, a Java
servlet called by a JSP must be placed in the designated directory for Java servle
and referenced on the CLASSPATH. The development environment used to create
the J2EE application determines the designated directory.
The second factor to be addressed is to avoid placing the JSP in the WEB-INF or
META-INF director.ies. The development environment prohibits this. The last factor
is that the directory name used to store a JSP mustn' t have the same name as the prefix
of the URL of the \Veb application.
■ Comment tag A comment tag opens with<%-- and closes with--%>, and is
followed by a comment that u sually describes the funcbon ality of statements
that follow the comment tag.
■ Declaration statement tags A declaration statement tag opens with <¾! and is
followed by a Java declaration statement(s) that define variables, objects, and
methods that are available to other components of the JSP program .
. ■ Directive tags A directive tag opens with<%@ and commands the JSP virtual
engine to perform a specific task, such as importing a Java package required by
objects and methods used in a declaration statement. The directive tag closes
with %>. There are three commonly used directives. TI1ese are import, include,
and taglib. The import tag is used to import Java packages into the JSP program.
The include tag inserts a specified file into the JSP p rogram replacing the include
tag. The taglib tag specifies a file that contains a tag library. Here are examples of
each tag. The first tag imports the java.sql package. The next tag includes
Optional Nasamajh
Optional Nasamajh
the books.html file located in the keogh directory. And the last tag loads the
myTags. tld library.
I
<%@ page import=" import java . sql.* "; %>
<%@ include ftle="keogh\books.html" %>
<%@ taglib uri= "rnyTags. tld" %>
■ Expression tags An expression tag opens with <%= and is used for an
expression statement whose result replaces the expression tag when the JSP
virtual engine resolves JSP tags. An expression tags closes with%> . .
■ Scriptlet tags A scriptlet tag opens with <% and contains corrunonly used Java
control statements and loops. A scriptlet tag closes with%>.
Chap te:r H : 38
Any Java declaration statement can be used in a JSP tag similar to ho,. tho e
statements are used in a Java program. You are able to place multiple tatem within
a JSP tag by extending the close JSP tag to another line in the JSP program. Tnis ·
illustrated in Listing 11-2 where three variables are declared.
Besides variables, you are also able to declare objects, arrays, a.,d Java collections
w ithin a JSP tag using techniques similar to those used in a Java program. Listing Jl-3
shows how to declare an object and an array.
In Listing 11-3, the JSP program creates three String objects, the firs t two d eclarations
implicitly allocate memory, and the third declaration explicitly allocates memory. ln
addition, this JSP program creates arrays and a Vector.
Optional Nasamajh
Optional Nasamajh
Methods
JSP offers the same versatility that you have with Java programs, such as defining
methods that are local to the JSP program. A method is defined similar to how a
method is defined in a Java program except the method definition is placed within
a JSP tag.
You can call the method from within the JSP tag once the method is defined.
Listing 11-4 illustrates how this is done. In this example, the method is passed a
student's grade and then applies a curve before returning the curved grade.
The method is called from within an HTML paragraph tag in this program,
although any appropriate tag can be used to call the method. Technically, the method
is called from within the JSP tag that is enclosed within the HTML paragraph tag.
The JSP tag that calls the method must be a JSP expression tag, which begins with
<%=. You'll notice that the method call is identical to the way a method is called within
a Java program. The JSP virtual engine resolves the JSP tag that calls the method by
replacing the JSP tag with the results returned by the method, which is then passed
along to the browser that called the JSP program.
re turn 10 + grade;
%>
<P> Your curved grade i s : <%=curve( 8 0)%> < / P>
</BODY>
< / HTML>
A JSP prograrn is capable of handling practically any kind of method that you
normally use in a Java program. For example, Listing 11-5 shows how to define and
use an overloaded method.
Both methods are defined in the same JSP tag, although each follows Java syntax
structure for defining a method. One method uses a default value for the curve, while
the overload method enables the statement that calls the method to provide the value
of the curve.
Once again, these methods are called from an embedded JSP tag placed inside two
HTML paragraph tags.
Optional Nasamajh
Optional Nasamajh
<HTML>
Listing 11-5 "
. . 1,1
De f 1n1ng . 'ii:-'! <HEAD>
and cal!i11g ij <T ITLE > ,TSP Programming < / T I TLE>
a method \1~
and an </ HEAD>
over:oaded <BODY>
met hod . <%! b oolean cur ve (int grad e )
r eturn 1 0 + g r ade;
}
b oo lean curve ( in t g r _a de , i nt curveValue )
{
return curve Value + g r ade;
%>
<P> Your cur ved g r a d e is : <% =cu rve( 80 , 10)% > < / P>
<P> Yo ur curved g rade is : <%=c urve(70)% > < / P>
< / BODY>
~ / HTML>
Control Statements
One of the most powerful features available in JSP is the ability to change the flow
of the program to truly create dynamic content for a web page based on conditions
rect".ived from the browser.
There are two control statements u sed to change the fl ow of a JSP program. These
are the if sta tement and the switch statement, both of w hich are also u sed to direct the
flow of a Java program.
The if statement evaluates a condition statement to de termine if one or mo re lines
of code are to be executed or skipped (as you probably remember from when you
learned Java). Similarly, a switch statement compares a v alue with one or more other
values associated w ith a case statement. The code segment that is associated with the
matching case statement is executed. Code segm ents associated with other case
statements are ignored.
The power of these controls comes from the fact that the code segment that is
executed or skip p ed can consist of HTML tags or a combination of HTML tags and JSP
tags. That is, these cod e segments don't n eed to be only Java statem ents or Java tags.
Listing 11-6 sh ow s how to intertwine I-ITML tags and JSP tags to alter the flow of
the JSP program. You'll notice that this program is confusing to read because the if
statement and the switch statement are broken into several JSP tags. This is necessary
because HTML tags are interspersed within these statements.
The if statement requires three JSP tags. The first contains the beginning of the if
statement, including the conditional expression. The second contains the else statement,
and the third has the cl osed French brace used to terminate the else block.
Optional Nasamajh
Optional Nasamajh
Two HTML paragraph tags contain information that the browser displays, depending
on the evaluation of the conditional expression in the if statement. Only one of the HTML
paragraph tags and related information are sent to the browser. ·
The switch statement also is divided into several JSP tags because each case
statement requires an HTML paragraph tag and related information. And, as with
the if statement, only one HTML paragraph tag and related information associated
with a case statement that matches the switch value are returned to the browser.
Lisfo1g 11-6 contains simple examples of the if statement and switch stateme,nt. You
can create more complex statements, such as nesting if statements, by using techniques
illustrated in this example. Any flow control statements that you use in Java can also
be incorporated into a JSP program. However, you must be careful to separate jSP
tags from HTML tags and information that will be executed when the program's flow
changes .
Optional Nasamajh
Optional Nasamajh
Loops
JSP loops are nearly identical to loops that you use in your Java program except you
can repeat HTML tags and related inform ation multiple times \vi thin your JSP program
without having to enter the additional HTtvIL tags.
There are three kinds of loops commonly used in a JSP program. These are the for
loop, the while ioop, and the do ... while loop. The for loop rep eats, usually a sp ecified
number of times, although you ca n create an endless for loop, which you no doubt
learned when you were introduced to Java . .
The while loop e 'ecute con tinually as lon g as a specified condition remains true.
Howe,·er, the l<Vhile loop may n ot execute because the condition may never be true.
In contrast, the do . ..while loop executes at least once; afterwards, the conditional
expres.sio in the do ... w hile loop is evaluated to d etermine if the loop should be
exea ·e another time.
Loops play an important role in JSP database programs because loop s are u sed
popula te HTML tables with data in the result set. However, Listing 11-7 shows a
sjmilar routine used to populate three HTML tables with values assigned to an artay.
All the tables appear the same, although a different loop is used to create each table.
The JSP program initially declares and initializes an array and an integer, and then
begins to create the first table.
There are two rows in each table. The firs t row contains three column headings that
are hard cod ed into the program. The second row also contains three columns each of
which is a value of an element of the array.
The first table is created using the for loop . The opening table row tag <TR> is
entered into the program before the for loop begins. This is because the for loop is only
populating columns and not rows.
A pair of HTML table data cell tags <TD> are placed inside the for loop along with
a JSP tag that contains an elem ent of the array. The JSP tag resolves to the value of the
array element by the JSP virtual program.
The close table row </TR> tag and the close </TABLE> tag are inserted into the
program following the French brace that closes the for loop block These tags terminate
the construction of the table.
A similar process is used to create the other two tables, except the while loop and
the do ... while loop are used in place of the for loop.
Optional Nasamajh
Optional Nasamajh
<'l""R> . ,
•
<TD>First</TD>
. ,
<TD>Second</TD> '
<TD>Thir.d< /TD> ,
</T.R>
<TR> .
9.:c- >
<% for ·(int l; i<3; i++) . ..
{ 0
<TD><%=Grade[i]%> </TD>
<% } %>
, .
;
</TR>
</TABLE>
<TABLE>
<TR>
<TD> F -1.1.-s t </TD>
<TD>Second</TD>
<TD>Third< / TD>
</TR>
<TR>
•·
. ,
<% while (x<3) { %>
<TD><%=Grade[x]%> < / TD> . .
,;.•
''~ .................
.,__,.,
<% x-+·+;
} %>
.
</TR>
< /TABIJE>
<TABLE>
' .
<TR> '
<rrD>Second,< /TD>
. .
<TD>Third</TD>
</TR>
<TR> ,
<% x=O;
do{%>
<TD><%=Grade[x]%></TD>
<%x++;
} v1hile (x<3) %>
Optional Nasamajh
Optional Nasamajh
</ TR>
</TABLE>
</BODY>
< / HTML>
L~ Tomcat
JSP programs are executed by a JSP Virtual Machine that runs on a web server.
Therefore, you'll need to have access to a JSP Virtual Machine to run your JSP program.
Alternatively, you can use an integrated development environment such as JBuilder
that has a built-in JSP Virtual Machine or you can download and install a JSP Virtual
Machine.
One of the m ost popular JSP Virtual Machines is Tomcat, and it is downloadable at
no charge from the Apache web site. Apache is also a popular web server that you can
al o download at no cost.
You'll also need to have the Java Development Kit (JDK) installed on your computer,
which you probably installed when you learned Java programming. You can download
the JDK at no charge from the www.sun.com web site.
Here's what you need to do to download and install Tomcat:
1. Connect to jakarta.apache.org.
2. Select Download.
3. Select Binaries to display the Binary Download page.
4. Create a folder from the root directory called tomcat.
5. Download the latest release of jakarta-tomcat.zip to the tomcat folder.
6. Unzip jakarta-tomcat.zip. You can download a demo copy of WinZip from
www:winzip.com if you don' t have a zip/unzip program installed on your
computer.
7. The extraction process should create the following folders in the tomcat
directory: bin, conf, doc, lib src, and webapps .
.8. Use a text editor such as Notepad and edit the JAVA_HOME variable in the
tomcat.bat file, which is located in the \tomcat\bin folder. Make sure the
JAVA_HOME variable is assigned the path where the JDK is installed on
your computer.
9. Open a DOS window and type \tomcat\bin\tomcat to start Tomcat.
10. Open your browser. Enter http://lQcalhost:8080. The Tomcat home page is
displayed on the screen verifying that Tomcat is running. ·
Optional Nasamajh
. ·-.:-iaTi?'"'
Optional Nasamajh
'The Comp I e t e Re f e r e n c e
• ~•..,t.i, ~ ,.. '. .,...,; -i \.'(,;l(-,·~~A•.t..~~. :.-~t>.,H'. .,;t.,,'r;£~·~~~'l'~"'t.ti<>,l';:'~~~V.~~~~~~'~\~~~~~,~ "t.~·,:_ ,i~:•; ~ :t*. ::~...._~,-~;>\.~ _,,.,.:<>,~f~fi'I:,.•,>.,~ •~ ~•.;;;.l((i.~~,-"'~.\.~~'- ~~~-w~•~vh,f(.<~ij-.,R:l•~•"~~~,;,.,t.,..,,;:;:..-.;),...,.,;.-., :~,;<'~1)~\(,{., I~~~ . ;i'i,.$ \ .;-~-lt 1-1' ~,;, •,·':¥. • .• ..--•
. .
I
Request String
_1"'he bro\vser gene1Aates a user reqt1est string wl1enever the Submit button is,,selecte·d .
111e user req11est string consists of the URL and the query string, as you learned at the ..- -
beginning of tl1is cl·1apter. fiere' s a typical reqt1est stri11g: ·.-'· ·
11 11 11
http: / /"1J.;"v-11tv . j imk.eogh. corr1 / j sp / n1yprogram. j sp? f name= Bc>b & lna:m e= ;, Smith.
Y<)t1:r progran1 P"eeds to parse tl1e qt1ery string to extract val½1es ()f fi~lds that a1·e to
.'1:,e processed b;y your program. Y<J-u ca11 p-ar·se the, qut!ry stri11g by u sir~g methocls of t}1e
JSP requ~st object. . .
Tht~ ge·tPara111~eter(Na-me)·is-thte.1rt~t~l1od ~sed.,~to parse a va.J.1.ii,e of :a ~spec~fic field . .J"'he 1-
ge-tfJaran1eter() method re·q uires a11 argume11t, wh.ich is the na111e of tl1e :field \vr·l()Se _·_ .
v,ilue y'O'U :want t() 1·et1~ieve. . . _. .
1~1e·t' s-say tli.at you \va.n t to retrieve tl1e vall1e of the fnarne field ,a nd the value o.f.thJ~ .
lr1.a111e fielcl in: t.h e previous rE:quest string. Here are the staten1ents that you'll l}ee(l i11
:Jre:11-tr _
Tg·prprbgrar11.: :, ·· .,·
'
'
-
< %!. S tr i ng F irstnarr.e = rec1~1e ·s t . getParameter ( fname) ;
· ~3t J.:- i 1ig L~ stna.rr,e = rec_rt1es t. ge:tPar_ameter ( l :name) ;
. .
{) ..
%"
, ..•
0 ,,
,; :
,. .
·:,
·'
. ~
I11 the fJreviOtlS eXill'nple/ tl1~~ first Sti.:itement t1sed the getPara'm eter() method to copy
· tl1e ,ralL1e of tl1e fnan1e fro111 tl1e req11e;;t s·tring a11d pssign that vali1e to the Firstname .
>
~ .. • ,• •
. • _.....
.- ~~•:.. ••
!' :-
<
~·
-. .; , ..-...;,
,~
..
.
'
.'
. ~
·prc)g·r am once the valt1es are assigned to v·a ria·b-les in yc;ur JSP ·progran1. _ .
11:1e.1·e are foµr pre-d efined implicit objects thc)t ai·e in every JSP program. 1"'.h ese are 1
reqt1est, response, se.s:3ion, and 011t. The previotts example used the requ·e st object's
.getParan1ete1~() metl1od to retrieve elements of the request string. The request object is
a1.1 insta1'1~e: e,)f tl1e HttpSe1·vletR. equest (s,e e t-=:_l].apter 9). 1!1e resp<.)nse object is a11 i11.s tanc:t~
of Http5entletResponse,· and the ses,s~,g n obje~t is_ ~n.sta.11ce·o:f.i-ittJ;Se~sion. Both· of ~-n.
tl1es,~-~-~~e desfr:tb~c:l ~n ~t?tai_! tn Ch3:pter 9: T]ie 011t object is an :_instance of the Jsp \tVriter
that 1S 1ised,to s~nd a:,·r,e.sportse the' cl.ient. ' . . ,. ' '. . . . . . to > • •
Copyil1g a valt1e frotn·a mt11tivalueci field such ·a s a selection list field ca11 be tri ck.y
si11ce 't here are multiple instances of the field na.me, each with a different value. I·Ic)\AJe\ 7er,
·y ou can easily hand.le n1ultivalt1ed fields J)y using the getPararp,ete-1·:Values() 1netl1o(l. .
Tne getParameterValues() metl1ocl is designed to ;return n1t1lt~ple value,s fro1~
the f:ield specified as the. argument to .the getPar~n1eterValues(). I-lere is how the
getParameterValues() is implemented ir1. a_•JSP progran1. •
·
Optional Nasamajh
Optional Nasamajh
Cha p t e r 11 : Ja v a ·.Se r ve r Pa ge s
In this example, we're retrieving the selection list field shown in Listing 11.:-8. The ...
name of the selection list field is EMAILADDRESS, the values of which are copied into ·
an array of String objects called EMAIL. Elements of the array are then displayed in JSP
expression tags.
I
Listing 11-8 <%! String [ EJ.'1AIL = request. getParameterValues ( "EMAILADDRESS ") %>
Selecting <P> <%= EMAIL [0)%> < / P>
a listing <P> <%= EMAIL [1)%> </P>
of fields.
You can parse field names by using the getParameterNames() method. This method
returns an enumeration of String objects that contains the field names in the request
string. You can use the enumeration extracting methods that you learned in Java to
copy field names to variables within your program.
The Quick Reference Guide in Chapter 9 contains a list of other commonly used
HttpSen letRequest class methods that you'll find useful when working with parameters.
Optional Nasamajh
Optional Nasamajh
Optional Nasamajh
Optional Nasamajh
MyCookieName String object to the name of the cookie that needs to be retrieved frotn
the client's hard disk. I call the cookie userID.
Two other String objects are created to hold the name and value of the cookie read
from the client. Also I created an int called found and initialized it to zero. This variable
is used as a flag to indicate whether or not the userID cookie is read.
Next an array of Cookie objects called cookies is created and •c1ssigned the results of
the request.getCookies() method, which reads all the cookies from the client's hard disk
and assigns them to the array of Cookie objects.
The program proceeds to use the get ame() and getValue() methods to retrieve the
name and value from each object of the array of Cookie objects. Each time a Cookie
object is read, the program compares the name of the cookie to the value of the
MyCooki Name String object, ·which is userID.
When a match is found, the program assigns the value of the current Cookie object
to the . I ·Co kieValue String object and changes the value of the found variable from
0 to 1.
After the program reads all the Cookie objects, the program evaluates the value of
the found variable. If the value is 1, the program sends the value of the MyCookieName
and MyCookieValue to the browser, which displays these values on the screen.
The Quick Reference Guide in Chapter 9 contains a list of other co~monly used .
Cookie class methods that you 'll find useful when working'wlth cookies. · ·
Optional Nasamajh
Optional Nasamajh
' t .- ·i>?~} J2 E£ : Th e Co mp I e t e Re f e r e n c e
int found=O;
Cookie [) cookies= request.getCookies();
for ( int i,=O ; i <cooki es . length ; i++) {
CName = cookies[i ) .getName () ;
CVal ue = cookies[i) . getValue();
if (MyCo o kieName .equals (cookieNames [i))) {
found= l;
MyCookieValue = cooki eValue;
Optional Nasamajh
Optional Nasamajh
Chapter l'l:
Optional Nasamajh
Optional Nasamajh
, 396 · J2 EE: Th e Co m p I e t e Re f e r e n c e
- ·-
__J Quick Reference Guide
Syntax Descriptions
Sytax Descriptions
Syntax Descriptions
Optional Nasamajh
Optional Nasamajh
Ch a pt e r 11 : J a va Se r ve r Pa g e s 391.
Syntax Descriptions
abstract Map peekPageScope() Peeks at the top of the page
scope stack.
abstract Map popPageScope() Removes a page scope from
the stack.
abstract void pushPageScope(Map Places a p age scope on the stack.
scopeState)
abstract void removeAttribu te(String name) Uses all scopes to delete an object
reference associated with a name.
ab tract void remove ttribute(String name, Delete an object by name.
int cope)
abstract void setAttribute(String name, Registers a name associated w ith
Object attribute) an object that has page scop e
semantics.
abstract void setAttribute(String n ame, Registers a name associated with
Object o, int scope) an object and scope.
Syntax Descriptions
abstract String getSpecificationVersion() Returns the version number of JSP
Syntax Descriptions
static JspFactory getDefaultFactory () Returns the default JSP factory.
abstract JspEnginelnfo getEnginelnfo() Returns information about the JSP
engine.
Optional Nasamajh
Optional Nasamajh
398 J 2 EE: Th e Co mp I e t e Re f e r e n c e
Syntax Descriptions
_____________________________ _____
sta tic void setDefaultFactory
(Jsp Factory deflt)
Sets the d efault factory.
.. .,._ ......
Table 1 1-5. public abstract class JspFactory extends Object (continued}- ·,.
""""'""-
I Syntax Descriptions
Table
•.
11-6.
-
.L ·-pub(ic
, ,. - , .
ab$tract. class
~ ,
JspWriter
.
extends
,;_ .• ~-
Writer
• •1 , ~,\,
,: : • l•.,
Optional Nasamajh
Optional Nasamajh
Syntax Descriptions
,. ~, . '
Optional Nasamajh
Optional Nasamajh
Syntax Descriptions
Syntax Descriptions
Object evaluate(String attributeName, Evaluates the expression contained in
String expression, Class expectedType, a request.
Tag tag, PageContext pageContext)
String validate(String attributeName, Validates an expression at translation
String expression) tin1e.
Syntax Descriptions
Object resolveVariable(String pName, Resolves a variable ,,vithin the given
Object pContext) context.
Syntax Descriptions
void dolnitBody() Prepares to evaluate the body.
void setBodyContent(BodyContent b) Sets the bodyContent property.
. , ~ • ' ' ·: . ~ • -. -~ ,;\. V' ' • \•, ,,
Table 11-10. public interface BodyTag extends' Iteration Tag
Syntax Descriptions
void setDynamicAttribu te(String uri, Sets a d ynamic a ttribute that is not
String loca!Name, Object value) declared in the Tag Library Descriptor.
Optional Nasamajh
Optional Nasamajh
' .
;,\
Syntax Descriptions
int doAfterBody() Processes the body content.
Syntax Descriptions
I,
,. r.
in t doTag() . Processes a tag.
: Object getParent() Returns the parent of a tag.
. .
void setJspBody(JspFragment jspBody) Sets the body of a tag as a
Jspfragment object.
void setJspContext(JspConte;t pc) Set a page context in the protected ·
jspContext field.
void setParent(Object parent) Sets a parent of a tag.
.
Table 11-14. public interface SimpleTag
~ ..' .., ,
Optional Nasamajh