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

module 4_2

The document provides a comprehensive overview of Java Server Pages (JSP), detailing its functionality, structure, and how it differs from Java servlets. It explains the methods and tags used in JSP, including how to declare variables, define methods, and implement control statements. Additionally, it covers installation requirements and best practices for creating and using JSP in web applications.

Uploaded by

sanjanasonu584
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

module 4_2

The document provides a comprehensive overview of Java Server Pages (JSP), detailing its functionality, structure, and how it differs from Java servlets. It explains the methods and tags used in JSP, including how to declare variables, define methods, and implement control statements. Additionally, it covers installation requirements and best practices for creating and using JSP in web applications.

Uploaded by

sanjanasonu584
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Optional Nasamajh

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

Java ServerPage GSP) is a server-side program that is similar in design and

A functionality to a Java servlet, which is described in the previous chapter. A JSP is


called by a client to provide a web service, the nature of which depends on the J2EE
application. A JSP processes the request by using logic built into the JSP or by calling other
web components built using Java servlet teclmology or Enterprise JavaBean technology, or
created using other technologies. Once the request is processed, the JSP responds by
sending the results to the client.
However, a JSP differs from a Java servlet in the way in which the JSP is written.
As you'll recall from Chapter 9, a Java servlet is written using the Java programming
language and responses are encoded as an output String object that is passed to the
println() method. The output String object is formatted in HTML, XML, or whatever
formats are required by the client.
In contrast, JSP is written in HTMJ;.,, XML, or in the client's format that is interspersed
with scripting elements, directives, and acti,ons comprised of Java programming
language and JSP syntax. In this chapter you'll learn how to create a JSP that can
be used as a middle-level program between clients and web services.

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

Chapter 11: 381

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.

__J JSP Tags


JSP program con sists of a combination of HTML tags and JSP tags. JSP tags define
Ja va code that i to be executed before the output of the JSP program is sent to the
browser.
AJSP tag begins with a <%, which is followed b y }::iva code, and ends with %>.
There is also an Extendable Markup Language (XML) \·ersion o f JSP tags, which are
formatted as <jsp:TagID> </ JSP:TagID>.
JSP tags are embedded into the HTML component of a JSP program and are
processed by a JSP virtual engine such as Tomcat, w hich is discussed later in this
chapter. Tomcat reads the JSP program whenever the program is called by a browser
and resolves JSP tags, then sends the HTML tags and related information to the browser.
Java code associated with JSP tags in the JSP program is executed when encountered
by Tomcat, and the result of that process is sent to the browser. The browser knows how
to display the result because the JSP tag is enclosed w ithin an ope'""' and closed HTML tag.
You'll see how this works in the next section.
There are five types of JSP tags that you'll use in a JSP program. These are as
follows:

■ 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 Complete Reference

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%>.

Variables and Objects


You can declare Java variables and objects that are used in a JSP program by using
the same coding technique as used to declare them in Java. However, the declaration
statement must appear as a JSP tag within the JSP program before the variable or object
is used in the program.
Listing 11-1 shows a simple JSP program that declares and uses a variable. In this
example, the program declares an int called age and initializes the variable with the
number 29. The declaration statement is placed within JSP tag.
You'll notice that this JSP tag begins with<%!. This tells the JSP virtual engine to
make statements contained in the tag available to other JSP tags in the program. You'll
need to do this nearly every time you declare variables or objects in your program
unless they are only to be used within the JSP tag where they are declared.
The variable age is used in an expression tag that is embedded within the HTML
paragraph tag <P>. A JSP expression tag begins with <%=, which is followed by the
expression.
The JSP virtual engine resolves the JSP expression before sending the output of
the JSP program to the browser. That is, the JSP tag <%=age%> is replaced with the
number 29; afterwards, the HTML paragraph tag and related information is sent to
the browser.

Listing 11-1 <HTML>


Declaring <HEAD>
and using a
<TITLE> JSP Programming </TITLE>
variable.
</HEAD>
<BODY>
<%! int age=29; %>
<P> Your age is: <%=age%> </P>
</BODY>
< / HTML>
Optional Nasamajh
Optional Nasamajh

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.

Listing 11-2 <HTML>


Declaring <HEAD>
multiple
variables
<TI'I'LE > JSP Prog r amming < / TI'rLE>
within a single • </HEAD>
JSP tag. <BODY>
<% ! int age=2 9;
fl o at salary;
int empnurnber ;
%>
< / BODY >
< / HTML>

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.

Listing 11-3 <HTML>


Declaring <HEAD>
objects and
<T ITLE> JSP Pr ogramming < / TITLE>
arrays
witl1in a < / HEAD>
single <BODY>
JSP tag. <%! String Name;
String ] Te l e p hone= { "2 0 1 -555-1212 ", "20 1- 55 5 - 44 33 " } ;
S tring Comp a ny = new S tr i ng () ;
Vec t or Assignment s= n e w Ve ctor() ;
i nt[ Grade= {100, 82 ,93};
%>
< / BODY>
< / HTML>

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.

isting 11-4 <HTML>


Defining <HEAD>
and cal ling
<TITLE> JSP Programming < / 'I'ITLE>
a method.
< / HEAD>
<BODY>
<%! boolean curve (in t grade)

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

Chapter 11: Java ServerPages

<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

The Complete Reference

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 .

•!sting 11-6 <HTML>


Using an if <HEAD>
statement
ind a switch <TITLE> JSP Programming </TITLE>
.tatement to </HEAD>
determine <BODY>
which HTML
<% ! int grade=70;%>
. tags and
information <% if (grade > 69) { %>
are to be <P> You passed! </ P>
sent to <%} else { %>
the browse r.
<P> Better luck n ext time. </P>
<%} %>
<% switch (grade) {
case 90 : %>
<P> Your fina l grade is a A </P>
<% break; %>
case 80 : %>
<P> Your final grade is a B </P>
<% break;
case 70 : %>
<P> Your final grade is a C </P>
<% break;
case 60 : %>
<P> Your final grade is an F </P>
<% break ;
}
%>
< / BODY>
</HTML>

Optional Nasamajh
Optional Nasamajh

Chaµ t er 11: J av a Se r , e r r , ; t , 38t

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.

sting 11-7 <HTML>


Using the <HEAD>
for loop, ),
<TITLE> JS P Programming </TITLE>
vhile loop,
and the ' </HEAD>
do ... while <BODY>
:>p to load
HTML
t ables.

Optional Nasamajh
Optional Nasamajh

J2,£,E:: Th e · Com p I e t,e Re f er e nc e

<% ! int [ J Grad~= {100,82,93};


int x=O;
%>
<TABLE> , .

<'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> '

< l"'D>F'irst< /TD>


1

<rrD>Second,< /TD>
. .

<TD>Third</TD>
</TR>
<TR> ,

<% x=O;
do{%>
<TD><%=Grade[x]%></TD>
<%x++;
} v1hile (x<3) %>

Optional Nasamajh
Optional Nasamajh

Chapter 11: Java ServerPages 3119

</ TR>
</TABLE>
</BODY>
< / HTML>

- ..,...... : e:...~.~~~-~r-~..-wa~ 1'/Ct·•.,.•"" • -----------ts._. ..-..-~


•~-• ~

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 .
>
~ .. • ,• •

. • _.....
.- ~~•:.. ••
!' :-
<


-. .; , ..-...;,
,~

..
.
'

.'
. ~

' ... . .{'


. . t)bject. T..,ike\.vise, the second s.t atemertt performs a simila.r fuI1ctior1, but using the vait1e
- ( )f tl1e:l11ame from tl1e reques,t string. You can ttse·request stri11g values tt1roughout' y()ttr

·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.

Parsing Other Information


The request string sent to the JSP by the browser is divided into two general components
that are separated by the question mark. The URL component appears to the left of the
question mark and the query string is to the right of the question mark.
In the previous section you learned how to parse components of the query string,
which are field names and values using request object methods. These are similar to
the method used to parse URL information.
The URL is divided into four parts, beginning with the protocol. The protocol defines
the rules that are used to transfer the request string from the browser to the JSP program.
Three of the more commonly used protocols are HTTP, HTTPS (the secured version of
HTTP), and FTP, which is a file transfer protocol. . ,..
Next is the host and port combination. The host is the Internet Protocol(IP) address
or name of the server that contains the JSP program:.: The port number is the port that
the host monitors. Usually the port is exduded from the request string whenever HTTP
is used because the assumption is the host is monitoring port 80. Following the host
anc port is the virtual path of the JSP program. The server maps the virtual path to the
physical path.
H ere's a typical URL. The http is the protocol. The host is ww_w.jimkeogh.com·.
There isn't a port because the browser assumes that the server is·monitoring port 80.
The virtual path is / jsp/myprogram:jsp. ·

I http:/ /WWW . j imkeogh. com/ j sp/myprogram . j sp

Optional Nasamajh
Optional Nasamajh

The Complete Reference ·

,..,.,. - ~~........ ~..... ~---~• ,-----~____,,.,.,.


... ..._,..........._ .....~~~.·~ .......-----..--.--~
L_J User Sessions
A JSP program must be able to track a session as a client moves between HTML pages
and JSP programs as discussed in Chapter 9. There are three commonly used methods
to track a session. These are by using a hidden field, by using a cookie, or by using a
JavaBean, which is discussed in the next chapter.
A hidden field is a field in an HTML form whose value isn ' t displayed on the
HTML page, as you learned in Chapter 8. You can assign a value to a hidden field
in a JSP program before the program sends the dynamic HTML page to the browser.
Let's say that yourJSP database system displays a dynamic login screen. The
browser sends the user ID and password. to the JSP program when the Submit button
is selected where these paramet~rs are parsed and stored into two memory variables
(see the "Request String" section).
The JSP program then validates the login information and generates another dynamic .
HTM L page once the user ID and password are approved. The new dynamically built
HTML page contains a form that contains a hidden field, 1mong other field s. And the
user ID is assigned as the ,·.,11..1.e to the hidden field.
'When the person selects the Submit button on the new HTML page, the user ID
stored in the hidden field and inform ation in other fields on the form are sent by the
browser to another JSP program for processing.
This cycle continues where the JSP program processing the request string receives
the user ID as a para.meter and then passes the user ID to the next dynamically built
HTML page as a hidden field. In this way, each HTML page and subsequent JSP
program has access to the user ID and therefore can track the session.
The Quick Reference Guide in Chapter 9 contains a list of other commonly used
HttpSession class methods that you'll find useful when working with a session.

c~··-1·c~~kies·---..-·----,-----·- ·-·------,•--1et•--·~~. -....;,,~-·--·-.. . . . . . . . . ~

As you learned in Chapter 9, a cookie is a small piece of information created by a JSP


program that is stored on the client's hard disk by the browser. Cookies are used to
store various kinds of information, such as user preferences and an ID that tracks a
session with a JSP database system.
You can create and rea·d a cookie by using methods of the Cookie class and the .
response object as illustrated in listing 11-9 and in Listing 11-10. Lisbng 11-9 creates
and writes a cool<;ie called userID that has a value of JK1234.
The program begins by initializing the cookie name an_d cookie value and then
passes these String objects as arguments to the constructor of a new cookie. This cookie
is then passed to the addCookie() method, which causes the cookie to be written to the
client's hard disk.
Listing 11-10 retneves a cookie and sends the cookie name and cookie value to the
browser, which displays these on the screen. This program begins by initializing the

Optional Nasamajh
Optional Nasamajh

Chapter 11: Java ServerPages

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. · ·

_istlng 11-9 <HTML>


How to <HEAD>
create a <TITLE> JSP Programming </TITLE>
cookie.
< / HEAO>
<BODY;;,.
<% ! String MyCookieName = "userID";
String MyCookieValue = "JK1234";
response . addCookie(new Cookie(MyCookieName, MyCookieValue}};
. %> .
</BODY>
</HTML>

:sting 11-10 <HTML>


How to read <HEAD>
a cookie. <TITLE> JSP Programming < / TITLE>
</HEAD>
<BODY>
<% ! String MyCookieName = "userID " ;
String MyCookieValu e;
String CName, CVal u e;

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;

if (found ==l) { %>


<P> Cookie name=<%= MyCoo kieNarne %> < / P>
<P> Cookie value=<% = MyCookieValue %> < / P>
<%}%>
; . < / BODY>
~ < / HTML>

:;__I Session Objects


AJSP database system is able to share information among JSP programs within a session
by using a session object. Each time a session is created, a unique ID is assigned to the
session and stored as a cookie.
The unique ID enables JSP programs to track multiple sessions simultaneously
while maintaining data integrity of each session. The session ID is used to prevent
the intermingling of information from clients.
In addition to the session ID, a session object is also used to store other types of
information, called attributes. An attribute can be login infonnation, preferences, or
even purchases placed in an eiectronic sh opping cart.
Let's say that you built a Java database system that enables customers to purchase
goods online. A JSP program dynamically generates catalogue pages of available
merchandise. A new catalogue page is generated each time the JSP program executes.
The customer selects merchandise from a catalogue page, then jumps to another
catalogue page wh ere additional merchandise is available for purchase. Your JSP
database system must be able to temporarily store purchases made from each catalogue
page; otherwise, the sys tem is unable to execute the checkout process. This means that
purchases must be accessible each time the JSP program executes.
There are several ways in which you can share purchases. You might store
merchandise temporally in a table, but then you 'll need to access the DBMS several
times during the session, w hich might cause performance degradation.
A better approach is to u se a session object and store information about purchases
as session attributes. Session attributes can be retrieved and modified each time the JSP
program r uns.

Optional Nasamajh
Optional Nasamajh

Chapter l'l:

Listing 11-11 illustrates how to assign information to a session attribute, In this


example, the program creates and initializes two String objects. One String object is
assigned the name of the attribute and ·t he other String object is assigned a value for the
attribute. Next, the program calls the setAttribute() method and passes this method the
name and value of the attribute.
Listing 11-12 reads attributes. The program begins by calling the getAttribute ames()
method that returns names of all the attributes as an Enumeration.
Next, the program tests whether or not the getAttributeNames() method returned
any attributes. If so, statements within the while loop execute, which assigns the attribute
name of the current element to the AtName String object. The AtName String object is
then passed as an argument to the getAttribute() method, which returns the value of the
attribute. The value is assigned to the AtValue String object. The program then sends
the attribute name and value to the browser.
The Quick Reference Guide in Chap ter 9 contains a list of other commonly used
Htr~Session class methods that you'll fin<l useful when working with a session.

U st ing 11-11 <HTML>


How o <HEAD>
create a <TITLE> JSP Programming </TITLE>
session
attribute.
</HEAD>
<BODY>
<% ! String AtNarne = "Product ";
String AtVa lue = " 1234";
sessi on .setAt tribute (AtName, AtVa lue) ;
%>
</BOD'?->
< / HTML>

Listing 11-12 <HTML>


How to <HEAD>
,ead session
<TITLE> JSP Pro9 ramming < / TITLE>
attributes.
< / HEAD>
<BODY>
<%! Enumeration purchases= sessi o n . g-etAttributeNarnes ( ) ;
while(purchases .hasMoreElements()) {
String AtName = (String) a ttributeNarnes. nextElernent();
String AtValue = (Stri ng) session . getAttribute(AtNarne ); %>
<P> Attribute Name<%= AtNarne %> < / P>
<P> Attribu te Value<%= AtValue %> < / P>
<%} %>
</ BODY>
</HTML>

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

void _jspService(HttpServletRequest request, Corresponds to the bod y of


HttpServletResponse response) the JSP page.

Sytax Descriptions

void jsp Destroy () Automatically invoked when a JSP page is to be destroyed .


'Oid jspIni t() Automatica lly invoked when the JSP page is initialized .

Table 11-2 . public interface JspPage extends Servlet

Syntax Descriptions

abstract Object findAttribute(String name) Returns the value of an attribute.


abstract Object getA ttribute(String name) Returns an object associated with
the name.
abstract Object getAt tribute(String n ame, int Returns an object associated with
scope) the n ame. .
abstract Enumeration Returns all attributes of a scope.
get A ttrib u teNa mes InScope(int scope)
abstract int getAttributesScope(String name) Returns the scope based on name.
abstract Expi'essionEvaluator Provides programmatic access to
getExpressionEv alua tor() the ExpressionEv aluator.
abstract Jsp Writer getOut() Determines if out object value of
a Jsp Writer.

Table 1 1-3J. p~bllc·abstr:a~t class JspCorit!Jxt.~xtends java.lang.Object ~ -_


·. ~~·~:~- . , . .,. ..

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.

Table 11-3. public abstract class JspContext extends Java.lang.Object (continued)

Syntax Descriptions
abstract String getSpecificationVersion() Returns the version number of JSP

Table 11-4. public abstract class JspEnginelnfo extends Object


',
' ..

Syntax Descriptions
static JspFactory getDefaultFactory () Returns the default JSP factory.
abstract JspEnginelnfo getEnginelnfo() Returns information about the JSP
engine.

Table 11-5. public abstract class JspFactory extends Object

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

abstract PageContext Returns an instance of a PageContext.


getPageContext(Serv let serv let,
ServletRequest request,
Ser vletResponse response,
String errorPageURl, boolean
n eed sSession, int buffer, boolean
autoflush)
abstract void releasePageContext Releases an allocated PageContext
(PageContext pc) object.

_____________________________ _____
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

abstract void clear() Resets a buffer.


abs tract void clearBuffer() Resets a b uffer.
abstract void close() Closes an d flushes a stream .
abstract void fl ush() Flvshes a stream.
int getBufferSize() Returns the size of the buffer u sed by the
JspWriter.
abstract int getRemaining() Returns the number of unused bytes in the
buffer.
boolean isAutoFlush() Determin es if a JspWriter is a utoFlushing.
abstract void newLin e() Writes a line separator.

Table
•.
11-6.
-
.L ·-pub(ic
, ,. - , .
ab$tract. class
~ ,
JspWriter
.
extends
,;_ .• ~-
Writer
• •1 , ~,\,

,: : • l•.,

Optional Nasamajh
Optional Nasamajh

Cha p t e r 11 : Ja i .ai e, :e r Pa g e s 399

Syntax Descriptions

abstract void print(boolean b) Prints a boolean value.


.abstract void print(char c) Prints a character.
abstract void print(char[] s) Prints an array of characters.
abstract void print(double d) Prints a double-precision floating-point
number.
abstract void print(float f) Prints a floating-point number.
absh·act Yoid print(int i) Prints an integer.
abstract void print(long 1) Prints a long integer.
abstract void print(Object obj) Prints an object.
abstract void print(String s) Prints a string.
abstract void println() Writes a line separator string to terminate a line.
abstract void println(boolean x) Prints a boolean value with a terminated lin e
abstract void println(char x) Prints a character with a terminated line.
abstract void println(char[] x) Prints an array of characters with a
terminated line
abstract void println(double x) Prints a double-precision floating-point
number with a terminated line.
abstract void println(float x) Prints a floating-point number with a
terminated line.
abstract void println(int x) Prints an integer with a terminated line.
abstract void println(long x) Prints a long integer with a terminated line.
abstract void println(Object x) Prints an Object with a terminated line.
abstract void println(String x) Prints a String with a terminated line.
'...,,. f:,Jf .<\-~ , ~-~ .l .. - _'.;;'~ f' ',.~' ; ,.; ' ,, • ,

Tab~e U-6. .. public abstract cla~s )ftjpWriter extends Writer (continued) ·


• ., ~. ~ . ·: ~ i · • • .. •

,. ~, . '

Optional Nasamajh
Optional Nasamajh

• 400 J2EE: The Complete Reference

Syntax Descriptions

abstrac t void forwa rd(Sfring Redirects the ServletRequest and


relativeUrlPath) ServletResponse to another active
comp onent in the app1ication .
abstract Excep tion getException() Returns the value of the exception objec t.
abstract Object getPage() Returns the value of the p age object.
abstract ServletRequest getRequest() Retun1 the value of the response object.
absh·act ServletResponse getResponse() Re turn s the value of the response object.
abstract ServletConfi g Returns the instance of the ServletConfig.
getServletConfig()
abstract ServletContext Returns the in tan ce of the ServletContext.
getServ letContext()
abstract HttpSession getSession() Returns the \'alue of the session object.
abstract void hand lePageException Redirects an unhandled page level
(Exception e) excep tion to an error page.
abstrac t void handlePageException Makes an unh andled page level exception
(Throwable t) Throwable.
abstract void include(String Processes the resource as part of the
rela tiveUrlPath) current ServletRequest.
abstract void initialize(Ser vlet Initializes an uninitialized PageContext.
serv let, Ser vletRequest request,
ServletResponse response, String
errorPageURL, boolean
needsSession, int bufferSize,
boolean autoFlush)
JspWriter popBod y() Updates the page scope "out" ath·ibute of
the PageContext; and returns the previous
Jsp Wri ter "out" saved by the ma tching
pushBody().
BodyContent p u shBody() Saves the current "out" JspWriter;
updates the page scope "out" attrib ute of
the PageContext; and returns a new
Bod yContent object.
abstract void release() Resets the internal sta te of a PageContext,
fo r potential re use.
r.~- ~ ------.. ------- -----------------"""'
Table U -7. public abstract class PageContext extends JspContext
Optional Nasamajh
Optional Nasamajh

Chapter 11: Java ServerPages 401

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.

Table 11-8. pub/ic interface ExpressionEvaluator

Syntax Descriptions
Object resolveVariable(String pName, Resolves a variable ,,vithin the given
Object pContext) context.

Table 11-9. public interface VariableResolver

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.

Table 11.-11.. public _interface DynamicAttributes

Optional Nasamajh
Optional Nasamajh

' .
;,\

Syntax Descriptions
int doAfterBody() Processes the body content.

Tab'i'e 11-12~ public interface Iteration Tag extends Tag

;;:, ,,.. ...


Syntax Descriptions
void invoke(Writer out, Map params) Executes the fragment and directs all
output to a Writer.

Table 11-13. public interface JspFragment

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

You might also like