Вы находитесь на странице: 1из 23

JSP Tutorial

Tutorial Overview
The prerequisites for the tutorial are:
HTML. You should be able to put together HTML pages.
Java. You should be able to program in Java.
This tutorial teaches JSP b progressing from ver simple e!amples to comple! e!amples.
"dvanced learners ma #ant to do a quic$ revie# of the introductor material and s$ip to the
lessons appropriate to their level.
The steps in the tutorial are outlined belo#:
%. &etting familiar #ith our JSP server
'. Your first JSP
(. "dding dnamic content via e!pressions
). Scriptlets
*. Mi!ing Scriptlets and HTML
+. ,irectives
-. ,eclarations
.. Tags
/. Sessions
%0. 1eans and 2orms Processing
%%. Tag Libraries
%'. 2orm 3diting
%(. Log4in pages
%). 2urther learning
2irst step: &etting familiar #ith our JSP server


JSP Tutorial
Getting Familiar with your JSP server
5f ou do not have a JSP capable #eb4server or application server6 the first step is to do#nload
one. There are man such servers available6 most of #hich can be do#nloaded for free
evaluation and7or development. Some of them are:
1la8i! from ,esiderata Soft#are 91.5 Megabytes, JSP, Servlets and EJBs:
Tom;at from "pache 9Approx 6 Megabytes:
<ebLogic from 13" Sstems 9Approx 4 Megabytes, JSP, Servlets and EJBs:
<ebSphere from 51M 9Approx 1 Megabytes, JSP, Servlets and EJBs:
To ta$e the best advantage of this tutorial6 it recommended that all the material should be tried
out #ith a real server.
=nce ou have a JSP capable #eb4server or application server6 ou need to $no# the follo#ing
information about it:
<here to place the files
Ho# to access the files from our bro#ser 9#ith an http: prefi!6 not as file::
You should be able to create a simple file6 such as
<HTML>
<BODY>
Hello, world
</BODY>
</HTML>
$no# #here to place this file and ho# to see it in our bro#ser #ith an http:// prefi!.
Since this step is different for each #eb4server6 ou #ould need to see the #eb4server
documentation to find out ho# this is done. =nce ou have completed this step6 proceed to the
ne!t tutorial.

>e!t tutorial: Your first JSP page ;ontents

JSP Tutorial
Your first JSP
JSP simpl puts Java inside HTML pages. You can ta$e an e!isting HTML page and change its
e!tension to ?.@sp? instead of ?.html?. 5n fact6 this is the perfect e!ercise for our first JSP.
Ta$e the HTML file ou used in the previous e!ercise. ;hange its e!tension from ?.html? to
?.@sp?. >o# load the ne# file6 #ith the ?.@sp? e!tension6 in our bro#ser.
You #ill see the same output6 but it #ill ta$e longerA 1ut onl the first time. 5f ou reload it
again6 it #ill load normall.
<hat is happening behind the scenes is that our JSP is being turned into a Java file6 compiled
and loaded. This compilation onl happens once6 so after the first load6 the file doesnBt ta$e long
to load anmore. 91ut evertime ou change the JSP file6 it #ill be re4compiled again.:
=f course6 it is not ver useful to @ust #rite HTML pages #ith a .@sp e!tensionA <e no# proceed
to see #hat ma$es JSP so useful.

>e!t tutorial: "dding dnamic content via e!pressions ;ontents

JSP Tutorial
Adding dynamic content via expressions
"s #e sa# in the previous section6 an HTML file can be turned into a JSP file b changing its
e!tension to .@sp. =f course6 #hat ma$es JSP useful is the abilit to embed Java. Put the
follo#ing te!t in a file #ith .@sp e!tension 9let us call it hello.jsp:6 place it in our JSP
director6 and vie# it in a bro#ser.
<HTML>
<BODY>
Hello! The time is now <%= new !"!#$til#D!te%& %>
</BODY>
</HTML>
>otice that each time ou reload the page in the bro#ser6 it comes up #ith the current time.
The character sequences <%= and %> enclose Java e!pressions6 #hich are evaluated at run time.
This is #hat ma$es it possible to use JSP to generate damic HTML pages that change in
response to user actions or var from user to user.
Exercise! <rite a JSP to output the values returned b '(stem#)et*ropert( for various sstem
properties such as !"!#"ersion, !"!#home, os#n!me, $ser#n!me, $ser#home,
$ser#dir etc.

>e!t tutorial: Scriptlets ;ontents
JSP Tutorial
Scriptlets
<e have alread seen ho# to embed Java e!pressions in JSP pages b putting them bet#een the
<%= and %> character sequences.
1ut it is difficult to do much programming @ust b putting Java e!pressions inside HTML.
JSP also allo#s ou to #rite bloc$s of Java code inside the JSP. You do this b placing our Java
code bet#een <% and %> characters 9@ust li$e e!pressions6 but #ithout the = sign at the start of the
sequence.:
This bloc$ of code is $no#n as a ?scriptlet?. 1 itself6 a scriptlet doesnBt contribute an HTML
9though it can6 as #e #ill see do#n belo#.: " scriptlet contains Java code that is e!ecuted ever
time the JSP is invo$ed.
Here is a modified version of our JSP from previous section6 adding in a scriptlet.
<HTML>
<BODY>
<%
// This is ! s+riptlet# ,oti+e th!t the -d!te-
// "!ri!.le we de+l!re here is !"!il!.le in the
// em.edded e/pression l!ter on#
'(stem#o$t#println% -0"!l$!tin) d!te now- &1
!"!#$til#D!te d!te = new !"!#$til#D!te%&1
%>
Hello! The time is now <%= d!te %>
</BODY>
</HTML>
5f ou run the above e!ample6 ou #ill notice the output from the ?'(stem#o$t#println? on the
server log. This is a convenient #a to do simple debugging 9some servers also have techniques
of debugging the JSP in the 5,3. See our serverBs documentation to see if it offers such a
technique.:
1 itself a scriptlet does not generate HTML. 5f a scriptlet #ants to generate HTML6 it can use a
variable called ?o$t?. This variable does not need to be declared. 5t is alread predefined for
scriptlets6 along #ith some other variables. The follo#ing e!ample sho#s ho# the scriptlet can
generate HTML output.
<HTML>
<BODY>
<%
// This s+riptlet de+l!res !nd initi!li2es -d!te-
'(stem#o$t#println% -0"!l$!tin) d!te now- &1
!"!#$til#D!te d!te = new !"!#$til#D!te%&1
%>
Hello! The time is now
<%
// This s+riptlet )ener!tes HTML o$tp$t
o$t#println% 'trin)#"!l$eOf% d!te &&1
%>
</BODY>
</HTML>
Here6 instead of using an e!pression6 #e are generating the HTML directl b printing to the
?o$t? variable. The ?o$t? variable is of tpe !"!/#ser"let#sp#3sp4riter#
"nother ver useful pre4defined variable is ?re5$est?. 5t is of tpe
!"!/#ser"let#http#Http'er"let6e5$est
" ?request? in server4side processing refers to the transaction bet#een a bro#ser and the server.
<hen someone clic$s or enters a CDL6 the bro#ser sends a ?request? to the server for that CDL6
and sho#s the data returned. "s a part of this ?request?6 various data is available6 including the
file the bro#ser #ants from the server6 and if the request is coming from pressing a SC1M5T
button6 the information the user has entered in the form fields.
The JSP ?re5$est? variable is used to obtain information from the request as sent b the
bro#ser. 2or instance6 ou can find out the name of the clientBs host 9if available6 other#ise the
5P address #ill be returned.: Let us modif the code as sho#n:
<HTML>
<BODY>
<%
// This s+riptlet de+l!res !nd initi!li2es -d!te-
'(stem#o$t#println% -0"!l$!tin) d!te now- &1
!"!#$til#D!te d!te = new !"!#$til#D!te%&1
%>
Hello! The time is now
<%
o$t#println% d!te &1
o$t#println% -<B6>Yo$r m!+hine7s !ddress is - &1
o$t#println% re5$est#)et6emoteHost%&&1
%>
</BODY>
</HTML>
" similar variable is ?response?. This can be used to affect the response being sent to the
bro#ser. 2or instance6 ou can call response#send6edire+t% !nother8rl &1 to send a
response to the bro#ser that it should load a different CDL. This response #ill actual go all the
#a to the bro#ser. The bro#ser #ill then send a different request6 to ?!nother8rl?. This is a
little different from some other JSP mechanisms #e #ill come across6 for including another page
or for#arding the bro#ser to another page.
Exercise! <rite a JSP to output the entire line6 ?HelloA The time is no# ...? but use a scriptlet for
the complete string6 including the HTML tags.

>e!t tutorial: Mi!ing scriptlets and HTML ;ontents
JSP Tutorial
Mi!ing Scriptlets and HTML
<e have alread seen ho# to use the ?out? variable to generate HTML output from #ithin a
scriptlet. 2or more complicated HTML6 using the out variable all the time loses some of the
advantages of JSP programming. 5t is simpler to mi! scriptlets and HTML.
Suppose ou have to generate a table in HTML. This is a common operation6 and ou ma #ant
to generate a table from a SEL table6 or from the lines of a file. 1ut to $eep our e!ample simple6
#e #ill generate a table containing the numbers from % to >. >ot ver useful6 but it #ill sho#
ou the technique.
Here is the JSP fragment to do it:
FT"1L3 1=D,3DG'H
FI
for 9 int i G 0J i F nJ iKK : L
IH
FTDH
FT,H>umberF7T,H
FT,HFIG iK% IHF7T,H
F7TDH
FI
M
IH
F7T"1L3H
You #ould have to suppl an int variable ?n? before it #ill #or$6 and then it #ill output a simple
table #ith ?n? ro#s.
The important things to notice are ho# the IH and FI characters appear in the middle of the
?for? loop6 to let ou drop bac$ into HTML and then to come bac$ to the scriptlet.
The concepts are simple here 44 as ou can see6 ou can drop out of the scriptlets6 #rite normal
HTML6 and get bac$ into the scriptlet. "n control e!pressions such as a ?#hile? or a ?for? loop
or an ?if? e!pression #ill control the HTML also. 5f the HTML is inside a loop6 it #ill be
emitted once for each iteration of the loop.
"nother e!ample of mi!ing scriptlets and HTML is sho#n belo# 44 here it is assumed that there
is a boolean variable named ?hello? available. 5f ou set it to true6 ou #ill see one output6 if ou
set it to false6 ou #ill see another output.
FI
if 9 hello : L
IH
FPHHello6 #orld
FI
M else L
IH
FPH&oodbe6 #orld
FI
M
IH
5t is a little difficult to $eep trac$ of all open braces and scriptlet start and ends6 but #ith a little
practice and some good formatting discipline6 ou #ill acquire competence in doing it.
3!ercise: Ma$e the above e!amples #or$. <rite a JSP to output all the values returned b
Sstem.getProperties #ith ?F1DH? embedded after each propert name and value. ,o not
output the ?F1DH? using the ?out? variable.

>e!t tutorial: JSP ,irectives ;ontents
JSP Tutorial
JSP irectives
<e have been full qualifing the !"!#$til#D!te in the e!amples in the previous sections.
Perhaps ou #ondered #h #e donBt @ust import @ava.util.NJ
5t is possible to use ?import? statements in JSPs6 but the snta! is a little different from normal
Java. Tr the follo#ing e!ample:
<%9 p!)e import=-!"!#$til#:- %>
<HTML>
<BODY>
<%
'(stem#o$t#println% -0"!l$!tin) d!te now- &1
D!te d!te = new D!te%&1
%>
Hello! The time is now <%= d!te %>
</BODY>
</HTML>
The first line in the above e!ample is called a ?directive?. " JSP ?directive? starts #ith <%9
characters.
This one is a ?page directive?. The page directive can contain the list of all imported pac$ages.
To import more than one item6 separate the pac$age names b commas6 e.g.
<%9 p!)e import=-!"!#$til#:,!"!#te/t#:- %>
There are a number of JSP directives6 besides the page directive. 1esides the page directives6 the
other most useful directives are include and taglib. <e #ill be covering taglib separatel.
The include directive is used to phsicall include the contents of another file. The included file
can be HTML or JSP or anthing else 44 the result is as if the original JSP file actuall contained
the included te!t. To see this directive in action6 create a ne# JSP
<HTML>
<BODY>
;oin) to in+l$de hello#sp###<B6>
<%9 in+l$de file=-hello#sp- %>
</BODY>
</HTML>
Oie# this JSP in our bro#ser6 and ou #ill see our original hello#sp get included in the ne#
JSP.
Exercise! Modif all our earlier e!ercises to import the @ava.util pac$ages.

>e!t tutorial: JSP ,eclarations ;ontents
JSP Tutorial
JSP ,eclarations
The JSP ou #rite turns into a class definition. "ll the scriptlets ou #rite are placed inside a
single method of this class.
You can also add variable and method declarations to this class. You can then use these variables
and methods from our scriptlets and e!pressions.
To add a declaration6 ou must use the FIA and IH sequences to enclose our declarations6 as
sho#n belo#.
FIP page importG?@ava.util.N? IH
FHTMLH
F1=,YH
FIA
,ate the,ate G ne# ,ate9:J
,ate get,ate9:
L
Sstem.out.println9 ?5n get,ate9: method? :J
return the,ateJ
M
IH
HelloA The time is no# FIG get,ate9: IH
F71=,YH
F7HTMLH
The e!ample has been created a little contrived6 to sho# variable and method declarations.
Here #e are declaring a ,ate variable the,ate6 and the method get,ate. 1oth of these are
available no# in our scriptlets and e!pressions.
1ut this e!ample no longer #or$sA The date #ill be the same6 no matter ho# often ou reload
the page. This is because these are declarations6 and #ill onl be evaluated once #hen the page
is loadedA 9Just as if ou #ere creating a class and had variable initiali8ation declared in it.:
3!ercise: Modif the above e!ample to add another function compute,ate #hich re4initiali8es
the,ate. "dd a scriptlet that calls compute,ate each time.
>ote: >o# that ou $no# ho# to do this 44 it is in general not a good idea to use variables as
sho#n here. The JSP usuall #ill run as multiple threads of one single instance. ,ifferent threads
#ould interfere #ith variable access6 because it #ill be the same variable for all of them. 5f ou
do have to use variables in JSP6 ou should use snchroni8ed access6 but that hurts the
performance. 5n general6 an data ou need should go either in the session ob@ect or the request
ob@ect 9these are introduced a little later: if passing data bet#een different JSP pages. Oariables
ou declare inside scriptlets are fine6 e.g. FI int i G )*J IH because these are declared inside the
local scope and are not shared.

>e!t tutorial: JSP Tags ;ontents
JSP Tutorial
JSP Tags
"nother important snta! element of JSP are tags. JSP tags do not use <%6 but @ust the <
character. " JSP tag is some#hat li$e an HTML tag. JSP tags can have a ?start tag?6 a ?tag
bod? and an ?end tag?. The start and end tag both use the tag name6 enclosed in < and >
characters. The end starts #ith a / character after the < character. The tag names have an
embedded colon character : in them6 the part before the colon describes the tpe of the tag. 2or
instance:
<some:t!)>
.od(
</some:t!)>
5f the tag does not require a bod6 the start and end can be convenientl merged together6 as
<some:t!)/>
Here b closing the start tag #ith a 7H instead of H character6 #e are ending the tag immediatel6
and #ithout a bod. 9This snta! convention is the the same as QML.:
Tags can be of t#o tpes: loaded from an e!ternal tag librar6 or predefined tags. Predefined
tags start #ith jsp: characters. 2or instance6 sp:in+l$de is a predefined tag that is used to
include other pages.
<e have alread seen the in+l$de directive. @sp:include is similar. 1ut instead of loading the
te!t of the included file in the original file6 it actuall calls the included target at run4time 9the
#a a bro#ser #ould call the included target. 5n practice6 this is actuall a simulated request
rather than a full round4trip bet#een the bro#ser and the server:. 2ollo#ing is an e!ample of
sp:in+l$de usage
<HTML>
<BODY>
;oin) to in+l$de hello#sp###<B6>
<sp:in+l$de p!)e=-hello#sp-/>
</BODY>
</HTML>
Tr it and see #hat ou get. >o# change the ?sp:in+l$de? to ?sp:forw!rd? and see #hat is
the difference. These t#o predefined tags are frequentl ver useful.
Exercise! <rite a JSP to do either a forw!rd or an in+l$de6 depending upon a boolean variable
9hint: The concepts of mi!ing HTML and scriptlets #or$ #ith JSP tags alsoA:

>e!t tutorial: JSP Sessions ;ontents
JSP Tutorial
JSP Sessions
=n a tpical #eb site6 a visitor might visit several pages and perform several interactions.
5f ou are programming the site6 it is ver helpful to be able to associate some data #ith each
visitor. 2or this purpose6 ?session?s can be used in JSP.
" session is an ob@ect associated #ith a visitor. ,ata can be put in the session and retrieved from
it6 much li$e a Hashtable. " different set of data is $ept for each visitor to the site.
Here is a set of pages that put a userBs name in the session6 and displa it else#here. Tr out
installing and using these.
2irst #e have a form6 let us call it &et>ame.html
<HTML>
<BODY>
<<O6M M0THOD=*O'T =>T?O,=-'!"e,!me#sp->
4h!t7s (o$r n!me@ <?,*8T TY*0=T0AT ,=M0=$sern!me '?B0=CD>
<*><?,*8T TY*0='8BM?T>
</<O6M>
</BODY>
</HTML>
The target of the form is ?Save>ame.@sp?6 #hich saves the userBs name in the session. >ote the
variable ?session?. This is another variable that is normall made available in JSPs6 @ust li$e
o$t and re5$est variables. 95n the Ppage directive6 ou can indicate that ou do not need
sessions6 in #hich case the ?session? variable #ill not be made available.:
<%
'trin) n!me = re5$est#)et*!r!meter% -$sern!me- &1
session#set=ttri.$te% -the,!me-, n!me &1
%>
<HTML>
<BODY>
<= H60<=-,e/t*!)e#sp->>ontin$e</=>
</BODY>
</HTML>
The Save>ame.@sp saves the userBs name in the session6 and puts a lin$ to another page6
>e!tPage.@sp.
>e!tPage.@sp sho#s ho# to retrieve the saved name.
<HTML>
<BODY>
Hello, <%= session#)et=ttri.$te% -the,!me- & %>
</BODY>
</HTML>
5f ou bring up t#o different bro#sers 9not different #indo#s of the same bro#ser:6 or run t#o
bro#sers from t#o different machines6 ou can put one name in one bro#ser and another name
in another bro#ser6 and both names #ill be $ept trac$ of.
The session is $ept around until a timeout period. Then it is assumed the user is no longer
visiting the site6 and the session is discarded.
Exercise! "dd another attribute ?age? to the above e!ample.

>e!t tutorial: Processing HTML 2orms in JSP ;ontents
JSP Tutorial
!eans and Form processing
2orms are a ver common method of interactions in #eb sites. JSP ma$es forms processing
speciall eas.
The standard #a of handling forms in JSP is to define a ?bean?. This is not a full Java bean.
You @ust need to define a class that has a field corresponding to each field in the form. The class
fields must have ?setters? that match the names of the form fields. 2or instance6 let us modif
our ;et,!me#html to also collect email address and age.
The ne# version of ;et,!me#html is
<HTML>
<BODY>
<<O6M M0THOD=*O'T =>T?O,=-'!"e,!me#sp->
4h!t7s (o$r n!me@ <?,*8T TY*0=T0AT ,=M0=$sern!me '?B0=CD><B6>
4h!t7s (o$r eEm!il !ddress@ <?,*8T TY*0=T0AT ,=M0=em!il '?B0=CD><B6>
4h!t7s (o$r !)e@ <?,*8T TY*0=T0AT ,=M0=!)e '?B0=F>
<*><?,*8T TY*0='8BM?T>
</<O6M>
</BODY>
</HTML>
To collect this data6 #e define a Java class #ith fields ?$sern!me?6 ?em!il? and ?!)e? and #e
provide setter methods ?set8sern!me?6 ?set0m!il? and ?set=)e?6 as sho#n. " ?setter? method
is @ust a method that starts #ith ?set? follo#ed b the name of the field. The first character of
the field name is upper4cased. So if the field is ?em!il?6 its ?setter? method #ill be
?set0m!il?. &etter methods are defined similarl6 #ith ?get? instead of ?set?. >ote that the
setters 9and getters: must be public.
p!+G!)e $ser1
p$.li+ +l!ss 8serD!t! H
'trin) $sern!me1
'trin) em!il1
int !)e1
p$.li+ "oid set8sern!me% 'trin) "!l$e &
H
$sern!me = "!l$e1
I
p$.li+ "oid set0m!il% 'trin) "!l$e &
H
em!il = "!l$e1
I
p$.li+ "oid set=)e% int "!l$e &
H
!)e = "!l$e1
I
p$.li+ 'trin) )et8sern!me%& H ret$rn $sern!me1 I
p$.li+ 'trin) )et0m!il%& H ret$rn em!il1 I
p$.li+ int )et=)e%& H ret$rn !)e1 I
I
The method names must be e!actl as sho#n. =nce ou have defined the class6 compile it and
ma$e sure it is available in the #eb4serverBs classpath. The server ma also define special folders
#here ou can place bean classes6 e.g. #ith 1la8i! ou can place them in the ?+l!sses? folder.
5f ou have to change the classpath6 the #eb4server #ould need to be stopped and restarted if it is
alread running. 95f ou are not familiar #ith setting7changing classpath6 see notes on changing
classpath.:
>ote that #e are using the pac$age name $ser6 therefore the file 8serD!t!#+l!ss must be
placed in a folder named $ser under the classpath entr.
>o# let us change ?'!"e,!me#sp? to use a bean to collect the data.
<sp:$seBe!n id=-$ser- +l!ss=-$ser#8serD!t!- s+ope=-session-/>
<sp:set*ropert( n!me=-$ser- propert(=-:-/>
<HTML>
<BODY>
<= H60<=-,e/t*!)e#sp->>ontin$e</=>
</BODY>
</HTML>
"ll #e need to do no# is to add the sp:$seBe!n tag and the sp:set*ropert( tagA The
use1ean tag #ill loo$ for an instance of the ?$ser#8serD!t!? in the session. 5f the instance is
alread there6 it #ill update the old instance. =ther#ise6 it #ill create a ne# instance of
$ser#8serD!t! 9the instance of the $ser#8serD!t! is called a bean:6 and put it in the session.
The setPropert tag #ill automaticall collect the input data6 match names against the bean
method names6 and place the data in the beanA
Let us modif ,e/t*!)e#sp to retrieve the data from bean..
<sp:$seBe!n id=-$ser- +l!ss=-$ser#8serD!t!- s+ope=-session-/>
<HTML>
<BODY>
Yo$ entered<B6>
,!me: <%= $ser#)et8sern!me%& %><B6>
0m!il: <%= $ser#)et0m!il%& %><B6>
=)e: <%= $ser#)et=)e%& %><B6>
</BODY>
</HTML>
>otice that the same use1ean tag is repeated. The bean is available as the variable named
?$ser? of class ?$ser#8serD!t!?. The data entered b the user is all collected in the bean.
<e do not actuall need the ?'!"e,!me#sp?6 the target of ;et,!me#html could have been
,e/t*!)e#sp6 and the data #ould still be available the same #a as long as #e added a
sp:set*ropert( tag. 1ut in the ne!t tutorial6 #e #ill actuall use '!"e,!me#sp as an error
handler that automaticall for#ards the request to ,e/t*!)e#sp6 or as$s the user to correct the
erroneous data.
Exercise! %: <rite a JSP7HTML set that allo#s a user to enter the name of a sstem propert6
and then displas the value returned b '(stem#)et*ropert( for that propert name 9handle
errors appripriatel.: ': &o bac$ to the e!ercises #here ou manuall modified boolean
variables. 5nstead of a boolean variable6 ma$e these come from a H5,,3> form field that can
be set to true or false.

>e!t tutorial: Tag Libraries ;ontents
JSP Tutorial
Tag li"raries
JSP %.% introduces a method of e!tending JSP tags6 called ?tag libraries?. These libraries allo#
addition of tags similar to sp:in+l$de or sp:forw!rd6 but #ith different prefi!es other than
sp: and #ith additional features.
To introduce ou to tag libraries6 in this tutorial #e use the 1la8i! tag librar as an e!ample.
This tag librar comes bundled #ith the 1la8i! server. 5f ou are not using the 1la8i! Server6 ou
ma @ust #ant to revie# the material to get familiar #ith the snta!6 and continue on to the ne!t
page.
3ach tag4librar #ill have its o#n tag4librar specific documentation. 5n order to use the tag
librar6 ou use the ?taglib? directive to specif #here our tag librarBs ?description? resides.
2or the 1la8i! tag librar6 the 9recommended: directive is as follo#s
<%9 t!)li. prefi/=-.l/- $ri=-/.l/#tld- %>
The ?uri? specifies #here to find the tag librar description. The ?prefi!? is unique for the tag
librar. This directive is saing that #e #ill be using the tags in this librar b starting them #ith
blx:
The 1la8i! tag librar provides a bl!:getPropert tag. This tag can be used to allo# the user to
edit form data. 5n our &et>ame.@sp file6 #e #ill no# add a @sp:use1ean and place the form
inside bl!:getPropert.
The ne# &et>ame.@sp is
<%9 t!)li. prefi/=-.l/- $ri=-/.l/#tld- %>
<sp:$seBe!n id=-$ser- +l!ss=-$ser#8serD!t!- s+ope=-session-/>
<HTML>
<BODY>
<.l/:)et*ropert( n!me=-$ser- propert(=-:->
<<O6M M0THOD=*O'T =>T?O,=-'!"e,!me#sp->
4h!t7s (o$r n!me@ <?,*8T TY*0=T0AT ,=M0=$sern!me '?B0=CD><B6>
4h!t7s (o$r eEm!il !ddress@ <?,*8T TY*0=T0AT ,=M0=em!il '?B0=CD><B6>
4h!t7s (o$r !)e@ <?,*8T TY*0=T0AT ,=M0=!)e '?B0=F>
<*><?,*8T TY*0='8BM?T>
</<O6M>
</.l/:)et*ropert(>
</BODY>
</HTML>
>ote that the bl!:getPropert doesnBt end #ith 7H but is instead terminated b a separate
F7bl!:getPropertH line. This puts all the form input fields inside the bl!:getPropert so the can
be appropriatel modified b the tag librar.
Tr putting a lin$ to &et>ame.@sp from the >e!tPage.@sp6 and ou #ill see that the beanBs data
sho#s up automaticall in the input fields.
The user can no# edit the data.
<e still have a couple of problems. The user cannot clear out the name field. Moreover6 if the
user enters a bad item in the ?age? field6 something #hich is not a valid integer6 a Java e!ception
occurs.
<e #ill use another tag from the 1la8i! tag librar to ta$e care of this. 1la8i! offers a
bl!:setPropert tag that can be used to ta$e care of these problems. .l/:set*ropert( allo#s us
to define an e!ception handler method. 5f an e!ception occurs6 #e can collect an error message
for the user and continue processing.
2ollo#ing is a version of Save>ame.@sp that processes an errors6 and either sho#s the user
&et>ame.@sp again to user can enter the data correctl6 or automaticall for#ards to
>e!tPage.@sp.
<%9 t!)li. prefi/=-.l/- $ri=-/.l/#tld- %>
<%!
.oole!n h!"e0rror1
'trin)B$ffer errors1
p$.li+ "oid errorH!ndler% 'trin) field,
'trin) "!l$e,
0/+eption e/ &
H
h!"e0rror = tr$e1
if % errors == n$ll &
errors = new 'trin)B$ffer%&1
else
errors#!ppend% -<*>- &1
errors#!ppend% -<*>J!l$e for field K-- L
field L -K- is in"!lid#- &1
if % e/ inst!n+eof !"!#l!n)#,$m.er<orm!t0/+eption &
errors#!ppend% - The "!l$e m$st .e ! n$m.er#- &1
I
%>
<%
// J!ri!.les m$st .e initi!li2ed o$tside de+l!r!tion!
h!"e0rror = f!lse1
errors = n$ll1
%>
<HTML>
<BODY>
<sp:$seBe!n id=-$ser- +l!ss=-$ser#8serD!t!- s+ope=-session-/>
<.l/:set*ropert( n!me=-$ser-
propert(=-:-
on0rror=-errorH!ndler-/>
<%
if % h!"e0rror & H
o$t#println% errors#to'trin)%&&1
p!)e>onte/t#in+l$de% -;et,!me#sp- &1
I else
p!)e>onte/t#forw!rd% -,e/t*!)e#sp- &1
%>
</BODY>
</HTML>
>ote that h!"e0rror and errors must be re4initiali8ed each time6 therefore the are being
initiali8ed outside of the declaration.
R"lso notice the use of p!)e>onte/t#in+l$de and p!)e>onte/t#forw!rd. These are li$e
sp:in+l$de and sp:forw!rd6 but are more convenient to use from #ithin Java bloc$s.
p!)e>onte/t is another pre4defined variable that ma$es it eas to do certain operations from
#ithin Java bloc$s.S
Here6 if an error occurs during the processing of .l/:set*ropert(6 #e displa the error and
then include the ;et,!me#sp again so user can correct the error. 5f no errors occur6 #e
automaticall for#ard the user to ,e/t*!)e#sp.
There is still a problem #ith the forms6 the ?age? sho#s up as 8ero initiall rather than being
empt. This can be fi!ed b adding ?empt(?nt=D- to both the .l/:)et*ropert( and
.l/:set*ropert( tags 9bean fields should be initiali8ed to 0.: 5t happens that ?0? is not a valid
value for age6 so #e can use ?0? to mar$ empt strings. 5f ?0? #ere a valid value for age6 #e
could have added ?empt(?nt=EM? 9and made sure to initiali8e the bean fields to 4%.:
"nother small problem is that the ?FHTMLH? tag gets doubled if there is an error and #e end up
including ?&et>ame.@sp?. " more elegant solution is to remove the out.println6 and pass bac$
the error as sho#n
<%
if % h!"e0rror & H
re5$est#set=ttri.$te% -errors-,
errors#to'trin)%&&1
p!)e>onte/t#forw!rd% -;et,!me#sp- &1
I else
p!)e>onte/t#forw!rd% -,e/t*!)e#sp- &1
%>
<e can then do a ?re5$est#)et=ttri.$te? in the ;et,!me#sp6 and if the returned value is
non4null6 displa the error.

>e!t Tutorial: 3diting forms #ithout a tag librar ;ontents
JSP Tutorial
Techni#ues for form editing
" tag librar such as the one that comes #ith the 1la8i! server6 ma not be available in our
environment. Ho# can ou allo# similar features #ithout using a tag librarT
5t is a little tedious6 but it can be done. 1asicall6 ou must edit each HTML tag ourself6 and put
in a default value. The follo#ing e!amples sho#s ho# #e modif &et>ame.@sp to provide
features similar to .l/:)et*ropert( but #ith manual HTML tag editing:
<sp:$seBe!n id=-$ser- +l!ss=-$ser#8serD!t!- s+ope=-session-/>
<HTML>
<BODY>
<<O6M M0THOD=*O'T =>T?O,=-'!"e,!me#sp->
4h!t7s (o$r n!me@ <?,*8T TY*0=T0AT ,=M0=$sern!me
'?B0=CD J=L80=-<%= $ser#)et8sern!me%& %>-><B6>
4h!t7s (o$r eEm!il !ddress@ <?,*8T TY*0=T0AT
,=M0=em!il '?B0=CD
J=L80=-<%= $ser#)et0m!il%& %>-><B6>
4h!t7s (o$r !)e@ <?,*8T TY*0=T0AT ,=M0=!)e
'?B0=F J=L80=<%= $ser#)et=)e%& %>>
<*><?,*8T TY*0='8BM?T>
</<O6M>
</BODY>
</HTML>
"s ou can see6 this simpl involves adding a ?O"LC3? field in the 5>PCT tags6 and initiali8ing
the field #ith an e!pressionA
To handle e!ceptions during input processing6 a simple approach is to use ?'trin)? fields in the
bean6 and do the conversion to the target datatpe ourself. This #ill allo# ou to handle
e!ceptions.

"dding a log4in feature to our pages ;ontents

JSP Tutorial
Protecting your we"site with a login page
Some sites require that all users log4in using a username and pass#ord6 before being able to visit
an page.
This can be done using JSP sessions or servlets6 and in fact this #as a common technique for a
#hile. 1ut starting #ith a ne# release of Servlets specifications 9'.': from Sun6 this feature is
no# ver simple to implement.
5t is no longer necessar to use JSP techniques to provide login7pass#ord protection6 but it is still
a ver common requirement of #eb4sites6 therefore a brief overvie# is provided here.
To pass#ord4protect our site6 ou @ust need to design a login page. This page can be as simple
or complicated as ou need it to be. 5t must contain a <<O6M> tag6 #ith the M0THOD set to *O'T
and the =>T?O, set to ?Nse+$rit(N+he+G?.
<<O6M M0THOD=*O'T =>T?O,=Nse+$rit(N+he+G>
The target Nse+$rit(N+he+G is provided b the application server6 and does not need to be
coded.
The form must contain t#o <?,*8T> fields6 named N$sern!me and Np!ssword respectivel for
the username and pass#ord. Tpicall6 the username field #ill be a T0AT input field6 and the
pass#ord field #ill be a *=''4O6D input field.
"fter this6 ou must tell our application server to pass#ord protect our pages using the login
page ou have provided. The details #ill var from server to server6 but a good implementation
#ill provide ou hoo$s that ou can use6 for e!ample6 to match usernames and pass#ords against
a database. 93.g.6 in 1la8i! ou can suppl an implementation of the interface
desisoft#deplo(#=$th>he+G to chec$ usernames and pass#ords against a database or other
sources.:

;onclusion: Material for further learning ;ontents
JSP Tutorial
Further learning
The JSP tutorial presented here covers the most useful JSP programming constructs.
The tutorial is focused on being practical and simple, therefore not all details have
been covered.
Specifcations
When you are comfortable with JSPs and ready to tackle more details, you may fnd
it useful to download the JSP specifcations from Suns JSP page. There is also a JSP
!uick reference card available from this site that can be handy to print out and
keep.
"n item to note is that JSPBs eventuall are turned into servlets6 and though JSPs are much
simpler than servlets6 for some cases servlets are still useful. Therefore ou ma #ant to also
learn about servlets.
Interface Defnitions
"f you need to know e#actly how to do some particular thing in JSP, e.g. how to get
the remote users machine name, or the !uery string, or how to re$direct the users
browser to a di%erent page, or some similar thing, one good place to start looking is
in these interface defnitions&
'ava#.servlet.http.(ttpServlet)e!uest
'ava#.servlet.http.(ttpServlet)esponse
'ava#.servlet.'sp.JspWriter
'ava#.servlet.'sp.Page*onte#t
SQL links
S+, Tutorial
S+, Tutorial
S+, Tutorial
Java Links
Some Java links&
J-uru
JSpin .JSP specifc/

Вам также может понравиться