Download as pdf or txt
Download as pdf or txt
You are on page 1of 259

[ T eam L iB ]

Week 1: At a Glance
1 G ettin g S ta rted!
2 H an dlin g D ata an d O p erators
3 B ra nch in g , Lo opin g, a nd C rea tin g M eth od s
4 R ea din g D ata from W eb Pa g es: B utton s a n d T ext Fields
5 R ea din g D ata from W eb Pa g es: C h eck B ox es, R a d io B utton s, a nd S elect C ontrols
6 C reatin g JS P C o m p on ents: Jav a B eans
7 T ra ck in g U s e rs W ith S essions a n d C ook ies
[ Team L iB ]

[ T eam L iB ]

Day 1. Getting Started!


W elcom e to Java S erv er Pages (JS P)! O v er th e n ext 21 d a ys, y ou'll get a n in -depth g u ided tou r of th e in s
an d outs of JS P. Fro m th e m ost ba sic asp e cts to th e m o st a dva n ced, w e're g oin g to be co m e m asters of
JS P in this boo k. Y ou'v e co m e to th e rig h t place.

If y ou w a n t to d o W eb pro g ra m m in g on th e serv er, the re's ju st n oth in g like JS P. It's easy to g et started
w ith JS P, a n d b eca u se it h as th e in credible pow e r of Java beh in d
it, th ere's n o lim it to h ow far y ou can g o. T radition ally, serv er p ro g ra m m in g w as a
task on ly for exp erts, b u t w ith JS P, th at's all in th e past — no w an y on e can m ake W eb pa ges com e alive as
ne ve r be fore.

Let's dig in to JS P im m e diately. In th is, ou r first day on th e job , w e're g oin g to take a loo k at th ese topics:

 W h at Java S e rv er Pag es can h elp you do


 S ettin g u p you r dev elop m e n t en viro n m en t
 R u n n in g th e To m cat S erver
 H o w w e got h ere: from H T M L to JS P
 B u ildin g an d dissectin g you r first JS Ps
 U n d ersta nd in g JS P sy ntax
 JS P resou rces on lin e

W e're goin g to w ork w ith Java S e rver Pag e s 1.2 in th is book , bu t as y ou'll find , JS P
itself is on ly th e begin n ing . B ecau se JS P lets y o u u se Java to create W e b pa ges on
th e serv er, m u ch of w h a t w e're goin g to stu d y is Java itself, as w e see w h at w e can do w ith JS P. A n d you 'll
fin d th ere's p ractically n o lim it.
[ T eam L iB ]

Week 1 – Page 1
[ T eam L iB ]

What Are JavaServer Pages Good For?


Take a look at Figu re 1.1 , w h ich sh ow s th e h o m e pa ge of D elta A irlin es. N ote th e
U R L at th e top of th e brow ser: http:// w w w .delta.co m /h o m e/in d ex.jsp . T h e JS P in th e
index.jsp portion is th e JS P in Java S e rv er Pag es.

Figure 1.1. The Delta Airlines home page.

It's easy to fin d JS P at w ork every w he re on th e W eb th ese day s. In fact, JS P is beco m in g th e n ew


stan dard for ea sily dev elope d , ea sily m aintain ed W eb ap p lication s.
A s y ou m igh t expect, th ere a re m a n y, m a n y rea son s for JS P 's soa rin g p opu larity, a n d m o re a re bein g
in vented all th e tim e. H ere are a coup le of th in g s th at JS P can d o for
you r W eb p ag e s— th is is ju st a sta rter list, of co u rse:

 M ak in g W eb pa g e s com e alive — T he re are too m a n y static p a ges on th e


Inte rn et alrea dy. W h y a dd yours to th e list? To get n oticed, you r pa ge m u st
be live — it m u st do som eth in g , or offer som e service. W h at better w ay to liven pa ges u p
you rself th an to u se JS P ? N ow you r W eb pa g e s can interact w ith th e u ser in real tim e.
 G e ttin g data fro m th e u ser— A ll th e text fields, radio button s, ch eck bo xes,
an d so on , you see in W eb p a ge s can h old d ata. JS P m ak es it easy to read
th at data back to th e se rv er, an d to sen d W eb p ages th at u se th at d ata back
to th e b row ser, as w e'll see in D ay 4, "R ea din g D ata fro m W eb Pag e s: B utton s an d Fields," an d
D ay 5 , "R ea din g D ata from W eb Pa ge s: C h e ck B ox es, R a dio
B utton s, an d S elect C on tro ls."
 E asier to p ro g ra m — T he re are plenty of server-s ide pro gra m m in g option s ou t th ere, bu t n on e
easier to p rogra m th an JS P. In fact, JS P is sp e cifically
desig n ed to b e easy to pro g ra m , a s y ou'll see today.

Week 1 – Page 2
 M ore p ow er th ro ug h Jav a — JS P lets you ru n Jav a cod e w h en creatin g W eb
pa ges. Th at fa ct alon e m ak es w h at y ou can d o w ith JS P practically bou nd less.
Java is an ev er-expan d ing , n early en d less pro gra m m in g pack a ge, an d JS P
puts it at you r service. A n d you don 't h ave to b e a Ja va expe rt eith er — you
can start sm all, as w e w ill in th is book , bu ildin g u p to w h atev er level y ou
w a nt.
 C onn ectin g to datab ase s— O n e of th e m ost p op u lar th in g s you can do w ith
JS P on th e server is con n ect to data b ases via Ja va. It's n ot as h a rd as y ou
m igh t th in k, an d w e'll see h ow to conn e ct to d a tab ases, ad d ou r ow n d ata to
th e m , get data ou t of th em , an d m ore in th is book.
 Perform a n ce — JS P is b u ilt to perform bette r th a n oth er server -sid e
pro g ra m m in g p acka ges. JS P is b u ilt righ t into th e serv er softw are itself, w h ich
m e an s th at m a n y u sers can access you r W eb pa ge w i th ou t u sin g a lot of extra
m e m o ry or d e gra din g p erform an ce. In som e oth er server -side pro g ra m m in g
pack a g e s, a w h ole ne w pro cess h as to start for ev ery u ser th at a ccesses y ou r
W eb pa g e, a n d if a lot o f u sers a re d ow n lo adin g th at p age, it can brin g th e
serv er to a virtu al h alt.
 S ep aratin g code an d da ta — A v ery big topic in th e p rogra m m in g w orld th ese
days is th e sep a ration o f code a n d d ata, an d JS P fits rig h t into th at. T h e idea
is th at w h en you r JS P p ro g ra m m in g code th at th e server run s is separa te
from th e d ata th at th at cod e w orks on , it's easier to w rite a n d m aintain you r
pro g ra m s. A s w e'll see in th is book, the re a re som e n ew w ays of w orkin g w ith
JS P th at let you sep arate cod e an d data v ery effectively.
 H and lin g cookies— A po pu lar u se of JS P is to w ork w ith cookies, sto rin g
in form ation on th e u ser's m ac h in e. S om e p eo ple love cookies, som e h a te
th e m , bu t th ere's n o d o ub t th at JS P allow s you to u se th e m . W an t to re cord a
u ser's spe cial setting s for you r W eb p ag e? A JS P cookie w ill do th at. Y o u'll see
h ow to w ork w ith coo kies in D ay 7, "T ra ck in g U sers w ith S ession s an d
C ookies."

In ch oosin g JS P, you 've ch osen th e righ t pack a g e for server -sid e pro gra m m in g . Y ou
can do startlin gly pow erfu l th ing s w ith JS P, beca u se JS P h as th e fu ll pow er of Java
beh in d it on th e serv er. For exa m p le, ta ke a loo k at Figu re 1.2 , w h ich sh ow s an
exa m p le w e'll develop la ter in th e b o ok (in D ay 20 , "C reating Im a g es o n th e S e rv er
an d H an dlin g Intern et P ro g ra m m in g ," w h e re you'll learn h ow to create an d draw
im a ges u sin g Java). In th is case, th e u ser can "dra w " a lin e in th e bro w ser u sin g th e
m o u se, an d th e softw a re w e'll develop for th e server w ill actu ally create th e
corresp on d in g im age file (a JP E G file) an d sen d th at im a ge b ack to th e bro w ser, as
you see in th e figu re. T h at's a JP E G im ag e file you're lookin g at in th e figu re, created
in teractively w ith Java on th e serve r th a n ks to JS P.

Figure 1.2. Creating a JPEG image file.

Week 1 – Page 3
Let's g et dow n to bu sin e ss by settin g u p you r o w n dev elop m e n t en viro n m en t in
w h ich to create an d u se JS P ou rselves. T h is dev elop m e n t en viro n m en t w ill give you a
JS P serv er an d allow yo u to d e velop y ou r ow n JS P -en a bled W eb pa g es. A ll th e
softw a re y ou'll n ee d is free, an d you can do w n load it fro m va riou s sites on th e W eb .
[ T eam L iB ]

[ T eam L iB ]

It All Starts with Java


T h e J in JS P is for th e Ja va progra m m in g lan g u age, an d w e're goin g to n ee d Ja va to
ru n JS P. If y ou already h ave a ccess to a W eb server th at run s Java a n d JS P,
cong ratu lation s— you 're all set. O n th e oth er h a n d , if you don 't yet h av e access to
su ch a server, or w an t to de velop you r JS P cod e offlin e on you r ow n com p uter, w e
can set u p ou r ow n de v elop m e n t en viro n m ent.

T h e first th in g to in stall is Java itself, w h ich th e W eb server w ill n ee d to access to ru n


you r JS P code . Java is a pro du ct of S u n M icrosy stem s, an d y ou can d ow n load it for
free from its W eb site. W e're goin g to u se Java 2 S ta nd ard E dition ; th e cu rren t
version is 1.4. (T h at m igh t be diffe ren t w h en y ou read th is, h ow ever — you sh ou ld get
th e latest version of th e Java 2 S ta n d ard E dition S D K , th e S oftw a re D evelop m e n t
K it.) H ere are th e U R L s you 'll n ee d:

 http://java.sun.com/j2se/— T h e h o m e p a g e for Java 2 S ta n d ard E dition .


G o h ere to see y ou r do w n load option s for Java.
 http://java.sun.com/j2se/1.4/download.html— T h e curren t dow n load
pa ge for Java 1 .4. Y ou can also dow n load th e Ja va do cu m entation h ere, w h ich
is a goo d idea.

Week 1 – Page 4
Caution

A llow so m e tim e to d ow n load Jav a — th e executa ble in stalla tion file is 20 –


36M B large, d epen d in g on w h at op eratin g syste m you're u sin g .

T h e in stallation in stru ction s a re on lin e (y ou can view th e m fro m th e d o w n load pa ge).


Ty pically, you ru n a self-extra ctin g executable file, su ch as j2sdk-1_4_0-win.exe in
W in d ow s, or j2re-1_4_0-solx86.sh for th e S olaris ope ratin g system . A fter you
follow th e in stallation in stru ction s, you 'll h ave Java in stalled.
[ T eam L iB ]

[ T eam L iB ]

The Tomcat Server


N ow th at you 've in stalled Java, y ou're h alfw ay th e re. T h e n ext step in creatin g you r
JS P dev elop m e n t en viro n m en t is to in stall a JS P -en abled W eb serv er on you r
com p ute r. T he re's n oth in g co m p lex in this, altho ug h th e idea of in stallin g a W eb
serv er on you r co m p ute r can sou n d a little da u n ting .

T h ere a re a n u m b e r of JS P -en a bled W eb serv ers, an d w e'll u se th e on e th at's


beco m e th e JS P sta nd a rd : th e A p ach e project's To m cat server. T h is server is th e
stan d ard th rou gh o u t th e JS P w orld, an d it's th e on e S u n u ses w h en cre a tin g its JS P
im ple m e ntation .

You can d ow n load th e T om cat serv er at http://jaka rta.a p a ch e.org/tom c at/ ("Jaka rta"
is th e n a m e of th e p roje ct th at T om cat is a p art of). W e'll u se th e m ost recen t
To m cat v ersion availa ble as of th is w riting , version 4.0.3, w h ich su p p orts JS P v ersion
1.2. C urrently, you can dow n load th is version from
http://jak a rta .ap a ch e.org/b uilds/jak a rta -to m cat-4.0/release/v4 .0.3/b in / . Ju st pick
th e ap p ropriate v ersion for you r system , su ch a s jakarta-tomcat-4.0.3.zip for
W in d ow s, an d u n zip it in a directo ry of y ou r ch oosing .

Note

In th is book, th e Z ip file w ill be copied to th e W ind o w s directo ry C:\tomcat


an d un zipp ed th ere, w h ich creates th e directory C:\tomcat\jakarta-
tomcat-4.0.3, an d plen ty of sub d irectories un d ern eath it. Y ou m ig h t w an t
to u se th e sa m e directory stru ctu re to m ak e it easier to follow th e
exa m p les w e'll develop (su b stitu te / for \ in U n ix).

T h at in stalls T om cat— n ow let's take a loo k at w h at w e'v e g ot.

Week 1 – Page 5
The Tomcat Directory Structure

A great deal of th is boo k h as to do w ith u n d erstan d in g h ow


th e stan d ard JS P server, T o m cat, w ork s. F or th e sa ke of
referen ce — so y ou can com e b ack to th is in form ation as you
pro g ress throu g h th e b o ok — h ere's th e directo ry stru ctu re th at
un zippin g T o m cat creates (th e "classes" he re re fer to Java
classes; for Java code to be accessible, it m u st be in a class,
an d you 're goin g to see m o re a b ou t classes in D ay 6,
"C reatin g JS P C o m p on e nts: JavaB e an s"):

jakarta-tomcat-4.0.3
|__bin Binary executable files
|__classes Classes available to all Web applications
|__common Classes available to internal classes and
Web applications
| |__classes Common Java classes
| |__lib Common Java classes in Java Archive (JAR)
format
|__conf Configuration files (such as passwords)
|__jasper JAR files used to process and run JSP
pages
|__lib JAR files available to Web applications
|__logs The server's log files
|__server Internal Tomcat classes
|__webapps Directory for Web applications
|__work Scratch directory for holding temporary
files

W e'll get m ore fa m iliar w ith th is directo ry stru c tu re w h en w e sta rt u sin g it in depth in
th e co m in g d ays.

N ote in particu lar th e webapps directo ry, w h ich is w he re th e W eb a pp lica tion s you
create g o so th ey're acc essible to th e b row ser. For in sta n ce, th e exa m p les fro m D a y
1 w ill go into th e ch01 directory w e'll add to webapps:

webapps
|__ch01 Our folder for Day 1 examples

T h e directory contain in g W eb a pp lication s m u st also contain a directo ry n a m e d WEB-


INF, w ith tw o sub d irectories, classes an d lib. WEB-INF, classes, an d lib m igh t all
be e m pty, bu t T o m cat w ill expect th em to be th ere b e fo re run n in g you r a p p lication :

webapps
|__ch01 Our folder for Day 1 examples
|__WEB-INF Information about Day 1's Web
applications
|__classes Java classes used by Day 1's Web
applications
|__lib JAR files used by Day 1's Web
applications

Week 1 – Page 6
W e'll create th e ch01, WEB-INF, classes, an d lib directo ries w e n ee d in a m o m ent,
bu t first, let's sta rt T o m cat itself.

Note

T h ere w ill be plenty of p ath specification s in this book, su ch as jakarta-


tomcat-4.0.3\webapps\ch01 in W in d ow s, or jakarta-tomcat-
4.0.3/webapps/ch01 in U n ix. If you 're u sin g W ind o w s an d you see forw ard
slash es (/) in a path , it's a U n ix path — ju st sub s titute b ackslash es ( \)
in stead, an d vice v ersa if y ou're a U n ix u ser w h o sees forw a rd slash es. T h e
To m cat directo ry stru ctu re is th e sa m e on all operatin g syste m s, exce p t for
ope ratin g system -d epen den t sy ntax, like u sin g \ in stead of /.

Starting Tomcat

W h en y ou sta rt T om cat, you m u st first set a few en v iro n m en t


variable s. A m o n g oth er th ing s, th ese en viro n m e n t varia bles
w ill let To m c at fin d Java so it can ru n ou r JS P cod e.

Tip

You can g et th e details on th ese en viro n m en t v ariables by tak in g a look at


th e readme.txt do cu m e n t th at com e s w ith T om cat, w h ich w ill refer you to
th e docu m e n t running.txt. It's also ava ila ble on lin e at
http://jak a rta .ap a ch e.org/to m cat/to m c a t -4.0 -d oc/R U N N IN G .tx t.

In p a rticu lar, th e en viron m en t varia bles to set a re th e follow in g :

 JAVA_HOME points to th e in stallation directo ry of Java; for ex a m p le, th at m ig h t


be C:\jdk1.4 in Windows.
 CATALINA_HOME points to th e in stallation directo ry of T o m cat; for exa m p le,
C:\tomcat\jakarta-tomcat-4.0.3 (you g et th is path w h en you un zip
To m cat 4.0.3 in C:\tomcat).
 PATH h olds th e search p ath th e co m p uter's op eratin g syste m w ill search for
pro g ra m s to run . M ak e su re y ou add Jav a 's bin directo ry to y ou r p ath — for
exa m p le, you w ou ld ad d C:\jdk1.4\bin to th e path if Java w as in stalled to
C:\jdk1.4.

T h e w a y you actu ally set th ese va ria bles va ries by o p eratin g syste m . F o r exa m p le, to
set JAVA_HOME to C:\jdk1.4 in W in d ow s 200 0 P rofession al, you can select S tart,
S ettin g s, C ontro l Pan el to op en th e control p an e l, an d do u b le -click th e S yste m icon
in th e con tro l p an el. N e xt, click th e A d van ced tab as y ou se e in Figu re 1.3 . D oin g so

Week 1 – Page 7
open s th e E n viro n m en t V aria bles dialog box; click th e N ew button in th e S y stem
V aria bles p art, op en in g th e N ew S y stem V aria ble dialog you see in Figu re 1.4 .

Figure 1.3. The Advanced tab in the System Properties dialog in


Windows 2000 Professional.

Figure 1.4. Setting an environment variable in Windows 2000


Professional.

Week 1 – Page 8
You can ente r th e n ew settin g for JAVA_HOME a s you see in Figu re 1.4 : C:\jdk1.4. T o
ch a ng e th e PATH va ria ble, w h ich already exists, you click th e E dit b utton in th e
S ystem V aria bles section a n d edit th e PATH variable to add th e Jav a bin directo ry to
it. For exa m p le, if you r path loo ks som eth in g like th is:

C:\WINDOWS;C:\Program Files

you 'd a dd a sem icolon an d th e p ath of th e Java bin directo ry:

C:\WINDOWS;C:\Program Files;C:\jdk1.4\bin

H o w y ou set en viro n m e n t varia bles depe n d s on th e op eratin g syste m , h ow ev er; for


exa m p le, th e process is com p letely differen t in W in d ow s 95 /98, w h ere you m u st edit
th e C:\autoexec.bat file in stea d.

Tip

You can fin d excellen t in stru ction s on settin g en viro n m e n t va ria bles for a ll
th e op eratin g system s th at ru n Java fro m th e Java dow n load p a ge , in th e
in stallation n otes. H ere's th e U R L w ith lin ks for variou s op eratin g system s:
http://jav a.su n .c om /j2 s e/1.4/install-opera tin gsyste m n a m e.htm l (for
exa m p le, for W in d ow s, th e U R L is http://jav a.s u n .co m /j2se/1.4 /in stall-
w in d ow s.htm l) . T h ese n otes are all abou t settin g th e PATH en viro n m e n t
variable, bu t you can u se th e m to set an y en viro n m en t va riable.

You can also set th e en viro n m e n t va ria bles w h e n y ou sta rt T om cat itself, an d you
m igh t fin d th at m ore con ven ient. Y ou'll fin d th e direction s for startin g T om cat in th e
running.txt docu m e n t th at co m es w ith To m ca t.

To start T om cat, y ou'll n ee d a co m m a n d p ro m pt. In W in d ow s, th at's th e D O S


pro m pt, w h ich you get in a D O S w in d ow . Y ou ca n open a D O S w in d ow b y selectin g
S tart, P ro g ra m s, A ccess ories, C o m m a n d P ro m p t in W ind o w s 20 00 P rofe s sion al;
S tart, P ro g ra m s, M S -D O S P ro m p t in W in d ow s 98, an d so on .

Week 1 – Page 9
To set th e en viro n m e n t variables (if you h av en 't set th em alread y), you can type th e
follow in g at th e D O S p rom pt. (M a k e th e v ersion nu m b ers an d p ath s m atch w h at you
h ave in stalled, of course . )

C:\>SET JAVA_HOME=C:\jdk1.4
C:\>SET CATALINA_HOME=C:\tomcat\jakarta-tomcat-4.0.3
C:\>SET PATH=%PATH%;C:\jdk1.4\bin

N ote th e last statem e nt, SET PATH=%PATH%;C:\jdk1.4\bin, w h ich is an easy w ay of


ad d in g C:\jdk1.4\bin to th e en d of th e path , w ith ou t m ak in g a n y ch an g es to th e
rest of th e p ath .

In th e U n ix bash sh ell, th is m ig h t loo k so m eth in g like th is in you r .bashrc file (start


a n ew sh ell to m ake th e ch a n g es take effect):

JAVA_HOME=/jdk1.4
export JAVA_HOME
SET CATALINA_HOME=/tomcat/jakarta-tomcat-4.0.3
export CATALINA_HOME
SET PATH=/usr/local/bin:/jdk1.4/bin
export PATH

In th e U n ix tcsh sh ell, it m ig h t loo k like th is in you r .tcshrc file (start a n ew sh ell to


m ake th e ch a n ge s tak e effect):

setenv JAVA_HOME /jdk1.4


setenv CATALINA_HOME /tomcat/jakarta-tomcat-4.0.3
setenv PATH /usr/local/bin:/jdk1.4/bin

A fter th ese en viro n m en t variables are set, w e're ready to sta rt T om cat. A g ain , th is
pro cess is op eratin g system -dep e n d ent; see th e T om cat d o cu m en t running.txt for
m o re d etails. In W in d ow s, g o to th e To m cat bin directo ry (th e bin directory is rig h t
un d er th e directo ry th at T om cat un zips itself to, su ch as C:\tomcat\jakarta-
tomcat-4.0.3\bin if T o m cat w as u n zip p ed in C:\tomcat) an d type startup:

C:\tomcat\jakarta-tomcat-4.0.3\bin\>startup

In U n ix, th at co m m a n d m igh t loo k like th is:

/tomcat/jakarta-tomcat-4.0.3/bin/startup.sh

T h at's it— n ow T o m cat is runn in g . In W in d ow s, you'll see a n ew D O S w in d ow op en


an d a m essa g e sim ilar to th is ap p e ar:

Starting service Tomcat-Apache


Apache Tomcat/4.0.3

Week 1 – Page 10
D on't close th is n ew w in dow — th at's w he re T om cat is run n in g . S o h ow d o w e pu t
To m cat to w ork? Y ou 'll n ee d a b row ser, su ch as M icro soft In tern et Explorer (w h ich
you can pick u p free at http:// w w w .m icro soft.c om /w in d ow s/ie/d efa u lt.asp ), or
N etscap e N av igator (fre e at http://b ro w sers.n etsca p e .co m /brow s ers/m a in .tm pl).
R u n th e brow ser n ow a n d enter th e U R L http://localhost:8080/index.html,
w h ich sh ou ld brin g u p th e p age you see in Figure 1.5 .

Figure 1.5. Running the Tomcat server.

A s th e fig u re say s, con g ratu lation s — n ow y ou're run n in g you r


ow n W eb serv er. N ote th e U R L w e'v e u sed —
http://localhost:8080/index.html. T h e localhost part is
th e n a m e of th e W eb se rv er, an d localhost is th e n a m e
reserv ed for W eb serv ers runn in g on you r ow n m ac h in e. 8080
is th e port nu m b e r. E a c h W eb serv er u ses a "p ort" nu m b er to
keep it sepa rate from oth er W eb serv ers. U su ally, W eb serv ers
u se p ort 80 , bu t T o m cat u ses po rt 808 0 so it w on't interfere
w ith oth er W eb servers.

Tip

If T om cat d oesn 't ru n fo r y ou , see th e T ro ub lesh oo tin g section in th e


running.txt docu m e n t th at co m es w ith To m ca t.

Week 1 – Page 11
To stop T o m cat, you u se th e shutdown co m m a nd . It looks som eth in g like th is in
W in d ow s:

C:\tomcat\jakarta-tomcat-4.0.3\bin\>shutdown

an d th is in U n ix:

/tomcat/jakarta-tomcat-4.0.3/bin/shutdown.sh

T h at's ou r first step — g e ttin g T o m cat itself run n ing . W e'v e already m a de pro g ress —
n ow let's see w h eth e r w e can display som e of ou r ow n pa g es u sin g this serv er.
[ T eam L iB ]

[ T eam L iB ]

Creating Web Documents


T h ro ug h ou t th is book, w e'll be creatin g ou r ow n docu m ents — H T M L do cu m e nts, Ja va
docu m e nts, JS P d ocu m e nts, an d so on . T h at m e an s th at w e'll n ee d an e d itor th at can
save plain text files as p art of ou r d ev elop m e n t en viro n m e nt.

You can u se an y editor or ev en w ord processor you like, su ch as W ordP ad in


W in d ow s, o r vi (or eve n pico) in U n ix. T h e m a in poin t h ere is th at you m u st sav e
th e files you create in plain text form at (n ot, for exa m p le, rich text form at, w h ich is
th e defa u lt for som e v ersion s of W ordPa d).

For exa m p le, you can see h ow to u se W ordP ad to create a W eb p ag e n a m e d


ch01_01.html (th at is, E xa m p le 1 fro m D a y 1) in Figu re 1.6 . W h en you sav e it, u se
th e File, S ave A s m en u item , an d select th e T ext D ocu m e n t item in th e S ave A s T ype
box of th e S av e A s dialog box th at ap p ears. W e'll see ho w to op en th is n ew H TM L
docu m e n t in To m cat later in th is D ay.

Figure 1.6. Creating a Web page.

Week 1 – Page 12
Tip

W h en w e d ev elop JS P -e n a bled p ages, w e'll give th em th e exten sion .jsp,


like index.jsp. W h en y ou sav e a file w ith th e e xten sion .jsp in W ordP ad,
it'll try to a dd th e exten sion .txt beca u se it do esn't kn ow abo u t th e .jsp
exten sion , givin g you index.jsp.txt. T o av oid th is, p u t q u otation m arks
aro un d th e n a m e of th e file w h en y ou sa ve it — if you sav e th e file as
"index.jsp", y ou'll get th e file index.jsp, n ot index.jsp.txt.

You can fin d th e H T M L p age cre ated in Fig u re 1.6 in Listin g 1.1 .

Listing 1.1 A Simple Web Page (ch01_01.html)

<HTML>
<HEAD>
<TITLE>
A Web Page
</TITLE>
</HEAD>

<BODY>
Hello there!
</BODY>
</HTML>

Week 1 – Page 13
W h ere can y ou sa ve th is do cu m e n t so you can view it w ith T o m cat? In th is book, it'll
be easiest to store th e exa m p les fro m D ay 1 in a directo ry n a m ed ch01, th e
exa m p les fro m D a y 2 in ch02, an d so on . T h ose directo ries a re sub d irectories of th e
webapps directo ry in th e T om cat directory stru ctu re:

jakarta-tomcat-4.0.3
|__webapps
|__ch01
|__ch02
|__ch03
.
.
.

C reate th e ch01 directo ry n ow — for exa m p le, you can u se th e W in d ow s E xplorer in


W in d ow s for th is pu rp o se. W e'll also n ee d a WEB-INF directo ry un d e r ch01, as w ell as
classes an d lib su b directo ries (ev en th ou g h th ey're e m pty):

jakarta-tomcat-4.0.3
|__webapps
|__ch01
|__WEB-INF
|__classes
|__lib
|__ch02
|__WEB-INF
|__classes
|__lib

C reate th is directo ry stru ctu re for ch01 n ow , an d sav e th e first exa m p le ,


ch01_01.html, in ch01 (th at is, in jakarta-tomcat-4.0.3\webapps\ch01 in
W in d ow s, or jakarta-tomcat-4.0.3/webapps/ch01 in U n ix).

W h at's th e U R L of ou r n ew d ocu m e nt? If w e h a d pu t it in to th e webapps directo ry


itself, it w ou ld be http://localhost:8080/ch01_01.html, bu t be ca u se w e've place d
it in th e webapps\ch01 directory, its U R L is
http://localhost:8080/ch01/ch01_01.html. E nter th at U R L into th e bro w ser n ow ,
an d you sh ou ld see th e resu lt in Figu re 1.7 .

Figure 1.7. Viewing a new document in Tomcat.

Week 1 – Page 14
A n d th a t's it— n ow ou r d ev elop m en t en viro n m e n t is co m p lete. W e'v e g ot Java, w e've
got a JS P serv er, w e've got a brow ser, a n d w e'v e got an editor w ith w h ich to w rite
ou r W eb d ocu m ents (altern atively, you cou ld ju st dow n loa d th e sou rce cod e for th is
boo k an d u se th a t). N ot bad — w e'v e m ad e a g re at deal of p ro g ress.

N ow w e're read y to sta rt w orkin g u p to JS P itself. A n d to do th at, it's a goo d idea to


start by tak in g a look at th e h istory of JS P.

[ T eam L iB ]

[ T eam L iB ]

A Brief History of JSP


To un de rsta n d JS P , y ou h ave to un d erstan d w h e re JS P ca m e fro m . T h e W eb started
w ith H TM L, an d JS P 's h istory sta rts th ere, to o, so th e first step is to take a loo k at
H T M L.

HTML

T h e pa g es into w h ich w e e m b ed ou r JS P a re H y pertext M a rku p Lan gu a ge (H TM L)


pa ges. (T h is book assu m es you a re alrea dy fa m iliar w ith H TM L.) H T M L is a
specification of th e W orld W ide W eb C on sortiu m (W 3C ), an d you can fin d th e official
h o m e p ag e for H T M L at http://w w w .w 3.org/M a rkU p . T h e cu rren t versio n of H T M L is

Week 1 – Page 15
4.01, an d you can fin d H T M L's official specification at http://w w w .w 3.org/T R /htm l4/ .

Tip

If y ou w a n t to b ru sh u p on H TM L , the re a re m an y r esources on th e
Inte rn et. H e re's a go od on e th at lists all H TM L tags an d attributes by
bro w ser version an d w h at th ey d o:
http://w w w .w illc a m .co m /cm at/htm l/ta gs.htm l .

W e've alrea dy seen ou r first H T M L exa m p le, ch01_01.html; th at exa m p le did n't do
an yth in g except sup p o rt a title for th e pa g e a n d display th e text Hello there!:

<HTML>
<HEAD>
<TITLE>
A Web Page
</TITLE>
</HEAD>

<BODY>
Hello there!
</BODY>
</HTML>

T h at's okay as far as it goes, bu t it doesn 't go v ery fa r. T h is pa ge is very static, an d


W eb d evelopers w an ted m o re as th e W eb b eca m e m ore an d m o re p op u lar. A t first,
clien t-side pro g ra m m in g beca m e p op u lar, u sin g script lan g u a ges like Java S cript.

JavaScript

D espite th e n a m e, Ja v a S cript is n ot related to Java. It a ctu ally beg an in 1995, w h en


a N etsca p e C o m m u n ication s C orp oration d e velo p er n a m e d B ren d an E ich w as given a
n ew project to w ork on . T h e origin al idea w as to give N etscape N av igator so m eth in g
extra; E ich to ok a loo k aro un d an d d e cided th at w h at w as n ee d ed w a s a scriptin g
lan gu ag e th at w as fa st an d easy to u se.

H e called h is creation LiveS cript, b u t it w as ren a m ed Java S cript (alth ou gh develop ed by


N etsca p e, S u n h ad th e trad e m a rks on Jav a , so, intere stin g ly, th e n a m e Java S cript
is actu ally a trade m ark of S u n M icrosy ste m s). T h e n ew lan gu a ge w as a nn ou n ced in a
join t press con feren ce w ith N etsca pe an d S u n on D ecem b e r 4, 19 95.

U n like JS P, w h ich is all abo u t p rogra m m in g on th e serv er , scriptin g lan g u a ges like
Java S cript are all abou t pro g ra m m in g on th e clien t side, in th e brow ser. You en close
you r Java S cript code in a <SCRIPT> ele m en t in an H T M L p ag e — for exa m p le, you can
see ho w to u se Java S cript to w rite th e m e ssa g e Hello there! to a W e b pa ge w h ile
th at pa ge is bein g loade d in Listin g 1.2 .

Week 1 – Page 16
Listing 1.2 Using JavaScript (ch01_02.html)

<HTML>
<HEAD>
<TITLE>
A Web Page
</TITLE>
</HEAD>

<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!—
document.write("Hello there!")
//—>
</SCRIPT>
</BODY>
</HTML>

Th is creates th e sa m e resu lts as w e saw for ou r H T M L pa g e in Figu re 1.7 , b u t n ow


w e're u sin g Java S cript to w rite to th e W eb pa g e . C lien t -side pro gra m m in g like th is
can be u sefu l— you 'll se e th at w e can u se Ja va S cript to pass data to JS P docu m ents
on th e serv er— bu t it's extre m ely lim ited. A s a resu lt of secu rity restr iction s, for
exa m p le, you ca n't acce ss files fro m Ja va S cript. A n d beca u se Ja va S cript h as to be
bu ilt into th e brow se r, it h as to be relatively sm all, an d ca n 't contain m ore th an a
sm all fraction of th e po w er of a fu ll pro gra m m in g lan gu a ge like Java. In fac t, du rin g
all th e tim e H T M L an d scriptin g lan g u a ges like Java S cript w ere de veloping , so w as
Java.

Java

Java w as n't origin ally created for th e Inte rn et. T h e first version w as actu ally beg u n in
199 1 an d w ritten in 18 m o nth s at S u n M icrosy stem s. In fact, it w asn 't ev en called
Java in th ose day s; it w as called O ak, an d it w a s u sed intern ally at S u n .

T h e origin al idea for O a k w as to create an op e ratin g system -in d epen d e n t lan g u a ge.
M a n y p rogra m m ers w ere con fin in g th e m selves to pro gra m m in g for th e IB M PC at
th at tim e, bu t th e corpo rate en viro n m en t can in clud e all kin d s of pro gra m m in g
platform s, fro m th e PC to hu g e m ain fra m es, an d th e in spiration beh in d O ak w as to
create so m eth in g th at cou ld be u sed on all th ose co m p ute rs. (A ctu ally, th e origin al
in spiration for O ak w as n ot w h at you 'd call esp e cially gla m oro u s — S u n w anted to
create a lan gu a ge it cou ld u se in con su m er electro n ics. )

O ak w as ren a m ed Java in 19 95 w h en it w as released for pu b lic con su m p tion , an d as


you pro ba bly kn ow , it's beco m e very popu lar. E ven th oug h it's n ot ta rg eted at th e
Inte rn et, y ou can still u se it to display th e m essage Hello there!; Listin g 1.3 details
a sm all Java a p plication n a m e d ch01_03.java th at does ju st th at.

Listing 1.3 A Java Application (ch01_03.java)

public class ch01_03

Week 1 – Page 17
{
public static void main(String[] args)
{
System.out.println("Hello there!");
}
}
To ru n th is exa m p le, y o u m u st com pile ch01_03.java an d
create a Ja va .class file: ch01_03.class. T h e com p ilation
pro cess creates th is .class file, w h ich is w h at you ne ed to ru n
th e pro gra m .

You co m p ile ch01_03.java w ith th e Java co m p iler, w h ich is n a m ed javac. If you 've
set u p y ou r path to in clud e th e Java bin directory as w e saw ea rlier, y ou can u se th e
javac co m m an d at th e com m a n d p ro m p t; h ere's h ow th at m igh t loo k in W ind ow s
(m ake sure y ou're in th e sa m e directo ry as ch01_03.java):

C:\>javac ch01_03.java

T h is creates ch01_03.class, w h ich you can ru n w ith th e Java to ol, sim p ly n a m ed


java. H e re's h ow th at w ou ld loo k in W in d ow s:

C:\>java ch01_03

You can see th e resu lts in Figu re 1.8 , w he re ou r Java a pp lication is display in g th e
m essag e Hello there!

Figure 1.8. Running a Java application.

JS P is based on Jav a , a n d a lot of th is book is a bou t learn in g to u se Jav a. Java 's a

Week 1 – Page 18
big p art of th e In tern et n ow be cau se S u n cou ldn't ign ore th e In tern et, an d Java's
first atte m p t at w orkin g w ith th e Inte rn et w a s to intro du ce a p p lets.

Java Applets

A n a p p let is ju st a Java .class file th at's sp ecially w ritten to


display gra p h ics in a W eb brow s er; you e m b ed a p p lets in W eb
pa ges u sin g th e H TM L <APPLET> ele m ent. W h en ru n in a W eb
pa ge, Java ap p lets are d ow n loa ded auto m atically an d ru n by
th e bro w ser, displayin g th e m selves in th e space you've
allocated for th e m in th e pa ge . T h ey can do an yth in g fro m
w orkin g w ith gra p h ics a n d displayin g an i m ation to h a n d lin g
H T M L text fields an d b utton s.

H ere's an exa m p le called ch01_04.java. T h e Ja va ap p let you see in Listin g 1.4


displays ou r Hello there! m essag e.

Listing 1.4 A Java Applet (ch01_04.java)

import java.applet.Applet;
import java.awt.*;

public class ch01_04 extends Applet


{
public void paint(Graphics g)
{
g.drawString("Hello there!", 60, 100);
}
}

To u se th is ap p let, you m u st first com p ile it w ith javac:

C:\>javac ch01_04.java

T h is creates ch01_04.class, w h ich you can u s e in th e H T M L <APPLET> elem e nt.


H ere's a sa m p le W eb pa ge th at do es th is by settin g aside an area 20 0 x 2 00 pixels in
w h ich to display th e a p p let in Listin g 1.5 .

Listing 1.5 Displaying an Applet (ch01_05.html)

<HTML>
<HEAD>
<TITLE>A Web Page</TITLE>
</HEAD>

<BODY>
<APPLET CODE="ch01_04.class" WIDTH="200" HEIGHT="200"></APPLET>
</BODY>
</HTML>

Week 1 – Page 19
If y ou store th e a p p let, ch01_04.class, an d th is W eb pa g e, ch01_05.html, in th e
webapps\ch01 directo ry , you can see th e a p p let at w ork b y n av igatin g to
http://localhost:8080/ch01/ch01_05.html, as y ou see in Figu re 1.9 .

Figure 1.9. Viewing an applet.

A pp lets can display text like th is, alon g w ith b u tton s, an d so on , b u t like Java S cript,
th ey're very lim ited. In fact, th eir tim e is m o stly past a s ne w client -side a pp lication s
like Flash take ov er; th e stan d ard v ersion of th e n ew est N etscap e N av ig ator n o
long er even sup p orts ap plets by defau lt.

B u t th e Intern et w a s still th ere to con qu e r. W ith th e de m ise of ap p lets, Java tu rn ed


to th e server side of th ing s, an d its first step in th e server w as to im p lem e n t
servlets.

Java Servlets

Java serv lets w ere th e first real atte m p t to get a ccess to th e


fu ll pow er of Ja v a in W e b ap p lication s. Like ap p lets, servlets
are w ritten co m p letely in Java; you com p ile th e m into .class
files, an d — u sin g serv ers like T o m cat th at can su p p ort
servlets— y ou can n av igate directly to tho se .class files an d
view th e resu lts in a bro w ser. In th is w ay, a servlet can alm ost
be th ou gh t of as an ap p let th at run s on th e serv er side (as th e

Week 1 – Page 20
n a m e servlet is m ea n t to im p ly).

Lis ting 1 .6 sh ow s a sa m ple servlet, ch01_06.java, w ritten in pu re Java th at w ill


display ou r m essa g e.

Listing 1.6 A Java Servlet (ch01_06.java)

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ch01_06 extends HttpServlet


{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>");
out.println("A Web Page");
out.println("</TITLE>");
out.println("</HEAD>");
out.println("Hello there!");
out.println("</BODY>");
out.println("</HTML>");
}
}

C o m p ilin g ch01_06.java in to ch01_06.class takes an a dd ition al step w e h av en't


seen be fore. M u ch of th e sup p ort for servlets is n ot bu ilt into th e core of Java, b u t is
stored in a Java A rch ive (JA R ) file n a m e d servlet.jar, w h ich stores m an y
specialized .class files in tern ally.

To m cat com e s w ith servlet.jar (located in th e jakarta-tomcat-


4.0.3\common\lib directory), an d to access it, w e h a ve to set th e CLASSPATH
en viro n m e n t va ria ble, w h ich is specific to Java. A s y ou m igh t expect fro m th e n a m e ,
CLASSPATH in dicates w h ere Java can look for th e .class files it n ee ds w h en gettin g
an ap p lication rea dy to run ; w e're u sin g CLASSPATH becau se w e n e ed a nu m b e r of
servlet .class files stored in servlet.jar. H ere's h ow you can set th e CLASSPATH
variable to in clu d e servlet.jar in W in d ow s (ch a ng e th e path to servlet.jar as
n ee d ed):

C:\>SET CLASSPATH=C:\tomcat\jakarta-tomcat-4.0.3\common\lib\servlet.jar

N ow Ja va can fin d w h at it n ee ds to com p ile serv lets. Y ou m ig h t h ave already set


CLASSPATH to oth er loca tion s, so if y ou ju st w a n t to add servlet.jar to th e

Week 1 – Page 21
CLASSPATH w ith ou t affectin g th e rest of w h at's a lrea dy in CLASSPATH, you can do th e
follow in g in W in d ow s (like othe r en viro n m en t v ariables, y ou sep a rate t h e location s
an d JA R filen a m es in th e CLASSPATH variable w ith se m icolon s):

C:>set classpath=%CLASSPATH%;d:\tomcat\jakarta-tomcat-
4.0.3\common\lib\servlet.jar

You 'll see m ore on u sin g an d settin g CLASSPATH in D ay 11 , "C reatin g M ore Pow erfu l
JavaB ea n s." N ow th at w e h av e acc ess to servlet.jar, n av ig ate to th e d irecto ry
w h ere ou r sa m p le servlet ch01_06.java is loca ted, an d u se javac to create
ch01_06.class (th is assu m es javac is in you r com p ute r's path ) :

C:\>javac ch01_06.java

N ow tran sfer ch01_06.class to jakarta-tomcat-4.0.3\webapps\ch01\classes—


n ote th at w e h av e to u s e th e classes directory for Java classes like ch01_06.class.

A n d th at's it— all w e h av e to do n ow is n av ig ate to


http://localhost:8080/ch01/servlet/ch01_06. Y ou can see th e resu lts in Figu re
1.1 0-n ote th at it loo ks ju st like ou r origin al H TM L do cu m e nt, b u t th is tim e, w e'v e
created th is W eb pa ge o n th e server.

Figure 1.10. Using a servlet.

Week 1 – Page 22
Tip

T h e servlet in http://localhost:8080/ch01/servlet/ch01_06 tells


To m cat th at you 're n av igatin g to a servlet th at it sh ou ld run . W e'll see h ow
w e can m ak e som e con figu ration ch a n g es th at w ill allow u s to om it th at
term in D ay 13 , "C reatin g M ore P ow erfu l S ervlets," m a kin g this U R L sim p ly
http://localhost:8080/ch01/ch01_06.

S ervlets are v ery p ow erfu l, b u t th ey're n ot easy to p ro g ra m . A s a resu lt, th ey


h av en 't b eco m e v ery po pu lar. B u t Java a n d th e Inte rn et w as a m atch m ean t to b e —
an d th e n ext step is JS P .

JSP

JS P is bu ilt on top of servlets, bu t JS P is m u ch e asier to p rogra m , an d th at's th e


w h ole poin t— th at's w h y JS P h as tak en off.

JS P, a sp ecification of S u n M icro sy stem s, first a p p eare d in 199 8. T h e official


version s, 1.0 an d 1.1, b oth ap p e a red in 199 9, a n d both w ere v ery pop u lar. T h e
cu rren t version , 1.2, a p p ea red in 20 01, an d is th e m o st pop u lar im p le m entation yet;
th is is th e version w e'll be u sin g in th is book .

Inte rn ally, each JS P pa g e is actu ally con verted into a servlet by th e server (w e'll see
exactly h ow th at w orks in D ay 13 ). In othe r w ord s, th is is really a boo k abo u t
servlets— b u t th ey're a ctin g entirely beh in d th e scen es.

Note

W e'll also see h ow to create servlets in th is book for so m e a dd ed p ow er —


see D a ys 13 an d 1 4.

Fro m ou r poin t of view , JS P pa ges are sim ply H TM L pa g es w ith e m b e dd ed Java in


th e m . A n d by u sin g JS P, w e av oid all th e h assle of creatin g fu ll-blow n Java
ap p lication s— th e serv er w ill do all th at for u s, tak in g ou r Java sn ipp ets of cod e an d
com p ilin g th e m for u s a uto m atically.

It's clea r th at S u n h a d g otten th e m e ssa g e a bou t m ak in g thin g s easy for th e


pro g ra m m e r w h en it ca m e u p w ith JS P, a n d w e're th e w in n ers. Le t's u s e JS P n ow to
create th e W eb pa g e w e 've already d eveloped — you can see w h at it loo k s like in
Lis ting 1 .7 , ch01_07.jsp (givin g this docu m en t th e exten sion .jsp m e a n s T o m cat
w ill kn ow th at it is a JS P docu m en t an d treat it accordin gly):

Listing 1.7 A JSP Page (ch01_07.jsp)

Week 1 – Page 23
<HTML>
<HEAD>
<TITLE>A Web Page</TITLE>
</HEAD>

<BODY>
<% out.println("Hello there!"); %>
</BODY>
</HTML>
N otice ho w sim p le th is is— it's ju st a sim p le H T M L p ag e , w ith
th e extra ele m en t <% out.println("Hello there!"); %>.
T h is ele m en t is called a scriptlet in JS P, a n d it en closes th e
Java w e u se to w rite th e m essa ge Hello there! to th e W eb
pa ge. Y ou can see th e resu lt by n av igatin g to
http://localhost:8080/ch01/ch01_07.js p, a s y ou see in
Figu re 1.1 1 .

Figure 1.11. Our first JSP.

Tip

A s y ou p rob a bly kn ow , a W eb server w ill sen d th e do cu m e n t n a m ed


index.html to th e b row ser if th at docu m en t is presen t in th e directo ry you
n av igate to on th e serv er, a n d y ou don 't sp ecify an y oth er do cu m e nt.
S im ilarly, index.jsp is th e defa u lt for JS P d ocu m e nts — T o m cat w ill sen d

Week 1 – Page 24
th at to th e b ro w ser if y ou do n't sp ecify an y sp e c ific docu m en t oth erw ise. If
both index.jsp an d index.html are p re sent, th e server ch ooses
index.html as th e de fa u lt.

A n d th at's it— n ow w e'v e created a n d ru n ou r first JS P! Let's see w h at m ak es it tick.

[ T eam L iB ]

[ T eam L iB ]

Dissecting Our First JSP


T h e cru cial lin e in ou r first JS P is th is on e, w h ere it u ses so m e Ja v a cod e :

<HTML>
<HEAD>
<TITLE>A Web Page</TITLE>
</HEAD>

<BODY>
<% out.println("Hello there!"); %>
</BODY>
</HTML>

Th e sp ecial JS P ta gs <% an d %> create a scriptlet, an d w e can en close Ja va code in


th e scriplet. In th is w ay, w e're a ble to em b ed Ja va directly into ou r p ag e 's H TM L .

T h e a ctu al Java w e 're u sin g h ere is out.println("Hello


there!"); (n ote th e sem icolon — all Java state m e nts en d w ith
a sem icolon ). H ere, w e're u sin g th e out obje ct to prin t Hello
there! to th e W eb pa g e before th at pa g e is sen t b ack to th e
bro w ser.
A Java object like out contain s all kin ds of p ro g ra m m in g
pow e r for u s. Fo r exa m ple, h ere w e're u sin g th e out obje ct's
println (w h ich stan d s for "prin t lin e") m eth od to w rite Hello
there! to th e W eb p a ge th at is bein g se n t to th e b row ser. T h e
m eth ods of an object let you p erform actions, su ch as w ritin g
text in a W eb p ag e. B esides m eth o ds, objects also sup p ort
data m e m b ers. Y ou u se data m e m b ers to con fig u re th e
object; for exa m p le, y ou can u se th e out.bufferSize data
m e m b e r of th e out obje ct to set th e size of th e in tern al b u ffer
u sed in th at object. Y ou 'll see m ore on objects, m eth ods, a n d
data m e m b ers in D ay 2, "H an d lin g D ata a n d O p erators," a n d
in detail in D ay 6— all th at's im p orta n t rig h t n ow is to kn ow
th at in JS P, you can u se th e out object's println m eth od to

Week 1 – Page 25
w rite text (in clu din g H T M L!) to a W eb p ag e th at is bein g sen t
back to th e b row ser.

T h e out obje ct is on e of th e obje cts already bu ilt into JS P for ou r u se. N ote th at in
ou r servlet exa m p le, w e h ad to create th is obje ct ou rselves, u sin g tech n iq u es w e'll
loo k at later in th is book:

public class servlet extends HttpServlet


{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.println("<HTML>");
.
.
.

In JS P , th e out object is already created for u s in ord er to m a ke th in g s easier, an d in


th is exa m p le, w e're u sin g th e println m eth od to w rite text to th e W eb pa ge bein g
sen t back to th e b ro w s e r. T h at's all th ere is to it.
[ T eam L iB ]

[ T eam L iB ]

Overview of JSP Syntax


N ow th at w e're actu ally w orkin g w ith JS P, th e n ext step is to get an ov erview of JS P
itself, w h ich m e an s g ettin g an overview of th e JS P sy ntax . A fter w e'v e gotten th e
com p on ents of JS P syntax dow n , everyth in g else w ill fit into th at fra m e w ork. T he re
are fou r differen t typ es of elem e nts you can u se in JS P:

 S criptin g ele m ents— T h is is w h ere you r Java go es, as in th e scriptlets w e'v e


already see n .
 C o m m e nts— C o m m e nts are text y ou ad d to an n otate a JS P d ocu m e n t —
th ey're like n otes to you rself or othe r p ro g ra m m ers. T h ey're ign ored by th e
W eb server, an d a re on ly for p ro g ra m m ers to re ad.
 D irectives— D irectives a re in stru ction s specific to a pa rticu lar p a ge th at let
you set ho w th e pa g e is to b e process ed. F or ex a m p le, you can u se a
directive to ind icate th at you w a n t th e outp u t of a pa ge to be X M L, n ot H T M L.
 A ctions — A ction s let you perform som e op e ration , su ch as in clu din g oth er
pa ges in th e curren t pa ge, or in clu din g Java a p p lets, or w orkin g w ith
JavaB ea n com p on e nts (w h ich you'll see in D ay 6 ). U n like directives, a ction s
are re-evalu ated each tim e th e pa ge is accesse d .

Let's tak e a look at th ese va riou s typ es of JS P elem e nts, sta rtin g w ith scriptin g

Week 1 – Page 26
ele m ents.

Scripting Elements

T h ere a re three typ e s of scriptin g ele m ents in JS P:

 S criptlets— S criptlets ca n contain Java cod e. T h is is th e m o st g en e ral of all


th e scriptin g ele m ents.
 D eclaration s— D eclares a variable or a m eth od for u se in you r cod e.
 E xp ressions— C ontain s a Java exp ression th at th e server evalu ates. T h e
resu lt of th e exp ression is in serte d into th e W eb page.

S c rip tle ts

T h e m ost g ene ral place for you r Ja v a code is in a scriptlet. S criplets h old Java code
frag m e nts, an d a re en closed w ith th e ta gs <% a n d %>. W e'v e alread y se en an
exa m p le of a scriptlet in ou r first JS P, w he re w e u sed th e Java state m e n t
out.println("Hello there!"); to display text in a W eb p a ge:

<HTML>
<HEAD>
<TITLE>A Web Page</TITLE>
</HEAD>

<BODY>
<% out.println("Hello there!"); %>
</BODY>
</HTML>

A scriptlet can h old an y nu m b e r of Java state m e nts, d e clarat ion s, or exp ression s,
m ak in g scriptlets th e m ost g en e ral of all th e JS P scriptin g ele m ents. N o te th at th ey
m u st h old valid Java sta tem ents, so y ou can 't in clud e direct H T M L in a scriptlet.

S criptlets are w h at m a n y JS P p ro g ra m m e rs th in k of w h en th ey th in k o f JS P.
S criptlets are u sed to e m b e d Java cod e in H T M L do cu m e nts, tu rn in g the m into JS P
docu m e nts. B u t b esides scriptlets, you can also u se d eclaration s an d ex pression s.

D e c la ra tio n s

A s y ou'll see tom o rrow , you can store d ata u sin g variables in
Java. Fo r exa m p le, h ere 's ho w y ou can sto re ou r text strin g
Hello there! in a varia ble of typ e String:

String msg = "Hello there!";

T h is declares a n ew va riable n a m ed msg th at h olds th e text Hello there!. In Java,


you m u st d eclare va riab les before you u se the m , givin g th em a n a m e. A fter you 'v e
n a m e d a va ria ble, you can refer to it in you r co d e u sin g th at n a m e.

T h ere's a spe cial set of tags, <%! a n d %>, th at y ou can u se to d eclare v ariables in JS P

Week 1 – Page 27
(y ou can also de clare va riables in scriptlets, w h ich is a m o re com m on th in g to do).
H ere's an exa m p le: In th is case, th e cod e de cla res th e variable msg:

<HTML>
<HEAD>
<TITLE>A Web Page</TITLE>
</HEAD>

<BODY>
<%! String msg = "Hello there!"; %>
</BODY>
</HTML>

N ow you can u se th is n ew v aria ble in a scriptlet; for exa m p le, he re's h ow y ou can
display th e text in msg in th e W eb p ag e u sin g th e out.println m etho d :

<HTML>
<HEAD>
<TITLE>A Web Page</TITLE>
</HEAD>

<BODY>
<%! String msg = "Hello there!"; %>
<% out.println(msg); %>
</BODY>
</HTML>

Th at's w h at th e process loo ks like in overview ; you'll get all th e details on d e clarin g
an d u sin g varia bles in D ay 2.

E x p re s sio n s

E xp ression s a re an y Jav a cod e fra g m en t th at ca n be evalu ated to yield a valu e. Fo r


exa m p le, th e exp ression 2 + 2 yields a valu e of 4, th e exp ression 44 - 10 yields 34,
an d so on . In JS P , you can su rrou n d a Java exp ression in th e tags <%= a n d %>. T h e
exp re ssion 's valu e is in serted into th e W eb pa g e as text by th e server.

You can ev en u se a variable as an exp ression — w h en su ch an exp ressio n is


evalu ated, it yields th e valu e of th e va riable. Fo r exa m p le, if w e h a d sto red ou r strin g
Hello there! in a varia ble n a m ed msg, w e can in sert th at strin g into th e W eb p ag e
sim ply by u sin g th e variable as an exp ression th is w ay:

<HTML>
<HEAD>
<TITLE>A Web Page</TITLE>
</HEAD>

<BODY>
<%! String msg = "Hello there!"; %>
<%= msg %>

Week 1 – Page 28
</BODY>
</HTML>

E xp ression s like th is are sim ilar to scriptlets, b e cau se you can place Jav a cod e in
th e m , bu t th ey h ave to be a ble to resu lt in a sin gle valu e w h en th ey're evalu ated.

E xp ression s like th is are u sefu l for sh orter JS P p ages, bu t n ote th at you don 't h av e to
u se th e m to in sert text into a W eb pa g e — y ou ca n u se m eth o ds like out.println in
scriptlets in stea d.

Comments

You can u se JS P com m e nts to d ocu m e n t w h at's goin g on in a JS P pa ge; th ey act like
n otes to you or othe r p rogra m m ers. C o m m ents are pu rely for th e b en efit of th e
pro g ra m m e rs th at w ork on th e pa g e, b e ca u se th e server w ill strip th em ou t be fore
send in g th e p ag e back to th e b row ser. Y ou en close th e text in a com m e n t betw een
th e tags <%-- an d --%>.

H ere's an exa m p le; in th is case, th e cod e in clu des th e com m e n t Display the
message now. to th is JS P exa m p le:

<HTML>
<HEAD>
<TITLE>A Web Page</TITLE>
</HEAD>

<BODY>
<%-- Display the message now. --%>
<% out.println("Hello there!"); %>
</BODY>
</HTML>

Th is co m m e n t lets you an d oth er p rogra m m e rs kn ow w h at's g oin g on in you r JS P.


You can ad d as m a n y co m m e nts to a JS P as you like — th ey're entirely fo r th e b ene fit
of p ro g ra m m e rs, an d w ill all be strip p ed ou t b e fore th e pa ge is sen t bac k to th e
bro w ser.

Directives

JS P directives let y ou give direction s to th e serv er o n ho w a p ag e sh ou ld be


pro cessed. T h ere a re th ree directives in JS P; w e'll see th e m th ro ug h ou t th e b o ok,
bu t h ere's an ov erview :

 page— T h is directive lets y ou con fig u re an entire JS P p ag e, su ch a s w h eth er


its outpu t is H T M L or X M L. You 'll see m ore on th is directive in D ay 6.
 include— T h is directive lets you in clu d e a n oth e r pa ge or resou rce in a JS P
pa ge.
 taglib— T h is directive lets you u se a set of cu stom JS P tags as defin ed in a
tag library. M ore on taglibs is co m in g u p in D ay 9, "U sin g C u sto m JS P Tags,"

Week 1 – Page 29
an d D ay 10 , C reatin g C u stom Ta g s."

T h e page directive is goin g to be a u sefu l on e for u s a s w e w ork w ith Java. Y ou c an


u se th is directive to con figu re th e pa ge y ou're w orkin g on . Like oth er directives, you
u se th e sp ecial ta gs <%@ an d %> w ith th is directive; to cre ate a page directive, you
also in clu d e th e keyw o rd page like th is: <%@ page ... %>.

H ere's an exa m p le to sh ow w h at th e page directive can do for


u s. In th is case, th e cod e w ants to in d icate th at if th ere's an
error in th e cu rre n t p a g e, th e server sh ou ld sen d an error
pa ge n a m e d error.jsp back to th e brow ser; th at w e're
pro g ra m m in g in Java; th at th e outpu t of th e cu rren t p a ge
sh ou ld be X M L (n ot H T M L, w h ich is th e defau lt — m o re on X M L
in D ay 18 , "U sin g X M L a n d X S LT in JS P"); an d th at w e w a n t to
im port th e java.sql p a cka ge so th at ou r code can w ork w ith
S Q L data ba ses. Y ou'll see m o re on im p ortin g Jav a packa g es
w h en w e sta rt w orkin g w ith Java in depth — Jav a is divided into
m a n y section s called p a cka g e s, a n d to u se a pa rticu lar
section's fun ction ality, y ou m u st im p ort th e corresp ond in g
pack a g e , w h ich m ak es it accessible to y ou r cod e.
You can d o all th at w ith attributes of a sin gle page directive.
In JS P , attrib utes w ork ju st as the y do in H TM L — th ey 're part
of an ele m ent's op en in g ta g, an d h av e th e form
attribute=value. H e re's ho w y ou can u se th e errorPage,
language, contentType, an d import attrib utes of th e page
directive to con figu re th e pa ge as you w an t (note th at th e
page directive com e s at th e v ery b egin n in g of th e pa ge):

<%@ page errorPage="error.jsp" language="java"


contentType="application/xml" import="java.sql.*" %>
<HTML>
<HEAD>
.
.
.

A s y ou can alread y see, th e page directive is go in g to give u s a lot of p rogra m m in g


pow er.

T h e include directive, w h ich looks like <%@ page ... %>, lets y ou in clud e an othe r
pa ge in th e curren t p ag e. W h en y ou in clu d e a p age at a pa rticu lar poin t, th at pa ge's
entire contents a re sim p ly in serted at th at poin t.

T h e taglib directiv e (w h ich loo ks like th is: <%@ taglib ... %>) spe cifies a library
of cu stom JS P ta gs (see D ays 9 an d 10) th at y ou w an t to u se in th e curren t p ag e.
Tag libraries let you d efin e y ou r ow n JS P ta g s. W e're goin g to see ho w to u se th is
directive later, so w e w on't go into th e details n ow .

Note

T h ere a re ru m ors th at scriptlets are g oin g to be ph ased ou t in JS P 2.0 a n d

Week 1 – Page 30
tag libraries w ill be u sed in stead, so it's a g o od idea to m ak e su re y ou k n ow
w h at's goin g on w ith ta g libraries in D ays 9 an d 10.

Actions

JS P also in clud es action s. A s th eir n a m e im p lies, action s let


you p erform som e actio n . U n like directives, a ction s a re re -
evalu ated ea ch tim e th e pa ge is accessed.

T h ere a re tw o type s of a ction s: cu stom an d sta n d ard. C u sto m action s are action s
you create you rself, an d stan d ard a ction s com e bu ilt into JS P. H ere a re th e stan d ard
action s in overview :

 <jsp:forward>— Fo rw a rds th e b row ser req ue st for a n ew W eb pa ge to an


H T M L file, JS P pa ge, or servlet. In th is w ay, you can delegate h ow you r W eb
ap p lication s resp on d to th e br ow ser.
 <jsp:include>— In clu d es a file or W eb co m p on ent. N ote th at
<jsp:include> is differen t th an th e include directive b e ca u se it re-ev alu ates
th e in clu d ed file ev ery tim e th e pa ge is accesse d , w he re a s th e include
directive d o es n ot.
 <jsp:plugin>— L ets yo u ex ecute ap p lets or Ja v aB ean s w ith a plu g -in . If th e
bro w ser d oesn 't h av e th e requ ired plu g -in m od u le, it w ill display a dialog box
ask in g you to d ow n lo ad it. W e'll see th is on e in D ay 13 .
 <jsp:getProperty>, <jsp:setProperty>, an d <jsp:useBean>— , Y ou u se
th ese action s w ith Java B ean com p on ents, a s y ou'll see in D ay 6.

W e'll get all th e details on th ese sta nd ard actio n s w h en w e p u t th em to w ork in th e


com in g days. A n d th at's it— th at co m p letes ou r ov erview of JS P syntax. N ow w e'v e
got th e foun d ation w e'll n ee d to m ov e on to D a y 2 .
[ T eam L iB ]

[ T eam L iB ]

Online JSP Resources


O u r first day of JS P w ork w ill en d by tak in g a look at so m e of th e resou rces a vaila ble to you
on lin e. T h ese resou rces are ava ilable for free, a n d th ey're th ere to au g m e n t you r JS P arsen al.
Let's sta rt w ith JS P itself:

 h ttp :/ / ja v a .su n .c o m / p ro d u c ts / js p — JS P 's official h o m e p a ge.


 h ttp :/ / ja v a .su n .c o m / p ro d u c ts / js p / p ro d u c t.h tm l — A u sefu l ov erview of JS P fro m
Sun.
 h ttp :/ / d e v e lo p e r.ja v a.s u n .c o m / d e v e lo p e r/ te c h n ic a lA rtic le s/ P ro g r a m m in g / jsp / —
A techn ical overview of JS P from S un .
 h ttp :/ / ja v a .su n .c o m / p ro d u c ts / js p / f aq .h tm l# te c h faq — T h e official JS P Freq u ently
A sk ed Q u estion s (FA Q ) list.
 h ttp :/ / ja v a .su n .c o m / p ro d u c ts / js p / ta g s / 1 2 / sy n t a x re f1 2 .h t m l— T h e JS P sy ntax

Week 1 – Page 31
gu ide on lin e.
 h ttp :/ / a rc h iv e s .ja v a .su n .c o m / a rc h iv e s / js p -in te re st.h t m l— A n interactive JS P
m ailin g list.
 h ttp :/ / ja v a .su n .c o m / p ro d u c ts / js p / te c h n ic al.h tm l— T echn ical pa ges an d
docu m e ntation on JS P.
 h ttp :/ / ja v a .su n .c o m / w e b s e rv ic e s / d o c s / e a 1 / tu t o ria l/ d o c / JS P T a g s.h t m l—
C reatin g cu sto m tag s in JS P.
 h ttp :/ / w w w .jsp in s id e r.co m / in d e x . v ie w — You 'll fin d lots of JS P re sources he re.

H ere's a sta rter list of o n lin e JS P tutorials:

 h ttp :/ / ja v a .su n .c o m / p ro d u c ts / js p / d o c s.h tm l— S u n 's Q u ick S tart g u ides to JS P; a


goo d tuto rial.
 h ttp :/ / ja v a .su n .c o m / w e b s e rv ic e s / d o c s / e a 2 / tu t o ria l/ d o c / JS P In tro .h t m l— A S u n
JS P tutorial.
 h ttp :/ / w w w .a p l.jh u .e d u / ~ h a ll/ ja v a / S e rv le t -T u t o ria l/ — A tutorial on servlets an d
JS P.
 h ttp :/ / w w w .jsp tu t.c o m / — A JS P tuto rial site.
 h ttp :/ / w w w .jsp in s id e r.co m / co n te n t/ rc a rn e s / jsp b _ in tro .v ie w — T h e JS P In side r's
tutorial.
 h ttp :/ / ja v a .su n .c o m / p ro d u c ts / js p / tu to ria l/ T a g L ib ra rie s T O C .h t m l— A tag library
tutorial.

A n d h ere a re som e JS P too ls ava ila ble on lin e (n ote th at the y're n ot ne c essarily free, h ow ever) :

 h ttp :/ / ja k a rta .a p ac h e .o rg / jm e t e r/ — A p ac h e's on lin e pe rform a n ce m eter, w h ich can


h elp test JS P p erform a n ce.
 h ttp :/ / w w w .m a c ro m e d ia .co m / so ftw a re / u ltra d e v / — A n autho rin g en viro n m e n t for
JS P ap p lication s.
 h ttp :/ / w w w -4 .ib m .c o m / so ftw a re / w e b s e rv e rs / s tu d io / — IB M 's W ebS p he re S tud io,
w h ich lets you create JS P ap p lication s.

Ev en th ou g h you can also fin d Java 1.4 do cu m e ntation on lin e or d ow n lo ad it, h ere are a few go od
U R Ls to kno w :

 h ttp :/ / ja v a .su n .c o m / j2 s e / 1 .4 / — T h e Java 1 .4 h om e pa g e .


 h ttp :/ / ja v a .su n .c o m / j2 s e / 1 .4 / d o c s / in d e x .h tm l— T h e on lin e Java 1.4
docu m e ntation .
 h ttp :/ / ja v a .su n .c o m / j2 s e / 1 .4 / d o w n lo ad .h tm l — D ow n loa da ble Jav a docu m e ntation .
 h ttp :/ / ja k a rta .a p ac h e .o rg / to m c at/ to m c a t -4 .0 -d o c / s e rv leta p i/ in d e x .h t m l—
S ervlet an d JS P Java ob ject do cu m e ntation ; a goo d on e to h av e. T he se are also in stalled
w ith To m cat on you r h a rd disk — tak e a look at jaka rta-to m cat-4.0.3 \w e b a p ps\to m cat-
docs\serv letap i\in d ex.htm l.
 h t t p :/ / ja v a .s u n .c o m / d o c s/ b o o k s / tu to ria l/ in d e x .h tm l — A Ja va tutorial fro m S u n .

T h ere's also som e To m c at docu m e ntation available:

 h ttp :/ / ja k a rta .a p ac h e .o rg / to m c a t/ — T h e To m cat h o m e p a ge .


 h ttp :/ / ja v a .su n .c o m / p ro d u c ts / js p / to m c a t/ — S u n's pa ge on T o m cat.
 h ttp :/ / ja v a .su n .c o m / p ro d u c ts / js p / to m c a t/ f a q .h tm l— T h e To m ca t FA Q .
 h ttp :/ / ja k a rta .a p ac h e .o rg / to m c at/ to m c a t -4 .0 -d o c / in d e x .h t m l — T h e T om cat
docu m e ntation on lin e. A lso in stalled on you r h a rd disk w h en y ou in stall To m cat; ta ke a

Week 1 – Page 32
loo k at jak a rta-to m cat-4.0.3 \w e ba p p s\to m cat-docs\in d ex.htm l.
 h ttp :/ / ja k a rta .a p ac h e .o rg / to m c at/ to m c a t -4 .0 -d o c / R U N N IN G .tx t— T h e
running.txt docu m e n t th at cov ers h ow to ru n To m cat. A lso in clud e d in th e T o m cat
dow n load.

A s y ou can see, th ere a re a g reat nu m b e r of on lin e resou rces ava ilable on JS P — tak e a loo k!

Note

N o JS P g rou p s h av e ap p eared on U sen et (yet). Ev en so, th e comp.lang.java gro u p s


(like comp.lang.java.help, comp.lang.java.databases, an d so on ) can offer a lot of
Java h elp.

[ T eam L iB ]

[ T eam L iB ]

Summary
In ou r first day w orkin g w ith JS P, w e'v e com e fa r. W e'v e gotten an idea of w h at JS P
is goo d for, a n d ho w it's u sed. W e'v e seen th at JS P gives u s th e po w e r of Java o n th e
W eb server, w h ich is an in co m p arable asset.

W e've also tak en a look at w he re JS P ca m e fro m , an d h ow it develop e d . W e'v e seen


th at as th e W eb h a s ev olved, Java h as b een a p art of th e pictu re — first w ith ap plets,
th en servlets, an d n ow JS P. A p p lets w e re n ice, bu t lim ited; servlets a re very
pow erfu l bu t co m p lex. JS P gives u s th e b est of both w orlds: T h ey're b o th very
pow erfu l (th ey're con v erted to servlets b efo re th ey're ru n ) an d ea sy to w rite.

You 'v e also in stalled th e T om cat serv er an d g otten it run n in g , a n d bu ilt th e


dev elop m e n t en viro n m e n t (Java, T om cat, b row s er, an d an editor) you 'll be u sin g in
th e co m in g d ays.

W e've also de veloped a n d ru n ou r first JS P. In stead of h av in g to w rite ev eryth in g in


Java, w e w ere a ble to sim p ly in sert th e Ja va w e w anted i nto an H T M L p age. T h at's
th e w h ole gen iu s of JS P — you u se an H T M L b a ckbon e a n d ju st a dd th e Java you
n ee d. A s w e've also see n , JS P offers a w h ole se t of b u ilt-in objects, w h ich m ea n s w e
can get aw ay w ith ev en less Java b eca u se w e don't h av e to create tho se objects
ou rselves.

W e also to ok a loo k at th e JS P sy ntax in overview h ere — so m e of w h ich m ig h t n ot


h ave m ad e a g reat deal of sen se y et. (B u t don 't w orry, th at's w h y th is is D ay 1 — it's
all com in g u p in depth in th e n ext d a ys.)

A n d th at's it— w e'v e sta rted ou r in -depth g u ided tou r of JS P, an d bu ilt th e foun d ation
w e'll n ee d in th e co m in g days. T o m o rrow , y ou'll see m ore d etails, su ch a s h ow to

Week 1 – Page 33
w ork w ith data an d ope rato rs in JS P, an d you 'll start w ritin g so m e real c od e.

[ T eam L iB ]

[ T eam L iB ]

Q&A

Q1: D o I h a v e to u s e th e T o m c a t se rv e r? A re n 't th e re a n y o th e r JS P -
e n a b le d W e b s e rv e rs o u t th e re ?

A1: T h ere sure a re — take a loo k at http:// klo m p .org /gn ujsp/ a n d
http://w w w .ca uch o.co m / for so m e oth er JS P W e b servers.

Q2: H o w c a n I fin d o u t w h eth e r m y In te rn et s e rv ic e p ro v id e r su p p o rts


JS P ?

A2: T h e b est w a y is sim p ly to ask you r IS P's tech su p p ort. If the y don 't
sup p ort JS P , su g g est to th em th at th ey con sider it — tell th e m th at JS P is
gro w in g all th e tim e a n d th at oth er u sers w ill soo n b e ask ing . M a n y of th e
larger com m ercial W eb serv ers offer so m e kin d of JS P sup p o rt the se da ys.

[ T eam L iB ]

[ T eam L iB ]

Workshop
T h is w orksh op tests w h eth er you un d erstan d all th e con cepts y ou learn ed toda y. It is
very h elpfu l to kn ow an d un d ersta n d th e an sw e rs b efore startin g tom o rro w 's lesson .
You can fin d th e an sw e rs to th e qu iz q u estion s in A p p en d ix A .

Quiz

1: C an you trace th e dev elop m en t of JS P fro m H T M L p ag e s a s y ou sa w to d ay?


K n ow in g th is h istory w ill help explain a great d e al w h en it com es to w orkin g
w ith servlets later in th e book.

2: W h at a re th e fou r diffe ren t type s of JS P ele m en ts discu ssed today ?

3: H o w m a n y differen t typ es of scriptin g ele m ents are th e re in JS P? W h at are


th ey?

4: W h at a re th e tag s you u se for th e th ree diffe ren t types of JS P sc riptin g


ele m ents?

Week 1 – Page 34
5: W h at a re th e th ree JS P directive type s?

Exercises

1: Take a loo k at th e JS P resou rces given in th e topic "O n lin e JS P R esou rces"
an d eith er b o ok m a rk or dow n loa d you r fav orit es. C o m p ilin g a list of rea dy
resou rces like th at can be a big h elp in you r JS P dev elop m ent. You m igh t
ev en w a n t to try a few of th e JS P tuto rials.

2: U se th e JS P exp ression <%= new java.util.Date() %> in a w elco m e


m essag e in a n ew JS P p age. T h is exp ression w ill in sert th e cu rren t date an d
tim e, perm ittin g you to cu sto m ize y ou r w elcom e pa ge .

[ T eam L iB ]

[ T eam L iB ]

Day 2. Handling Data and Operators


W elcom e to D ay 2 ! T od ay, you 'll see ho w to ge t dow n to th e b rass tack s of JS P
pro g ra m m in g as w e see h ow to w ork w ith an d h an d le d ata in JS P. W orkin g w ith data
is th e very h eart of pro g ra m m in g , an d it's ou r logical first step. In fact, th e cap a bility
to w ork w ith an d h an dle data is w h at sep a rates JS P from static H T M L — a n d w e h av e
th e fu ll pow e r of Java b eh in d u s w h en w e w ork w ith data in JS P.

W e're also g oin g to see h ow to u se op erators to w ork w ith


data today. O p erators e n a ble you to p erform sim p le
m ath e m atical operation s on you r data. F or exa m p le, to add 2
an d 5, y ou can u se th e + op e rator in Java, so th e Java
exp re ssion 2 + 5 resu lts in th e valu e 7. (In th is ope ration , 2 is
th e first op era nd , + is th e ope rato r, an d 5 is th e secon d
ope ra n d .) Y ou're g oin g to see h ow to p erform a ll kind s of
m ath w ith operato rs tod ay . H ere's an overview of today 's
topics:

 T h e JS P p rogra m m in g e n viro n m en t
 H and lin g d ata
 C reatin g varia bles an d a rra ys
 W orkin g w ith string s
 U sin g operato rs
 U n d ersta nd in g operator precede n ce

N ow th at w e're diggin g into real pro g ra m m in g in Java S e rv er Pag es, th e first th in g to


n ote is th at w e are in d e e d dealin g w ith Java. Y ou'll see w h at th at m ean s n ext.

[ T eam L iB ]

Week 1 – Page 35
[ T eam L iB ]

Java in JSP
N ote th e w ord Java in Java S e rv er Pa ge s. Ja va itself is a very larg e pro g ra m m in g
lan gu a ge, b u t you d on't h ave to b e a Ja va expe rt to u se th is boo k, or even kn ow it at
all— w e're goin g to cov e r w h at w e n ee d. B u t y ou sh ou ld kn ow th at Java pro g ra m m in g
is a hu g e topic, an d w e're n ot goin g to h av e spa ce to cov er it all h ere . T h ere a re
th ick m u ltiple-volu m e b oo k sets on Java contain in g th ou san d s of p ag e s th at don't
cov er Java p rogra m m in g co m p letely — an d be ca u se th is is a book a bou t JS P, it's clear
w e're n ot g oin g to be a b le to cover all of Java h e re, eith er.

If y ou press on in JS P p ro g ra m m in g , yo u m ig h t w an t to pick u p a g oo d boo k on Ja va


pro g ra m m in g . You can also fin d th e com p lete Java do cu m entation on lin e, as w ell as
Java tutorials— see th e " O n lin e JS P R esou rces" topic in D ay 1, "G ettin g S tarted!".

Fortun ately, you don't n ee d a great d eal of Java prow ess to b e


able to bu ild extre m ely pow erfu l JS P a pp lication s, a s y ou'll
see. T h e ba sics are very sim ple — Java cod e is brok en u p into
statem e nts, each of w h ich m u st en d in a se m icolon , like th is
on e:

<HTML>
<HEAD>
<TITLE>Creating a Greeting</TITLE>
</HEAD>

<BODY>
<H1>Creating a Greeting</H1>
<%
out.println("Hello from JSP!");
%>
</BODY>
</HTML>
A state m e nt, in tu rn , ca n be m a d e u p of expre ssion s, an d
w e've alrea dy seen w h a t an exp ression is — it's a set of term s
(2 + 2, for exa m p le) th at Java can evalu ate to yield som e
valu e (su ch as 4 h ere). W h at's im p orta n t to re m e m b e r a b ou t
exp re ssion s is th at th ey can be evalu ated to yield a valu e in
Java.

You can also co m m e n t you r Java cod e u sin g th e Java // com m en t m a rker, w h ich
m ak es Java ig n ore all th e rest of th e text on a lin e. A s w ith JS P com m e nts, Java
com m e nts a re m e an t a s n otes to you rself or oth er p rogra m m e rs explain in g w h at's
goin g on in th e cod e, as you can see in Listin g 2.1 .

Listing 2.1 Using Comments (ch02_01.jsp)

<HTML>

Week 1 – Page 36
<HEAD>
<TITLE>Creating a Greeting</TITLE>
</HEAD>

<BODY>
<H1>Creating a Greeting</H1>
<%
out.println("Hello from JSP!"); //Display the greeting
%>
</BODY>
</HTML>

If th is w ere a bo ok on Java p rogra m m i ng , w e'd h ave to cov er a g reat m an y m o re


details befo re w ritin g an y code , su ch a s h ow to create Ja va classes, an d so on , w h ich
you ne ed ju st to get sta rted. W e're lu cky in th at th is is a book on JS P, w h ere th ose
back g roun d details are tak en care of for u s — as w e're goin g to see. W e ju st n ee d to
u se th e Java cod e th at w e'll actu ally w a n t to ex ecute; n o extra s th at Ja va w ou ld
n orm ally n ee d to set th e sta g e. T h at's b e ca u se JS P already sets th e sta ge for u s, a s
w e'll discu ss n ext.
[ T eam L iB ]

[ T eam L iB ]

The JSP Programming Environment


W h en y ou create a p u re -Java W eb ap p lication , like a servlet, you n ee d to set u p a
Java class an d p erform all kin d s of oth er w ork ju st to g et sta rted. T h at's n ot
n ecess a ry in JS P — you ju st p u t th e actu al Java statem e nts y ou w a n t to ex ecu te into
scriptlets, an d you're se t. T h e JS P serv er d oes th e rest, creatin g a fu ll servlet for y ou
auto m atically.

In fa ct, JS P even d oes m o re for u s — w e'v e alre ady see n th at JS P co m e s w ith a b u ilt-
in Java object n a m ed out, w h ich w e can u se to sen d text to a W eb p ag e. T he re a re a
nu m b e r of b u ilt-in objects like out already set for u s to u se in JS P p ag e s, an d w e'll
list th e m h ere for refere n ce.

E ach of th ese objects is created from a Java class (w e'll see h ow to create Java
classes ou rselves in D ay 6 , "C reatin g JS P C o m p on ents: Jav a B ean s"). H ere, you'll see
w h ich Java class each b u ilt-in object is created fro m , so th at if you w an t to fin d ou t
m o re a b ou t an y object, you can che ck th e Java docu m e ntation (see
http://jav a.su n.c o m /j2 s e/1.4/d ocs/ in d ex.htm l for th e on lin e docu m e n ta tion , or
http://jav a.su n.c o m /j2 s e/1.4/d ow n load.htm l to dow n load it). N ote th at th ere's n o
n ee d to read th e Java d ocu m entation directly — th ese obje cts a re cov ere d in detail in
th e co m in g d ays.

H ere's a list of th e bu ilt-in JS P objects; it'll be h ard to ap preciate th is list rig h t n ow ,


bu t it's goo d to h ave for later referen ce:

 application— H olds da ta for th e curren t W eb a p p lication (see D ay 7,


"Tra ck in g U sers w ith S e ssion s an d C oo kies"). T h is is an object of th e Java
javax.servlet.http.HttpSession class.

Week 1 – Page 37
 config— H olds con fig u ration d ata like pass w ord s. T h is is an obje ct of th e
Java javax.servlet.ServletConfig class.
 exception— L ets you h an d le errors (see D a y 8, "H an d lin g Erro rs"). T h is is an
object of th e Java java.lang.Throwable class.
 out— T h e object you u se to sen d text to a W eb pa ge. T h is is an object of th e
Java javax.servlet.jsp.JspWriter class.
 page— G ives y ou access to th e cu rren t JS P pa g e 's u nd erlyin g servlet (see D ay
6). T h is is an object of th e Java javax.servlet.jsp.HttpJspPage class.
 pageContext— H olds da ta from th e JS P pa g e's u nd erlyin g servlet (see D ay
10 , "C reatin g C u sto m T ags"). T h is is an obje ct of th e Java
javax.servlet.jsp.PageContext class.
 request— H olds data sen t to you fro m th e bro w ser (see D a y 4, "R e adin g
D ata fro m W eb Pag e s: B utton s an d T ext Fields"). T h is is an object of th e Java
javax.servlet.http.HttpServletRequest cla ss.
 response— H olds data you a re send in g b ack to th e brow ser (see D ay 7 ). T h is
is an object of th e Java javax.servlet.http.HttpServletResponse class.
 session— H olds data a bou t th e cu rren t session (see D a y 7). T h is is an object
of th e Java javax.servlet.http.HttpSession class.

W e're goin g to intro du c e an d u se the se obje cts as w e n ee d th em . T od a y, y ou're on ly


goin g to u se th e out object. W e'v e seen th at object h as a m eth od n a m e d println,
w h ich you can u se to sen d text to a W eb pa g e. For exa m p le, h ere's ho w w e prin t
"H ello fro m JS P !" to a W eb p a ge:

out.println("Hello from JSP!");


In th is case, w e're pa ssin g th e text strin g "Hello from JSP!"
to th e println m eth od so it can prin t th at text to th e W eb
pa ge. W h en y ou in voke a m eth od like th is, you call it, so th e
ap p ro p riate term in ology h ere is w h at w e're callin g th e
println m eth od a n d p a ssin g th e text strin g "Hello from
JSP!" to it.

B esides println, the re are othe r m eth ods av a ilable in th e out obje ct, a n d you can
see th em all in Table 2.1 . Y ou p a ss differen t ty pes of data to th ese va riou s m eth ods,
an d th e type of data y ou can p ass is in dicated in th at table. W e're goin g to see all
th ese data typ e s today — for exa m p le, th is entry in Table 2.1

println(char x);

m e an s th at you can pa s s an in divid u al ch aracter (su ch a s 'a' or 'x') to th e println


m eth od.

N ote th at th e print an d println m eth ods in T a ble 2.1 h ave m u ltiple version s w ith
th e sa m e n a m e th at tak e differen t data typ es. T h is m ea n s you can call th e sa m e
m eth od w ith differen t ty pes of data — for exa m p le, you can pass a sin gle ch ara cte r to
th e println m eth od, or a String object (a s w e'll see today), or a floatin g poin t
valu e, an d so on , as ind icated in Ta ble 2.1 .

Week 1 – Page 38
Tip

H ere's so m eth in g u sefu l to kn ow ab ou t th e println m eth od — b eca u se its


n a m e m ea n s "p rin t lin e ," you m ig h t th in k it'll w rite outp u t to a W eb pa g e
an d th en sk ip to th e n ext lin e. In fact, th e outpu t on ly sk ips to th e n ext lin e
w h en you 're w ritin g plain -text files. A lth ou g h th at lets you form at th e text
in you r H T M L files n icely, w h en th e bro w ser dis p lays th at H TM L , it w ill
ign ore th e atte m p t to sk ip to th e n ext lin e. If you w a n t to skip to th e ne xt
lin e in th e bro w ser, m a k e su re you prin t th e H T M L to do th at, su ch a s u sin g
a <BR> ele m en t (for exa m p le, out.println("<BR>");). N ote th at th e out
object also h as a print m eth od, w h ich doe sn 't sk ip to th e ne xt lin e after
prin tin g its text.

Table 2.1. Methods of the out Object


M e th o d D o e s T h is
clear() C lears all intern al data in th e obje ct.
clearBuffer() C lears th e contents of th e intern al data bu ffer.
close() C loses th e outp u t "strea m ," w h ich is th e strea m of
data goin g to th e W eb p age.
flush() Flu sh es th e outp u t strea m , send in g a n y d ata in it to
th e W eb pa g e .
getBufferSize() G e ts th e size of th e intern al data bu ffer.
getRemaining() G e ts th e nu m b e r of un u sed b ytes in th e d ata b u ffer.
isAutoFlush() Ind icates if out auto flu sh es, w h ich m ea n s it w rites
its data ou t fu lly each tim e you w rite.
newLine() S kips to th e ne xt lin e in plain text files.
print(boolean b) P rints a B oolean valu e.
print(char c) P rints a ch ara cter.
print(char[] s) P rints an arra y of ch ara cters.
print(double d) P rints a doub le-precision floatin g -poin t nu m b er.
print(float f) P rints a floatin g -poin t n u m b er.
print(int i) P rints an integer.
print(long l) P rints a lon g integer.
print(java.lang.Object P rints an object.
obj)
print(java.lang.String s) P rints a string .
println() S kips to th e ne xt lin e in plain text files.

Week 1 – Page 39
println(boolean x) P rints a B oolean valu e a n d th en sk ips to th e n ex t
lin e in plain text files.
println(char x) P rints a ch ara cter an d th en skips to th e ne xt lin e in
plain text files.
println(char[] x) P rints an arra y of ch ara cters an d th en sk ips to th e
n ext lin e in plain text files.
println(double x) P rints a doub le-precision floatin g -poin t nu m b er an d
th en sk ips to th e n ext lin e in plain text files.
println(float x) P rints a floatin g -poin t n u m b er an d th en sk ips to th e
n ext lin e in plain text files.
println(int x) P rints an integer an d th en sk ips to th e n ext lin e in
plain text files.
println(long x) P rints a lon g integer an d th en sk ips to th e ne xt lin e
in plain text files.
println(java.lang.Object P rints an Object an d th en sk ips to th e n ext lin e in
x) plain text files.
println(java.lang.String P rints a String an d the n sk ips to th e n ext lin e in
x) plain text files.
[ T eam L iB ]

[ T eam L iB ]

Handling Data in JSP


W h en y ou h a n d le data v alu es directly into you r cod e, the y're
called literals in Java. F or exa m p le, in th e cod e in Listin g 2.2 ,
a strin g literal ("Number of days = ") is p asse d to println
first, an d an integer literal (365) second .

Listing 2.2 Using Literals (ch02_02.jsp)

<HTML>
<HEAD>
<TITLE>Using a Literal</TITLE>
</HEAD>

<BODY>
<H1>Using a Literal</H1>
<%
out.println("Number of days = ");
out.println(365);
%>
</BODY>
</HTML>

Week 1 – Page 40
Th is code displays th ose literals, as y ou see in Figu re 2.1 .

Figure 2.1. Using a literal in Java.

You can 't w ork w ith or ch a n g e th e valu e of literals in you r cod e, so Jav a also h as
variables.

[ T eam L iB ]

[ T eam L iB ]

Creating Variables
V aria bles co m e in differen t type s an d serv e as placeh olders in
m e m o ry for data. T h e d iffere n t typ es h ave to d o w ith th e
form at th e d ata is store d in , an d h ow m u ch m e m o ry is set
aside to h old th at data. For exa m p le, an inte ger varia ble type,
th e int typ e, is m a de u p of fou r bytes, or 32 bits, an d y ou u se
it to store integer valu e s. T h is gives th e data in th e int typ e a
sub stantial ran g e of p ossible valu es fro m 2,14 7 ,483,648 to
2,14 7,48 3,6 47. T he re a re qu ite a few differe n t variable types
bu ilt into Java, su ch a s integers, floatin g -poin t n u m b ers, an d
in dividu al ch aracters, w h ich w e'll see today.

Week 1 – Page 41
B efore y ou u se a va ria ble in Java, y ou m u st d eclare it,
specify in g its data type. H ere's h ow y ou de cla re varia bles:
ty pe is th e typ e of varia ble (like int), n a m e is th e n a m e of th e
variable (th at m u st start w ith a letter an d can o n ly contain
letters, nu m b ers, an d/o r un d erscore s), an d valu e is th e valu e
you w an t to store in th e varia ble (re m e m be r th a t term is in
squ are bra ck ets, [] an d is option al).

type name [= value][, name [= value]...];

Let's see ho w th is w ork s; he re's an exa m p le sh o w in g h ow to d eclare a varia ble of th e


int type, w h ich m ean s you can store an integ e r in it. T h is variable is n a m e d days,
like th e follow in g:

int days;

N ow you can assign a v alu e to th is varia ble, w h ich stores th e integer 3 6 5 in days:

int days;
days = 365;

N ow days h olds 365, a s you can see in Listin g 2.3 . H ere, th e code is u sin g th e +
ope rato r to join th e valu e in days to th e text "Number of days = "— y ou'll see m ore
on join in g text togeth e r like this later tod ay.

Listing 2.3 Creating Variables (ch02_03.jsp)

<HTML>
<HEAD>
<TITLE>Creating a Variable</TITLE>
</HEAD>

<BODY>
<H1>Creating a Variable</H1>
<%
int days;
days = 365;
out.println("Number of days = " + days);
%>
</BODY>
</HTML>

Y ou can see th e resu lts of th is cod e in Figu re 2.2 .

Figure 2.2. Creating a variable.

Week 1 – Page 42
A s w e kno w , you can also d eclare va riables in d eclaration scriptin g elem e nts,
en closed in <%! an d %> th is w ay:

<HTML>
<HEAD>
<TITLE>Creating a Variable</TITLE>
</HEAD>

<BODY>
<H1>Creating a Variable</H1>
<%!
int days;
%>
<%
days = 365;
out.println("Number of days = " + days);
%>
</BODY>
</HTML>
[ T eam L iB ]

[ T eam L iB ]

Initializing Variables
You can also store a valu e in a varia ble w h en you d e clare it,
w h ich is called in itializin g th e va riable. Y ou can do th at by

Week 1 – Page 43
u sin g an = sign , called th e assign m e n t op erator in Java, like
th is:

<HTML>
<HEAD>
<TITLE>Creating a Variable</TITLE>
</HEAD>

<BODY>
<H1>Creating a Variable</H1>
<%
int days = 365;
out.println("Number of days = " + days);
%>
</BODY>
</HTML>

In th is case, th e cod e is assig n in g a valu e of 365 to days at th e sa m e tim e th at th e


variable is declared , w h ich is a h an d y sho rtcut.
[ T eam L iB ]

[ T eam L iB ]

Data Types
T h e int type is on ly on e kin d of sim ple varia ble th at y ou can u se. H ere a re th e
possibilities in overview :

 Integ ers — T he se type s are: byte, short, int, an d long, w h ich h old sign e d,
w h ole-valu e n u m b ers.
 Floatin g -poin t n u m b ers — T he se type s a re: float an d double, w h ich h old
sign ed floatin g -poin t n u m b e rs.
 C h aracters — T h is is th e char type , w h ich h olds rep resentation s of ch a ra cters
su ch as lette rs an d n u m b ers.
 B oo lean — T h is type is d esign ed to h old on ly tw o typ es of valu es: true an d
false.

You can see th ese typ es in m ore d epth in Ta ble 2.2 .

Table 2.2. Data Types


Type B yte s Range
Used
boolean 2 true, false
byte 1 –1 2 8 – 12 7
char 2 N /A

Week 1 – Page 44
double 8 –1.797 69 31 348 62 32 E 3 08 to –4.94 065 64 584 1 2 47 E -32 4 for
n eg ative valu es, an d fro m 4.9 40 656 45 841 24 7 E -324 to
1.79 769 31 34 862 32 E 3 0 8 for p ositive valu es
float 4 –3.402 82 3 E 38 to – 1.4 0 129 8 E -4 5 for n eg ative v alu es, an d fro m
1.40 129 8 E -45 to 3.40 2 823 E 3 8 for po sitive value s
int 4 –2,147,48 3,6 48 to 2,1 4 7,48 3,64 7
long 8 –9,223,37 2,0 36,8 5 4,7 7 5,80 8 to 9 ,22 3,37 2,0 3 6 ,854,775,80 7
short 2 –3 2,76 8 to 32 ,7 67

For exa m p le, th e double type h olds "dou b le-pre cision " floatin g -poin t n u m b ers, w h ich
you can u se to sto re floatin g -poin t nu m b ers w ith greater p recision th an w ith th e
ordin ary floatin g -poin t type, float. H ere's h ow you can d eclare a double varia ble
n a m e d pi to h old th e v alu e of pi to 10 d e cim al places:

<HTML>
<HEAD>
<TITLE>Creating a Variable</TITLE>
</HEAD>

<BODY>
<H1>Creating a Variable</H1>
<%
double pi = 3.1415926535;
out.println("Pi = " + pi);
%>
</BODY>
</HTML>
[ T eam L iB ]

[ T eam L iB ]

Converting Between Data Types


Java is a stron g ly ty ped lan gu a ge, w h ich m e an s you h av e to
be ca refu l w h en tryin g to m ix data type s. F or exa m p le, say
th at you h ave a float v ariable, float1, an d a double
variable, double1. D ou b le-precision variables ca n h old valu es
w ith greater p recision th an sim ple float varia bles, so if you
try to assign th e valu e in double1 to float1, Ja va realizes
th ere m igh t be a loss in precision , an d w ill cau se an error. T h is
m e an s th at Jav a w ill n ot ru n th is code:

<HTML>
<HEAD>
<TITLE>Mixing Data Types</TITLE>
</HEAD>

<BODY>

Week 1 – Page 45
<H1>Mixing Data Types</H1>
<%
float float1;
double double1 = 1;

float1 = double1;

out.println("float1 = " + float1);


%>
</BODY>
</HTML>

In cases like th is, you n eed to con v ert betw een data types. T h ere a re tw o w a ys you
can do th at— u sin g auto m atic type con version , or d oin g th e type con v e rsion you rself.

Automatic Conversions

W h en y ou're a ssig n in g on e typ e of data to a va riable of an oth e r typ e, Java w ill


con v ert th e data to th e n ew va ria ble type auto m atically. For exa m p le, you can assign
a float valu e to a double variable, becau se double varia bles h ave a la rge r ra ng e
th an float valu es, so n o data w ill be lost in th e type con v ersion . Y ou ca n see an
exa m p le in Listin g 2.4 .

Listing 2.4 Automatic Data Conversions (ch02_04.jsp)

<HTML>
<HEAD>
<TITLE>An Automatic Data Conversion</TITLE>
</HEAD>

<BODY>
<H1>An Automatic Data Conversion</H1>
<%
double double1;
float float1 = 1;

double1 = float1;

out.println("double1 = " + float1);


%>
</BODY>
</HTML>

Java w ill h ave n o p ro ble m w ith th is code, as you see in Figu re 2.3 . T h ese type s of
con v ersion s, w h ere y ou con v ert to a data type w ith a larger ran g e, a re called
w iden in g con v ersion s.

Figure 2.3. An automatic data conversion.

Week 1 – Page 46
Performing Type Conversions
If y ou're a ssign in g a data valu e to a varia ble of a type th at h as a larg e r ran g e th an th e
variable you 're assign in g it to, w h ich is called a n a rrow in g con version , th e Ja va
com p iler w ill n ot perform n arrow in g con v ersion s auto m atically, beca u se th e re is th e
possibility th at precision w ill be lost. If you w an t to p erform a n a rrow in g con v ersion ,
you m u st u se an explicit type cast.

A ty pe cast lets you con vert betw een d ata typ es. Fo r exa m p le,
in th e cod e you see in Listin g 2.5 , th e code is con vertin g
double1 from typ e double to typ e float w ith th e Java typ e
cast (float) an d a ssig n in g th e resu lt to float1.

Listing 2.5 Casting to a New Data Type (ch02_05.jsp)

<HTML>
<HEAD>
<TITLE>Casting to a New Type</TITLE>
</HEAD>

<BODY>
<H1>Casting to a New Type</H1>
<%
float float1;
double double1 = 1;

float1 = (float) double1;

Week 1 – Page 47
out.println("float1 = " + float1);
%>
</BODY>
</HTML>

W ith o u t th e explicit type ca st, Ja va w ou ld object, bu t w ith th e type cast, th ere's n o


pro ble m . Jav a de cides w h at you kn ow ab ou t th e po ssibility of losin g som e d ata w h en
you cra m a po ssibly larg er valu e into a sm aller type, an d a re tak in g resp on sibility for
th e resu lts. Y ou can see th e resu lts in Fig u re 2.4 .

Figure 2.4. Using a type cast.

Note

For in form ation on con v ertin g text string s to nu m b e rs an d vice versa , s ee


"U sin g N a m ed T a rgets" in D ay 5, "R ea din g D ata fro m W eb Pag es: C he c k
B oxes, R a dio B utton s, a n d S elect C on tro ls."

[ T eam L iB ]

[ T eam L iB ]

Week 1 – Page 48
Strings
B esides n u m b e rs, text string s are an im p ortan t part of p rogra m m in g . In Java, strin g s
are sup po rted b y th eir o w n class, t h e String cla ss, an d you can th in k of th e String
class as d efin in g a n ew data type. Fo r exa m p le, you can create a strin g n a m e d
greeting, w h ich h olds th e text "H e llo fro m JS P !" in Listin g 2.6 .

Listing 2.6 Creating a String (ch02_06.jsp)

<HTML>
<HEAD>
<TITLE>Creating a String</TITLE>
</HEAD>

<BODY>
<H1>Creating a String</H1>
<%
String greeting = "Hello from JSP!";

out.println(greeting);
%>
</BODY>
</HTML>

Y ou can see th e resu lts in Figu re 2.5 .

Figure 2.5. Creating a string.

Week 1 – Page 49
A lth ou g h string s are n ot on e of th e sim ple d ata types in Java, th ey d eserv e a place
h ere, b eca u se m ost pro g ra m m e rs treat th em a s th ey w ou ld an y othe r d ata type. Fo r
exa m p le, h ere's h ow y ou can create th ree strin gs an d join th e m into on e strin g w ith
th e + op erato r:

String string1 = "Hello ";


String string2 = "from ";
String string3 = "JSP!";
String greeting = string1 + string2 + string3;

In th is case, th e resu ltin g strin g in greeting w ou ld be "Hello from JSP!".

You can see a selection of th e Java String class's m eth o ds in Table 2.3 . For
exa m p le, tak e a loo k at th e entry int indexOf(String str) in th at table. T h is
m eth od sea rch es a strin g for a su b strin g :

index = string1.indexOf("JSP");

H ere, th e code is sea rch in g th e text in th e String string1 for th e text "JSP".
B esides p a ssin g data to m eth ods, m eth ods can also retu rn data, an d th e int in th is
entry in Table 2.3 , int indexOf(String str), m e an in g th is m eth od re tu rn s an
in teger valu e. In th is ca se, th e indexOf m eth od retu rn s th e ch ara cter ind ex at w h ich
th e sub strin g w as foun d in th e strin g you 're sea rch in g (th e first ch aracter in th e m ain
strin g h as ind ex 0, th e n ext in d ex 1, an d so on ). In th e p reviou s lin e of cod e, th en ,
I'm assign in g th e in d ex at w h ich "JSP" w as fou n d in th e text in string1 to th e

Week 1 – Page 50
variable index. If th e sub strin g w as n ot foun d , indexOf w ill retu rn a v alu e of –1.

Table 2.3. Selected Methods of the String Object


M e th o d D o e s T h is
boolean equals(Object C o m p a res th is strin g to an object. R etu rn s true if
anObject) th e string s are equ al.
int indexOf(int ch) R etu rn s th e ind ex w ith in th is strin g of th e first
occu rren ce of th e given ch aracter, or –1 if th e
sea rch w a s un su ccessfu l.
int indexOf(int ch, int R etu rn s th e ind ex w ithin th is strin g of th e first
fromIndex) occu rren ce of th e given ch aracter startin g at th e
given in d ex, or –1 if th e sea rch w as u n su cc essfu l.
int indexOf(String str) R etu rn s th e ind ex w ith in th is strin g of th e first
occu rren ce of th e given su b strin g , or –1 if th e
sea rch w a s un su ccessfu l.
int indexOf(String str, R etu rn s th e ind ex w ithin th is strin g of th e first
int fromIndex) occu rren ce of th e given sub strin g startin g at th e
given in d ex, or –1 if th e sea rch w as un su cc essfu l.
int lastIndexOf(String R etu rn s th e ind ex w ithin th is strin g of th e
str) rightm ost occu rre n ce of th e given sub strin g , or –1
if th e sea rch w a s un su c cessfu l.
int lastIndexOf(String R etu rn s th e ind ex w ithin th is strin g of th e last
str, int fromIndex) occu rren ce of th e given sub strin g , or –1 if th e
sea rch w a s un su ccessfu l.
int length() R etu rn s th e length of th is strin g .
String replace(char R etu rn s a n ew strin g by replacin g all occu rren ce s
oldChar, char newChar) of oldChar in th is strin g w ith newChar.
String substring(int R etu rn s a n ew strin g th at is a sub strin g of th is
beginIndex) string .
String substring(int R etu rn s a n ew strin g th at is a su b strin g of th is
beginIndex, int endIndex) string , allow in g you to specify th e en d ind ex.
String toLowerCase() C on verts all th e ch aracters in th is strin g to
low erca se, retu rn in g a n ew string .
String toUpperCase() C on verts all th e ch aracters in th is strin g to
up p erca se, retu rn in g a n ew strin g object.
String trim() R e m o ves w h ite space from both end s of th is
string .

N ow let's get to th e details of creatin g an d u sin g strin g s.


[ T eam L iB ]

[ T eam L iB ]

Week 1 – Page 51
Creating Strings
T h ere a re m a n y w ays to create strin g s. H ere's a w ay w e've already se en :

String s1 = "Hello from JSP!";


.
.
.

T h e cod e is assign in g a strin g literal to s1. In fa ct, w h en you u se a strin g literal like
"Hello from JSP!" in you r code, Java treats it as a String object, so w h at's really
h a p p en in g h ere is th at th e code is assign in g on e String obje ct to an oth er.

Tip

S trin g literals like "Hello from JSP!" are en closed in dou b le qu otes. Ja va
also su pp orts sin g le ch a racter literals, w h ich you can assign to va riables of
th e ch ara cter typ e char. T o create a ch a racter literal in Java, yo u m u st
en close th e literal in sin gle q u otes, n ot doub le q u otes (w h ich w ill create a
string ), like 'a' or 'x'.

You can also, of course, declare a strin g first an d th en assig n a valu e to it, like th is:

String s1;
s1 = "Hello from JSP!";
.
.
.

T h ere a re oth er w ays of creatin g string s as w ell— a n d th ey rely on th e fact th at


string s are really strin g objects. T o un de rsta n d th ese othe r w ays of crea tin g string s,
you ne ed to un d e rstan d th e object n atu re of string s.
[ T eam L iB ]

[ T eam L iB ]

Strings Are Objects


S trin g s aren't exa ctly like th e othe r kind s of va ria bles w e've be en seein g, be ca u se
th ey're really objects of th e String class, n ot sim p le varia bles of typ es like int or
double. A s m ention ed in D ay 1, an obje ct can h ave bu ilt-in m eth od s — su ch as th e
println m eth od w e'v e seen in th e out obje ct, as w ell as data m e m b ers you u se to
store data in th e object. W e'v e already see n a selection of m eth o ds b u ilt into String

Week 1 – Page 52
objects in Table 2.3 .

You can th in k of Ja va classes, like th e String class, as a sort of te m p late or cookie


cutter. Y ou u se th at coo kie cutter to create obje cts. In th is w ay, a class is an object's
type, ju st like int is th e type of an integer v ariable. Y ou can store objects in
variables th at you d e cla re to b e of th at object's type (for exa m p le, you can store
String obje cts in variab les declared to b e of ty p e String).

S o h ow do you create a n obje ct from a class like th e String


class? Y ou can u se th e class's con stru cto r. A con stru cto r is a
special m eth od th at h as th e sa m e n a m e a s th e class itself
(su ch as String), w h ich you can u se to create objects of th at
class. Fo r exa m p le, to create a String object from th e String
class, w e can p a ss th e text th at w e w a n t th e ne w String
object to contain to th e String class's con stru ctor, an d it w ill
retu rn th e ne w String object, w h ich w e sto re in a varia ble
n a m e d s1:

String s1 = new String("Hello from JSP!");


out.println(s1);
.
.
.

T h is creates th e ne w ob ject s1, w h ich h olds th e strin g "Hello from JSP!". W e can
pass th is obje ct to println to display th at text in a W eb p a ge, as th e code is d oin g
h ere.

N ote also th e u se of th e new k eyw ord in th is cod e. W h en y ou create a n ew object


u sin g a con stru cto r, y ou n ee d to u se th e new keyw ord in th is w ay. W e d idn 't h ave to
do th at w h en in itializin g a sim p le variable of th e types int an d float th at you see in
Table 2 .2 , bu t w h en you create a n ew object u sin g a con stru cto r, you h ave to u se
th e new keyw ord as w e're doin g h ere. D oin g so in dicates to Java th at it m u st create
an d in itialize a n ew obje ct, n ot ju st a sim p le variable.
[ T eam L iB ]

[ T eam L iB ]

Determining String Length


T h ere a re plenty of m eth ods bu ilt into String o bjects a vaila ble for u se, as y ou can
see in Table 2.3 . Fo r ex a m p le, you can fin d th e length of a strin g (in ch aracters)
u sin g th e String length m eth od, as sh ow n in Listin g 2.7 .

Listing 2.7 Getting String Length (ch02_07.jsp)

<HTML>
<HEAD>
<TITLE>Getting String Length</TITLE>

Week 1 – Page 53
</HEAD>

<BODY>
<H1>Getting String Length</H1>
<%
String s1 = "Hello from JSP!";

out.println("\"" + s1 + "\"" + " is " + s1.length()


+ " characters long.");
%>
</BODY>
</HTML>

Y ou can see th e resu lts in Figu re 2.6 .

Figure 2.6. Determining string length.

N ote th at th e text "Hello from JSP!" in th e outp u t is qu oted


in Figu re 2.6 . B u t th e text w e p ass to println m u st also be
qu oted in code (out.println("Like this");)— so h ow d o w e
m ake su re println d oe sn't get con fu sed w ith th e q u otation
m arks su rrou n d in g th e text w e p a ss it an d th e q u otation
m arks w e actu ally w a n t to display? W e d o th at b y precedin g
th e qu otation m arks w e w a n t to display w ith a b ackslash ( \),
w h ich w ill m ake sure Ja va treats th em as it w ou ld an y oth er
ch aracter, an d do e s n ot try to interpret th em in an y sp ecial
w ay. T h is is called esca pin g a ch aracter, an d h ere a re th e

Week 1 – Page 54
ch aracters y ou can esca pe:

 \'— S in gle qu ote


 \"— D oub le qu ote
 \\— B ackslash
 \b— B acksp ace
 \ddd— O ctal ch aracter, w h ere ddd is th e code for th e ch a racter
 \f— Fo rm feed
 \n— N ew lin e (sk ips to th e n ext lin e in plain text files)
 \r— C arriag e retu rn
 \t— Tab
 \uxxxx— H exad ecim al U n ico de ch a ra cter, w h e re xxxx is th e cod e for th e
ch aracter

For exa m p le, if y ou w a n t to display a q u otation m ark u sin g out.println, y ou m u st


esca pe it in th e text you pass to th at m eth o d: "He said, \"hello,\" when he saw
me." T h is w ay, println w ill n ot get con fu sed a n d th in k th e tw o q u otation m a rks in
th e m id dle of th e text a re actu ally begin n in g or end in g th e text itself.
[ T eam L iB ]

[ T eam L iB ]

Creating and Working with Arrays


S im ple types like int are fin e for sto rin g sin gle data ite m s,
bu t d ata is often m ore c om p lex th an th at. S u p p ose th at y ou
w a n t to sta rt a n ew ba n k, th e JS P B a n k, an d y ou n ee d to k eep
track of th e a m o un t of m o n ey in every a ccou nt, as ind ex ed by
accoun t nu m b e r. A m eth od of w orkin g w ith m o re th an sim ple
variables is n eeded h ere , an d th at's w h at a rrays provide.

U sin g an array, you can gro u p sim ple d ata type s into a m o re com p ou n d data
stru cture, an d refer to th at n ew data stru ctu re by n a m e. M ore im p orta n tly, you can
refer to th e ind ividu al data item s sto red in th e arra y by n u m eric ind ex. T h at's
im p orta nt, becau se com puters ex cel at pe rform in g m illion s of op eration s v ery
qu ickly, so if you r d ata m ay be referen ced w ith a nu m eric ind ex, y ou ca n w ork
th ro ug h a w h ole set of d ata very qu ick ly sim ply by in cre m entin g th e array in dex.

In th is case, you m ig h t start JS P B an k w ith 10 0 n ew a ccou nts, a n d each on e w ill


h ave its ow n entry in an array n a m ed accounts[]. T h e squ a re b races a t th e en d of
accounts[] in dicate th a t it's an arra y, an d you place th e in d ex n u m b er of th e item in
th e array you w a n t to a ccess in th e braces. H ere's h ow you can create th e
accounts[] array, givin g each entry in it th e double type for a little extra precision .
First, you can de clare th e a rra y, an d th en create it w ith th e new ope rato r— a rrays a re
actu ally ob jects in Java, w h ich m ea n s y ou ne ed to u se th e new op erator to create
th e m :

<HTML>

Week 1 – Page 55
<HEAD>
<TITLE>Creating an Array</TITLE>
</HEAD>

<BODY>
<H1>Creating an Array</H1>
<%
double accounts[];
accounts = new double[100];
.
.
.
%>
</BODY>
</HTML>

Th is creates an array of 100 double valu es. Y ou can refer to th e in divid u al ele m ents
in th e array u sin g an in dex nu m b e r in sq u are b rack ets like th is: accounts[0], w h ich
refers to th e first ele m e n t in th e array (a rra y in dices are zero -based in Java, so
accounts[0] refers to th e first elem e nt), accounts[1], w h ich refers to th e secon d
ele m en t in th e arra y, an d so on . F or exa m p le, y ou can sto re $11 9 .6 3 in
accounts[3], an d retrie ve th at valu e to display it, as sh ow n in Listin g 2.8 .

Listing 2.8 Creating an Array (ch02_08.jsp)

<HTML>
<HEAD>
<TITLE>Creating an Array</TITLE>
</HEAD>

<BODY>
<H1>Creating an Array</H1>
<%
double accounts[];
accounts = new double[100];
accounts[3] = 119.63;

out.println("Account 3 holds $" + accounts[3]);


%>
</BODY>
</HTML>

Y ou can see th is code at w ork in Figu re 2.7 .

Figure 2.7. Creating an array.

Week 1 – Page 56
You can n ow refer to th e ite m s in th e array u sin g a nu m eric in d ex, w h ich orga n izes
th em in an easy w ay. Y ou can also com b in e th e declaration an d creation steps into
on e step:

<HTML>
<HEAD>
<TITLE>Creating an Array</TITLE>
</HEAD>

<BODY>
<H1>Creating an Array</H1>
<%
double accounts[] = new double[100];
accounts[3] = 119.63;

out.println("Account 3 holds $" + accounts[3]);


%>
</BODY>
</HTML>

In fa ct, you can also in itialize arrays w ith valu es w h en you create th e a rray. To do
th at, you en close th e list of valu es y ou w a n t to store in th e array in cu rly bra ces ({
an d }). Fo r exa m p le, th is code creates fou r acc ounts, an d stores $23.6 6 in
accounts[0], $68.0 9 in accounts[1], $288 9.0 0 in accounts[2], an d $11 9.63 in
accounts[3]:

Week 1 – Page 57
<HTML>
<HEAD>
<TITLE>Initializing an Array</TITLE>
</HEAD>

<BODY>
<H1>Initializing an Array</H1>
<%
double accounts[] = {23.66, 68.09, 2889.00, 119.63};

out.println("Account 3 holds $" + accounts[3]);


%>
</BODY>
</HTML>

Tip

H ere's an oth e r th in g to re m e m b er ab o u t a rray s — you can get th e len gth of


an arra y (th at is, th e n u m b er of ele m ents in an arra y) w ith th e length data
m e m b e r. Fo r exa m p le, th e exp ression accounts.length w ill h old 4 in th e
previou s exa m p le. S e e " T h e for L oo p " in D ay 3, "B ran ch in g , Loopin g , an d
C reatin g M eth o d s," for a n exa m p le.

T h is is fin e as fa r a s it goes, bu t the re's m o re. F or exa m p le, w h at if ou r cu sto m ers


w a n t a ch e ck in g accou n t in a ddition to a sav in g s accou nt? H ow can w e h a n dle th at
an d still kee p th in g s in dex ed by a ccou n t n u m be r?

T h e accounts[] array w e've already created is a on e-dim en sion al arra y, w h ich


m e an s you can th in k of it as a sin gle list of nu m b ers th at y ou can in d ex w ith on e
ind ex nu m b er. H o w ev er, array s can h a ve m u ltiple dim e n sion s in Java, w h ich m ean s
th at you can h av e m u ltiple array in d exes. In th is n ext exa m p le, y ou ca n exten d
accounts[] into a tw o -dim en sion al a rra y, accounts[][], to h a nd le both a sav in g s
an d ch eckin g account. T h e first in d ex of accounts[][] w ill be 0 for sav in gs accounts
an d 1 for ch eckin g acco unts, an d th e secon d ind ex w ill be th e accoun t nu m b e r as
befo re. You can see ho w th at loo ks in cod e in Listin g 2.9 .

Listing 2.9 Using Multidimensional Arrays (ch02_09.jsp)

<HTML>
<HEAD>
<TITLE>Using Multidimensional Arrays</TITLE>
</HEAD>

<BODY>
<H1>Using Multidimensional Arrays</H1>
<%
double accounts[][] = new double[2][100];

Week 1 – Page 58
accounts[0][3] = 119.63;
accounts[1][3] = 194.07;

out.println("Savings Account 3 holds $" + accounts[0][3] +


"<BR>");
out.println("Checking Account 3 holds $" + accounts[1][3]);
%>
</BODY>
</HTML>

N ow th at accounts[][] is a tw o -dim e n sion al array, ea ch item in it is referred to


u sin g tw o in dex valu es; for exa m p le, th e sav ing s balan ce for accoun t 3 is n ow
accounts[0][3], an d th e che ck in g balan ce is accounts[1][3]. Y ou ca n see th e
resu lts in Figu re 2.8 .

Figure 2.8. Creating a multidimensional array.

T h at gives u s a solid sta rt w ith storin g data in Ja v a— w e'v e tak en a loo k at w orkin g
w ith literals, sim ple variables, strin g s, objects, an d arra ys. W e'v e g otte n d ata
storag e d ow n , n ow let's take a look at h ow to w ork w ith an d m an ipu late th at d ata
u sin g operato rs.
[ T eam L iB ]

[ T eam L iB ]

Week 1 – Page 59
Working with Operators
T h e m ost ba sic w ay to w ork w ith th e data in a pro g ra m is w ith th e b u ilt-in Java
ope rato rs. Fo r exa m p le, say you h av e sto red a valu e of 23 in on e va riable an d a
valu e of 4 in an oth e r. Y ou can m u ltiply th ose tw o valu es w ith th e Java m u ltiplication
ope rato r, *, w h ich you can see in Listin g 2.1 0 .

Listing 2.10 Using Operators(ch02_10.jsp)

<HTML>
<HEAD>
<TITLE>Using Operators</TITLE>
</HEAD>

<BODY>
<H1>Using Operators</H1>
<%
int operand1 = 23, operand2 = 4, product;

product = operand1 * operand2;

out.println(operand1 + " * " + operand2 +


" = " + product);
%>
</BODY>
</HTML>

Y ou can see th e resu lts in Figu re 2.9 , w he re w e learn th at 23 * 4 is 92.

Figure 2.9. Using Java operators.

Week 1 – Page 60
T h e follow in g operato rs are ava ilable in Java:

 D ecre m en t op e rato r ( --)


 S u btraction ope rato r (-) T h is is also th e n egation op erator if you u se it in
fro n t of a valu e; for exa m p le, th e exp ression -x evalu ates to th e valu e in x
w ith th at valu e's nu m eric sign flip p ed — positive valu es beco m e n eg ative an d
n eg ative valu es be co m e positive.
 Logical u n ary NOT op era tor (!)
 N ot equ al to ope rator (!=)
 M od u lu s op e rato r ( %)
 M od u lu s assig n m e n t op erat or (%=)
 Logical AND operato r (&)
 S h ort-circu it AND ope rator (&&)
 B itw ise AND assig n m e n t ope rato r ( &=)
 M u ltiplication ope rato r ( *)
 M u ltiplication assign m e n t op e rato r ( *=)
 D ivision operato r ( /)
 D ivision assig n m en t operato r (/=)
 if-th en -else op erator (?:)
 Logical Xor operato r (^)
 B itw ise Xor assig n m e n t ope rato r ( ^=)
 Logical OR operator (|)
 S h ort-circu it OR ope rato r (||)
 B itw ise OR assig n m e n t o p erator (|=)
 B itw ise u n ary NOT op e ra tor (~)

Week 1 – Page 61
 A dd ition operato r (+)
 In cre m en t ope rato r (++)
 A dd ition assign m en t op erator (+=)
 Less th an op erato r (<)
 S h ift left ope rato r (<<)
 S h ift left assign m en t operator ( <<=)
 Less th an or eq u al to op erator ( <=)
 A ssig n m e n t op e rato r ( =)
 S u btraction assig n m e n t ope rato r ( -=)
 E qu al to ope rato r (==)
 G reater th a n op erato r ( >)
 G reater th a n or equ a l to ope rato r (>=)
 S h ift righ t operato r (>>)
 S h ift righ t assig n m e n t operator ( >>=)
 S h ift righ t w ith zero fill ope rato r ( >>>)
 S h ift righ t zero fill assign m en t ope rator ( >>>=)

W e'll see th ese va riou s ope rato rs, an d h ow to u se th e m , throu g h ou t th e bo ok —


startin g righ t h ere, w ith a loo k at th e com m on Java op erators.

[ T eam L iB ]

[ T eam L iB ]

Assignment Operators
T h e m ost ba sic ope rators are th e assig n m e n t op erators, w h ich w e'v e already seen .
You u se th e = op erator to assign a varia ble a literal valu e, th e valu e in an oth er
variable, an d so on , like th is, w h ere th e cod e is assign in g th e variable n a m ed var1 a
valu e of 12:

<HTML>
<HEAD>
<TITLE>Assignment Operators</TITLE>
</HEAD>

<BODY>
<H1>Assignment Operators</H1>
<%
int var1;

var1 = 12;

out.println("The total value = " + var1);


%>
</BODY>
</HTML>

Week 1 – Page 62
Java also su p po rts co m bin ation assig n m en t op e rators, w h ich
com b in e an op erator like +, -, or * w ith th e assign m en t
ope rato r =. H e re's an ex a m p le sh ow in g h ow th at w orks: S a y
th at w e h av e stored 15 in a varia ble n a m e d var1:

int var1 = 15;

To add 12 to th e valu e in th is variable, w e can u se th is cod e:

int var1 = 15;


var1 = var1 + 12;

O n th e othe r h a n d , w e can u se th e co m b in ation ope rato r += to d o th e sa m e th ing ;


th is ope rato r is sh ort fo r "ad d th e valu e of th e secon d op era n d to th e v alu e of th e
first ope ran d an d a ssign th e resu lt to th e first o p eran d ":

int var1 = 15;


var1 += 12;

Th ere a re qu ite a few co m b in ation assig n m e n t op erators in Java:

 M od u lu s assig n m e n t ( %=)
 B itw ise AND assig n m e n t (&=)
 M u ltiplication assign m e n t ( *=)
 D ivision assig n m en t ( /=)
 B itw ise Xor assig n m e n t (^=)
 B itw ise OR assig n m e n t (|=)
 A dd ition assign m en t (+=)
 S h ift left assign m en t (<<=)
 Less th an or eq u al to (<=)
 S u btraction assig n m e n t (-=)
 S h ift righ t assig n m e n t (>>=)
 S h ift righ t zero fill assign m en t ( >>>=)

[ T eam L iB ]

[ T eam L iB ]

Incrementing and Decrementing Operators


T h e Java ++ ope rato r in cre m ents its ope ran d by one , an d th e -- op erator
decrem e nts its op eran d by on e. F or exa m p le, if value h olds 0, th en afte r y ou
ex ecute value++, value w ill h old 1.

H ere's an im p orta n t point; ++ an d -- can be eith er p ostfix


ope rato rs (value++) or prefix ope rato rs (++value). W h en

Week 1 – Page 63
u sed a s a p ostfix op erator, th ey a re executed a fter th e rest of
th e statem e nt, a n d w h e n u sed a s a p refix ope ra tor, before th e
rest of th e state m ent. T h is is som eth in g you h a ve to w atch
ou t for, be cau se if you h ave cod e like th is

value2 = value1++;

w h en th e state m en t is com p leted, value2 w ill actu ally be left w ith th e origin al valu e
in value1 (n ot th e in crem e nted v a lu e), an d th e valu e in value1 w ill h ave b ee n
in cre m ented. Y ou can see an exa m p le sh o w in g cod e u sin g ++ as both a prefix an d
postfix op erator in Listin g 2.1 1 .

Listing 2.11 Incrementing and Decrementing Using Operators


(ch02_11.jsp)

<HTML>
<HEAD>
<TITLE>Incrementing and Decrementing</TITLE>
</HEAD>

<BODY>
<H1>Incrementing and Decrementing</H1>
<%
int value1 = 0, value2 = 0;

out.println("value1 = " + value1 + "<BR>");


out.println("value2 = " + value2 + "<BR>");

value2 = value1++;

out.println("After <B>value2 = value1++</B>:" + "<BR>");


out.println("value1 = " + value1 + "<BR>");
out.println("value2 = " + value2 + "<BR>");

int value3 = 0, value4 = 0;

out.println("<BR>");
out.println("value3 = " + value3 + "<BR>");
out.println("value4 = " + value4 + "<BR>");

value4 = ++value3;

out.println("After <B>value4 = ++value3</B>:" + "<BR>");


out.println("value3 = " + value3 + "<BR>");
out.println("value4 = " + value4 + "<BR>");
%>
</BODY>
</HTML>

You can see th e resu lts of th is cod e in Figu re 2.1 0 , w h e re y ou can see th e ++
ope rato r w orkin g as both a p refix a n d postfix op erator.

Week 1 – Page 64
Figure 2.10. Using ++ as both a prefix and postfix operator.

[ T eam L iB ]

[ T ea m L iB ]

Multiplication and Division Operators


You u se * to m u ltiply va lu es an d / to divide valu es in Java. Y ou can see an exa m p le
w h ere th e code u ses * a n d / on double valu es in Listin g 2.1 2 .

Listing 2.12 Multiplication and Division (ch02_12.jsp)

<HTML>
<HEAD>
<TITLE>Multiplication and Division</TITLE>
</HEAD>

<BODY>
<H1>Multiplication and Division</H1>
<%

Week 1 – Page 65
double double1 = 6, double2 = 8, double3 = 5, doubleResult;
doubleResult = double1 * double2 / double3;
out.println("6 * 8 / 5 = " + doubleResult);
%>
</BODY>
</HTML>

Y ou can see th e resu lts of th is cod e in Figu re 2.1 1 .

Figure 2.11. Using multiplication and division.

Caution

You don 't h ave to u se double valu es w ith m u ltiplication a n d division , of


course, b u t n ote th at if you u se division on integer valu es, y ou ru n th e risk
of h av in g you r resu lts trun cated, losin g th e decim al part w h en th e resu lts
are stored in integer form at.

[ T eam L iB ]

[ T eam L iB ]

Addition and Subtraction Operators


A s y ou m igh t expect, th e m ost b a sic op e rato rs are + an d -, w h ich you u se for
ad d ition an d su btraction . You can see an exa m p le puttin g th e m to w ork in Listin g

Week 1 – Page 66
2.1 3.

Listing 2.13 Addition and Subtraction (ch02_13.jsp)

<HTML>
<HEAD>
<TITLE>Addition and Subtraction</TITLE>
</HEAD>

<BODY>
<H1>Addition and Subtraction</H1>
<%
int operand1 = 15, operand2 = 24, sum, difference;

sum = operand1 + operand2;


difference = operand1 - operand2;

out.println(operand1 + " + " + operand2 + " = " + sum +


"<BR>");
out.println(operand1 + " - " + operand2 + " = " + difference);
%>
</BODY>
</HTML>

You can see th ese tw o o p erators at w ork in Figure 2.1 2 , w h e re Ja va is p erform in g


variou s ad d ition s an d su btraction s for u s.

Figure 2.12. Using addition and subtraction.

Week 1 – Page 67
[ T eam L iB ]

[ T eam L iB ]

Relational Operators
You u se th e relation al operators ( >, >=, <, <=, ==, an d !=) to
create logical exp ressio n s th at you can test w ith cond ition al
statem e nts like th e if state m en t (w h ich w e'll see tom o rrow ).
A logical expression eva lu ates to eith er true or false (th ese
are th e p ossible valu es for th e B oo lean data typ e — see Ta ble
2.2).

S u p p ose w e set an integer variable n a m e d temperature to 70; in th at case, th e


logical expression temperature < 55 evalu ates to false. You can u se th is logical
exp re ssion in an if statem e nt, as w e'll see in D ay 3; if th e logical expre ssion in th e
if state m en t is true, th e code in th e bo dy of th e if statem en t is ex ecuted (an d n ot
oth erw ise). Fo r exa m p le , th e m essa ge "Just right." is w ritten to th e W eb pa g e if
th e valu e in temperature is less th an 8 0 deg re e s in Listin g 2.1 4 .

Listing 2.14 Using Relational Operators (ch02_14.jsp)

<HTML>
<HEAD>
<TITLE>Using Relational Operators</TITLE>
</HEAD>

<BODY>
<H1>Using Relational Operators</H1>
<%
int temperature = 70;

if (temperature < 80) {


out.println("Just right.");
}
%>
</BODY>
</HTML>

Y ou can see th e resu lts in Figu re 2.1 3 , w h ere w e see th at th e tem p e ratu re is ju st
right.

Figure 2.13. Using relational operators.

Week 1 – Page 68
H ere are all th e Java relation al operato rs, an d w e'll see th e m at w ork to m o rro w an d
th ro ug h ou t th e b ook:

 G reater th a n (>) Fo r ex a m p le, operand1 > operand2 retu rn s true if


operand1 is greater th a n operand2.
 G reater th a n or equ al to (>=)
 Less th an (<)
 Less th an or eq u al to (<=)
 E qu al to (==)
 N ot equ al to (!=)

You can com b in e m u ltiple logical exp ression s w ith th e logical operato rs — com in g u p
n ext.

Tip

H ere's a pitfall to av oid — w h en y ou're creatin g a logical express ion to test if


tw o valu es a re eq u al, m ake sure y ou u se == in stead of ju st =. Fo r exa m ple,
th e exp ression budget == 0 is true if th e valu e in budget is 0, bu t th e
exp re ssion budget = 0 assig n s a valu e of 0 to budget. U sin g = in stead of
== in logical expression s is a very co m m on m istak e.

[ T eam L iB ]

[ T eam L iB ]

Week 1 – Page 69
Logical Operators
You u se th e logical operators, && an d ||, to con n ect logical expression s, as w h en y ou
w a n t to m ak e sure th e tem p e ratu re is both ab o ve 60 deg rees an d belo w 90 de g ree s.
T h e tw o logical operato rs are th e logical AND (&&), an d th e logical OR (||).

H ere's h ow th ese ope rators w ork: th e OR op erator || retu rn s false w h en both its
ope ra n d s a re false, an d true othe rw ise. T h e AND ope rator && retu rn s true w h en
both its ope ran d s a re true, an d false oth erw ise . Y ou u se th ese op e ra to rs to tie
logical expression s tog e th er— u se && w h en you w a n t tw o logical expression s to b oth
be true, an d || w h en y ou on ly req u ire on e of tw o exp ression s to be tru e. Fo r
exa m p le, you can see h ow to m ak e sure th e tem p eratu re is both ab ov e 60 d egre es
an d below 90 deg rees in Listin g 2.1 5 .

Listing 2.15 Using Logical Operators (ch02_15.jsp)

<HTML>
<HEAD>
<TITLE>Using Logical Operators</TITLE>
</HEAD>

<BODY>
<H1>Using Logical Operators</H1>
<%
int temperature = 70;

if (temperature < 90 && temperature > 60) {


out.println("Picnic time!");
}
%>
</BODY>
</HTML>

Y ou can see th e resu lts in Figu re 2.1 4 , w h ere w e see it's tim e for a picn ic.

Figure 2.14. Using logical operators.

Week 1 – Page 70
You can see h ow th e || an d && op erators w ork on th eir tw o op eran d s (n a m ed a an d
b h ere) in Ta ble 2.4 . Fo r exa m p le, if a is true a n d b is false, a || b is true, bu t a
&& b is false.

Table 2.4. The Logical Operators


a b a || b (OR) a && b (AND)
false false false false
true false true false
false true true false
true true true true
[ T eam L iB ]

[ T eam L iB ]

Understanding Operator Precedence


A s y ou'v e seen tod ay , Java su pp o rts a large n u m b er of op erators. B u t w h at h a p p en s
if you start m ixin g th em in th e sa m e state m ent? W h ich operato r w ill Ja va execu te
first? Fo r exa m p le, tak e a loo k at th is exa m p le, w h ere th e code is tryin g to ad d 10
an d 24 (to get 34) an d th en d ivide th e su m by 2 (to get 17):

double value;
value = 10 + 24 / 2;

Week 1 – Page 71
out.println("The value = " + value);

B u t h ere's w h at y ou see w h en y ou execute th is cod e:

The value = 22.0


C learly, th ere's som eth in g differe n t g oin g on from w h at w a s
exp ected . In fa ct, th ere's a w ell-defin ed ord er th at Java
ex ecute s op e rato rs in w h en th ere a re m u ltiple operators in an
exp re ssion , an d th at ord er is called ope rato r p re ceden ce. A s
far a s ou r exa m p le g oe s , / h as h igh er p reced en ce th an +, so
th e exp ression 24 / 2 is evalu ated first to g et 12, an d th at 12
is ad d ed to 10, to g et 2 2.

To spe cify to Java th e e xact ord er in w h ich you w a n t th e op erators to b e evalu ate d,
you can u se pa renth ese s to g rou p th ose ope ration s y ou w a n t p erform e d first. Y ou
can see h ow th at look s in Listin g 2.1 6 , w h ere th e pa renth e ses aro un d 10 + 24 m ake
su re th e ad d ition operation is perform ed first.

Listing 2.16 Using Operator Precedence (ch02_16.jsp)

<HTML>
<HEAD>
<TITLE>Checking Operator Precedence</TITLE>
</HEAD>

<BODY>
<H1>Checking Operator Precedence</H1>
<%
double value;

value = (10 + 24) / 2;

out.println("The value = " + value);


%>
</BODY>
</HTML>

Y ou can se e th e resu lts in Figu re 2.1 5 , w he re w e do ind ee d get th e an s w er w e


exp ected .

Figure 2.15. Using operator precedence.

Week 1 – Page 72
You 'll fin d th e Java ope rator p receden ce in Table 2.5 , fro m h igh est to low est—
ope rato rs w ith hig h er p receden ce a re ex ecuted befo re ope rato rs w ith low er
preced e n ce in a co m p ou n d expression . O p erators on th e sa m e lin e h ave th e sa m e
preced e n ce, an d if Java find s a nu m b er of ope ra tors of th e sa m e preced en ce in a
com p ou n d exp ression , th ose op erators a re executed from left to rig ht.

Table 2.5. Java Operator Precedence


( ) [ ] .

++ — ~ !
* / %

+ -

>> >>> <<

> >= < <=


== !=

&

&&

||

?:

Week 1 – Page 73
= [operator]=

N ow you h av e th e fou nd ation you'll n ee d to w ork w ith d ata a n d ope rators th rou gh ou t
th e bo ok. T o m o rrow , y o u're goin g to bu ild on th at Java foun d ation , seein g h ow to
m ake d ecision s in code, as w ell as h ow to cre ate loo pin g state m e nts an d m eth o ds.

[ T eam L iB ]

[ T eam L iB ]

Summary
Tod ay you 'v e m a d e a lo t of p ro g ress in w orkin g w ith Java. Y ou'v e g otte n th e b asics
dow n of th e Ja va en viron m en t th at you 'll be w o rkin g w ith in JS P, in clu din g gettin g an
ov erview of th e rea d y -m a de Java obje cts (like out) th at are already a v ailable for you
to u se in th at en viro n m ent.

Tod ay you 'v e sta rted g e ttin g to th e v ery h ea rt of pro gra m m in g — w orkin g w ith d ata.
T h ere a re a nu m b e r of w ays of h a n d lin g d ata in Java. T h e first is sim p ly to u se
literals, w h ich are literal nu m b ers or text ente re d directly in to you r code state m ents.
Literals are fin e, b u t yo u ca n't really m an ipu late th e m in code — fo r th at, y ou ne ed
variables.

V aria bles en a ble y ou to store data in a pro gra m an d refer to th at data b y n a m e. Fo r


exa m p le, if y ou n a m e a n in teger va ria ble temperature, you can sto re integer valu es
in temperature an d u se th at n a m e to refer to th e stored valu e in you r cod e. In
ad d ition , you can co m b in e a w h o le set of data into a rray s.

T h ere a re plenty of data types in Java, ea ch w ith its ow n ca pacity — fo r exa m p le, a
double variable can sto re valu es w ith h igh er m ath e m atical precision th an a sim p le
float varia ble. Java is a stick ler abou t m aintain in g type integ r ity, so y ou don 't lose
an y precision in a dverte n tly, an d th ere a re tw o w ays to con v ert b etw ee n d ata types —
auto m atically, an d w ith a type cast.

You also learn ed m o re a bou t Java objects toda y . You can create obje cts from
classes, an d in th at w ay, a class is a n object's type, m u ch like int is th e typ e of th e
temperature variable w e ju st discu ssed. Y ou ca n also sto re obje cts in v ariables
w h ose typ e is th e object's class.

U n like sim ple varia bles, obje cts can contain m eth ods an d m u ltiple d ata m e m b e rs.
You can crea te objects u sin g a con stru cto r, w h ich is a spe cial m eth od w ith th e sa m e
n a m e as th e class you 're creatin g objects fro m , togeth er w ith th e new op erator. T h e
con stru cto r m eth od w ill retu rn th e ne w ly create d object.

You can m an ipu late a n d w ork on th e data in you r code w ith Java op e ra tors. T h ere's a
goo d selection of op erators in Java, as w e'v e se en , an d the y provide u s w ith a basic
w ay of w orkin g on data. B esides nu m erical op erators, Java also sup po rts relation al
an d logical operato rs th at en a ble you to w ork w ith valu es of true an d false of th e

Week 1 – Page 74
kin d w e'll u se in if statem e nts tom orrow .

[ T eam L iB ]

[ T eam L iB ]

Q&A

Q1: I c a n 't c h a n g e th e co n te n ts o f a String o b jec t— is th e re a n y s trin g


cla ss I c a n c h a n g e th e c o n te x t o f, a fte r a n o b jec t o f th a t c la ss h a s
b e e n c re a te d ?

A1: Yes. Y ou can u se th e StringBuffer class, w h ich w e'll see in D ay 4.

Q2: H o w a re Ja v a o b je cts d iffe re n t fro m J a v a 's b u ilt -in b a sic d a ta


ty p e s lik e int?

A2: A ll Java objects a re bas ed on th e java.lang.Object class, w h ereas ba sic


data types are n ot. T h at is, all objects alread y h ave m eth od s an d d ata
m e m b e rs bu ilt into th em fro m java.lang.Object, w h ich th e b asic d ata
types d on 't. Y ou 'll see m o re on th is issu e in D a y 7.

[ T eam L iB ]

[ T eam L iB ]

Workshop
T h is w ork sh op tests w h eth er y ou un d erstan d all th e con cepts y ou learn ed tod a y. It's
a goo d idea to m a ster today's con cepts b y h on in g you r kn ow led g e he re before
startin g tom o rrow 's m aterial. Y ou can fin d th e a n sw ers to th e q u iz q u estion s in
A pp e n d ix A .

Quiz

1: W h at a re th e b u ilt-in ob jects in JS P?

2: H o w do you sk ip to th e n ext lin e in th e bro w ser w h en u sin g println?

3: N a m e all th e floatin g -po int bu ilt-in d ata types in Java.

4: W h at valu es can B oo lea n varia bles h old?

Week 1 – Page 75
5: If y ou can 't ch an g e a String obje ct after it's b e en created, w h y a re the re
String m eth od s like toLowerCase, toUpperCase, an d replace?

Exercises

1: C an you g u ess w h at th e exp ression 2 + 3 / 5 * 17 + 7 * 9 evalu ate s to ?


T ry it ou t in a JS P p a ge to ch eck you r an sw er.

2: U sin g th e String object's indexOf an d substring m eth o d s, fin d an d


display th e sixth w ord in th e senten ce "Jav aS e rver Pa g es is g oin g to
do m in ate th e w orld!" (H in t: search for sp aces re p eatedly!)

[ T eam L iB ]

[ T eam L iB ]

Day 3. Branching, Looping, and


Creating Methods
Tod ay w e're g oin g to g e t so m e m ore essential Java p rogra m m in g u n d er ou r b elts.
W e'll see th ree cru cial techn iqu es h ere — b ra n ch ing , loo pin g , a n d creatin g m eth o ds.
T h ese a re all basic skills for th e JS P prog ra m m e r, an d w e'll n ee d th e m in ou r
pro g ra m m in g arsen al th ro u gh o u t th e b o ok. H ere's an overview of tod a y 's topics:

 B ran ch in g state m ents — if an d switch


 Loopin g state m ents— for, while, an d do-while
 C reatin g m eth o ds
 Passin g d ata to m eth o d s
 R etu rn in g d ata fro m m e th ods

B ran ch in g state m e nts (also called con d ition al statem e nts) let
you m ak e d ecision s in code. Fo r exa m p le, w e'v e alrea dy see n
th e m o st pop u lar Jav a b ran c h in g state m en t at w ork — th e if
statem e n t— in D ay 2, "H an d lin g D ata an d O p e ra tors." In
exa m p le ch02_15.jsp, w e u sed th e if statem e n t to display
th e m e ssa g e "Picnic time!" if th e te m pe ratu re w a s betw een
60 an d 90 deg rees Fa hrenh eit:

<HTML>
<HEAD>
<TITLE>Using Logical Operators</TITLE>
</HEAD>

<BODY>
<H1>Using Logical Operators</H1>

Week 1 – Page 76
<%
int temperature = 70;

if (temperature < 90 && temperature > 60) {


out.println("Picnic time!");
}
%>
</BODY>
</HTML>

Y ou'll see m o re ab o u t b ran ch in g statem e nts like th is on e tod ay.

Loops let y ou execute som e code ov er an d ove r on a set of


data. Loops are on e of th e m ain reason s co m p u ters are so
pow erfu l, becau se th at's w h at com p ute rs a re g o o d at:
ex ecutin g large a m o un ts of code qu ick ly. For ex a m p le, you
m igh t h ave an array h oldin g stud e n t scores fro m a class
you 're teach in g on JS P, an d u sin g a loo p, you ca n ad d all th e
scores to fin d th e av era ge score. E ach tim e thro ug h th e loo p,
called a loo p iteration , y ou can in crem e n t th e a rray ind ex,
givin g you access to th e n ext a rra y ele m ent. A s you iterate
th ro ug h th e w h ole a rray of stud e n t scores th is w ay, you can
ad d each score to a run n in g total. W h en th e loo p is fin ish ed,
you can divide th e ru nn in g total by th e total n u m b er of
stud e nts to get th e av erage sco re. Y ou'll see h o w th at w orks
today.

W e'll also see h ow to create ou r ow n m eth od s today. W e'v e seen m eth ods ev er sin ce
D ay 1, w he re w e u sed th e out object's println m eth od to w rite text to th e W eb
pa ge bein g sen t b a ck to th e brow ser. H ere, w e're goin g to see ho w to w rite ou r ow n
m eth ods. D ividin g you r cod e into m eth od s is a goo d idea w h en you r co d e gets long ;
it h elps keep th in g s org an ize d. U n less y ou b rea k y ou r cod e u p into sm a ller un its, you
cou ld en d u p w ith m an y pages of tan g led Java. If y ou divid e th at code into m eth od s,
each of w h ich is called to execute a sp ecific, discrete ta sk, th in g s stay m a n a gea ble.

T h at's it for th e intro du c tion — let's get pro gra m m in g , startin g w ith bran ch in g
statem e nts.
[ T eam L iB ]

[ T eam L iB ]

Branching Statements
T h e ne xt step u p fro m u sin g th e sim ple op e rato rs w e sa w in D ay 2 is to u se
bra n ch in g state m ents in you r cod e . Y ou u se bra n ch in g state m ents to m ake d ecision s
based on th e valu e of y ou r d ata, a n d to m ake th e flow of th e pro gra m go in differe n t
direction s accordin g ly.

T h ere a re tw o bran ch in g state m ents in Jav a — th e if statem e nt, a n d th e switch


statem e nt.

Week 1 – Page 77
The if Statement
W h en y ou w a n t to test cond ition s a n d execu te cod e accordin gly, it's a g oo d idea to
u se a statem e n t like th e if state m ent. H ere's h ow y ou u se th is state m en t in
gen e ral:

if (condition) statement1;
[else statement2;]

If condition evalu ates to true, statement1 is ex ecuted. O th erw ise, if th ere is an


else clau se to th e state m e nt, th e cod e in it ( statement2) is execute d.

In Jav a , statement1 an d statement2 can b oth be com pou n d state m ents, w h ich
m e an s th at the y can b e m a de u p of a nu m b er of statem e nts en closed in cu rly
braces, like th is:

if (condition){
statement;
statement;
.
.
.
}
else {
statement;
statement;
.
.
.
}

Let's tak e a look at so m e exa m p les to see h ow th is w orks. Fo r exa m p le, w h at if you
w a nted to fin d th e a bsolute valu e of a nu m b e r? O n e w ay to get an absolute valu e is
to sta rt by che ck in g w h eth er th e valu e is greater th an 0, an d if so, ju st prin t ou t th e
valu e itself. Listin g 3.1 sh ow s h ow to m a ke th at test w ith an if statem e nt.

Listing 3.1 Using an if Statement (ch03_01.jsp)

<HTML>
<HEAD>
<TITLE>Using the if Statement</TITLE>
</HEAD>

<BODY>
<H1>Using the if Statement</H1>
<%
int value = 10;

if(value > 0)
out.println("Absolute value of " + value + " = " + value);

Week 1 – Page 78
%>
</BODY>
</HTML>

N ote th e if state m ent's cond ition h ere , value > 0, w h e re th e cod e is u sin g th e >
relation al operator (see th e section " R elation al O p e rato rs" in D ay 2), w h ich w ill be
true if th e valu e is grea ter th an 0, an d false oth erw ise. Y ou can see th e resu lts of
th is cod e in Figu re 3.1 .

Figure 3.1. Using the if statement.

E x e c u tin g C o m p o u n d S ta te m e n ts

N ote th at in th is case, th e state m e n t th at's exe cuted if th e if state m e n t is true is a


sin gle state m en t, bu t you can also ex ecu te m u ltiple state m ents if y ou m ake th em
part of a co m p ou n d statem e n t surro u n d ed b y { an d }, as you see in Listin g 3.2 .

Listing 3.2 Using a Compound Statement (ch03_02.jsp )

<HTML>
<HEAD>
<TITLE>Using Compound Statements</TITLE>
</HEAD>

Week 1 – Page 79
<BODY>
<H1>Using Compound Statements</H1>
<%
int value = 10;

if(value > 0) {
out.println("The number was positive.");
out.println("Absolute value of " + value + " = " + value);
}
%>
</BODY>
</HTML>

Y ou can see th e resu lts of th is cod e in Figu re 3.2 .

Figure 3.2. Using compound statements.

T h e else S ta te m e n t

S o fa r, ou r if state m en t on ly displays an absolute valu e if th e valu e is greater th an


0. Y ou can expa n d th at if state m en t by ad d in g an else clau se, w h ich is execu ted if th e
if state m ent's con d ition is false. Y ou can see h ow th at looks in Listin g 3.3 . T h is
en a bles u s to fin d th e a bsolute valu e of n eg ative nu m b e rs a s w ell as positive one s
(n ote th at th e cod e is also u sin g th e Java n e gation op erator ( -) to ch a n g e th e sign of

Week 1 – Page 80
value if n ee de d; see th e topic "O pe rato rs" in D ay 2 for m o re on th is op erator).

Listing 3.3 Using an else Clause (ch03_03.jsp)

<HTML>
<HEAD>
<TITLE>Using an else Clause</TITLE>
</HEAD>

<BODY>
<H1>Using an else Clause</H1>
<%
int value = -10;

if(value > 0) {
out.println("Absolute value of " + value + " = " + value);
}
else {
out.println("Absolute value of " + value + " = " + -value);
}
%>
</BODY>
</HTML>

Y ou can see th e resu lts of th is cod e in Fig u re 3.3 .

Figure 3.3. Using an else clause.

Week 1 – Page 81
N e s ted if S ta te m e n ts

You can also n est if sta tem ents in side each oth er; h ere's an exa m p le sh ow in g h o w
th at w ork s. In th is case, say th at y ou w a n t to display th e recipro cal of a nu m b er —
bu t on ly if th at nu m b er is positive. A lso, you d o n 't w an t to ev en try to get th e
recipro cal if th e n u m b er is zero, b ecau se th e recipro cal of zero is n ot d efin ed. Listin g
3.4 sho w s h ow y ou can pu t all th is into code u sin g a n ested if statem e n t (n ote th at
th e code is u sin g th e relation al operato r != he re , w h ich m ea n s "n ot equ al to," as you
saw in D ay 2).

Listing 3.4 Nested if Statements (ch03_04.jsp)

<HTML>
<HEAD>
<TITLE>Nested if Statements</TITLE>
</HEAD>

<BODY>
<H1>Nested if Statements</H1>
<%
double value = 2;

if (value != 0) {
if (value > 0)

Week 1 – Page 82
out.println("The result = " + (1 / value));
else
out.println("Sorry, we need a positive number.");
}
%>
</BODY>
</HTML>

if-else L a d d e rs

It's p ossible to create a n entire seq u en ce of if-else state m ents called an if-else
lad d er. Y ou can see an exa m p le sh ow in g h ow th is w orks in Listin g 3.5 ; in th is case,
th e code kee ps testin g th e valu e in a String va riable un til it find s a m a tch to th e
cu rren t day of th e w eek .

Listing 3.5 Using an if-else Ladder (ch03_05.jsp)

<HTML>
<HEAD>
<TITLE>Using an if-else Ladder</TITLE>
</HEAD>

<BODY>
<H1>Using an if-else Ladder</H1>
<%
String day = "Friday";

if(day == "Monday")
out.println("It\'s Monday.");
else if (day == "Tuesday")
out.println("It\'s Tuesday.");
else if (day == "Wednesday")
out.println("It\'s Wednesday.");
else if (day == "Thursday")
out.println("It\'s Thursday.");
else if (day == "Friday")
out.println("It\'s Friday.");
else if (day == "Saturday")
out.println("It\'s Saturday.");
else if (day == "Sunday")
out.println("It\'s Sunday.");
%>
</BODY>
</HTML>

Y ou can se e th e resu lts of th is cod e in Fig u re 3.4 , w h e re w e see th at it's Frid ay.

Figure 3.4. Using an if-else ladder.

Week 1 – Page 83
A lth ou g h it's possible to create if-else lad d ers like th is, Java actu ally in clu d es a
statem e n t exp ressly for situ ation s like th is: th e switch state m ent.

The switch Statement

T h e switch statem en t is Java 's m u ltiw ay bra n ch state m ent, an d it pro v ides th e sa m e
kin d of fu n ction ality as an if-else lad d er, b u t in a m u ch ea sier form . H ere's w h at
th e switch state m en t looks like in gen eral:

switch (expression) {
case value1:
statement1;
[break;]
case value2:
statement2;
[break;]
case value3:
statement3;
[break;]
.
.
.
default:
default_statement;

Week 1 – Page 84
}

H ere, th e valu e of th e expression, w h ich m u st be of typ e byte, char, short, or int,


is co m p a red a gain st th e variou s test valu es in th e case state m ents: value1, value2,
an d so on . If th e exp res sion m atch es on e of th e test valu es in th e case statem e nts,
th e code a ssociated w ith th at case statem e n t is execute d. If ex ecution reache s a
break state m ent, th e switch state m en t en ds.

Lis ting 3 .6 sh ow s a n ex a m p le in w h ich th e code displays th e d ay of th e w eek b a sed


on a nu m e ric valu e u sin g a switch state m ent.

Listing 3.6 Using the switch Statement (ch03_06.jsp)

<HTML>
<HEAD>
<TITLE>Using the switch Statement</TITLE>
</HEAD>

<BODY>
<H1>Using the switch Statement</H1>
<%
int day = 3;

switch(day) {
case 0:
out.println("It\'s Sunday.");
break;
case 1:
out.println("It\'s Monday.");
break;
case 2:
out.println("It\'s Tuesday.");
break;
case 3:
out.println("It\'s Wednesday.");
break;
case 4:
out.println("It\'s Thursday.");
break;
case 5:
out.println("It\'s Friday.");
break;
default:
out.println("It must be Saturday.");
}
%>
</BODY>
</HTML>

Y ou can see th e resu lts of th is cod e in Figu re 3.5 .

Week 1 – Page 85
Figure 3.5. Using the switch statement.

Take a look at th is switch state m ent; n ote th at each case statem e n t in th e switch
statem e n t m atch e s a p a rticu lar valu e of th e day varia ble. If th e valu e in day m atche s
th at given in a specific case state m ent, th e cod e in th at case statem en t is execu ted,
u p to th e break statem ent, w h ich en d s th e switch state m ent:

int day = 3;

switch(day) {
case 0:
out.println("It\'s Sunday.");
break;
case 1:
out.println("It\'s Monday.");
break;
case 2:
out.println("It\'s Tuesday.");
break;
case 3:
out.println("It\'s Wednesday.");
break;
case 4:
out.println("It\'s Thursday.");
break;

Week 1 – Page 86
case 5:
out.println("It\'s Friday.");
break;
default:
out.println("It must be Saturday.");
}

You can h a ve m u ltiple state m ents in each case statem e n t if you so d esire:

case 1:
out.println("It\'s Monday.<BR>");
out.println("Have you had your coffee yet?<BR>");
out.println("Time to go to work...<BR>");
break;

N ote also th e (option al) default state m en t at th e en d of th e switch state m en t in


th e ex a m p le— if n o case statem e n t is execu ted, th e code in th e default state m ent,
if th ere is on e, is execu ted. Y ou can even n est switch state m ents, ju st like if
statem e nts.

If y ou don 't place a break state m en t at th e en d of a case statem e nt, e xecution w ill
continu e w ith th e cod e in th e n ext case state m ent. S o m etim es th at's u sefu l, as w h en
you w an t to execute th e sa m e code for m u ltiple case test valu es, a s you see in
Lis ting 3 .7 .

Listing 3.7 Testing for Multiple Conditions (ch03_07.jsp )

<HTML>
<HEAD>
<TITLE>Testing for Multiple Conditions</TITLE>
</HEAD>

<BODY>
<H1>Testing for Multiple Conditions</H1>
<%
int temperature = 64;

switch(temperature) {
case 60:
case 61:
case 62:
out.println("Sorry, too cold!");
break;
case 63:
case 64:
case 65:
out.println("Pretty cool.");
break;
case 66:
case 67:
case 68:
case 69:

Week 1 – Page 87
out.println("Nice!");
break;
case 70:
case 71:
case 72:
case 73:
case 74:
case 75:
out.println("Fairly warm.");
break;
default:
out.println("Too hot!");
}
%>
</BODY>
</HTML>

Y ou can see th e resu lts of th is cod e in Figu re 3.6 , w h e re w e see th at th e te m p eratu re


is pretty cool.

Figure 3.6. Testing for multiple conditions in a switch statement.

T h at co m p letes ou r look at bra n ch in g state m en ts; n ext, w e'll loo k at loop s.


[ T eam L iB ]

[ T eam L iB ]

Week 1 – Page 88
Loops
Loops a re basic pro gra m m in g con stru cts th at let y ou h a n d le task s b y ex ecutin g
specific cod e ov er an d over. F or ex a m p le, y ou m igh t w an t to h a n d le th e ite m s in a
set of data by w orkin g w ith each item in su ccession , or k eep pe rform in g a task until
a particu lar cond ition becom es true.

T h ere a re a nu m b e r of d iffere n t loo p state m ents in Java, an d w e'll take a loo k at


th em all h ere, sta rtin g w ith th e for loo p.

The for Loop

In Jav a , th e basic loo p state m en t is th e for statem e nt, w h ich is a very gen e ral loo p
statem e nt. It's u su ally u sed to let you ex ecu te cod e u sin g a loo p in d ex. E ach tim e
th ro ug h th e loo p, th e loo p in d ex w ill h ave a differen t valu e, an d y ou ca n u se th e loo p
ind ex to access a differe n t d ata item in you r data set; su ch as w h en you u se th e loo p
ind ex as an ind ex into an arra y.

H ere's w h at th e for loop loo ks like in gen eral:

for (initialization_expression; end_condition; iteration_expression) {


statement;
}

T h e initialization_expression is ex ecuted befo re th e loop is ex ecu ted th e first


tim e; end_condition is che ck ed every tim e th ro u g h th e loo p, an d w h e n it beco m e s
false, th e loo p en d s; a n d iteration_expression is executed a fter ea ch tim e
th ro ug h th e loo p. statement m ak es u p th e bod y of th e loo p , h oldin g th e cod e y ou
w a n t executed ea ch tim e th rou g h th e loo p (n ote th at statement can b e a com p ou n d
statem e nt, in clu d in g several sin gle state m e nts in side cu rly braces).

For exa m p le, you can in itialize a loo p in d ex in th e initialization_expression,


pro vide a test for end in g th e loo p w h en th at test be co m es false in th e
end_condition, an d p rovide som e w ay of ch a n g in g — u su ally in cre m en tin g — th e loo p
ind ex in th e iteration_expression.

Let's m ak e th is con crete w ith an exa m p le. In th is ca se, th e cod e w ill execute a for
loo p 10 tim es. H ere, th e cod e a ssig n s a loo p in dex varia ble n a m ed loopIndex th e
valu e 1 to sta rt (as you can see in th e in itialization exp ression loopIndex = 1) an d
en d th e loo p w h en th at loo p in d ex exceeds 10 (as y ou can see in th e e n d con d ition
loopIndex <= 10, w h ich beco m e s false w h en loopIndex is greater th an 10). T h is
m e an s th at th e loo p bo d y w ill execute exa ctly 10 tim es. E a ch tim e after th e cod e in
th e body of th e loo p ex ecute s, th e code in cre m ents loopIndex b y on e (in th e
iteration expression , w h ich is loopIndex++ here ), as you see in Listin g 3.8 .

Listing 3.8 Using the for Statement (ch03_08.jsp)

Week 1 – Page 89
<HTML>
<HEAD>
<TITLE>Using the for Statement</TITLE>
</HEAD>

<BODY>
<H1>Using the for Statement</H1>
<%
int loopIndex;

for (loopIndex = 1; loopIndex <= 10; loopIndex++) {


out.println("This is iteration number "
+ loopIndex + "<BR>");
}
%>
</BODY>
</HTML>

Y ou can see th e resu lts of th is cod e in Figu re 3.7 .

Figure 3.7. Using a for loop.

H ere's an oth e r exa m p le , sho w in g h ow for loo p s an d a rray s n atu rally go tog eth e r. In
th is case, th e code w ill u se a for loo p to su m u p th e gra d es of a nu m b er of stu d ents
in an array an d com p ute th e stu d ents' av era g e gra de. In th is case, th e co d e sta rts

Week 1 – Page 90
loopIndex at 0 an d in cre m e nts it each tim e th roug h th e loo p, so you can access a
n ew stud e nt's g ra de ea c h tim e th ro u g h th e loo p . N ote th at in ad d ition to initializin g
th e loo p ind ex to 0 in th e in itialization expressio n of th e for loo p, th e c ode also
declare s th e loo p ind ex at th e sa m e tim e via int loopIndex = 0, w h ich is a h a n d y
sh ortcu t th at Java allow s (othe rw ise, y ou'd h av e to d e clare loopIndex befo re u sin g it
in th e loo p), as y ou see in Listin g 3.9 .

Listing 3.9 Finding Average Grades (ch03_09.jsp)

<HTML>
<HEAD>
<TITLE>Finding Average Grades</TITLE>
</HEAD>

<BODY>
<H1>Finding Average Grades</H1>
<%
double grades[] = {88, 98, 73, 56, 86, 64};
double sum, average;

sum = 0;

for (int loopIndex = 0; loopIndex < grades.length; loopIndex++)


{
sum += grades[loopIndex];
}

average = sum / grades.length;

out.println("Average grade = " + average);


%>
</BODY>
</HTML>

Tak e a loo k at th e for state m en t in th is exa m p le:

for (int loopIndex = 0; loopIndex < grades.length; loopIndex++) {


sum += grades[loopIndex];
}

T h is code loo ps ov er all ite m s in th e grades array an d ad d s th e m , leav in g th e resu lt


in th e variable n a m e d sum. T h e loop in d ex sta rts at 0 (b eca u se of th e in itialization
exp re ssion int loopIndex = 0) an d is steadily in cre m ented ea ch tim e th ro ug h th e
loo p, end in g after th e last item in th e array is processed (be ca u se of th e en d
cond ition loopIndex < grades.length— as w e saw in D ay 2, you can u se th e
length data m e m b er to fin d th e len gth of an array). Y ou can see th e re su lts of th is
cod e in Figu re 3.8 .

Figure 3.8. Using a for loop on an array.

Week 1 – Page 91
You can u se very gen eral expression s in th e ex pression s in a for loo p. For exa m p le,
Java lets y ou separate e xpression s in th e p arenth eses in a for loo p w ith co m m a s, as
you see in Listin g 3.1 0 , w h ere th e code su p po rts tw o loo p ind exes.

Listing 3.10 Using Two Loop Indexes (ch03_10.jsp)

<HTML>
<HEAD>
<TITLE>Using Two Loop Indexes</TITLE>
</HEAD>

<BODY>
<H1>Using Two Loop Indexes</H1>
<%
for (int loopIndex = 0, doubleIndex = 0; loopIndex <= 10;
loopIndex++, doubleIndex = 2 * loopIndex) {
out.println("loopIndex: " + loopIndex +
" doubleIndex: " + doubleIndex + "<BR>");
}
%>
</BODY>
</HTML>

Y ou can see th e resu lts of th is cod e in Fig u re 3.9 .

Week 1 – Page 92
Figure 3.9. Using two loop indexes.

You can b e ev en trick ier if you w a nt — for in stan ce, you d on 't h av e to give a for loo p
an y body at all. Y ou can see an exa m p le in w h ich th e code a verag es all th e ele m ents
of an a rray in a for loo p w ith ou t an y code in its body in Listin g 3.1 1 .

Listing 3.11 Using the for Loop (ch03_11.jsp)

<HTML>
<HEAD>
<TITLE>Using the for Statement</TITLE>
</HEAD>

<BODY>
<H1>Using the for Statement</H1>
<%
int array[] = {1, 2, 3, 4, 5}, sum = 0;

for (int loopIndex = 0;


loopIndex < array.length;
sum += array[loopIndex++]);

out.println("The average = " + sum / array.length);


%>
</BODY>

Week 1 – Page 93
</HTML>

E xp ertise w ith th is loo p com es in tim e; for n ow , w e h a ve w h at w e ne ed to kno w .


T h at tak es ca re of th e for loo p — n ext u p is th e while loo p.

The while Loop

A while loop k ee p s ex e cutin g th e state m en t in its body (w h ich m ay b e a co m p ou n d


statem e nt, w ith a n u m ber of sing le state m e nts in side cu rly braces) w h ile a p a rticu lar
cond ition evalu ates to true. H ere's w h at a while loo p looks like in gen e ral:

while(condition)
statement

N ote th at if th e condition is n ot true, th e body of th e loo p is n ot ev en ex ecuted


on ce.

H ere's an exa m p le p uttin g th e while loo p to w ork; in th is case, th e cod e w ill display
a valu e, th en subtra ct o n e fro m it th e n e xt tim e th ro u g h th e loo p , as lo n g as th at
valu e stays p ositive. W h en th e valu e beco m e s 0, th e while loop stops, beca u se th e
cond ition u sed (value < 0) h as be co m e false, as you see in Listin g 3.1 2 .

Listing 3.12 Using a while Loop (ch03_12.jsp)

<HTML>
<HEAD>
<TITLE>Using the while Loop</TITLE>
</HEAD>

<BODY>
<H1>Using the while Loop</H1>
<%
int value = 5;

while (value > 0) {


out.println("The value is now " + value-- + ".<BR>");
}
%>
</BODY>
</HTML>

You can see th e cou ntd ow n in Fig u re 3.1 0 .

Figure 3.10. Using the while loop.

Week 1 – Page 94
H ere's an oth e r while loop exa m p le, th is tim e calcu latin g
facto rials. T h e factorial of a positive integer is th e p rod u ct of
th at integer w ith all th e positive integers less th an it — for
exa m p le, th e factorial of 6 is 6 x 5 x 4 x 3 x 2 x 1 = 72 0.

You can see h ow to fin d th e fa c to rial of 6 w ith a while loo p— e ach tim e th ro ug h th e
loo p's b ody, th e cod e find s th e cu rren t prod u ct an d m ov es on to th e n ex t low er
in teger until it h as foun d th e w h ole fa cto rial, as you see in Listin g 3.1 3 .

Listing 3.13 Finding a Factorial (ch03_13.jsp)

<HTML>
<HEAD>
<TITLE>Finding a Factorial</TITLE>
</HEAD>

<BODY>
<H1>Finding a Factorial</H1>
<%
int value = 6, factorial = 1, temporaryValue = value;

while (temporaryValue > 0) {


factorial *= temporaryValue;
temporaryValue--;

Week 1 – Page 95
}

out.println("The factorial of " + value + " is " + factorial +


".");
%>
</BODY>
</HTML>

Y ou can see th e resu lts of th is cod e in Figu re 3.1 1.

Figure 3.11. Finding a factorial.

T h ere's an oth er type of while loo p in Jav a — th e do-while loo p, an d th a t's ne xt.

The do-while Loop

T h e do-while loo p is ju st like a while loo p , except th at th e test cond ition is


evalu ated at th e en d of th e loo p, n ot at th e b egin n in g . H e re's w h at th e do-while
loo p loo ks like (as b efore, state m en t can b e a com p ou n d state m en t w ith a nu m b er of
sin gle state m ents in side cu rly brac es):

do
statement
while(condition);

Week 1 – Page 96
O n e situ ation in w h ich you w ou ld u se a do-while loo p in stead of a while loo p is
w h en you ne ed th e b od y of th e loo p to b e ru n a t least on ce. F or exa m p le, th e
follow in g is a case in w h ich th e valu e th e cod e is testin g is n ot even ava ilable for
testin g u n til th e en d of th e loo p, w h ich m ea n s a while loo p w ou ld n ot b e
ap p ro p riate:

int values[] = {1, 2, 3, 0, 5}, test, index = 0;

do {
test = 5 * values[index++];
} while (test < 15);

O n th e othe r h a n d , th ere a re tim es w h en you sh ou ld u se a while loo p in stead of a


do-while loo p, as in cases in w h ich th e body of th e loo p sh ou ld n 't even ru n on ce if
th e test cond ition is n ot true. Tak e a look at th is ca se, w h ere a do-while loo p
evalu ates th e recipro cal of a valu e, b u t can on ly test if th e valu e at th e en d of t h e
loo p is n onzero :

<HTML>
<HEAD>
<TITLE>Finding Reciprocals</TITLE>
</HEAD>

<BODY>
<H1>Finding Reciprocals</H1>
<%
double values[] = {4, 3, 2, 1, 0, 1, 2, 3, 4};
int loopIndex = 0;

do {
out.println("The reciprocal = " + 1 / values[loopIndex] +
".<BR>");
} while (values[loopIndex++] != 0);
%>
</BODY>
</HTML>

Th is w ay w e w on 't av oid atte m ptin g to fin d th e recipro cal of 0, w h ich w ill cau se
m ath e m atical pro ble m s. It's b ette r he re to u se a while loo p to test for 0 before th e
body of th e loo p is executed, as you see in Listin g 3.1 4 .

Listing 3.14 Finding Reciprocals (ch03_14.jsp)

<HTML>
<HEAD>
<TITLE>Finding Reciprocals</TITLE>
</HEAD>

<BODY>

Week 1 – Page 97
<H1>Finding Reciprocals</H1>
<%
double values[] = {4, 3, 2, 1, 0, 1, 2, 3, 4};
int loopIndex = 0;

while (values[loopIndex] != 0){


out.println("The reciprocal = " + 1 / values[loopIndex++] +
".<BR>");
}
%>
</BODY>
</HTML>

Using the break Statement to End a Loop

You can also u se th e break state m en t to en d a loo p, as in Listin g 3.1 5 , w h ere th e


cod e en d s a loo p if a su m beco m es g re ate r th a n 12.

Listing 3.15 Using the break Statement (ch03_15.jsp)

<HTML>
<HEAD>
<TITLE>Using the break Statement</TITLE>
</HEAD>

<BODY>
<H1>Using the break Statement</H1>
<%
double array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;

for(int loopIndex = 0; loopIndex <


array.length; loopIndex++) {

sum += array[loopIndex];
if (sum > 12) break;
out.println("Looping...<BR>");
}
out.println("The sum exceeded the maximum allowed value.");
%>
</BODY>
</HTML>

Y ou can see th e resu lts of th is cod e in Figu re 3.1 2 , w h e re th e loo p keep s loo pin g
un til th e valu e in sum ex ceeds 12 , w h en w e u se th e break statem en t to en d th e loo p.

Figure 3.12. Using the break statement.

Week 1 – Page 98
A s y ou can see, th e break state m en t gives you control over th e execution of a loo p.
In fa ct, Ja va also h as an oth er state m e n t th at gives y ou sim ilar control — th e continue
statem e nt.

Using the continue Statement to Skip Iterations

You can u se th e continue state m en t to sk ip to th e n ext iteration of a loop. W h y


w ou ld you w a n t to d o th at? Y ou m ig h t en cou nte r so m e data in th e d ata set you're
w orkin g on th at you d on 't w an t to p rocess, for exa m p le, so you can u se th e
continue state m en t to m ov e on to th e n ext loop iteration .

H ere's an exa m p le to sh ow ho w th at w ork s — h ere, th e code is prin tin g ou t


recipro cals, an d it sh ou ld av oid tryin g to prin t ou t th e recipro cal of 0. If th e cu rren t
loo p in d ex eq u als 0, you can ju st skip th e cu rren t iteration an d m ove on to th e n ext
on e, as you see in Listin g 3.1 6 .

Listing 3.16 Skipping an Iteration (ch03_16.jsp)

<HTML>
<HEAD>
<TITLE>Using the continue Statement</TITLE>
</HEAD>

Week 1 – Page 99
<BODY>
<H1>Using the continue Statement</H1>
<%
for(double loopIndex = 6; loopIndex > -6; loopIndex--) {
if (loopIndex == 0) continue;
out.println("The reciprocal of " + loopIndex +
" is " + (1 / loopIndex) + ".<BR>");
}
%>
</BODY>
</HTML>

You can see th e resu lts of th is cod e in Figu re 3.1 3 — n ote th at th e display sk ips over
th e lin e w h ere it w ou ld try to calcu late th e reciprocal of 0.

Figure 3.13. Using the continue statement.

A n d th at co m p letes ou r loo k at loo ps in Java. W e'v e ta ken a loo k at for loo ps, while
loo ps, an d do-while loop s, an d w e've see n th e break an d continue sta tem ents to
brea k ou t of loo p s a n d continu e on to th e n ext iteration for extra p ow er. N ow let's
tu rn to th e last topic for today — cre atin g m etho d s.
[ T eam L iB ]

[ T eam L iB ]

Week 1 – Page 100


Creating Methods
W e've b e en u sin g m eth ods ev er sin ce p rin tin g ou t ou r first m essage w ith
out.println, so w e're fa m iliar w ith th e con cept — a m eth od contain s co d e th at you
can ex ecute by callin g th at m eth od:

<% out.println("Hello there!"); %>

In th is case, th e cod e is passin g th e text "Hello there!" to out.println, an d th at


m eth od w rites th at text to th e W eb p a ge.

N ow it's tim e to get th is pow er for ou rselv es. H ere's h ow y ou create a m eth od in
Java:

[access] [static] type methodName (argument_list)


.
.
.
}
To d eclare an d d e fin e a m eth od in Java, you ca n u se an
access sp ecifier, w h ich can be public, private, or
protected. T h e se acces s sp ecifiers a re u sed w h en you 're
creatin g Java classes, a n d w e'll see m ore a b ou t th e m in D ay
11 , "C reatin g M ore Pow erfu l JavaB ea n s." T h e k eyw ord static
is also all a bou t w orkin g w ith classes, an d lets p ro g ra m m e rs
u se you r m eth od w ith ou t creatin g an object from it. W e w on 't
n ee d th at h ere, so w e'll also defer th at to D a y 1 1 .
N ext, y ou m u st sp ecify th e retu rn ty p e of a m eth od, w h ich is
specified by type in th e precedin g code. T h e retu rn type
in dicates w h at kin d of data th e m eth od retu rn s w h en you call
it. For exa m p le, if you h ave a m eth od n a m ed addem th at you
pass tw o integers to , an d it a dd s th ose intege rs an d retu rn s
th e su m — of typ e int— th e retu rn typ e for th e m eth od w ill be
int. R etu rn typ e s in clu de an y valid type, su ch a s th e sim ple
data types int, float, double, an d so on . Y ou can also retu rn
an arra y, u sin g retu rn types like int[], double[], an d so on .
If y ou r m eth od d oes n ot retu rn a valu e, u se th e retu rn type
void.

N ext, y ou give th e m eth od's n a m e an d place th e list of th e a rgu m ents y ou inten d to


pass to th e m eth od afte r th at n a m e. N ote th at yo u m u st sp e cify th e ty pe of each
arg u m e nt, a s in th is case, in w h ich th e cod e is d eclarin g th e addem m eth od (to w h ich
you pass tw o integers), an d it's n a m in g th ose in tege rs op1 an d op2 (for "op e ra n d 1"
an d "op e ra n d 2"):

int addem(int op1, int op2)

Week 1 – Page 101


T h e a ctu al bo dy of th e m eth od — th e code th at w ill be ex ecuted w h en y ou call th e
m eth od — is en closed in a cod e block (delim ited w ith cu rly braces, { an d }) follow in g
th e m eth od 's d eclaration . N ote in p articu lar th a t you m u st d eclare m eth ods in JS P
declaration s (su rrou n de d by <%! an d %>), an d n ot in scriptlets (w h ich are su rroun d ed
by <% an d %>):

<HTML>
<HEAD>
<TITLE>Creating a Method</TITLE>
</HEAD>

<BODY>
<H1>Creating a Method</H1>
<%!
int addem(int op1, int op2)
{
.
.
.
}
%>
</BODY>
</HTML>

Th e cod e h as n a m e d th e tw o integers passed to th is m eth od p a rt of th e m eth od


declaration , an d n ow y o u can refer to th o se integers in th e bo dy of th e m eth od w ith
th ose n a m es. T o retu rn th eir su m fro m th is m eth od, you c an u se th e return
statem e nt:

<HTML>
<HEAD>
<TITLE>Creating a Method</TITLE>
</HEAD>

<BODY>
<H1>Creating a Method</H1>
<%!
int addem(int op1, int op2)
{
return op1 + op2;
}
%>
</BODY>
</HTML>

Th e cod e in a m eth od like addem isn 't ru n u ntil you call it. O n th e oth er h a n d , th e
cod e in a gen e ral scriple t, outside an y m eth od, is ru n a s soo n as th e p a ge is loaded.
Lis ting 3 .1 7 sh ow s h ow to call th e n ew addem m eth od, a dd 2 + 2 , an d d isplay th e
resu lt.

Week 1 – Page 102


Listing 3.17 Creating a Method (ch03_17.jsp)

<HTML>
<HEAD>
<TITLE>Creating a Method</TITLE>
</HEAD>

<BODY>
<H1>Creating a Method</H1>
<%!
int addem(int op1, int op2)
{
return op1 + op2;
}
%>

<%
out.println("2 + 2 = " + addem(2, 2));
%>
</BODY>
</HTML>

Y ou can see th e resu lts of th is cod e in Figu re 3.1 4 , w h e re w e're u sin g th e fu ll pow er
of Java to tell u s th at 2 + 2 = 4 .

Figure 3.14. Creating a method.

Week 1 – Page 103


H ere's so m eth in g to n ote — b ecau se y ou m u st d e clare m eth o d s in JS P declaration s,
n ot scriplets, th e code in you r m eth od s d oes no t h ave a ccess to th e bu ilt -in JS P
objects like out. T h at m igh t a pp e ar to b e a seriou s d raw b ack if you w a n t to sen d text
to a W eb p ag e from a m eth od, b u t you can ge t aro un d th is pro ble m if you pass th e
out obje ct to a m eth o d. W e'll see h ow th is w ork s later tod a y.

Declaring Multiple Methods

You can d eclare m u ltiple m eth o ds in th e sa m e JS P declaration , as seen in Listin g


3.1 8. T h is exa m p le declares a m eth od n a m ed subractem th at su btracts on e integer
from a n othe r an d retu rn s th e differen ce.

Listing 3.18 Declaring Multiple Methods (ch03_18.jsp)

<HTML>
<HEAD>
<TITLE>Declaring Multiple Methods</TITLE>
</HEAD>

<BODY>
<H1>Declaring Multiple Methods</H1>
<%!
int addem(int op1, int op2)
{
return op1 + op2;
}

Week 1 – Page 104


int subtractem(int op1, int op2)
{
return op1 - op2;
}
%>

<%
out.println("2 + 2 = " + addem(2, 2) + "<BR>");
out.println("8 - 2 = " + subtractem(8, 2) + "<BR>");
%>
</BODY>
</HTML>

Y ou can see th e resu lts of th is cod e in Figu re 3.1 5 .

Figure 3.15. Declaring and using multiple methods.

Using Built-In JSP Methods

T h e Java class th at JS P pa ges a re b u ilt on , HttpJspBase, h as tw o m eth ods b u ilt into


it th at are a u to m atically called at specific ti m es in th e lifecycle of a JS P -en a bled
pa ge. T h e first m eth od , jspInit, is auto m atically called w h en th e p a ge is first
created, a n d th e secon d , jspDestroy, is autom atically called w h en th e pa ge is
u n loaded a n d d e stroy ed by th e serv er.

Week 1 – Page 105


T h e pu rp ose of jspInit is to let you ru n in itialization code for
th e pa ge, a n d th e p u rp o se of jspDestroy is to let y ou ru n
clean -u p code a fte r th e pa ge is don e , w h ich can in volve
open in g an d closin g d atab ase con n ec tion s. H ere 's an exa m p le
u sin g jspInit to set a varia ble to 5 w h en th e p a ge loads, an d
settin g th at variable to 0 w h en th e pa g e is d e stroy ed. N ote
th at n eith er jspInit no r jspDestroy tak e an y arg u m e nts or
retu rn a valu e. A lso, n ote th at in th is case w e h a v e to u se th e
public keyw ord, b e ca u se w e're a ctu ally ov errid in g (overridin g
m e an s red efin ing , as y ou'll see in D ay 11 ) th e jspInit an d
jspDestroy m eth o d s. B ecau se the y w ere d eclared in
HttpJspBase w ith th e public keyw ord, Java in sists th at you
u se th at sa m e keyw ord h ere w h en red e fin in g the se m eth ods
(m ore on th e public ke yw ord in D ay 11 ), a s y o u see in
Lis ting 3 .1 9 .

Listing 3.19 Using jspInit and jspDestroy (ch03_19.jsp)

<HTML>
<HEAD>
<TITLE>Using jspInit and jspDestroy</TITLE>
</HEAD>

<BODY>
<H1>Using jspInit and jspDestroy</H1>
<%!
int number;

public void jspInit()


{
number = 5;
}
public void jspDestroy()
{
number = 0;
}
%>

<%
out.println("The number is " + number + "<BR>");
%>
</BODY>
</HTML>

A n d th at's all it tak es— n ow th is pa ge h as b oth initialization an d clean -u p cod e th at


th e serv er run s auto m atically at th e righ t tim e.

Recursion

It's also w orth kn ow in g th at JS P m eth o ds can call th e m selv es,


a process called recu rsion . T h is isn 't n ecessary kn ow led g e for

Week 1 – Page 106


th e w ork w e'll do in th is book, so y ou can skip it if you like.

You 'v e alread y seen ho w factorials w ork (for ex a m p le, th e factorial of 6 is 6 x 5 x 4 x


3 x 2 x 1 = 720), a n d fa ctorials len d th e m selves to recu rsion . T h is exa m ple su pp orts
a m eth od n a m e d factorial th at you p ass an integer to, an d it retu rn s an integer. If
th e integer w e're p asse d is 1, w e're all don e, b ecau se th e fa cto rial of 1 is 1, so w e
retu rn th at v alu e:

int factorial(int n)
{
if (n == 1) {
return n;
}
.
.
.
}

O th erw ise, all w e h a v e to do is retu rn th e cu rre n t n u m b er— sa y th at's n, m u ltiplied


by th e fa cto rial of n-1 (w h ich w e can fin d by ca llin g th e factorial m eth od ag ain ):

int factorial(int n)
{
if (n == 1) {
return n;
}
else {
return n * factorial(n - 1);
}
}

H ere's h ow th is m eth od loo ks in an exa m p le, in w h ich th e code is callin g it to fin d th e


facto rial of 6, as you see in Listin g 3.2 0 .

Listing 3.20 Using Recursion (ch03_20.jsp)

<HTML>
<HEAD>
<TITLE>Using Recursion</TITLE>
</HEAD>

<BODY>
<H1>Using Recursion</H1>
<%!
int factorial(int n)
{
if (n == 1) {
return n;
}
else {
return n * factorial(n - 1);

Week 1 – Page 107


}
}
%>

<%
out.println("The factorial of 6 is " + factorial(6));
%>
</BODY>
</HTML>

You can see th e resu lts of th is cod e in Figu re 3.1 6 , w h e re w e see th at th e factorial of
6 is 720.

Figure 3.16. Using recursion.

Scope

W h en y ou discu ss th e creation of m eth o ds, th e issu e of scop e


beco m e s im p orta nt. A n ite m 's scop e is th e a rea of you r
pro g ra m in w h ich you can refere n ce it— th at is, it's w h e re an
ite m in visible. For ex a m p le, in th e follow in g code, th e variable
n a m e d number is d e clare d outside a n y m eth od , so it's
accessible in side th e b o d y of an y m eth o d:

<%!
int number;

Week 1 – Page 108


public void jspInit()
{
number = 5;
}

public void jspDestroy()


{
number = 0;
}
%>

H o w ev er, if y ou h ad d e clared number in side a m eth od, it w ou ld be priv a te to th at


m eth od, an d you cou ldn 't access it in th e oth er m eth od:

<%!

public void jspInit()


{
int number;
number = 5;
}

public void jspDestroy()


{
//Can't use number here!
.
.
.
}
%>

In th is w ay, d eclarin g variables in m eth ods lim its th e scope of th ose va riables, w h ich
com p a rtm entalizes y ou r cod e — if a va riable is lim ited to a m eth o d, the re's less
ch a n ce th at oth er code m ig h t in a dvertently affe ct its valu e.

Note

You 'll see m ore on scop e later in th e b o ok — for exa m p le, in D ay 6,


"C reatin g JS P C o m p on e nts: JavaB e an s," you'll see ho w to lim it th e scop e of
you r d ata to a W eb pa g e or a n entire W eb ap p lication .

Passing Objects to Methods

W h en y ou pass sim p le d ata item s like integers o r floatin g -


poin t valu es to a m eth o d , a copy of th ose v alu es is m a de, an d
th e copy is actu ally passed to th e m eth od . T h at's called th e
act of passin g by valu e . H ow ever, w h en you pa ss an object to
a m eth od, a copy of th e obje ct is n ot m a de (b e c au se so m e
objects can b e h u g e); in stead, th e location of th e object in

Week 1 – Page 109


m e m o ry is p assed to th e m eth o d. T h at's called passin g by
referen ce.

T h at's im p ortan t to kno w , b e ca u se w h en an object is p assed b y referen ce, y ou th en


h ave direct access to th at object — if you ch an g e som e data in th e object in you r
m eth od, you 'll be ch an g in g th e data in th e origin al object p assed to th e m eth od
(w h ich doe sn't h a p p en w h en you pass by valu e ).

Let's tak e a look at an exa m ple to m ak e th is clearer — h ere, you can pas s an array
(rem e m b e r th at a rra ys an d strin g s are both objects) to a m eth od n a m e d doubler.
T h at m eth od w on't retu rn a n y th in g , bu t it w ill doub le th e valu e of ea ch elem en t in
th e array. B ecau se th e arra y w a s passed by referen ce, th at w ill do u ble each ele m en t
in th e origin al array a s w ell. H e re's h ow th at looks w h en you d eclare doubler to tak e
an integer array:

void doubler(int a[])


{
.
.
.
}

A n d in th e body of doubler, y ou m igh t loo p ov e r th e a rray an d d ou b le e ach valu e:

void doubler(int a[])


{
for (int loopIndex = 0; loopIndex < a.length; loopIndex++) {
a[loopIndex] *= 2;
}
}

A n d th at's all it tak es— th e fin al code displays b oth th e origin al valu es in th e a rray
an d valu es after th e call to doubler, as you see in Listin g 3.2 1 .

Listing 3.21 Passing Arrays to Methods (ch03_21.jsp)

<HTML>
<HEAD>
<TITLE>Passing Arrays to Methods</TITLE>
</HEAD>

<BODY>
<H1>Passing Arrays to Methods</H1>
<%!
void doubler(int a[])
{
for (int loopIndex = 0; loopIndex < a.length;
loopIndex++) {
a[loopIndex] *= 2;
}

Week 1 – Page 110


}
%>

<%
int array[] = {1, 2, 3, 4, 5};

out.println("Before the call to doubler...<BR>");


for (int loopIndex = 0; loopIndex < array.length;
loopIndex++) {
out.println("array[" + loopIndex + "] = " +
array[loopIndex] + "<BR>");
}

doubler(array);

out.println("After the call to doubler...<BR>");


for (int loopIndex = 0; loopIndex < array.length;
loopIndex++) {
out.println("array[" + loopIndex + "] = " +
array[loopIndex] + "<BR>");
}
%>
</BODY>
</HTML>

Y ou can see th e resu lts of th is cod e in Fig u re 3.1 7 — n ote th at each elem e n t in th e
arra y th at w e passed to doubler w as ind ee d d o ub le d, even th oug h doubler didn 't
retu rn an y valu es.

Figure 3.17. Passing arrays to methods.

Week 1 – Page 111


Passin g objects to m eth ods is esp e cially valu able w h en it co m e s to w orkin g w ith
bu ilt-in objects like th e out obje ct (w h ich are oth erw ise n ot accessible to you in
m eth ods, be cau se m eth ods h av e to b e d e clared in JS P declaration s, n ot scriptlets).

H ere's an exa m p le th at pass es th e out object to a m eth od


n a m e d printem, so th at m eth od can display som e text in a
W eb pa g e. N ote th at w e h ave to sp ecify th e typ e of object
w e're p assin g to printem, an d as w e sa w in D ay 2, out is an
object of th e Java javax.servlet.jsp.JspWriter class. In
ad d ition , n ote th e throws java.io.IOException clau se
ad d ed to th e d eclaration of printem. W e n ee d th is clau se,
beca u se if th ere's b ee n an error, th e out obje ct can "throw "
an exception of th e java.io.IOException class— th at's h ow
Java h a n d les runtim e errors, as w e're g oin g to see in D ay 8,
"H a nd lin g Errors." B eca u se th e out object can th ro w an
exception of th e java.io.IOException class, y ou're g ettin g a
sn eak p eek at ex ception h an d lin g h ere b y a d d in g th e throws
java.io.IOException clau se to th e d eclaration of printem
(Java w ill in sist th at w e do th is), as y ou see in Listin g 3.2 2 .

Listing 3.22 Passing the out Object to a Method (ch03_22.jsp)

Week 1 – Page 112


<HTML>
<HEAD>
<TITLE>Passing the out Object to a Method</TITLE>
</HEAD>

<BODY>
<H1>Passing the out Object to a Method</H1>
<%!
void printem(javax.servlet.jsp.JspWriter out) throws
java.io.IOException
{
out.println("Hello from JSP!");
}
%>

<%
printem(out);
%>
</BODY>
</HTML>

A s y ou can see in Figu re 3.1 8 , y ou can u se th e out obje ct in a m eth od .

Figure 3.18. Passing the out object to a method.

Week 1 – Page 113


H ere's an oth e r easier w ay of doin g th is — you ca n sim ply declare a n ew variable, su ch
as out2, in th e JS P d eclaration , cop y out to out2 in scriptlet code , th en u se out2 in
th e m eth od s in th e declaration as you see in Listin g 3.2 3 .

Listing 3.23 Using the out Object (ch03_23.jsp)

<HTML>
<HEAD>
<TITLE>Passing the out Object to a Method</TITLE>
</HEAD>

<BODY>
<H1>Passing the out Object to a Method</H1>
<%!
javax.servlet.jsp.JspWriter out2;

void printem() throws java.io.IOException


{
out2.println("Hello from JSP!");
}
%>

<%
out2 = out;
printem();
%>
</BODY>
</HTML>
[ T eam L iB ]

[ T eam L iB ]

Summary
A n d th at's it for b ra n ch ing , loo pin g , an d creatin g m eth od s tod ay . T h is d iscu ssion w as
all abou t a ddin g m ore p ow er to you r Java a rsen al.

W e started by ta kin g a loo k at b ra n ch in g state m ents th at en able y ou to m ak e


decision s in code. Y ou can u se if state m ents in JS P for th is p u rp o se: if th e con d ition
given in an if statem en t is true, th e code in th e bod y of th e if statem en t is
ex ecuted, a n d n ot othe rw ise. W e also saw th at if state m ents cou ld h a ve else
clau ses, a n d th at th e b o d y of an else clau se is ex ecuted if th e if state m e nt's
cond ition is false. A n d w e saw ho w to create if-else la d d ers th at cou ld h an dle
m u ltiple true/false con d ition s.

T h e switch statem en t tak es u p w h e re if-else lad d ers leave off, b ecau se su ch


lad d er state m ents can b eco m e v ery aw k w ard to pro g ra m w h en th ey get large. T h e
switch state m en t lets y ou ch eck a data item a g ain st on e or m ore case statem e nts,
an d if th ere's a m atch , th e code in th e bo dy of th e m atch in g case state m e n t is
ex ecuted. W e also sa w th at switch state m ents cou ld h ave a d efau lt sta tem en t w ith

Week 1 – Page 114


cod e to execute if n o ca se m atch ed.

You also too k a loo k at th e ava ilable loo p state m e nts toda y — th e for loo p, th e while
loo p, an d th e do-while loo p. loop state m ents let y ou loo p ov er you r code, executin g
th at code m u ltiple tim es on y ou r d ata .

A s w e'v e seen , th e for loo p is a very g en e ral loo p th at is m ost often u s ed w ith a
loo p ind ex th at you can in cre m en t (or d ecrem en t) each tim e th ro ug h th e loo p. T h e
while loo p k ee p s execu tin g th e cod e in its body w h ile th e cond ition you give it
re m ain s true, an d th e do-while loo p is th e sa m e as th e while loo p, ex cept th at th e
loo p's cond ition is ch eck ed at th e en d of th e loo p , n ot at th e begin n in g as in th e
while loo p.

Fin ally, w e took a look a t creatin g m eth o ds in JS P. M eth ods let you org a n ize you r
cod e into discrete un its, w h ich is great w h en y o u r code g ets lon g . Id eally, each
m eth od sh ou ld h a n dle on e discrete ta sk. Y ou ca n p ass data to m eth ods, process th at
data, an d retu rn oth er data fro m m eth ods.

You also too k a look at u sin g th e bu ilt-in m eth o ds jspInit an d jspDestroy today,
w h ich can be u sed for in itializin g a n d clean in g u p a W eb p ag e . W e also saw th at
w h en you pass a n object to a m eth o d, th at m eth od is passed by refere n ce, w h ich
m e an s th at you h av e direct access to th e object.

To m orro w you 're g oin g to sta rt w orkin g w ith a very p opu lar JS P topic — rea din g th e
data th e u ser sen d s y ou (as typ ed into text field s in a W eb pa g e, for ex am p le) in
you r JS P code . T o d o th at, w e're g oin g to start creatin g so m e real -w orld JS P p a ge s.

[ T eam L iB ]

[ T eam L iB ]

Q&A

Q1: A JS P d ec la ra tio n e le m e n t is g o o d fo r d e c la rin g d a ta a n d


m e th o d s — a n y th in g e lse ?

A1: Yes, as y ou'll see in D ay 8, y ou can also d e clare Java classes in a JS P


declaration ele m ent.

Q2: C a n a m e th o d re tu rn m u ltip le v a lu e s?

A2: S o m e lan g u a ges like P e rl let you retu rn m u ltiple valu es fro m a m eth od . In
Java, y ou can d o th at b y retu rn in g an array , or by creatin g a cu stom
object th at h olds th e d a ta valu es you w ant, bu t you can 't retu rn m u ltiple
sin gle valu es from a m e th od in Java.

[ T eam L iB ]

Week 1 – Page 115


[ T eam L iB ]

Workshop
T h is w ork sh op tests w h eth er y ou un d erstan d all th e con cepts y ou learn ed tod a y. It's
a goo d idea to m a ster tod ay's con cepts b y h on in g you r kn ow led g e he re before
startin g tom o rrow 's m aterial. Y ou can fin d th e a n sw ers to th e q u iz q u estion s in
A pp e n d ix A .

Quiz

1: If y ou w a nted to m atch a String valu e a g ain st fiftee n po ssible oth er


string s, w h ich w ou ld you u se, an if-else lad d e r or a switch state m e nt ?

2: H o w do you m ak e su re certain code is alw ays ru n in a switch statem e n t if


n o case state m en t is ex ecuted ?

3: W h at a re th e th ree exp ression s in side th e p aren th eses of an if statem e nt,


an d w h at do th ey do ?

4: W h at state m en t lets y ou en d a loo p ea rly?

5: W h at's th e differen ce b e tw ee n p a ssin g by valu e an d passin g by referen c e?

Exercises

1: O n e th in g Java lacks is a h a nd y m et h od n a m e d square th at retu rn s th e


squ are of valu es y ou p a ss to it. C re ate su ch a m eth od no w th at takes an
int valu e an d retu rn s a long valu e (w h y sh ou ld you retu rn a long valu e ?)
h oldin g th e squ are of th e integer. A n d don't forg et to test it ou t w ith a few
test valu es!

2: Factorials can get p retty big pretty fa st. M odify th e factorial code in tod a y's
cod e so it avoids tryin g to fin d a facto rial th at is larger th an can fit into an
int varia ble. T h e larg e s t possible integer valu e is Integer.MAX_VALUE in
Jav a. (H int: In th e cu rre n t sta ge of th e fa cto rial cod e, ch eck to see if yo u're
goin g to exceed Integer.MAX_VALUE by u sin g cond ition al state m ents to
com p a re th e valu e return ed by factorial(n-1) to Integer.MAX_VALUE /
n, w h e re n is th e n u m b e r y ou're a b ou t to m u ltiply factorial(n-1) by.)

[ T eam L iB ]

[ T eam L iB ]

Week 1 – Page 116


Day 4. Reading Data from Web
Pages: Buttons and Text Fields
Tod ay , th e glov es com e off an d w e g et dow n to som e seriou s JS P p ro g ra m m in g — th e
kin d th at JS P w as b u ilt for. In th e p reviou s tw o days, w e'v e be en g earin g u p ou r Ja va
exp ertise, an d n ow w e'll pu t it to w ork as w e cre ate JS P prog ra m s th at let th e u ser
sen d data to u s.

W e'll do th at by see in g h ow to w ork w ith H TM L controls today


an d to m o rrow . C on tro ls are th ose b u ilt-in H TM L ele m ents th at
th e u ser can interact w ith a n d enter data in , su ch as button s,
ch eck bo xes, text fields (so m etim es called text boxes b ecau se
th at's w h at th ey're called in variou s pro g ra m s, bu t th e tru e
H T M L n a m e is text field), drop -dow n lists, an d so on . W e're
goin g to p u t th ese H T M L contro ls to w ork sta rtin g n ow . H ere's
an ov erview of today's topics:

 S u p p ortin g H TM L contro ls
 W orkin g w ith H TM L form s
 S u b m ittin g form s to th e serv er
 U sin g req u est obje cts
 U sin g text fields an d sub m it bu tton s
 U sin g text areas, pass w ord con tro ls, an d h id d en controls
 U sin g button s

Tod ay's w ork w ill start b y see in g h ow to place H TM L controls in H TM L W eb p a ge s,


u sin g H TM L form s. A s y ou p rob ably kn ow , H T M L form s a ren't visible in W eb pa g es;
th ey're pu rely H TM L con stru cts th at en close H T M L controls. W e'll n ee d form s to
h a n dle H T M L controls in ou r W eb pa g e s, b eca u s e brow sers in sist th at contro ls be
em b e dd ed in form s. Y ou 'll learn abou t creatin g H T M L form s an d con figu rin g th em as
you ne ed th e m .

W h en th e u ser clicks a sub m it b utton in ou r W e b pa ges, all th e d ata in th e variou s


controls (su ch as text in th e text fields) is sen t back to th e serv er. In JS P, y ou can
get access to th at d ata u sin g th e bu ilt -in request obje ct (an obje ct of th e Java
javax.servlet. http.HttpServletRequest class). Y ou'll see th e request obje ct
today an d w h at it can d o for you as w e extract th e data th e u ser h as se nt.

T h at's w h at th is an d th e n ext day are all abou t — a d d in g H TM L controls to W e b p ag es


an d rea din g th e data th e u ser entere d into th ose controls. L et's start w ith an
ov erview of exactly w h a t H T M L controls are av a ilable to u s.
[ T eam L iB ]

[ T eam L iB ]

HTML Controls
It tu rn s ou t th at the re a re plenty of H T M L controls availa ble. H ere's th e list, in clu din g

Week 1 – Page 117


th e H TM L elem e n t y ou u se to cre ate th em — n ote in particu lar th at m a n y H TM L
controls are created w ith th e <INPUT> elem e nt, u sin g a differe n t valu e for th e TYPE
attribute to create th e v ariou s differen t controls:

 T ext fields (<INPUT TYPE="TEXT">)— T he se contro ls let th e u ser ente r a n d


edit a lin e of text. T h ey're th e m ost com m on te xt-oriented H T M L contro ls.
 B utton s (<INPUT TYPE="BUTTON">)— T h e sta n d ard clicka ble b utton s yo u see
in so m a n y W eb p ag es th ese day s.
 C h eck box es (<INPUT TYPE="CHECKBOX">)— U su ally display ed as a sm a ll box
w ith a ch eck m a rk in it. T h e u ser can tog g le th e ch eck m a rk on or off by
click in g th e ch eck b ox.
 R a dio button s (<INPUT TYPE="RADIO">)— U su a lly display ed as a circle th at,
w h en selected, displays a dot in th e m iddle, the se con tro ls act m u ch like
ch eck bo xes, ex cept th a t th ey w ork in m utu ally exclu sive g rou p s; on ly o n e
radio button m ay b e selected at a tim e.
 File u ploa din g contro ls ( <INPUT TYPE="FILE">)— A llow th e u ser to up load
files to th e server.
 H id d en controls (<INPUT TYPE="HIDDEN">)— H id d en contro ls store d ata th at
is n ot visible to th e u ser (u n less sh e view s th e p age's H TM L sou rce).
 Passw ord contro ls (<INPUT TYPE="PASSWORD">)— Like a text field, bu t th is
control m asks ea ch typ e d ch aracte r by sim p ly displayin g an asterisk (*)
in stead of th e ch ara cter itself. T h at m ea n s th is control is goo d for typin g in
pass w ord s, b eca u se if som e on e is peekin g over you r sh ou lder, h e ca n't read
you r p assw ord on th e scree n . (W a tch in g you r fing ers on th e keyb oard is, of
course, an oth er m atter.)
 R eset button s (<INPUT TYPE="RESET">)— R e se t button s are g reat for
com p lex form s, b e ca u se th ey let th e u sers clear all th e data th ey'v e ente red
to sta rt over.
 S u b m it b utton s (<INPUT TYPE="SUBMIT">)— T h e sub m it b utton is a very
im p orta n t contro l in form s, b eca u se w h en y ou click th is b utton , all th e data in
th e form (th at is, all th e data in th e controls in th e form ) is sen t to a W e b
serv er for m ore p rocessing .
 Im a g e controls (<INPUT TYPE="IMAGE">)— Ju st like sub m it button s, ex cept
th ey are im ages th e u s e r can click. T h e actu al location th at th e u ser clicked in
th e im a ge is also sen t to th e serv er w ith th e re st of th e data from th e form .
 S election lists (<SELECT>)— A lso called select controls, the se controls w ork
m u ch like dro p -d ow n list box es.
 C u sto m iza ble B utton s ( <BUTTON>)— T h is ele m e n t is a button th at can d isplay
im a ges an d othe r H T M L in side itself.
 T ext areas (<TEXTAREA>)— T h e se contro ls a re tw o -dim e n sion al text fields,
en a blin g th e u ser to enter m o re th an on e lin e of text. T ext a rea s can also
sup p ort text w ra p p in g .

T h e ne xt step is to start add in g th ese controls to W eb pa g es an d m ak in g u se of th em


in JS P code. To place an H T M L control in a W eb pa ge, y ou n e ed to en close it in an
H T M L form .

[ T eam L iB ]

[ T eam L iB ]

Week 1 – Page 118


HTML Forms
H T M L controls m u st be en closed in H TM L form s , w h ich you create w ith th e <FORM>
ele m ent. F or exa m p le, if you w an t to ad d a text field to a W eb pa ge u sin g th e
<INPUT TYPE="TEXT"> elem ent, th at ele m en t m u st be in side a form :

<HTML>
<HEAD>
<TITLE>Enter Your Data!</TITLE>
</HEAD>

<BODY>
<H1>Enter Your Data!</H1>
<FORM NAME="form1" ACTION="jsp1.jsp" METHOD="POST">
<INPUT TYPE="TEXT" NAME="text">
<INPUT TYPE="SUBMIT" VALUE="Click Me!">
</FORM>
</BODY>
</HTML>

Tip

Th e <FORM> ele m en t h a s be en a ro u n d sin ce th e first v ersion s of both


Inte rn et E xplore r an d N etsca p e N av igator. T ech n ically speak ing , you do n't
n ee d a form to display H T M L controls for Inte rn et E x plorer. H ow ever, w e'll
n ee d form s to ind icate w h ere th e data in ou r H TM L controls is to be sent. In
N etscap e N av igator, y ou n ee d form s — th e b ro w ser w on't display controls
u n less the y're in an H T M L form .

T h e attributes of th e <FORM> ele m en t a re goin g to be very im p ortan t to u s, b e ca u se


th ey'll let u s in dicate w h ere th e d ata in ou r W eb page is to b e sent. H ere a re th e
attributes of th e <FORM> elem e n t an d w h at th e y do:

 ACCEPT-CHARSET— Ind icates a list of p ossible lang u age ch ara cter sets for th e
form data. T h is attrib u te is su pp o rted b y th e W orld W ide W eb C on sortiu m
(W 3C ) for th e <FORM> elem e nt, b u t is n ot sup p o rted in Inte rn et E xplorer or
N etscap e N av igator yet.
 ACTION— T h is attribute gives th e U R L th at w ill h an d le th e form d ata. N ote
th at you can om it th is a ttrib ute, in w h ich case its d e fa u lt is th e U R L of th e
cu rren t do cu m ent. S et to an U R L .
 CLASS— T h e style class of th e elem ent. Inte rn et E xplorer on ly.
 DIR— G ives th e directio n of direction ally -n eutra l text (text th at d o esn 't h ave
in h ere n t direction , so yo u sh ou ld read it). P ossib le valu es are LTR (left-to-
righ t text or table), an d RTL (righ t-to-left text or ta ble). Inte rn et E xplore r
on ly.
 ENCTYPE— S ets th e M IM E (M u ltip u rpose In tern et M ail E xten sion ) type u sed to

Week 1 – Page 119


en cod e th e n a m e/v alu e pairs w h en sen t to th e a ction U R L. W e w on't u se th is
un til later in th e boo k , su ch as in D ay 20 , "C re a ting Im a g es on the S erv er an d
H andling Intern et P rog ra m m in g ." T h e defa u lt is "application/x-www-form-
urlencoded", bu t you can also u se "multipart/form-data", w h ich cre ates
m u ltip art form s, as fo r <INPUT TYPE="FILE"> elem ents.
 ID— A un iqu e alph an u m eric identifier for th e form elem e nt, w h ich you can
u se to refer to it. Inte rn et E x plorer on ly.
 LANG— B ase la ng u a ge u sed for th e form ele m en t. Intern et E xplor er on ly.
 LANGUAGE— S criptin g lang u age u se d for th e form elem e nt. In tern et E x plore r
on ly.
 METHOD— S pe cifies th e m eth od or p rotocol for send in g d ata to th e targ e t
action U R L. T h e GET m e th od is th e defau lt. T h is m eth od sen d s all form
n a m e/v alu e p air in form ation in an U R L th at loo ks like
URL?name=value&name=value&name=value, as w e'll discu ss today . O n th e
oth er h a n d , u sin g th e POST m eth o d, th e conten ts of th e form a re en cod ed, a s
w ith th e GET m eth od, b u t are sen t in en viro n m en t variables. S et to GET (th e
defa u lt) or POST.
 NAME— H olds a n a m e fo r th e form , so th at you can referen ce it in clien t -side
cod e (su ch a s Java S crip t). S et to an alp h a n u m e ric string .
 STYLE— In lin e style in dicatin g h ow to ren d e r th e contents of th e <FORM>
ele m ent.
 TARGET— Ind icates a n a m e d fra m e for th e b ro w ser to display th e form resu lts
in . S ee th e section "U sin g N a m e d Targ ets" tom orro w .
 TITLE— H olds ad d ition al in form ation (as m ig h t be display ed in too l tips) for
th e ele m ent. Intern et E xplore r on ly.

T h e im p orta n t attrib utes of th e <FORM> elem e n t are co m in g u p n ext.

The ACTION Attribute

You u se th e ACTION attribu te to sp ecify w h ere th e data in th e controls in a form a re


sen t to w h en th e form 's sub m it button is click ed . Fo r exa m p l e, to sen d th e d ata in a
form to http://www.starpowder.com/jsps/jsp1.jsp, y ou w ou ld set th e ACTION
attribute to th at U R L:

<FORM NAME="form1" ACTION="http://www.starpowder.com/jsps/jsp1.jsp"


METHOD="POST">
<INPUT TYPE="TEXT" NAME="text">
<INPUT TYPE="SUBMIT" VALUE="Click Me!">
</FORM>

You can also sp ecify a U R L relative to th e directory th e curren t d ocu m e n t is in . For


exa m p le, to sen d a form 's d ata to jsp1.jsp in th e sa m e directo ry a s th e curren t
docu m e nt, you can set th e ACTION attribute th is w ay:

<FORM NAME="form1" ACTION="jsp1.jsp" METHOD="POST">


<INPUT TYPE="TEXT" NAME="text">
<INPUT TYPE="SUBMIT" VALUE="Click Me!">
</FORM>

Week 1 – Page 120


Y ou can also o m it th e ACTION attribute. If you d o, th e d ata in th e form is sen t back
to th e exa ct sa m e U R L as th e curren t d ocu m e n t.

The METHOD Attribute

T h e METHOD attrib ute en ables you to sp ecify th e w ay y ou sen d th e form 's data back
to th e server. T h ere a re tw o p ossible setting s fo r th is attribute — GET an d POST, an d
JS P can h an d le both .

If y ou u se th e GET m eth od, th e data in th e form is treated as text an d a p p en d ed to


th e U R L th at th e b ro w se r n av ig ates to . T h e serv er w ill decod e th at data ap p en ded to
th e U R L an d p a ss it on to ou r JS P cod e.

For exa m p le, say th at y ou h ave tw o text fields in a form , an d th at you've n a m e d


th ese text fields (u sin g th e NAME attrib ute of th e <INPUT TYPE="TEXT"> elem e nt)
text1 an d text2, to let th e u ser ente r h is first a n d last n a m es:

<FORM NAME="form1" ACTION="http://www.starpowder.com/jsps/jsp1.jsp"


METHOD="GET">
First Name:
<INPUT TYPE="TEXT" NAME="text1">
Last Name:
<INPUT TYPE="TEXT" NAME="text2">
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>

If th e u s er enters Ralph in text1 an d Kramden in text2, an d th en clicks th e sub m it


button , th is is th e kin d of U R L th e b row ser w ill n av igate to:

http://www.starpowder.com/jsps/jsp1.jsp?text1=Ralph&text2=Kramden

T h is w ay certain ly w ork s, bu t it's n ot exa ctly private — all you r form 's da ta is ou t in
th e op en .

You can also u se th e POST m eth od, w h ich w ork s ju st as w ell as GET as far a s w e a re
con cern ed, b u t en cod es th e data as p art of th e a ctu al H ypertext T ran sfer P roto col
(H TTP) req ue st sen t to th e server. T h is m ea n s th at th e data is n ot visible to th e u ser
in th e b row ser. T h ere a re n o real disa dvanta ges to u sin g POST, except p erh aps th at
you can 't b o ok m a rk POST U R Ls an d exp ect an y n ee d ed form d ata to be sen t w h en
you open th at bo ok m a rk (as w ill h a p p en if you u se a GET U R L). A s far a s w e're
con cern ed, JS P can h an dle eith er GET or POST, so th ere's very little diffe ren ce for ou r
cod e he re.

The TARGET Attribute

T h e <FORM> ele m ent's TARGET attribute en a bles you to sp ecify w he re th e resu lts sen t
back by th e serv er w ill ap p ear. B y defau lt, w h e n you click th e su b m it b utton an d th e
serv er send s back a n ew W eb pa ge , th e n ew p age replaces th e cu rre n t page.

Week 1 – Page 121


H o w ev er, you can displa y th e n ew W eb p ag e in a n ew w ind o w if you p re fer, by
settin g th e TARGET attribute to _blank. H e re are th e p redefin ed valu es you can u se
for th e TARGET attrib ute:

 _blank— D isplay a n ew pa ge in a n ew bla n k w in d ow .


 _parent— D isplay a n ew pa ge in th e pa ren t of th e curren t fra m e.
 _self— R eplac es th e cu rren t w in d ow 's content.
 _top— R eplaces th e curren t contents of th e entire b row ser w ind o w .

You can also display th e n ew W eb p ag e sen t ba ck by th e server in a n a m e d H T M L


fra m e; you 'll see an exa m p le of th is to m o rrow .

[ T eam L iB ]

[ T eam L iB ]

Submitting Forms
You can sub m it a form to th e serv er n ow ; th is first exa m p le w ill ju st display a sub m it
button (an <INPUT TYPE="SUBMIT"> ele m ent), w h ich H TM L u ses to sen d a form 's
data to th e serv er, a s y ou see in Listin g 4.1 .

Listing 4.1 Submitting a Form (ch04_01.html)

<HTML>
<HEAD>
<TITLE>Submitting a Form</TITLE>
</HEAD>

<BODY>
<H1>Submitting a Form</H1>
<FORM NAME="form1" ACTION="ch04_02.jsp" METHOD="POST">
<INPUT TYPE="SUBMIT" VALUE="Click Me!">
</FORM>
</BODY>
</HTML>

N ote th at sub m it b utton s don 't n eed to h a ve th e ca ption "S u b m it" — yo u can u se an y
caption by settin g th e VALUE attribute. W h en th e u ser clicks th e su b m it button , an
H T T P req ue st is sen t to ch04_02.jsp on th e server, w h ich w ill ju st ack n ow ledg e th at
th e u ser click ed th e su b m it b u tton , as y ou see in Listin g 4.2 .

Listing 4.2 Getting Data From the Server (ch04_02.jsp)

<HTML>
<HEAD>
<TITLE>Back From the Server</TITLE>

Week 1 – Page 122


</HEAD>

<BODY>
<H1>Back From the Server</H1>
You clicked the button!
</BODY>
</HTML>

You can see th e H T M L p a ge w ith th e sub m it bu tton in Figu re 4.1 . W h en th e u ser


clicks th at b utton , an H TTP requ est is sen t to ch04_02.jsp on th e serv er, w h ich
retu rn s th e W eb pa ge y ou see in Figu re 4.2 .

Figure 4.1. Using a submit button.

Figure 4.2. Acknowledging an HTTP request.

Week 1 – Page 123


[ T eam L iB ]

[ T eam L iB ]

Sending Data to the Server


T h e ne xt step is to sen d som e data to th e serve r an d rea d it th ere. F or exa m p le, say
th at you h ave a text field in a W eb pa ge th at you w a n t th e u ser to ente r h is n a m e in ,
as y ou see in Listin g 4.3 .

Listing 4.3 Submitting Text Fields (ch04_03.html)

<HTML>
<HEAD>
<TITLE>Submitting Text Fields</TITLE>
</HEAD>

<BODY>
<H1>Submitting Text Fields</H1>
<FORM ACTION="ch04_05.jsp" METHOD="POST">
Please enter your name:
<INPUT TYPE="TEXT" NAME="text1">
<BR>
<INPUT TYPE="SUBMIT" value="Submit">

Week 1 – Page 124


</FORM>
</BODY>
</HTML>

N ote in p articu lar th at th is code u ses th e NAME attribute to give th e tex t field a n a m e,
text1. O n th e server, w e'll be a ble to access th e text in th e text field u sin g th at
n a m e. Y ou can see th is W eb pa g e in Figu re 4.3 . W h en th e u ser ente rs h is n a m e an d
clicks S u b m it, w e'll read th e text h e h a s entered back on th e serv er .

Figure 4.3. Submitting text fields.

To rea d th e d ata in th e text field text1, w e'll u se th e b u ilt-in JS P request obje ct.

[ T eam L iB ]

[ T eam L iB ]

Using request Objects


T h e request obje ct give s u s a ccess to th e data sen t to u s fro m H T M L fo rm s. It's an
object of type javax.servlet.http.HttpServletRequest, w h ich is b uilt on top of
javax.servlet.ServletRequest, w h ich m ea n s th e request object in clud es all th e
m eth ods in both javax.servlet.http.HttpServletRequest an d

Week 1 – Page 125


javax.servlet.ServletRequest.

You can see th e m eth od s of javax.servlet.http.HttpServletRequest in Ta ble


4.1 , an d th e m eth od s of javax.servlet.ServletRequest in Ta ble 4.2 . Tog eth e r,
th ese tw o ta bles h old th e m eth o ds ava ila ble in th e response object th at w e'll be
u sin g tod ay. Y ou can se e all th ese m eth o d s for th e sak e of referen ce — th is boo k w ill
u se m a n y , b u t n ot all, of th em in t h is an d th e com in g d ays.

N ote th at w e h av en 't seen som e of th e obje ct types retu rn ed fro m th ese m eth o ds
yet, su ch a s java.util.Enumeration, bu t th e details on th ese kind s of obje cts a re
com in g u p soo n (w e'll see h ow to u se java.util.Enumeration in D ay 5 , "R ea din g
D ata fro m W eb pa g e s: C h eck B ox es, R a dio B u tton s, an d S elect C ontro ls"). N ote also
th e w ord d ep recated in th is ta ble, in th is sen se m e an in g th at an item is con sidered
obsolete. A lth ou g h still available, dep recated item s w ill be replaced in com in g Java
version s.

Table 4.1. Methods of javax.servlet.http.HttpServletRequest


M e th o d D o e s T h is
java.lang.Object getAttribute R etu rn s th e valu e of th e n a m ed attrib ute
(java.lang.String name) as an object.
java.util.Enumeration R etu rn s an enu m e ration contain in g th e
getAttributeNames() n a m es of th e attrib utes in th is H T T P
req u est.
java.lang.String R etu rn s th e n a m e of th e ch a racter
getCharacterEncoding() en codin g u sed in th e bo d y of th is req ue st.
int getContentLength() R etu rn s th e length (in bytes) of th e b ody
of th e H TTP req u e st (or –1 if th e length is
n ot kn ow n ).
java.lang.String R etu rn s th e M IM E typ e of th e bo dy of th e
getContentType() req u est, or null if th e type is n ot kn ow n .
ServletInputStream R etu rn s th e body of th e req u est a s bin ary
getInputStream() data u sin g a ServletInputStream (see
Day 15 for m o re on Ja va read ers an d
strea m s).
java.util.Locale getLocale() R etu rn s th e preferred locale th at th e clien t
u ses; for exa m p le, en_US m e an s U S
E ng lish .
java.util.Enumeration R etu rn s an enu m e ration of Locale objects
getLocales() in dicatin g th e locales th at are accepta ble
to th e b row ser.
java.lang.String getParameter R etu rn s th e valu e of a requ e st p ara m eter
(java.lang.String name) as a String, or null if th e p ara m ete r d oes
n ot exist.
java.util.Map getParameterMap() R etu rn s a Java Map obje ct h oldin g th e

Week 1 – Page 126


para m eters in th is requ est.
java.util.Enumeration R etu rn s an enu m e ration of String objects
getParameterNames() contain in g th e n a m es of th e para m eters
contain ed in th is requ es t.
java.lang.String[] R etu rn s an a rray of String obje cts
getParameterValues contain in g all th e valu es th e given requ e st
(java.lang.String name)
para m eter h as, or null if th e para m eter
does n ot exist.
java.lang.String getProtocol() R etu rn s th e n a m e an d v ersion of th e
pro to col th e req u est u se s in th is form :

protocol/majorVersion.minorVersion
(for exa m p le, H TTP /1.1 ).
java.io.BufferedReader R etu rn s th e body of th e req u est a s
getReader() ch aracter d ata u sin g a Java
BufferedReader obje ct (see Day 15 for
m o re on Java rea de rs a n d strea m s).
java.lang.String getRealPath D ep recated. A s of version 2.1 of th e Java
(java.lang.String path) S ervlet A PI, u se ServletContext.getReal
Path(java.lang.String) in stea d.
java.lang.String getRemoteAddr() R etu rn s th e Inte rn et P rotocol (IP) a dd ress
th at th e req u est co m es fro m .
java.lang.String getRemoteHost() R etu rn s th e n a m e of th e clien t th at sen t
th e req u est.
java.lang.String getScheme() R etu rn s th e n a m e of th e proto col u sed in
th is requ est; for exa m p le: H TT P , H T T P S , or
FTP.
java.lang.String getServerName() R etu rn s th e h ostn a m e o f th e server th at
received th e req ue st.
int getServerPort() R etu rn s th e po rt nu m b e r on w h ich this
req u est w a s received.
boolean isSecure() R etu rn s true if th is req u est w a s m a d e
u sin g a secure ch a nn el, su ch as H T TP S ,
an d false othe rw ise.
void R e m o ves an attribute from th is requ est
removeAttribute(java.lang.String (m ore on req ue st attrib utes la ter).
name)
void S tores an attrib ute in th is req ue st (m o re
setAttribute(java.lang.String on req ue st attributes later).
name, java.lang.Object)
void setCharacterEncoding O v errides th e n a m e of th e ch a racter
(java.lang.String env) en codin g u sed in th e bo d y of th is requ e st.

Week 1 – Page 127


Table 4.2. Methods of javax.servlet.ServletRequest
M e th o d D o e s T h is
java.lang.String getAuthType() R etu rn s th e n a m e of th e auth entication
sch e m e u sed to protect th e pa ge.
java.lang.String getContextPath() R etu rn s th e part of th e requ est U R L th at
in dicates th e context of th e req u est. W e'll
see m ore a b ou t requ e st con texts later.
Cookie[] getCookies() R etu rn s an a rray contain in g all th e Cookie
objects sen t w ith th is re qu est.
long R etu rn s th e valu e of th e s pe cified requ e st
getDateHeader(java.lang.String h ea de r corresp on d in g to a Jav a Date
name) object.
java.lang.String getHeader R etu rn s th e valu e of th e sp e cified req ue st
(java.lang.String name) h ea de r as a String.
java.util.Enumeration R etu rn s an enu m e ration of all th e h ea d e r
getHeaderNames() n a m es th is re qu est con tain s.
java.util.Enumeration getHeaders R etu rn s all th e valu es of th e in dicated
(java.lang.String name) req u est he a de r as an Enumeration of
String obje cts.
int getIntHeader(java.lang.String R etu rn s th e valu e of th e sp e cified req ue st
name) h ea de r as an int.
java.lang.String getMethod() R etu rn s th e n a m e of th e H T T P m eth od
w ith w h ich th is requ est w as m ad e, for
exa m p le, GET, POST, or PUT.
java.lang.String getPathInfo() R etu rn s an y extra p ath in form ation
associated w ith th e U R L sen t fo r th is
req u est.
java.lang.String R etu rn s an y extra p ath in form ation ,
getPathTranslated() tran slatin g it into a real path .
java.lang.String getQueryString() R etu rn s th e qu e ry strin g th at is contain ed
in th e req u est U R L after th e p ath .
java.lang.String getRemoteUser() R etu rn s th e login of th e u ser m ak in g th is
req u est if th e u ser h as b ee n auth e nticated
(or null if th e u ser h a s n ot be en
auth en ticated).
java.lang.String R etu rn s th e session ID of th e re qu e st.
getRequestedSessionId()
java.lang.String getRequestURI() R etu rn s th e p art of th is req u est's U R L
from th e p ro tocol n a m e to th e qu ery
string .
java.lang.StringBuffer R etu rn s th e U R L th e clien t u sed to m ak e

Week 1 – Page 128


getRequestURL() th e req u est.
java.lang.String getServletPath() R etu rn s th e part of th is req u est's U R L th at
calls th e servlet.
HttpSession getSession() R etu rn s th e cu rre n t session associated
w ith this requ est; or if th e req u e st do es
n ot h ave a session , crea tes on e.
HttpSession getSession(boolean R etu rn s th e curren t session associated
create) w ith th is req u est.
java.security.Principal R etu rn s th e n a m e of th e cu rre n t
getUserPrincipal() auth en ticated u ser.
boolean Ind icates w h eth e r th e requ ested session
isRequestedSessionIdFromCookie() ID cam e from a cookie.
boolean D ep recated. A s of V ersion 2.1 of th e Java
isRequestedSessionIdFromUrl() S ervlet A PI, u se th e
isRequestedSessionIdFromURL()
m eth od in stead.
boolean Ind icates w h eth e r th e requ ested session
isRequestedSessionIdFromURL() ID cam e from th e re qu e st U R L.
boolean Ind icates w h ethe r th e session ID is still
isRequestedSessionIdValid() valid.
boolean Ind icates w h eth e r th e u ser is in clud ed in
isUserInRole(java.lang.String th e sp ecified logical "ro le" (ro les a re p a rt
role) of auth entication sch e m es th at in d icate
w h at gro u p a u ser is associated w ith ).

T h e request obje ct h old s a great d eal of in form ation th at is u sefu l to JS P


pro g ra m m e rs. Y ou can see a sa m p le pa ge th at d isplays so m e of th at in form ation in
Lis ting 4 .4 .

Listing 4.4 Decoding an HTTP request (ch04_04.jsp)

<HTML>
<HEAD>
<TITLE>Decoding an HTTP Request</TITLE>
</HEAD>

<BODY>
<H1> Request Information </H1>
JSP request method: <%= request.getMethod() %>
<BR>
URL for the request: <%= request.getRequestURI() %>
<BR>
Protocol of the request: <%= request.getProtocol() %>
<BR>
Server name: <%= request.getServerName() %>
<BR>

Week 1 – Page 129


Path: <%= request.getServletPath() %>
<BR>
Server port: <%= request.getServerPort() %>
<BR>
Remote address: <%= request.getRemoteAddr() %>
<BR>
Remote host: <%= request.getRemoteHost() %>
<BR>
Locale: <%= request.getLocale() %>
<BR>
User agent: <%= request.getHeader("User-Agent") %>
</BODY>
</HTML>

You can see th e resu lts of th is in Figu re 4.4 , displayin g su ch in form ation as th e form
m eth od, serv e r po rt, an d so on .

Figure 4.4. Deciphering the request object.

N ote in particu lar th e u ser a gen t in form ation yo u see in Figu re 4.4 , w h ich gives y ou
access to th e typ e of b row ser th e u ser is u sing . In Fig u re 4 .4 , you see Intern et
E xplorer 6 .0, an d you can see th at in th e text retu rn ed b y th e call to
request.getHeader("User-Agent"):

Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; COM+ 1.0.2204; .NET


CLR 1.0.3512)

You can u se Java String m eth od s (see Table 2.3 ) to extra ct th e type a n d version of
th e u ser's b row ser from th is data. B ecau se b ro w sers h ave differen t ca pa bilities, th is
in form ation is often essential w h en you 're creatin g W eb pa ges to sen d back to th e

Week 1 – Page 130


u ser— for exa m p le, you can tailor you r W eb p ag e on e w a y for Inte rn et E xplorer, an d
an oth er for N etsca pe N a vigator:

<HTML>
<HEAD>
<TITLE>Determining User Agent</TITLE>
</HEAD>

<BODY>
<H1>Determining User Agent</H1>
<%
if(request.getHeader("User-Agent").indexOf("MSIE") >= 0){
out.println("You're using Internet Explor er.");
//Internet Explorer code.
}
if(request.getHeader("User-Agent").indexOf("Netscape") >= 0){
out.println("You're using Netscape Navigator.");
//Netscape Navigator code.
}
%>
</BODY>
</HTML>

Tip

Th e u ser age n t text is th e sa m e a s in th e userAgent pro p erty of th e


navigator obje ct th at y ou can a ccess u sin g Jav a S cript in th e bro w ser. In
Inte rn et E xplore r, you 'll alw ays fin d "MSIE" follow ed by th e version of th e
bro w ser in th is text. In N etscap e N av igator, y ou'll fin d "Netscape" follow ed
by th e v ersion n u m ber. In earlier v ersion s of N e tsca pe N av ig ator, y ou w on't
fin d "Netscape"— in stead, u se th e v ersion nu m b er, w h ich you'll fin d righ t
after th e text "Mozilla/".

[ T eam L iB ]

[ T eam L iB ]

Reading Data on the Server


In JS P code, y ou u se th e request obje ct's getParameter m eth od to rea d data fro m
H T M L controls. Fo r exa m p le, w e n a m e d th e tex t field in ou r exa m p le text1:

<HTML>
<HEAD>
<TITLE>Submitting Text Fields</TITLE>
</HEAD>

Week 1 – Page 131


<BODY>
<H1>Submitting Text Fields</H1>
<FORM ACTION="ch04_05.jsp" METHOD="POST">
Please enter your name:
<INPUT TYPE="TEXT" NAME="text1">
<BR>
<INPUT TYPE="SUBMIT" value="Submit">
</FORM>
</BODY>
</HTML>

O n th e server, you can get th e d ata th at th e u ser p u t in th at text f ield by p assin g


th at n a m e to request.getParameter, as you se e in Listin g 4.5 .

Listing 4.5 Reading Data from Text Fields (ch04_05.jsp)

<HTML>
<HEAD>
<TITLE>Reading Data From Text Fields</TITLE>
</HEAD>

<BODY>
<H1>Reading Data From Text Fields</H1>
Your name is
<% out.println(request.getParameter("text1")) ; %>
</BODY>
</HTML>

Th at's all it tak es— u sin g th e exp ression request.getParameter("text1"), w e can


retrieve th e text in th e text fie ld n a m e d text1, as y ou see in Figu re 4.5 .

Figure 4.5. Reading text from a text field.

Week 1 – Page 132


T h at's ho w it w orks in gene ral— you can u se th e request.getParameter m eth od to
retrieve data from H T M L contro ls, p a ssin g th at m eth od th e n a m e you'v e given to th e
control. In th is case, th e text field w as n a m ed text1, an d passin g th at n a m e to
request.getParameter retu rn s th e data th at w a s in th e text field (th e d ata is
retu rn ed as a Ja v a strin g).

[ T eam L iB ]

[ T eam L iB ]

Using Text Fields


A s w e'v e seen , you can retrieve th e data in a text field w ith th e
request.getParameter m eth od. Y ou can d o m ore th an ju st retriev e th e data fro m
controls like text fields; you can also in sert data in th ose contro ls w h en you sen d
th em b ack fro m th e server.

In th is case, for exa m p le, th e code w ill let th e u ser click a b utton , an d w h en h e d oes,
it w ill display a m essa ge in a text field. Y ou can see th e H TM L p a g e in Listin g 4.6 .

Listing 4.6 Inserting Text into Text Fields (ch04_06.html )

<HTML>
<HEAD>
<TITLE>Inserting Text into Text Fields</TITLE>
</HEAD>

Week 1 – Page 133


<BODY>
<H1>Inserting Text into Text Fields</H1>
<FORM NAME="form1" ACTION="ch04_07.jsp" METHOD="POST">
<INPUT TYPE="TEXT">
<INPUT TYPE="SUBMIT" VALUE="Click Me!">
</FORM>
</BODY>
</HTML>

You see th is pa ge in Figu re 4 .6 .

Figure 4.6. Web page with a text field.

W h en th e u ser clicks th e S ub m it b utton , you ca n sim ply sen d back th e sa m e p ag e


from th e serv er, except w ith th e m essa g e in th e text field, w h ich you ca n set w ith
th e text field's VALUE attribute, as you see in Listin g 4.7 .

Listing 4.6 Putting Text into Text Fields (ch04_07.jsp)

<HTML>
<HEAD>
<TITLE>Inserting Text into Text Fields</TITLE>
</HEAD>

<BODY>
<H1>Inserting Text into Text Fields</H1>
<FORM NAME="form1">
<INPUT TYPE="TEXT" VALUE="Hello from JSP!">
<INPUT TYPE="SUBMIT" VALUE="Click Me!">
</FORM>
</BODY>

Week 1 – Page 134


</HTML>

Y ou can see th e resu lts in Figu re 4.7 — w h en th e u ser clicks th e b utton , th e m e ssa g e
"Hello from JSP!" ap p ea rs in th e text field. T h is gives you r cod e th e feel of clien t -
side pro g ra m m in g , bu t it's really serve r-side pro gra m m in g — to m ak e th a t m essa ge
ap p ea r ta kes a roun d -trip to th e serv er, w h ich can take tim e. If you n e e d m o re
im m ediate resu lts w ith ou t w aitin g a n d do n't n ee d to access Java on th e serv er, u se a
scriptin g lan gu a ge su ch as Java S cript in th e bro w ser.

Figure 4.7. Inserting text into a text field.

W h en th e u ser enters text into a text field, you can read th at text in yo u r code an d
com p a re it ag ain st variou s text string s, an d n ow th at w e're dealin g w ith th e text
in put, w h ich brin g s u p an im p ortan t poin t abou t Java strin g h an dling . To co m p a re
tw o string s, you sh ou ld u se th e String class's equals m eth o d, n ot th e == relation al
ope rato r w e saw in D ay 2 . Fo r exa m p le, he re's h ow y ou can ch eck w h eth er th e u ser
h as typed "JSP rules!" in a text field:

<HTML>
<HEAD>
<TITLE>Checking Your Response</TITLE>
</HEAD>

<BODY>
<H1>Checking Your Response</H1>
<%
if(request.getParameter("text1").equals("JSP rules!")){
out.println("You typed JSP rules!");
}
else {

Week 1 – Page 135


out.println("You didn't type JSP rules!");
}
%>
</BODY>
</HTML>

Tip

If a form on ly h as a text field an d n o oth er controls (in clu din g n o su b m it


button ), th e brow s er co n vention is to su b m it th e data fro m th e text field
w h en th e u ser presses th e <Enter> k ey — n o sub m it b u tton is n ee ded.

[ T eam L iB ]

[ T eam L iB ]

Using Text Areas


T ext areas a re like text fields, except th at you can ente r m u ltiple lin es o f text. A lso
u sin g text area s in code is m u ch like u sin g text fields as w el l; you can see an
exa m p le th at displays a text a rea n a m e d textarea1— th e u ser can ente r text a n d
click th e su b m it button to sen d th at text ba ck to th e serv er — in Listin g 4 .8 .

Listing 4.8 Submitting Text Areas (ch04_08.html)

<HTML>
<HEAD>
<TITLE>Submitting Text Areas</TITLE>
</HEAD>

<BODY>
<H1>Submitting Text Areas</H1>
<FORM ACTION="ch04_09.jsp" METHOD="POST">
Please enter your text:
<BR>
<TEXTAREA NAME="textarea1" ROWS="5"></TEXTAREA>
<BR>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</BODY>
</HTML>

Y ou can see th is text area in Figu re 4.8 , alon g w ith so m e m u lti-lin e text in it.

Figure 4.8. Using a text area.

Week 1 – Page 136


You can h a nd le th at m u ltilin e text by displayin g it w ith th e lin e break s intact in th e
JS P pa ge, ch04_09.jsp. T h e lin e break s in th e text fro m th e text a rea a re
rep rese n ted b y '\n' ch aracters (see "D eterm in in g S trin g Len gth " in D a y 2). T h at
ch aracter stan d s for a lin e b reak in text a s Java h an d les it, bu t th e bro w ser w ill
ign ore it beca u se it's no t H T M L. To create lin e brea ks in th e b row ser, w e h av e to
replace '\n' ch a racters in th e text fro m th e tex t area w ith th e strin g "<BR>".

T h e p ro ble m w ith doin g th at is th at th e String class replace m eth od (see Table


2.3) on ly en a bles y ou to replace a sin g le ch aracter w ith an oth er sin g le ch aracter (so
th at th e strin g's length w on't ch a n g e). In stea d, w e can u se th e Java StringBuffer
class (w h ich you 'll fin d d ocu m en ted in th e Java docu m e ntation — see "O n lin e JS P
R esou rces" in D ay 1), w h ich sup p orts string s you can m o dify, an d w h ose replace
m eth od en a bles you to su b stitute on e su b strin g for a n oth er. O n th e oth er h a n d , th e
StringBuffer class doe sn't h ave an indexOf m eth od th at en a bles you to sea rch th e
text for '\n' ch a racters (th e StringBuffer m eth ods are g e a red to m o d ifyin g text,
n ot sea rch in g it). S o, to m ake w h at w e w a n t to h a p p en actu ally h ap p e n , w e can start
by sto rin g th e text from th e text are a in a StringBuffer obje ct n a m e d text:

<HTML>
<HEAD>
<TITLE>Reading Text Areas</TITLE>
</HEAD>

<BODY>

Week 1 – Page 137


<H1>Reading Text Areas</H1>
You typed:
<BR>
<%
StringBuffer text = new
StringBuffer(request.getParameter("textarea1"));
.
.
.

Th en , to search for th e ch aracter '\n', w e can create a tem p ora ry String obje ct
based on text, an d u se th is n ew obje ct's indexOf m eth od (w h ich return s –1 if '\n'
isn't foun d ):

<HTML>
<HEAD>
<TITLE>Reading Text Areas</TITLE>
</HEAD>

<BODY>
<H1>Reading Text Areas</H1>
You typed:
<BR>
<%
StringBuffer text = new
StringBuffer(request.getParameter("textarea1"));

int loc = (new String(text)).indexOf('\n');


.
.
.

A ll th at's left is to replace all '\n' ch aracters w ith "<BR>" u sin g th e text obje ct's
replace m eth o d, a n d y ou can see w h at th at looks like in th e while loo p in Listin g
4.9 .

Listing 4.9 Reading Text from Text Areas (ch04_09.jsp)

<HTML>
<HEAD>
<TITLE>Reading Text Areas</TITLE>
</HEAD>

<BODY>
<H1>Reading Text Areas</H1>
You typed:
<BR>
<%
StringBuffer text = new
StringBuffer(request.getParameter("textarea1"));

int loc = (new String(text)).indexOf('\n');

Week 1 – Page 138


while(loc > 0){
text.replace(loc, loc+1, "<BR>");
loc = (new String(text)).indexOf('\n');
}
out.println(text);
%>
</BODY>
</HTML>

N ow you 're a ble to display th e m u ltilin e text from th e text area in a W e b pa ge u sin g
<BR> ele m ents, as you see in Fig u re 4.9 .

Figure 4.9. Reading text from text areas.

[ T eam L iB ]

[ T eam L iB ]

Using Password Controls


O n e of th e rea son s pe op le u se JS P is to auth e nticate u sers by che ck in g pass w ord s,
an d you can u se p assw o rd con tro ls ( <INPUT TYPE="PASSWORD">) to let th e u ser

Week 1 – Page 139


enter a p assw ord. Y ou can see an exa m p le in Listin g 4.1 0 .

Listing 4.10 Using Password Controls (ch04_10.html)

<HTML>
<HEAD>
<TITLE>Using Password Controls</TITLE>
</HEAD>

<BODY>
<H1>Using Password Controls</H1>
<FORM ACTION="ch04_11.jsp" METHOD="POST">
Please enter your password:
<INPUT TYPE="PASSWORD" NAME="password">
<BR>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</BODY>
</HTML>

Y ou can see th e p assw o rd control at w ork in Figu re 4 .1 0 .

Figure 4.10. Using password controls.

Week 1 – Page 140


N ow you can ch eck th e pass w ord an d resp on d a ccordin gly, as you see in Listin g
4.1 1.

Listing 4.11 Reading Text from Password Controls (ch04_11.jsp)

<HTML>
<HEAD>
<TITLE>Reading Password Controls</TITLE>
</HEAD>

<BODY>
<H1>Reading Password Controls</H1>
<%
if(request.getParameter("password").equals("Open Sesame"){
out.println("You're in!");
}
else {
out.println("I don't think so!");
}
%>
</BODY>
</HTML>

Th at's all th ere is to it, as y ou see in Fig u re 4.1 1 , w h e re w e'v e read th e passw ord
an d verified th e u ser.

Figure 4.11. Reading text from a password control.

Week 1 – Page 141


[ T eam L iB ]

[ T eam L iB ]

Using Hidden Controls


H id d en controls let you store text in a W eb pa g e th at th e u se r do esn 't see (un le ss
sh e sp e cifically view s th e H T M L source for th e p age). T h ese controls are a go od
altern ative to u sin g coo kies to sto re pa ge -sp ecific data. You can see an exa m p le
w h ere th e code is storin g so m e text in a h id d en field in Listin g 4.1 2 .

Listing 4.12 Submitting Hidden Fields (ch04_12.html)

<HTML>
<HEAD>
<TITLE>Submitting Hidden Fields</TITLE>
</HEAD>

<BODY>
<H1>Submitting Hidden Fields</H1>
<FORM ACTION="ch04_13.jsp" METHOD="POST">
<INPUT TYPE="HIDDEN" NAME="HIDDEN" VALUE="Hello from JSP!">

Week 1 – Page 142


<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</BODY>
</HTML>

A n d you can see a JS P p age th at reads th e text in th e h id d en control in Listin g 4.1 3 .

Listing 4.13 Reading Text from Hidden Controls (ch04_13.jsp)

<HTML>
<HEAD>
<TITLE>Reading Hidden Controls</TITLE>
</HEAD>

<BODY>
<H1>Reading Hidden Controls</H1>
The hidden text is:
<% out.println(request.getParameter("HIDDEN")); %>
</BODY>
</HTML>

Y ou can see th e resu lts in Figu re 4.1 2 .

Figure 4.12. Reading text from a hidden control.

Week 1 – Page 143


H id d en controls can be very u sefu l in JS P pro g ra m m in g , as w e'll see in th e n ext
topic.

[ T eam L iB ]

[ T eam L iB ]

Using Buttons
B esides su b m it button s, you can u se stan d ard H TM L b utton s w ith JS P. H ere's an
exa m p le th at u ses thre e stan d a rd b utton s. W h e n th e u ser clicks on e of th e button s,
ou r JS P code w ill in dicate w h at button w a s click ed.

T h is exa m p le w ork s u sin g so m e Java S cript in th e brow s er (w e'll take a m o re in -


depth look at u sin g Java S cript w ith JS P in D ay 21 , "C lien t-Side P ro gra m m in g an d
D eployin g Y ou r P ro jects"). W h en th e u ser clicks a button , a Ja va S cript fun ction is
called th at sets a h idd en field w ith th e n a m e of th e b utton click ed (su ch as B utton 1),
an d th en su b m its th e fo rm u sin g th e Java S cript submit m eth od. Y ou ca n see w h at
th e code looks like in Listin g 4.1 4 .

Listing 4.14 Using Buttons (ch04_14.html)

Week 1 – Page 144


<HTML>
<HEAD>
<TITLE>Using Buttons</TITLE>
</HEAD>

<BODY>
<H1>Using Buttons</H1>
<FORM NAME="form1" ACTION="ch04_15.jsp" METHOD="POST">
<INPUT TYPE="HIDDEN" NAME="buttonName">
<INPUT TYPE="BUTTON" VALUE="Button 1" ONCLICK="button1()">
<INPUT TYPE="BUTTON" VALUE="Button 2" ONCLICK="button2()">
<INPUT TYPE="BUTTON" VALUE="Button 3" ONCLICK="button3()">
</FORM>

<SCRIPT LANGUAGE="JavaScript">
<!--
function button1()
{
document.form1.buttonName.value = "button 1"
form1.submit()
}
function button2()
{
document.form1.buttonName.value = "button 2"
form1.submit()
}
function button3()
{
document.form1.buttonName.value = "button 3"
form1.submit()
}
// -->
</SCRIPT>
</BODY>
</HTML>

You can see th is p a ge in Figu re 4.1 3 .

Figure 4.13. Using standard buttons.

Week 1 – Page 145


In th e JS P cod e, all you n ee d to do is recov er th e n a m e of th e b utton th at w as
click ed fro m th e h idd en control an d display it, a s y ou see in Listin g 4.15 .

Listing 4.15 Determining Which Button Was Clicked (ch04_15.jsp)

<HTML>
<HEAD>
<TITLE>Determining Which Button Was Clicked</TITLE>
</HEAD>

<BODY>
<H1>Determining Which Button Was Clicked</H1>
You clicked
<%= request.getParameter("buttonName") %>
</BODY>
</HTML>

You can see th e resu lts in Figu re 4.1 4 , w h ere, w ith a little h elp fro m h id d en contro ls
an d Java S cript, w e see th at B utton 2 w as click e d . T h at's on e w ay of h a nd lin g
m u ltiple b utton s— stay tun ed for a few m ore.

Figure 4.14. Determining which button was clicked.

Week 1 – Page 146


[ T eam L iB ]

[ T eam L iB ]

JSP to JSP—Navigating Directly to JSP Pages


S o fa r toda y, w e'v e u se d H T M L p ag es th at y ou n av igate to first, an d JS P pa g e s to
h a n dle in p u t fro m th ose H T M L pa g es. In oth er w ord s, w e'v e u sed intro du ctory H TM L
pa ges to give u sers a cc ess to ou r J S P pa g es.

H o w ev er, it's im p ortan t to realize th at you can n av ig ate directly to JS P p ages, even
w h en you 're sen d in g da ta to th ose pa g es. W h en you open th e JS P pa g e for th e first
tim e, you 're n ot send in g an y data fro m H TM L contro ls to th at pa ge, so
request.getParameter("controlName") w ill retu rn th e Ja va valu e null, w he re
controlName is a con tro l in you r pa ge w h ose da ta you w ant. Y ou can u se th is fact to
determ in e w h ethe r th ere's an y data sen t to y ou from H T M L controls, an d if n ot,
sim ply display an intro d u ctory W eb p ag e th e w a y y ou w a n t th e u sers to see it before
th ey'v e ente red a n y d ata.

For in sta n ce, you can rew rite th e p reviou s exa m ple, p uttin g everyth in g into on e JS P
pa ge — if th e u ser h as clicked a button , you can ind icate w h at button w a s click ed;

Week 1 – Page 147


oth erw ise, y ou can ju st display th e b utton s, as you see in Listin g 4.1 6 .

Listing 4.16 Using Buttons (ch04_16.jsp)

<HTML>
<HEAD>
<TITLE>Using Buttons</TITLE>
</HEAD>

<BODY>
<%
if(request.getParameter("buttonName") != null) {
%>
You clicked
<%= request.getParameter("buttonName") %>
<%
}
%>

<FORM NAME="form1" METHOD="POST">


<INPUT TYPE="HIDDEN" NAME="buttonName">
<INPUT TYPE="BUTTON" VALUE="Button 1" ONCLICK="button1()">
<INPUT TYPE="BUTTON" VALUE="Button 2" ONCLICK="button2()">
<INPUT TYPE="BUTTON" VALUE="Button 3" ONCLICK="button3()">
</FORM>

<SCRIPT LANGUAGE="JavaScript">
<!--
function button1()
{
document.form1.buttonName.value = "button 1"
form1.submit()
}
function button2()
{
document.form1.buttonName.value = "button 2"
form1.submit()
}
function button3()
{
document.form1.buttonName.value = "button 3"
form1.submit()
}
// -->
</SCRIPT>
</BODY>
</HTML>

To see h ow th is w orks, you can n a vigate to


http://localhost:8080/ch04/ch04_16.js p, click a b utton , an d you'll see th e resu lts
in Fig u re 4.1 5 . E v eryth in g is h a n dled by th at on e JS P p ag e — n o intro d u ctory H T M L
pa ge is n ee d ed.

Week 1 – Page 148


Figure 4.15. Using a literal in Java.

N ote th at th ere a re tim e s w h en th e data in H T M L contro ls m ig h t actu ally retu rn a


valu e of null w h en y ou u se getParameter, so h ere's a m ore g en e ral w a y of testin g
if data w as sen t to you — you can u se th e request obje ct's getParameterNames
m eth od (th at w e'll see tom o rrow ), w h ich retu rn s th e n a m es of th e H T M L contro ls
th at sen t y ou data. If th is m eth od retu rn s null, it's a sure b et th at th er e's n o data
w aitin g for you to p roce ss:

if(request.getParameterNames() != null) {
//Process data from HTML controls
}
else {
//Display introductory Web page
}

In th is exa m p le, w e'v e bee n h an d lin g m u ltiple button s in a form w ith th e aid of
Java S cript. B u t th is isn't a b o ok on Java S cript, it's a b ook on JS P. Isn't th ere a w ay
to h a nd le m u ltiple b utton s ju st u sin g JS P? T he re is — you can u se m u ltiple H TM L
form s.
[ T eam L iB ]

[ T eam L iB ]

Week 1 – Page 149


Using Multiple Forms
A sin gle W eb pa g e can sup p ort m u ltiple H TM L form s, an d th at's often u sefu l. Fo r
exa m p le, on e w ay to su p p ort m u ltiple b utton s in a W eb pa ge is to m ak e th e m all
sub m it bu tton s an d place th e m ea ch in th eir ow n form . W h en th e u se r clicks a
button , th at form 's d ata is sen t to th e serv er. T o distin gu ish betw ee n th e va riou s
form s, you can g ive each form a h id d en control w ith iden tifyin g text th a t you can
read in you r JS P cod e.

For exa m p le, you can see h ow to sup p ort th ree differen t button s in th re e differe n t
form s in Listin g 4.1 7 , w h ere each form contain s h id den text h oldin g th e button 's
n a m e. W h en th e u se r clicks a b utton , ou r cod e can display th e click ed b utton's n a m e
u sin g th at h id d en text.

Listing 4.17 Using Multiple Forms (ch04_17.jsp)

<HTML>
<HEAD>
<TITLE>Using Multiple Forms</TITLE>
</HEAD>

<BODY>
<H1>Using Multiple Forms</H1>
<%
if(request.getParameter("buttonName") != null) {

%>
You clicked
<%= request.getParameter("buttonName") %>
<%
}
%>

<FORM NAME="form1" METHOD="POST">


<INPUT TYPE="HIDDEN" NAME="buttonName" VALUE="button 1">
<INPUT TYPE="SUBMIT" VALUE="Button 1">
</FORM>

<FORM NAME="form2" METHOD="POST">


<INPUT TYPE="HIDDEN" NAME="buttonName" VALUE="button 2">
<INPUT TYPE="SUBMIT" VALUE="Button 2">
</FORM>

<FORM NAME="form3" METHOD="POST">


<INPUT TYPE="HIDDEN" NAME="buttonName" VALUE="button 3">
<INPUT TYPE="SUBMIT" VALUE="Button 3">
</FORM>
</BODY>
</HTML>

Y ou can see th e resu lts in Figu re 4.1 6 .

Week 1 – Page 150


Figure 4.16. Supporting multiple forms.

In fa ct, th ere's an easie r w ay to d o th is. S u b m it button s are H T M L controls like an y


oth er, w h ich m e an s you can read th e text in th eir VALUE attributes— th at is, th eir
caption s— u sin g getParameter. If you give each su b m it b utton th e sa m e n a m e b u t
differe n t caption s, you can read th ose caption s in ou r JS P code to d ete rm in e w h at
button w as clicked, as y ou see in Listin g 4.1 8 .

Listing 4.18 Using Multiple Forms Using Buttons with Multiple


Names (ch04_18.jsp )

<HTML>
<HEAD>
<TITLE>Using Multiple Forms</TITLE>
</HEAD>

<BODY>
<H1>Using Multiple Forms</H1>
<%
if(request.getParameter("submit") != null) {
%>
You clicked
<%= request.getParameter("submit") %>
<%

Week 1 – Page 151


}
%>

<FORM NAME="form1" METHOD="POST">


<INPUT TYPE="SUBMIT" NAME="submit" VALUE="Button 1">
</FORM>

<FORM NAME="form2" METHOD="POST">


<INPUT TYPE="SUBMIT" NAME="submit" VALUE="Button 2">
</FORM>

<FORM NAME="form3" METHOD="POST">


<INPUT TYPE="SUBMIT" NAME="submit" VALUE="Button 3">
</FORM>
</BODY>
</HTML>

Y ou see th e resu lts in Figu re 4.1 7 , w h ere, th an k s to m u ltiple H TM L form s, w e see


th at B utton 3 w as click e d .

Figure 4.17. Using multiple HTML forms with buttons with


different names.

[ T eam L iB ]

[ T eam L iB ]

Week 1 – Page 152


Summary
You 'v e seen q u ite a lot today. Y ou've gotten sta rted u sin g H T M L controls in W eb
pa ges an d rea din g data from th ose H T M L contro ls in JS P code .

You 'v e learn ed h o w to u se th e va riou s attributes of th e <FORM> elem en t to tailor you r


H T M L form s a s y ou w a n t th e m , a n d to sen d th e data in th e form 's controls b ack to
th e serv er. You u se sub m it b u tton s to a ctu ally sen d th at d ata to th e U R L given in th e
form 's ACTION attribute.

You can d eciph er th e d a ta sen t to y ou in you r JS P code u sin g th e request obje ct,
an d you learn ed th e m e th ods of th at object tod ay. T h e m eth od w e focu sed on toda y
w as th e getParameter m eth od, w h ich lets you read th e d ata fro m va riou s controls.

T h e controls you 've seen today in clu d ed sub m it button s, text fields, tex t area s,
passw ord con tro ls, h idden controls, stan d ard b u tton s, an d reset b utton s. Y ou can
h a n dle all th ese controls w ith th e getParameter m eth od .

You also learn ed h ow to u se m u ltiple form s, an d h ow y ou can u se the m to sup p ort


m u ltiple b utton s in th e sa m e W eb p ag e . A n d w e got a little tricky by storin g form
data in h id d en contro ls, both w ith an d w ith o u t th e h elp of Ja va S cript.

To m orro w , w e'll continu e ou r w ork w ith H T M L controls as w e tu rn to th e oth er


controls th at are ava ilable, fro m ch eck bo xes to select controls.
[ T eam L iB ]

[ T eam L iB ]

Q&A

Q1: W h a t if a c o n tro l c a n re tu rn m u ltip le v a lu e s, s u c h a s a m u ltiv a lu e


se le ct c o n tro l? I c a n 't u s e getParameter in s u c h a c a se .

A1: T h ere a re oth er m eth o d s y ou u se in stead — S e e th e topic "U sin g M u ltiple -


S election S elect C o ntrols " in D ay 5.

Q2: C a n I u se th e re q u e st o b je ct in s e c u re c h a n n e ls su c h a s H T T P S ?

A2: Yes. O n e h an d y m eth od if you 're u sin g a secure ch a n n el is th e request


object's isSecure m eth od, w h ich retu rn s true if th is reque st w a s m a d e
u sin g a secure ch an n el, su ch as H T TP S , a n d false othe rw ise.

[ T eam L iB ]

[ T eam L iB ]

Week 1 – Page 153


Workshop
T h is w ork sh op tests w h eth er y ou un d erstan d all th e con cepts y ou learn ed tod a y. It's
a goo d idea to m a ste r today 's con cepts b y h on in g you r kn ow led g e he re before
startin g tom orrow 's m aterial. Y ou can fin d th e a n sw ers to th e q u iz q u estion s in
A pp e n d ix A .

Quiz

1: W h at attrib ute of th e <FORM> ele m en t d o y ou u s e to sp ecify w h ere to se n d


th e form data ?

2: W h at's th e differen ce b e tw ee n th e GET an d POST m eth o d s?

3: N a m e tw o controls th at can sub m it a form 's data back to th e server.

4: W h at Java class is th e request obje ct an object of?

5: W h ich m eth od can y ou u se to determ in e w h at b ro w ser th e u ser h a s?

Exercises

1: G ive th is on e a try — ju st read th e text th at th e u ser h as en tered into a


pass w ord con trol an d re tu rn it in a text field. D oin g so w ill give you p rac tice
in h an dlin g both readin g an d send in g d ata u sin g H T M L controls.

2: Follow in g th e exa m p le in th e topic " U sin g R eq u est O bjects" tod ay, u se th e


request.getHeader("User-Agent") m eth od to che ck w h at b row ser th e
u ser h as. If th e u ser is u sin g Intern et E xplorer, display a greetin g u sin g th e
<MARQUEE> ele m ent; oth erw ise , u se th e <H1> elem e nt.

[ T eam L iB ]

[ T eam L iB ]

Day 5. Reading Data from Web


Pages: Check Boxes, Radio Buttons,
and Select Controls
W elcom e to D ay 5! T od ay, w e're goin g to continu e th e w ork w e sta rted yesterday —
w orkin g w ith H TM L con tro ls an d H TTP req ue sts. Y ou'll also learn h ow to deal w ith
ch eck bo xes, ra dio button s, an d select contro ls, as w ell as m a n y othe r topics. T he se
are prim ary H T M L contro ls th at u sers exp ect to see in th e p a ges w e'll sen d th e m .

Week 1 – Page 154


B esides th ese controls, w e'll also take a look at w orkin g w ith im a ge con tro ls, w h ich
let you determ in e w he re th e u se r h as click ed an im a ge. T h at's g reat for im a ge
m a ps— th ose clicka ble im a ges w ith "h otspots" th at perform va riou s action s — w h ich
w e'll also see tod ay . T o im ple m e n t im a ge m a ps, w e'll loo k at th e <jsp:forward>
action , w h ich lets you n av ig ate to n ew U R Ls in you r JS P code . U sin g <jsp:forward>,
you can n a vigate to a n ew U R L w h en th e u ser clicks a h otsp ot in th e im age m ap
corresp on d in g to th at U R L (for exa m p le, ou r im age m ap is goin g to con tain a h otspot
m ark ed "W eathe r," an d w h en th e u ser clicks it, w e'll open a pa ge on th e w eath e r).
H ere's an overview of tod ay 's topics:

 W orkin g w ith ch eck b ox es


 W orkin g w ith radio b utton s
 S electin g an d deselectin g ch eck b ox es an d ra dio button s in code
 W orkin g w ith select con tro ls (creatin g dro p -dow n lists)
 H and lin g im a ge controls an d im a ge m a ps
 Forw a rdin g requ e sts to oth er p ag e s.

Let's sta rt w ith th e H T M L contro ls w e're goin g to see tod a y, b egin n in g w ith H TM L

Week 1 – Page 155


ch eck bo xes.

[ T eam L iB ]

[ T eam L iB ]

Using Check Boxes


You create che ck b ox es w ith th e <INPUT TYPE="CHECKBOX"> ele m ent, a n d you can
u se th e NAME attribute o f th is ele m en t to give th e ch eck bo x a n a m e. In you r code,
you can see w h eth e r a ch eck b ox h as b ee n ch e cked by p assin g its n a m e to
request.getParameter.

H ere's an exa m p le; in th is case, th e cod e w ill add th ree ch eck b o xes to a W eb p ag e
an d n a m e th e m check1, check2, an d check3 (n ote th at th e first ch eck box, check1,
w ill a p p ear ch e ck ed w h en th e p a g e first a pp e a rs, b ecau se th e code u ses th e
stan d alon e CHECKED attribu te for th at ch eck b o x ). Y ou can see th e cod e in Listin g
5.1 .

Listing 5.1 Submitting Check Boxes (ch05_01.html)

<HTML>
<HEAD>
<TITLE>Submitting Check Boxes</TITLE>
</HEAD>

<BODY>
<H1>Submitting Check Boxes</H1>
<FORM ACTION="ch05_02.jsp" METHOD="post">
<INPUT TYPE="CHECKBOX" NAME="check1" VALUE="check1"
CHECKED>
Checkbox 1
<BR>
<INPUT TYPE="CHECKBOX" NAME="check2" VALUE="check2">
Checkbox 2
<BR>
<INPUT TYPE="CHECKBOX" NAME="check3" VALUE="check3">
Checkbox 3
<BR>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</BODY>
</HTML>

Y ou can see th is W eb p a ge w ith th e che ck b ox es in Figu re 5.1 .

Figure 5.1. Using check boxes and responding to check box


actions.

Week 1 – Page 156


In th e JS P cod e, you ca n exa m in e ea ch ch eck b ox by p assin g its n a m e to
request.getParameter to see w h eth er it h as bee n che ck ed — if a che ck box is
ch ecked, request.getParameter w ill retu rn th e text in th e che ck box 's VALUE
attribute (w h ich is check1, check2, or check3 in th is exa m p le, a s y ou see in th e
VALUE attributes in Listin g 5.1 ), or null if th e ch eck b ox w as n ot ch eck ed, a s you see
in Listin g 5.2 .

Listing 5.2 Reading Check Boxes (ch05_02.jsp)

<HTML>
<HEAD>
<TITLE>Reading Checkboxes</TITLE>
</HEAD>

<BODY>
<H1>Reading Checkboxes</H1>
<%
if(request.getParameter("check1") != null) {
out.println("Checkbox 1 was checked.<BR>");
}
else {
out.println("Checkbox 1 was not checked.<BR>");
}

if(request.getParameter("check2") != null) {
out.println("Checkbox 2 was checked.<BR>");
}
else {

Week 1 – Page 157


out.println("Checkbox 2 was not checked.<BR>");
}

if(request.getParameter("check3") != null) {
out.println("Checkbox 3 was checked.<BR>");
}
else {
out.println("Checkbox 3 was not checked.<BR>");
}
%>
</BODY>
</HTML>

N ow you can see th e re su lts in Fig u re 5.2 .

Figure 5.2. Examining check boxes in code.

T h at's all it tak es to see w h ethe r a che ck b ox w as ch eck ed or n ot. Y ou'll see m ore
abo u t che ck in g an d un ch eck in g ch eck bo x es in cod e in a few p ag e s.

[ T eam L iB ]

[ T eam L iB ]

Using Radio Buttons

Week 1 – Page 158


R a dio button s ope rate in gro u p s, an d on ly on e radio button in a gro u p can be
selected at a tim e. To create a radio b utton g rou p , you give a set of ra dio button s
th e sa m e n a m e (u sin g th e H TM L NAME attribute). H ow d o y ou tell th e ra dio button s
ap art? Y ou u se th e VALUE attribute, givin g th em differen t valu es.

Tip

You can h a ve m u ltiple radio gro u p s, w h ich w ill ope rate in d epe nd e ntly, in
th e sa m e W eb p ag e. Ju st give all th e radio butto n s in each g r ou p th e sa m e
n a m e, u sin g a differen t n a m e for ea ch g rou p .

You can see an ex a m p le in Listin g 5.3 , in w h ich th e code is ad d in g th ree radio


button s to a W eb pa ge an d n a m in g th e m all radios to g ro u p th e m tog eth er, an d
givin g th em differen t va lu es ( radio1, radio2, a n d radio3).

Listing 5.3 Submitting Radio Buttons (ch05_03.html)

<HTML>
<HEAD>
<TITLE>Submitting Radio Buttons</TITLE>
</HEAD>

<BODY>
<H1>Submitting Radio Buttons</H1>
<FORM ACTION="ch05_04.jsp" METHOD="post">
<INPUT TYPE="radio" NAME="radios" VALUE="radio1" CHECKED>
Radio Button 1
<BR>
<INPUT TYPE="radio" NAME="radios" VALUE="radio2">
Radio Button 2
<BR>
<INPUT TYPE="radio" NAME="radios" VALUE="radio3">
Radio Button 3
<BR>
<INPUT TYPE="submit" VALUE="Submit ">
</FORM>
</BODY>
</HTML>

Y ou can see th e resu lts in Figu re 5.3 , w h ich sho w s th e th ree ra dio b utton s.

Figure 5.3. Using radio buttons and responding to radio button


actions.

Week 1 – Page 159


You can see w h eth e r a radio b utton h as bee n se lected by p a ssin g th e n a m e radios
to request.getParameter. If th e request.getParameter retu rn s radio1, th e first
radio button w as selected; if it retu rn s radio2, th e secon d ra dio b utto n w as selected ,
an d so on . Y ou can see h ow to determ in e w h ich radio b utton s w ere sele cted in
Lis ting 5 .4 .

Listing 5.4 Reading Radio Buttons (ch05_04.jsp)

<HTML>
<HEAD>
<TITLE>Reading Radio Buttons</TITLE>
</HEAD>

<BODY>
<H1>Reading Radio Buttons</H1>
<%
if(request.getParameter("radios") != null) {
if(request.getParameter("radios").equals("radio1")) {
out.println("Radio button 1 was selected.<BR>");
}
else {
out.println("Radio button 1 was not
selected.<BR>");
}
if(request.getParameter("radios").equals("radio2")) {
out.println("Radio button 2 was selected.<BR>");
}
else {

Week 1 – Page 160


out.println("Radio button 2 was not
selected.<BR>");
}
if(request.getParameter("radios").equals("radio3")) {
out.println("Radio button 3 was selected.<BR>");
}
else {
out.println("Radio button 3 was not
selected.<BR>");
}
}
%>
</BODY>
</HTML>

Y ou can see th e resu lts in Figu re 5.4 , w he re w e see th at in th is case, on ly th e first


radio button w as selected.

Figure 5.4. Checking radio buttons.

A s you can see, it's easy to d eterm in e w h ich ch eck bo x or radio b utton th e u ser h as
selected . B u t w h at if y ou w a n t to select or d ese lect th ese contro ls y ourself in co de?
T h at's com in g u p n ext.

[ T eam L iB ]

[ T eam L iB ]

Week 1 – Page 161


Selecting and Deselecting Check Boxes and
Radio Buttons in Code
U sin g th e stan d alon e CHECKED attribute, you h a ve control over w h eth e r che ck b ox es
an d radio b utton s a p pe a r selected w h en th eir contain in g W eb p a ge first ap p ea rs.
U sin g this attribute, you can select an d d eselect che ck b ox es an d radio button s in
cod e.

H ere's an exa m p le, w h ich you can see in Figu re 5.5 . T h is exa m p le lets u sers select
w h ich san d w ich th ey w a nt, as y ou can see in th e fig u re. T h e u ser can select a
san d w ich u sin g th e radio button s on th e left, an d ou r p ro g ra m w ill ch eck th e
corresp on d in g in g redien t ch eck bo xes on th e rig h t w h en th e u ser clicks th e S u b m it
button . T h e cod e also d eterm in es w h ich radio b utton w as selected , a n d m ak es su re
th e sa m e ra dio b utton is selected w h en a n ew p age is sen t back to th e bro w ser.

Figure 5.5. Selecting and deselecting check boxes and radio


buttons in code.

S electin g an d deselectin g ch eck b ox es an d ra dio button s in JS P cod e is sim ply a


m atter of u sin g th e CHECKED attribute. In th is e xa m p le, w e w a n t to set th e che ck
boxes to m atch w h ich radio b utton w as selecte d . To do th at, you can d eclare th ree
variables for ea ch of th e th ree ch eck b o xes, check1, check2, an d check3, settin g
each to an e m pty strin g ("") at first:

Week 1 – Page 162


String check1 = "", check2 = "", check3 = "";

If a p a rticu lar radio b utton is selected, su ch as th e on e for tu rkey san d w ich es, w e
can set th e corresp o nd in g ch eck bo x es' varia ble to "CHECKED":

if(request.getParameter("radios").equals("turkey")){
check1 = "CHECKED";
check3 = "CHECKED";
}

T h en w h en w e display each che ck b ox, w e can sim ply in dicate w h eth er or n ot th e


ch eck bo x sh ou ld be ch ecked:

<INPUT TYPE="CHECKBOX" NAME="check3" VALUE="check3"


<%= check3%>
>

You can see th e fu ll cod e for th is exa m p le in Listin g 5.5 .

Listing 5.5 Design Your Sandwich (ch05_05.jsp)

<HTML>
<HEAD>
<TITLE>Design Your Sandwich!</TITLE>
</HEAD>

<BODY>
<%
String cheese = "", turkey = "", ham = "";
String check1 = "", check2 = "", check3 = "";
if(request.getParameter("radios") != null) {
if(request.getParameter("radios").equals("cheese")){
cheese = "CHECKED";
check2 = "CHECKED";
}
if(request.getParameter("radios").equals("turkey")){
turkey = "CHECKED";
check1 = "CHECKED";
check3 = "CHECKED";
}
if(request.getParameter("radios").equals("ham")){
ham = "CHECKED";
check1 = "CHECKED";
check2 = "CHECKED";
check3 = "CHECKED";
}
}
%>

<H1>Design Your Sandwich!</H1>

Week 1 – Page 163


<FORM METHOD="POST">
<TABLE BORDER="1" ALIGN="LEFT">
<TR>
<TH>
Sandwich
</TH>
</TR>
<TR>
<TD>
<INPUT TYPE="radio" NAME="radios"
VALUE="cheese"
<%= cheese %>
>
Cheese Sandwich
<BR>
<INPUT TYPE="RADIO" NAME="radios" VALUE="turkey"
<%= turkey %>
>
Turkey Sandwich
<BR>
<BR>
<INPUT TYPE="RADIO" NAME="radios" VALUE="ham"
<%= ham %>
>
Ham Sandwich
<BR>
</TD>
</TR>
</TABLE>

<TABLE BORDER="1" ALIGN="LEFT">


<TR>
<TH>
Ingredients
</TH>
</TR>
<TR>
<TD>
<INPUT TYPE="CHECKBOX" NAME="check1"
VALUE="check1"
<%= check1 %>
>
Meat
<BR>
<BR>
<INPUT TYPE="CHECKBOX" NAME="check2"
VALUE="check2"
<%= check2 %>
>
Cheese
<BR>
<BR>
<INPUT TYPE="CHECKBOX" NAME="check3"
VALUE="check3"
<%= check3%>
>
Lettuce

Week 1 – Page 164


</TD>
</TR>
</TABLE>
<BR CLEAR="ALL">
<BR>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</BODY>
</HTML>

W e've got a lot of p ow er over che ck b ox es an d radio b utton s n ow , an d can


determ in e w h ethe r th e u ser h as selected th e m , an d w e can also select an d deselect
th em in code. N ext, ou r discu ssion w ill cover th e u se of sel ect con trols.

[ T eam L iB ]

[ T eam L iB ]

Using Select Controls


S elect contro ls display scrollable lists an d dro p - dow n lists. T h ese kind s of controls
com e in tw o va rieties— th ose th at let you select on e item at a tim e, an d th ose th at
let you select m u ltiple item s. W e'll loo k at sing le -selection select controls first.

You create a select contro l w ith th e <SELECT> elem e nt, en closin g th e item s y ou w a n t
to ap p ea r in th e select control in <OPTION> elem ents. H ere's an e xa m p le in w h ich th e
cod e is creatin g a select control n a m ed select1 w ith th ree ite m s in it: Option 1,
Option 2, an d Option 3:

<SELECT NAME="select1">
<OPTION>Option 1</OPTION>
<OPTION SELECTED>Option 2</OPTION>
<OPTION>Option 3</OPTION>
</SELECT>

Lis ting 5 .6 sh ow s h ow y ou can u se th is con trol in a sa m p le H TM L docu m ent.

Listing 5.6 Submitting a Select Control (ch05_06.html)

<HTML>
<HEAD>
<TITLE>Submitting Select Controls</TITLE>
</HEAD>

<BODY>
<H1>Submitting Select Controls</H1>
<FORM ACTION="ch05_07.jsp" METHOD="POST">
<SELECT NAME="select1">
<OPTION>Option 1</OPTION>

Week 1 – Page 165


<OPTION SELECTED>Option 2</OPTION>
<OPTION>Option 3</OPTION>
</SELECT>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</BODY>
</HTML>

Y ou can see w h at th is W eb p ag e loo k s like in Fig u re 5.6 .

Figure 5.6. Using a select control.

You can read th e selected option in sin gle -selection select con tro ls in you r JS P code
by p assin g th e n a m e of th e contro l to request.getParameter. Listin g 5.7 sho w s th e
cod e th at determ in es w h ich item th e u ser selected in th e select control.

Listing 5.7 Reading Select Controls (ch05_07.jsp)

<HTML>
<HEAD>
<TITLE>Reading Select Controls</TITLE>
</HEAD>

<BODY>
<H1>Reading Select Controls</H1>
You selected
<% out.println(request.getParameter("select1")); %>

Week 1 – Page 166


</BODY>
</HTML>

Y ou can see th e resu lts in Figu re 5.7 , w he re w e learn th at w e'v e selecte d O ption 2.

Figure 5.7. Determining a selection in a select control.

A n d th at's h ow you u se sin gle -selection select controls. M u ltiple selection select
controls are co m in g u p n ext.

[ T eam L iB ]

[ T eam L iB ]

Using Multiple-Selection Select Controls


If y ou u se th e MULTIPLE stan d alon e H T M L attribute in a select control, th at control
can accept m u ltiple selection s:

<SELECT NAME="select1" SIZE="5" MULTIPLE>


<OPTION>Option 1</OPTION>
<OPTION SELECTED>Option 2</OPTION>
<OPTION>Option 3</OPTION>

Week 1 – Page 167


<OPTION>Option 4</OPTION>
<OPTION>Option 5</OPTION>
</SELECT>

Lis ting 5 .8 sh ow s h ow y ou can display a m u ltiple -selection select contro l.

Listing 5.8 Using Multiple-Selection Select Controls


(ch05_08.html)

<HTML>
<HEAD>
<TITLE>Submitting Multiple Selection Select Controls</TITLE>
</HEAD>

<BODY>
<H1>Submitting Multiple Selection Select Controls<H1>
<FORM ACTION="ch05_09.jsp" METHOD="POST">
<SELECT NAME="select1" SIZE="5" MULTIPLE>
<OPTION>Option 1</OPTION>
<OPTION SELECTED>Option 2</OPTION>
<OPTION>Option 3</OPTION>
<OPTION>Option 4</OPTION>
<OPTION>Option 5</OPTION>
</SELECT>
<BR>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</BODY>
</HTML>

Caution

N ote th at th is code is u sin g th e SIZE attrib ute h ere to display a nu m b er of


ite m s in th e select control at on ce . If y ou don't u se th e SIZE attribute (as w e
didn 't in th e previou s sing le -selection exa m p le), you get a drop -d o w n
list, b u t dro p -dow n lists don 't su p p ort m u ltiple selection s.

You can see th is W eb p a ge in Figu re 5.8 , in w h ich th e u ser is selectin g tw o item s.


(H o w you select m u ltiple ite m s in a select con trol like th is varies by op e ratin g sys te m —
for exa m p le, in W in d ow s, y ou can u se th e C trl key tog ethe r w ith th e m o u se
to select m u ltiple item s by clickin g th e m , or th e S h ift ke y w ith th e m ou se to select a
ran g e of ite m s.)

Figure 5.8. Using a multiple-selection select control.

Week 1 – Page 168


T h e ne xt step is to d ete rm in e w h ich ite m s w e re selected w h en th e S u b m it b u tton
w as click ed an d th e form 's d ata w as sen t to u s on th e serv er. T h is is th e first tim e a
control h as sen t u s m u ltiple valu es, an d th e getParameter m eth od isn't goin g to
w ork h ere (it w ou ld sim ply retu rn th e first selected item ). In stea d , y ou u se th e
req u est object's getParameterValues m eth od in th is case.

A s y ou can see in Table 4.1 , th e getParameterValues m eth od retu rn s a n arra y of


string s corresp on d in g to all th e valu es associate d w ith a contro l. T h at's exactly w h at
you ne ed h ere to get all th e selected ite m s in th e select control. Y ou ca n loo p ov er
th e item s in th e retu rn e d strin g array a n d displa y th em a s you see in Listin g 5.9 .

Listing 5.9 Reading Multiple-Selection Select Controls


(ch05_09.jsp)

<HTML>
<HEAD>
<TITLE>Reading Multiple Selection Select Controls</TITLE>
</HEAD>

<BODY>
<H1>Reading Multiple Selection Select Controls</H1>
You selected:
<BR>
<% String[] items = request.getParameterValues("select1");
for(int loopIndex = 0; loopIndex < items.length; loopIndex++){
out.println(items[loopIndex] + "<BR>");
}

Week 1 – Page 169


%>
</BODY>
</HTML>

N ow you can determ in e w h ich ite m s th e u ser h a s selected in a m u ltiple-selection


select control, as y ou see in Figu re 5.9 .

Figure 5.9. Determining which options were selected.

[ T eam L iB ]

[ T eam L iB ]

Check Box Groups


W e've see n th at you ca n create ra dio button group s by givin g ra dio bu tton s th e sa m e
n a m e; in th e sa m e w ay, you can create ch eck b ox g ro u p s. H ow ev er, ch eck bo x
gro u p s are differen t fro m ra dio b utton grou p s, beca u se m u ltiple ch eck boxes can be
ch ecked at th e sa m e tim e in th e sa m e g rou p . Listin g 5.10 illu strates h ow to create a
ch eck bo x grou p w ith th ree ch eck b oxes, all n am e d checks, b u t w ith differen t
valu es.

Listing 5.10 Submitting Check Boxes (ch05_10.html)

Week 1 – Page 170


<HTML>
<HEAD>
<TITLE>Submitting Check Boxes</TITLE>
</HEAD>

<BODY>
<H1>Submitting Check Boxes</H1>
<FORM action="ch05_11.jsp" method="post">
<INPUT TYPE="CHECKBOX" NAME="checks" VALUE="check1"
CHECKED>
Checkbox 1
<BR>
<INPUT TYPE="checkbox" NAME="checks" VALUE="check2">
Checkbox 2
<BR>
<INPUT TYPE="checkbox" NAME="checks" VALUE="check3">
Checkbox 3
<BR>
<INPUT TYPE="submit" VALUE="Submit">
</FORM>
</BODY>
</HTML>

Y ou can see th is W eb p a ge in Figu re 5.1 0 .

Figure 5.10. Creating a check box group.

Week 1 – Page 171


To d eterm in e w h ich che ck b oxes w ere che ck ed, you can u se
request.getParameterValues an d loo p over th e a rra y th at m eth od retu rn s, a s y ou
see in Listin g 5.1 1 .

Listing 5.11 Reading Check Boxes (ch05_11.jsp)

<HTML>
<HEAD>
<TITLE>Reading Checkboxes</TITLE>
</HEAD>

<BODY>
<H1>Reading Checkboxes</H1>
You checked:
<BR>
<% String[] items = request.getParamete rValues("checks");
for(int loopIndex = 0; loopIndex < items.length; loopIndex++){
out.println(items[loopIndex] + "<BR>");
}
%>
</BODY>
</HTML>

Y ou can see th e resu lts in Figu re 5.1 1 . U sin g getParameterValues in th is w ay, y ou


can sup po rt ch eck box gro u p s an d determ in e w h ich ch eck bo xes in th e gro u p w ere
ch ecked.

Figure 5.11. Using a check box group.

Week 1 – Page 172


[ T eam L iB ]

[ T eam L iB ]

Uploading Files
A n oth er H T M L control is th e file u pload control ( <INPUT TYPE="FILE">), bu t h ere th e
To m cat server isn't goin g to h elp u s ou t m u ch . To up loa d files you'll u se m u ltip art
form s, w h ich you create w ith th e <FORM> ele m e nt's ENCTYPE attribute:

<FORM ACTION="ch05_13.jsp" METHOD="POST" ENCTYPE ="multipart/for m-


data">
<INPUT TYPE="FILE" NAME="filer">
<BR>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>

H o w ev er, To m cat do esn 't su p po rt m u ltip art form s y et, so you h a ve to u se a stan d ard
form , a s y ou see in Listin g 5.1 2 .

Listing 5.12 Uploading Files (ch05_12.html)

<HTML>
<HEAD>
<TITLE>Uploading Files</TITLE>

Week 1 – Page 173


</HEAD>

<BODY>
<FORM ACTION="ch05_13.jsp" METHOD="POST">
<INPUT TYPE="FILE" NAME="filer">
<BR>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</BODY>
</HTML>

Figu re 5.12 sh ow s th e file control created by th is W eb pa g e.

Figure 5.12. Using a file upload control.

T h is file u ploa d control isn't goin g to do m u ch for u s. Listin g 5.1 3 sh ow s you h ow to


recover th e in form ation it sen d s you .

Listing 5.13 Uploading Files (ch05_13.jsp)

<HTML>
<HEAD>
<TITLE>Uploading Files</TITLE>
</HEAD>

<BODY>

Week 1 – Page 174


<H1>Uploading Files</H1>
You selected
<%= request.getParameter("filer") %>
</BODY>
</HTML>

Y ou can see th e resu lts in Figu re 5.1 3 , w h ere w e see th at th e file u p load control h as
given u s on ly th e n a m e of th e file w e h ad w ante d to u p load in th is case. P resu m a bly,
file up loa d contro ls w ill be su p po rted in later v ersion s of th e serve r softw are.

Figure 5.13. Getting a filename.

[ T eam L iB ]

[ T eam L iB ]

Image Controls
Im a g e controls (<INPUT TYPE="IMAGE">) act m u ch like su b m it button s, ex cept th ey
display im a ges th e u ser can click. T h e location th at th e u se r click ed in th e im a ge is
also sen t to th e serv er w ith th e rest of th e d ata fro m th e form .

H ere's an exa m p le sh ow in g h ow th is w ork s. H ere, th e code w ill u se an im a ge control


to display a clicka ble im age, an d w h en th e u ser clicks it, th e m o u se loca tion is sen t

Week 1 – Page 175


to th e server auto m atically, w ith n o sub m it b u tton n ee d ed. In th e JS P cod e, w e can
determ in e an d display th e m ou se location . Listin g 5.14 details th e H T M L pa ge th at
displays th e im a ge a n d th e im a ge con tro l— n ote th at th is code n a m es th e im ag e
control images.

Listing 5.14 Using Image Controls (ch05_14.html)

<HTML>
<HEAD>
<TITLE>Using Image Controls</TITLE>
</HEAD>

<BODY>
<H1>Using Image Controls</H1>
<FORM ACTION="ch05_15.jsp" METHOD="POST">
<INPUT TYPE="IMAGE" NAME="images" SRC="ch05_14.jpg">
</FORM>
</BODY>
</HTML>

Y ou can see th is pa ge a t w ork in Figu re 5.1 4 , w h ere th e u se r is abou t to click th e


im a ge.

Figure 5.14. Using an image control.

T h e n a m e of ou r im a ge control is images, w h ich m ea n s th at th e ( x, y ) m o u se

Week 1 – Page 176


location is passed to u s as th e req u est p a ra m eters images.x an d images.y. Y ou can
see ho w to display th at m o u se location w h en y ou get it in Listin g 5.1 5 .

Listing 5.15 Reading Image Controls (ch05_15.jsp)

<HTML>
<HEAD>
<TITLE>Reading Image Controls</TITLE>
</HEAD>

<BODY>
<H1>Reading Image Controls</H1>
You clicked the image at
(<%=request.getParameter("images.x")%>,
<%=request.getParameter("images.y")%>).
</BODY>
</HTML>

Th e resu lts ap p ear in Figu re 5.1 5 , w h ere w e se e th e location at w h ich th e u ser


click ed th e im a ge.

Figure 5.15. Reading data from an image control.

B ecau se th ey can re po rt m ou se location s, im a ge controls are often u sed for im a g e


m a ps, tho se clicka ble im a ges w ith h otspots th at w ill take you to differen t U R Ls. In
fact, there is a w ay to sen d th e b ro w ser to a n e w U R L — y ou can u se th e

Week 1 – Page 177


<jsp:forward> action . You 'll see <jsp:forward> first, th en pu t it to w ork in an
im a ge m ap w ith h otspots th at th e u ser can click to n av ig ate to n ew U R L s.
[ T eam L iB ]

[ T eam L iB ]

Using <jsp:forward>
You can u se th e <jsp:forward> action to forw a rd an H TTP req ue st to a n oth er W eb
pa ge:

<jsp:forward page="relativeURL" />

N ote th e X M L-style tag term in ator he re, />, w h ich you'll see a lot in JSP action
ele m ents. T h is is ju st a sh ortcu t th at lets you o m it a closin g ta g; th e p reviou s li n e of
cod e is th e sa m e as th is version , w h ich u ses th e closin g tag </jsp:forward>:

<jsp:forward page="relativeURL" ></jsp:forward>

H ere, relativeURL is th e U R L of an othe r pa g e a ccessible as part of th e sa m e W eb


ap p lication . For exa m p le, relativeURL can h old th e n a m e of an oth e r H T M L or JS P
file in th e sa m e server d irectory a s th e curren t d ocu m ent.

You can also ch a ng e or ad d n ew p a ra m eters to th e req u est bein g forw a rded to th e


n ew U R L w ith <jsp:param> ele m ents:

<jsp:forward page="relativeURL" >


<jsp:param name="parameterName1" value="parameterValue1" />
<jsp:param name="parameterName2" value="parameterValue2" />
.
.
.
</jsp:forward>

H ere, parameterName1 is th e n a m e of th e first p ara m eter you w an t to set a v alu e


for, an d parameterValue1 is th e valu e you w an t to give th at para m ete r, an d so on .
W e'll see h ow to p ass n ew p a ra m eters on to ne w U R Ls th is w ay in D ay 9, "U sin g
C u sto m JS P Tags."

To create ou r im a ge m a p, all w e'll n ee d to d o is u se <jsp:forward> to sen d th e


bro w ser to a n ew U R L , an d th at's com in g u p n e xt.

Tip

H ere's an oth e r w a y to redirect a b row ser, th is tim e u sin g Java S cript. Y ou


can set th e href p rop e rty of th e location obje ct to redirect th e brow s er to
a n ew U R L. F or ex a m ple , if you w a n t to sen d th e brow se r to

Week 1 – Page 178


http://www.sun.com, y ou cou ld sen d th is H TM L back to th e b row ser:
<HTML><SCRIPT LANGUAGE =
"JavaScript">location.href="http://www.sun.com"</SCRIPT></HTML >.

[ T eam L iB ]

[ T eam L iB ]

Creating Image Maps


T h is n ew im a ge m ap w ill be base d on an im a ge control n a m ed imagemap; th e code
for th e W eb pa ge th at contain s it ap p ears in Listin g 5.1 6 .

Listing 5.16 Using an Image Map (ch05_16.html)

<HTML>
<HEAD>
<TITLE>Using Image Maps</TITLE>
</HEAD>

<BODY>
<H1>Using Image Maps</H1>
<FORM ACTION="ch05_17.jsp" METHOD="POST">
<INPUT TYPE="IMAGE" NAME="imagemap" SRC="ch05_16.jpg">
</FORM>
</BODY>
</HTML>

You can see th e im a ge m a p w e'll be u sin g in Figu re 5.16 (th is im ag e is in clud ed in


th e code you can do w n load for th is boo k). T h e u ser is abou t to click th e W eathe r
h otspot in th is fig u re.

Figure 5.16. An image map.

Week 1 – Page 179


A ll th e u ser h as to d o is click on e of th e h otspots you see in Fig u re 5.1 6 , an d th e
m o u se location w ill be sen t to ou r JS P pa g e , ch05_17.jsp. T h ere w e d e term in e th e
m o u se location w ith th e follow in g code frag m e n t. (N ote th at th e cod e is u sin g th e
Integer.parseInt m eth od to con v ert th e strin g text w e g et fro m
request.getParameter into an integer; see th e n ext topic " U sin g N a m e d Ta rg ets"
for all th e details on con vertin g text to nu m e ric form at, in clu din g th e
Integer.parseInt m eth od.)

<%
int x = Integer.parseInt(request.getParameter("imagemap.x"));
int y = Integer.parseInt(request.getParameter("imagemap.y"));
%>

You can d eterm in e w h ich h otspot th e u ser clicked by ch e ck in g th e m ou se location ;


h ere th e cod e is ch eck in g w h ethe r th e W e ath er h otspot w a s click ed, an d if so,
forw ardin g th e bro w ser to th e W eath er pa g e ( ch05_19.html):

<%
if(x > 98 && x < 209
&& y > 104 && y < 126) {
%>
<jsp:forward page="ch05_19.html" />
<%
}
%>

H ere's w h at th e H T M L for ch05_19.html loo k s like:

Week 1 – Page 180


<HTML>
<HEAD>
<TITLE>Weather</TITLE>
</HEAD>

<BODY>
<H1>Weather</H1>
During the day, light. During the night, dark.
</BODY>
</HTML>

Figu re 5.17 de picts w h a t ch05_19.html loo ks lik e in th e brow s er after th e u ser clicks
th e W eath er lin k in th e im a ge m a p.

Figure 5.17. Forwarding to a new URL.

A n d th at's all it tak es— n ow w e're redirectin g bro w sers b a sed on im a ge m a ps. T h e
fu ll code ap p e a rs in Listin g 5.1 7 .

Note

N ote th at th is exa m p le also in clu d es ch05_18.html u p to ch05_23.html, so


th e n ext exa m p le in th e follow in g topic w ill be ch05_24.jsp.

Week 1 – Page 181


Listing 5.17 Reading an Image Map (ch05_17.jsp)

<HTML>
<HEAD>
<TITLE>Reading Image Controls</TITLE>
</HEAD>

<BODY>
<% int x =
Integer.parseInt(request.getParameter("imagemap.x"));
int y =
Integer.parseInt(request.getParameter("imagemap.y"));
%>

<% if(x > 16 && x < 127


&& y > 39 && y < 61) {
%>
<jsp:forward page="ch05_18.html" />
<%
}
%>

<% if(x > 98 && x < 209


&& y > 104 && y < 126) {
%>
<jsp:forward page="ch05_19.html" />
<%
}
%>

<% if(x > 62 && x < 173


&& y > 71 && y < 93) {
%>
<jsp:forward page="ch05_20.html" />
<%
}
%>

<% if(x > 411 && x < 522


&& y > 35 && y < 57) {
%>
<jsp:forward page="ch05_21.html" />
<%
}
%>

<% if(x > 360 && x < 471


&& y > 67 && y < 89) {
%>
<jsp:forward page="ch05_22.html" />
<%
}
%>

Week 1 – Page 182


<% if(x > 328 && x < 439
&& y > 98 && y < 120) {
%>
<jsp:forward page="ch05_23.html" />
<%
}
%>
</BODY>
</HTML>
[ T eam L iB ]

[ T eam L iB ]

Using Named Targets


H ere's an oth e r im p orta n t aspect a bou t H T M L form s — you can u se th e <FORM>
ele m ent's TARGET attrib ute to ind icate w h ere to sen d th e outp u t of you r JS P cod e .
W e saw yesterd ay th at th ere a re va riou s p red efin ed settin g s for th is attribute, su ch
as _blank w h en you w a n t th e p a ge sen t b a ck from y ou r JS P code to op en a ne w
w in d ow . Y ou can also u se th e TARGET attribute to sen d outp u t fro m JS P cod e to
an oth er fra m e in th e sa m e b row ser w ind o w , an d th at's co m in g u p n ext.

In th is exa m p le, you ca n create th e JS P C alcu lator, sho w n in Fig u re 5.1 8 . In th e top
fra m e, you ente r tw o nu m b e rs to a dd , click th e = button , an d th e serv er w ill sen d th e
resu lts b ack to th e b ottom fra m e as y ou see in th e figu re. (T h is exa m p le is also
specifically desig n ed to sh ow h ow to con vert th e text y ou rea d from H T M L controls
in to nu m eric d ata typ es, su ch a s intege rs — so m eth in g th at's fru strated a lot of JS P
pro g ra m m e rs.)

Figure 5.18. Using targeted frames with JSP.

Week 1 – Page 183


You can see th e m ain W eb p a ge th at displays th e tw o fra m e s in Figu re 5.18 in Listin g
5.1 8 — n ote th at th e cod e n a m e s th e botto m fra m e frame2.

Listing 5.18 Displaying Frames (ch05_24.html)

<HTML>
<FRAMESET ROWS="70%, 30%">
<FRAME SRC="ch05_25.html">
<FRAME NAME="frame2">
</FRAMESET>
</HTML>

You can see th e calcu lator p a rt of th e ap p lication , w h ich go es in th e top fra m e, in


Lis ting 5 .1 9 . N ote th at th e code is u sin g th e form 's TARGET attribute to in dicate th at
th e resu lts of ou r JS P co d e sh ou ld go into frame2, th e b ottom fra m e (th e cod e sets
th e caption of th e = button to "&nbsp;&nbsp;=&nbsp;&nbsp;", w h ere &nbsp; is th e
H T M L code for a n on bre ak in g sp ace, to w iden th at b utton in stead of ju st givin g it th e
n arrow caption =).

Listing 5.19 The JSP Calculator (ch05_25.html)

<HTML>
<HEAD>
</HEAD>

<BODY>
<FORM NAME="form1" ACTION="ch05_26.jsp" TAR GET="frame2"
METHOD="POST">

Week 1 – Page 184


<CENTER>
<H1>The JSP Calculator</H1>
<INPUT TYPE="TEXT" NAME="op1" VALUE="">
<BR>
+
<BR>
<INPUT TYPE="TEXT" NAME="op2" VALUE="">
<BR>
<INPUT TYPE="SUBMIT" VALUE="&nbsp;&nbsp;=&nbsp;&nbsp;">
</CENTER>
</FORM>
</BODY>
</HTML>

Fin ally, you can see th e JS P cod e th at w ill ad d th e tw o nu m b e rs a n d display th e


resu lt in th e bottom fra m e of th e a p p lication in Listin g 5.2 0 .

Listing 5.20 Displaying Numeric Results (ch05_26.jsp)

<HTML>
<HEAD>
</HEAD>

<BODY>
<H2>
<CENTER>
The sum is:
<%

out.println(Integer.parseInt(request.getParameter("op1")) +
Integer.parseInt(request.getParameter("op2")));
%>
</CENTER>
</H2>
</BODY>
</HTML>

N ote th at th e valu es w e get fro m request.getParameter are string s, a n d in Java,


you can 't ju st assig n string s to in teger varia bles (an d you can 't u se a ty p e ca st he re,
eith er). In stea d, y ou m u st u se th e Integer class's parseInt m eth o d, w h ich reads
strin g text an d retu rn s a n integer like int integer1 =
Integer.parseInt(request.getParameter("op1") ). O th e r m eth od s to con v ert
string s into nu m b ers in clud e Float.parseFloat, Double.parseDouble, an d so on .
You con v ert th e text y o u read from H T M L controls into nu m b ers by u sin g th ese
m eth ods.

Tip

H o w do you con vert a n u m b er to a text strin g ? You can u se th e String


class's valueOf m eth od like th is: String string1 =
String.valueOf(number), w h e re number is a n u m b er of data type int,

Week 1 – Page 185


float, double, an d so on .

O u r calcu lator is fu lly fun ction al (as lon g as th e on ly m ath ope ration you w an t to
perform is ad d in g integers, th at is). U sin g n a m e d fra m e s like th is is a cool techn iqu e
to kno w — th e H T M L in th e top fra m e h ere d oesn't ch a n g e, b u t th e H T M L in th e
bottom fra m e can be u p dated fro m th e serv er w h en ev er y ou w a nt.

[ T eam L iB ]

[ T eam L iB ]

Getting All Parameter Names


W e've see n a lot abo u t request obje cts yesterd ay an d today . T h ere a re tw o m ore
pow erfu l m eth o ds w e sh ou ld take a loo k at— getParameterNames an d
getHeaderNames— to ad d ev en m ore p ow er to ou r JS P a rsen al. You 'll see
getParameterNames h ere, an d getHeaderNames in th e n ext section .

T h e getParameterNames m eth od retu rn s a Jav a Enumeration object h oldin g th e


n a m es of th e pa ra m eters bein g p assed to you r JS P code. Enumeration o bjects a re
like arra ys in th at th ey h old collection s of ite m s , bu t you u se tw o m eth ods to m ov e
th ro ug h an en u m e ration , rathe r th an u sin g an a rra y ind ex (th ese a re th e on ly tw o
m eth ods th at en u m e ration s sup p ort):

 boolean hasMoreElements()— R etu rn s true if th is enu m eration contain s


m o re elem ents th at you h av en't a ccessed y et.
 Object nextElement()— R etu rn s th e n ext elem e n t of th is enu m eratio n if th is
enu m eration object h as at least on e m o re ele m e n t you h av en 't accessed yet.

H ere's a loo k at an exa m p le to see how to u se getParameterNames to determ in e th e


n a m es of all th e para m e ters sen t to ou r code . Listin g 5.21 sh ow s a sa m ple W eb p ag e
w ith a text field n a m e d text1 an d a select control n a m ed select1 th at you can u se
to test getParameterNames.

Listing 5.21 Getting Parameter Names (ch05_27.html)

<HTML>
<HEAD>
<TITLE>Getting Parameter Names</TITLE>
</HEAD>

<BODY>
<H1>Getting Parameter Names<H1>
<FORM ACTION="ch05_28.jsp" METHOD="POST">
<INPUT TYPE="TEXT" NAME="text1">

Week 1 – Page 186


<BR>
<SELECT NAME="select1" SIZE="5" MULTIPLE>
<OPTION>Option 1</OPTION>
<OPTION selected>Option 2</OPTION>
<OPTION>Option 3</OPTION>
<OPTION>Option 4</OPTION>
<OPTION>Option 5</OPTION>
</SELECT>
<BR>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</BODY>
</HTML>

You can see th is p a ge in Figu re 5.1 9 .

Figure 5.19. A test page to use with the getParameterNames


method.

You can see th e JS P pa g e th at w ill accept th e requ est para m eters w e sen d it an d u se
th e getParameterNames m eth od to display th e n a m es of th ose pa ra m eters in Listin g
5.2 2. N ote th at w e're u sin g a Java Enumeration obje ct he re, u sin g th e
hasMoreElements m eth od in a while loo p, an d th e nextElement m eth o d to recov er
su ccessive ele m ents fro m th at Enumeration.

Listing 5.22 Reading Parameter Names (ch05_28.jsp )

<HTML>
<HEAD>

Week 1 – Page 187


<TITLE>Reading Parameter Names</TITLE>
</HEAD>

<BODY>
<H1>Reading Parameter Names</H1>
Parameter Names:
<BR>
<% java.util.Enumeration names = request.getParameterNames();
while(names.hasMoreElements()){
out.println(names.nextElement() + "<BR>");
}
%>
</BODY>
</HTML>

Y ou can see th e resu lts in Figu re 5.2 0 , w he re w e see th at th e p a ra m ete rs w e've sen t
to th e server are select1 an d text1, as th ey sh ou ld be.

Figure 5.20. Getting parameter names.

[ T eam L iB ]

[ T eam L iB ]

Getting Request Header Information


A n oth er im p orta n t request obje ct m eth od is getHeaderNames,
w h ich gets th e n a m e s of req ue st h ead e rs. T h ese h ead ers sto re

Week 1 – Page 188


a great deal of in form ation abo u t th e b row ser a n d th e req u est
itself, in clu din g su ch in form ation as th e typ e of bro w ser th e
u ser h as (see "U sin g R e qu est O bjects" in D ay 4 , "R e adin g
D ata Fro m W eb Pag es: B utton s an d T ext Fields,") an d w h at
types of d ata th e b ro w ser accepts. Y ou can u se th ese h ead er
n a m es w ith an oth er m eth od, getHeader, to g et th e h ea d er's
data.

N ext, y ou can tak e a look at th e req ue st h ea d e rs p a ssed to y ou r cod e to see w h at


th ey a re an d w h at th ey can offer you . Listin g 5 .23 sh ow s a sim ple W eb page w ith
ju st a form a n d a su b m it button th at you can u se.

Listing 5.23 Getting Header Data (ch05_29.html)

<HTML>
<HEAD>
<TITLE>Getting Header Data</TITLE>
</HEAD>

<BODY>
<H1>Getting Header Data</H1>
<FORM ACTION="ch05_30.jsp" METHOD="POST">
<INPUT TYPE="submit" VALUE="Submit">
</FORM>
</BODY>
</HTML>

Y ou can see th e JS P p a g e th at w ill read an d disp lay th e requ est he a de rs you sen d to
it fro m ch05_29.html in Listin g 5.2 4 .

Listing 5.24 Reading Header Information (ch05_30.jsp)

<HTML>
<HEAD>
<TITLE>Reading Header Information</TITLE>
</HEAD>

<BODY>
<H1>Reading Header Information</H1>
Here are the request headers and their data:
<BR>
<% java.util.Enumeration names = request.getHeaderNames( );
while(names.hasMoreElements()){
String name = (String) names.nextElement();
out.println(name + ":<BR>" + request.getHeader(name) +
"<BR><BR>");
}
%>
</BODY>
</HTML>

Week 1 – Page 189


Y ou can see th e resu lts in Figu re 5.2 1 . A s you see in th at figu re, th e accept h ea de r
in form s y ou w h at kind s of data th e b row se r can accept, th e user-agent h ea de r tells
you w h at b ro w ser th e u ser h as, th e referer he ader tells you th at th e U R L of th e
W eb pa g e th at th e u ser w as ju st loo kin g at w as
http://localhost:8080/ch05/ch05_29.html, an d so on — all u sefu l in form ation .

Figure 5.21. Getting request header data.

[ T eam L iB ]

[ T eam L iB ]

Reset Buttons

Week 1 – Page 190


N o discu ssion on H TM L form s w ou ld be com p lete w ith ou t a dd in g reset b u tton s, an d it's
ap p ro priate to en d o u r d iscu ssion on form s w ith th is contro l. T h e u ser ca n click a
reset button to clear all th e data in th e c ontrol in th e form an d reset th em to th eir
defa u lt valu es. Y ou u su a lly a dd a reset button to a form ne xt to th e su b m it bu tton :

<HTML>
<HEAD>
<TITLE>Using a Reset Button</TITLE>
</HEAD>

<BODY>
<H1>Using a Reset Button</H1>
<FORM ACTION="ch04_05.jsp" METHOD="POST">
Please enter your name:
<INPUT TYPE="TEXT" NAME="text1">
<BR>
<INPUT TYPE="SUBMIT" value="Submit">
<INPUT TYPE="RESET" value="Reset">
</FORM>
</BODY>
<HTML>

Y ou can see th e reset b utton in Figu re 5.2 2 .

Figure 5.22. Adding a reset button to a form.

A n d th at's all it tak es— n ow th e u se r can reset all th e d ata in th e form ju st by clickin g
th is b utton . A lth ou g h n ot m a nd atory , it's a n ice con v en ien ce to h av e a reset button

Week 1 – Page 191


available in you r form s.

[ T eam L iB ]

[ T eam L iB ]

Summary
W e've see n a great d eal tod ay. W e to ok a look at w orkin g w ith so m e prim ary H T M L
controls h ere — ch eck b o xes, radio button s, an d select controls.

C h eck box es u su ally op erate ind e pen d ently, an d it's easy to recov er th e d ata fro m a
n a m e d ch eck box w ith th e getParameter m eth od. R a dio button s ope ra te in gro up s,
w h ere y ou give th em th e sa m e n a m e, bu t differen t valu es; an d it's ea sy to fin d
w h ich radio b utton is selected by u sin g th at n a m e w ith getParameter to get th e
valu e of th e selected ra dio button . W e've also see n h ow to select an d d esel ect both
ch eck bo xes an d radio b utton s in code.

C h eck box es can w ork in gro u p s, w he re y ou giv e all ch eck bo xes th e sa m e n a m e b u t


differe n t v alu es. In th at case, you u se th e getParameterValues m etho d , n ot
getParameter, to d eterm in e w h ich ch eck bo x es are ch e ck ed.

W e took a look at u sin g dro p -do w n select controls, as w ell as m u ltiple -selection
select controls, lettin g th e u ser select variou s item s in th ose controls an d
determ in in g w h ich ite m s are selected in code .

W e've also seen h ow to u se im a ge controls a n d create serv er-side im a g e m a ps. T o


create an im a ge m ap, y ou u se th e JS P action <jsp:forward>, w h ich lets you forw a rd
a req u est to an oth er W e b pa ge. Im a ge con tro ls act like su b m it button s, except th at
th ey also pass th e m ou s e location on to th e serv er, w h ich is w h at m ak es it possible
to im ple m en t im a ge m a ps.

W e've see n th at you ca n u se th e <FORM> elem e nt's TARGET attribute to sen d th e


outp u t fro m you r JS P cod e to an oth e r fra m e in a W eb pa ge, a n d w e lea rn ed ho w to
con v ert th e text data w e got from th e getParameter m eth od into n u m b ers.

W e took a look at diss ectin g th e in form ation in a requ est b y gettin g all th e p ara m ete r
n a m es sen t to ou r JS P code u sin g th e getParameterNames m eth od , as w ell as
decip h erin g th e in form a tion in th e requ e st h ead ers w ith th e getHeaderNames
m eth ods.

A t th is point, you'v e gain ed a solid foun d ation in w orkin g w ith requ ests an d H T M L
controls. You kn ow h ow to h a nd le data th e u ser send s, an d h o w to retu rn y ou r ow n
W eb pa g es. N ow th at you r cod e is actu ally doin g som eth in g su b sta n tial, it's ti m e to
start learn in g h ow to org a n ize th at cod e u sin g JavaB e an s.
[ T eam L iB ]

[ T eam L iB ]

Week 1 – Page 192


Q&A

Q1: W h a t if th e u se r o n ly se le cts o n e ite m in a m u lti- s e le ct se lec tio n


co n t ro l? S h o u ld I u se getParameter in th a t c a se ?

A1: N o, you still u se getParameters, bu t th e retu rn ed enu m eration w ill only


h ave on e item in it— th e item th e u ser selected.

Q2: D o im a g e m a p s s e n d a n y o th e r request o b jec t p a ra m e te rs b e s id e s


th e x a n d y m o u s e lo c a tio n ?

A2: N o, th ose a re th e on ly tw o. H ow ever, y ou can u se th e p resen ce of th ose


para m eters to determ in e th at th e im a ge m ap w as clicked, w h ich lets yo u
u se it as a g ra ph ical su bm it b u tton if you w a n t to.

[ T eam L iB ]

[ T eam L iB ]

Workshop
T h is w ork sh op tests w h eth er y ou un d erstan d all th e con cepts y ou learn ed tod a y. It's
a goo d idea to m a ster today 's con cepts b y h on in g you r kn ow led g e he re before
startin g tom o rrow 's m aterial. Y ou can fin d th e a n sw ers to th e q u iz q u estion s in
A pp e n d ix A .

Quiz

1: If a control contain s m u ltiple selection s, w h at m eth od d o you u se to get


th ose selection s fro m th e requ e st object?

2: H o w do you create a ra dio button gro u p ?

3: W h at h ap p en s if you d o n't u se th e SIZE attribu te in a select control?

4: If an im ag e contro l is n a m e d image1, w h at a re th e n a m es of th e requ e st


object pa ra m eters h oldin g th e x an d y m o u se location s?

5: H o w can you set re qu es t object p ara m eters w h e n forw a rdin g a requ e st to


an oth er U R L?

Exercises

Week 1 – Page 193


1: P u t w h at you've learn ed to w ork no w by enh an c in g th e create -you r-ow n
san d w ich exa m p le (Listin g 5.5 ) to read w h at ch eck bo x es are che ck ed an d
display a total price for th e san d w ich (u se $1.0 0 for each ch eck b ox
ch ecked, for exa m p le).

2: D ev elop a JS P p ag e th at displays seven radio contro ls th at let th e u ser


display th e d ay of th e w eek (M on d ay, T u esd a y, an d so on ) — a n d m ak e su re
th at th e cu rren t d ay of th e w eek's rad io button is alrea dy selected w h en th e
pa ge first ap p ea rs. Y ou can do th at w ith th e Date an d Calendar classes
you 'll see to m o rro w — u se th is page directive at th e top of you r cod e: <%@
page import="java.util.*" %>. T h en u se th is cod e: GregorianCalendar
calendar = new GregorianCalendar(); Date date1 = new Date();
calendar.setTime(date1); int day = calendar.get
(Calendar.DAY_OF_WEEK);, w h ich leav es th e d ay of th e w eek (S un d ay = 1,
M on d ay = 2, an d so on ) in th e varia ble n a m ed day. (Fo r m ore d etails on
dates, see Listin g 6.1 5 , com in g u p to m orrow !)

[ T eam L iB ]

[ T eam L iB ]

Day 6. Creating JSP Components:


JavaBeans
Tod ay , y ou w ill learn h ow to create y ou r ow n Ja v a classes, as w ell as JavaB ea n s. A s
you d evelop you r Java code, it'll get long er a n d long er, an d after a w h ile , it's n ot
goin g to fit easily into scriptlets an y m ore. A s it tu rn s out, JS P servers a re sp ecially
bu ilt to let you r JS P pa g es interact w ith Java classes th at y ou w rite you rself. N ow
th at ou r a pp lication s are g ettin g m ore in volved , w e're g oin g to see h o w th is w ork s.
H ere's an overview of tod ay 's topics:

 C reatin g a n d co m p ilin g Java classes


 C reatin g Java m eth o ds
 U sin g Java classes from JS P
 C reatin g Ja va p ack a ges
 C reatin g a n d u sin g Jav aB ean s
 C reatin g B ea n pro p erties

A s w e'll see , a Java B e a n w ill give you a ccess to pro p erties an d m eth od s th at you can
u se in JS P, called expo sing . T h at is, today w e're goin g to be w orkin g on th e Java p a rt
of Java S erv er Page s, an d you 're goin g to learn h ow to create co m p iled Java classes
accessible fro m JS P.

P uttin g you r cod e in com p iled Java .class files is a g o od idea for sev eral reason s.
First, it en ables y ou to o rga n ize you r cod e an d d ivide it in to m a n a gea ble
com p on ents, w h ich is especially im p orta n t as you r a pp lication s get m o re in volved.
Im a gin e tryin g to p u t tw enty pa g es of Ja va cod e into a scriplet, for ex am p le — it's

Week 1 – Page 194


m u ch easier to h a nd le th at cod e in its ow n Java file an d interact w ith it as ne eded in
JS P. T h e JS P serv er also h as to com p ile th ose 2 0 p ages of code ea ch tim e y ou open
th e pa ge, so th at it also sav es a g reat d eal of tim e to co m p ile you r cod e first an d
save it in a Java .class file.

Tip

You 'll see ho w to create Java classes directly in you r JS P code (in stead of
Java sou rce cod e files a s w e'll do tod ay) in D ay 8, "H a n d lin g Errors," bu t
n ote th at su ch classes a re inten tion ally kept sh ort — for lon ge r Java cod e ,
you u su ally u se a Java B ean .

C reatin g co m p on ents su ch as th is is also h ow JS P sup p o rts cod e reu se. W h eth e r y ou


h av e, say, 10 differen t W eb pa g es th at u se th e sa m e code to a ccess a data base, it's
far m ore efficien t to p u t th at cod e into a co m po n en t su ch as a Java B e a n in stead of
h av in g to repeat th at cod e in each pa g e . B eca u s e an y n u m b e r of W eb p ages can call
th e Java cod e in a Jav a B ean , Jav a B ea n s p rovid e u s w ith co m p on ents th at allow u s to
reu se ou r code a s n ee d e d.

N ow th at w e're tak in g a closer loo k at Java pro g ra m m in g , you'll also learn h ow to


w ork w ith som e Ja v a utility classes today — th e Date an d Calendar classes, w h ich
en a ble you to w ork w ith an d display dates an d tim es, a v ery p opu lar pa rt of W eb
pro g ra m m in g .

T h at's th e p rogra m for today — cre atin g Java co m p o n ents th at can sto re y ou r cod e
an d th at you can intera ct w ith in JS P easily, as w ell as startin g to take a loo k at
som e of th e pow er av a ilable to u s in th e utility classes bu ilt into Java. T oday w e're
goin g to w rite actu al Java pro gra m s, co m p ile th e m ou rselves, an d in stall th em on th e
serv er, so th at w e can reach th em in JS P. W e'll take it step -by-step, an d it all starts
by creatin g a Java class.

Tip

For th e official docu m en tation on Java B ean s, se e


http://jav a.su n.c o m /p ro du cts / ja va b ea ns/do cs /.

[ T eam L iB ]

[ T eam L iB ]

Creating a Java Class


In th is first exa m p le, y o u'll create a Java class n a m ed ch06_01 th at w ill in clud e a
m eth od n a m e d msg th at w ill retu rn th e strin g "Hello from JSP!". W e'll be able to

Week 1 – Page 195


call this m eth od fro m JS P. T o create a Java class, y ou u se th e Java class state m ent,
w h ich looks like th is in g ene ral:

access class classname [extends ...] [implements ...]


{
[access] [static] type variable1;
.
.
.
[access] [static] type variableN;

[access] [static] type method1 (parameter_list)


{
.
.
.
}
.
.
.
[access] [static] type methodN (parameter_list)
{
.
.
.
}
}

W e'll get fa m iliar w ith th e parts of th is statem en t in m o re d etail in D ay 1 1 , "C reatin g


M ore P ow erfu l Java B ean s." T h e a ccess term sp e cifies th e a ccessibility of th e class or
class m e m b ers to th e re st of th e p ro g ra m , a n d can be public, private, or
protected. Y ou u se th e extends an d implements keyw o rds w ith class inh erita n ce,
as w e'll see in D ay 11 .

To create ch06_01.class, w h ich is a co m p iled Java class file, you h a ve to sta rt w ith
th e actu al Java cod e for th is class, w h ich you m u st sto re in a file n a m e d
ch06_01.java. T h e class in th is file w ill be n a m ed ch06_01, a n d you create it w ith
th e Java class state m e nt:

public class ch06_01


{
.
.
.
}
E nter th e p recedin g text into ch06_01.java n ow . Java sou rce
cod e files m u st h ave th e exten sion .java, an d w e m u st n a m e
th is file ch06_01.java b ecau se it contain s a pu b lic class
n a m e d ch06_01. A pu b lic class is accessible to oth er Java code
outside th e cu rren t file, an d you can on ly h ave on e p ub lic
class p e r source code file. If ou r pu b lic class w a s n a m e d

Week 1 – Page 196


addem, w e'd n ee d to sto re it in a Java sou rce co d e file n a m e d
addem.java. Y ou can also h av e p rivate classes, as w e'll
discu ss later— a p rivate class is on ly accessible in th e sa m e file
th at it's defin ed in , an d you can h a ve as m a n y p rivate classes
in a file as y ou w a nt.

Let's g et sta rted on th e actu al Java code he re, startin g by ad din g a con s tru cto r to
ou r class.

[ T eam L iB ]

[ T eam L iB ]

Creating a Constructor
You u se a con stru cto r to create an obje ct fro m a class. In Ja va, a con stru cto r is a
m eth od w ith th e sa m e n a m e as th e class itself, so th at you can add a con stru ctor to
th e ch06_01 class like th is:

public class ch06_01


{
public ch06_01()
{
}
.
.
.
}

H ere, th e code ad d s a m eth od n a m e d ch06_01 to th e ch06_01 class. T h is p articu lar


con stru cto r d oesn't do a n yth in g ; it's a defa u lt con stru ctor. Later today , you'll see
h ow you can pa ss data to a con stru cto r s u ch as th is to con figu re th e object — in
particu lar, you 'll see ho w to u se th e con stru cto r to set th e text th at th e msg m eth od
w ill retu rn . N ow it's tim e to create th e msg m eth od.

[ T eam L iB ]

[ T eam L iB ]

Creating a Method
T h e msg m eth od is sim p ly sup p osed to retu rn th e text "Hello from JSP!", an d you
don 't pass an y data to it. T h is is a m eth od of th e ch06_01 class, so you can m ak e its
defin ition part of th at class, as you see in Listin g 6.1 .

Week 1 – Page 197


Listing 6.1 Creating a Method (ch06_01.java)

public class ch06_01


{
public ch06_01()
{
}

public String msg()


{
return "Hello from JSP!";
}
}

N ote th at th is m eth od is declared pu b lic. A pu b lic m eth o d su ch a s th i s can be called


from outside a class an d an y othe r classes base d on th is class. W e h av e to m ak e msg
a pu b lic m eth od so th at it'll be accessible outsid e th e ch06_01 class an d w e can call it
from JS P.

T h at's all you n ee d to start— y ou'v e created a p ub lic clas s, given it a d e fau lt
con stru cto r, an d ad d ed a m eth od, msg, to it. T h e msg m eth od w ill return ou r m essa ge
w h en it's called, so let's take a look at callin g th at m eth od fro m a JS P p age n ow .
[ T eam L iB ]

[ T eam L iB ]

Compiling a Java Class


T h e first step in m ak in g th e msg m eth od a ccessible to ou r JS P cod e is to co m p ile th e file
ch06_01.java, crea tin g th e file ch06_01.class. T h is is a step th at th e JS P server
h as be en tak in g care of for u s, b u t n ow th at w e w a n t to com p ile a Java class, w e'll
h a n dle th is task ourselv es.

In D a y 1, "G ettin g S tarted!," w e set ou r co m p uter's path to in clu de th e Java bin


directory (su ch as C:\jdk1.4\bin), w h ich gives u s a ccess to th e Java too ls th at w e'll
u se he re— in th is case, w e'll u se th e Java co m p iler, javac. M ak e su re th at you're in
th e sa m e directory a s ch06_01.java, an d en ter javac ch06_01.java a t th e
com m a n d p ro m p t to co m p ile ch06_01.java. Fo r exa m p le, in W in d ow s, th at m igh t
loo k like

C:\ch06>javac ch06_01.java

Tip

If y ou h av en 't set you r path as w e discu ssed in D ay 1, y ou can still u se


javac to com p ile Java files if you give th e fu ll path of th at com p iler, w h ich
m igh t loo k like th is in W ind ow s: C:\ch06>C:\jdk1.4\binjavac

Week 1 – Page 198


ch06_01.java.

T h is w ill co m p ile ch06_01.java an d create ch06_01.class in th e sa m e directory.


T h is n ew file, ch06_01.class, is th e file w e're goin g to n ee d so th at o u r JS P cod e
can call th e msg m eth o d .

[ T eam L iB ]

[ T eam L iB ]

Installing a Compiled Java Class


S o w he re can w e p u t ch06_01.class, so th at w e'll h ave access to it in a W eb pa ge ?
T h e exa m p les for tod a y go into th e webapps\ch06 directo ry in th e T om cat
directories. A s w e saw in D ay 1, directo ries like th e ch06 directo ry n eed a
sub d irectory n a m ed WEB-INF, w h ich itself h as tw o su bd irecto ries, classes an d lib:

webapps
|____ch06
|____WEB-INF
|____classes
|____lib

To give th e JS P p ag es in th e ch06 directory acc ess to Java .class files, th ose .class
files m u st go into th e ch06\WEB-INF\classes directo ry. T h at's all it tak es to give
you r JS P code access to ch06_01.class— ju st p u t th at file into th e ch06\WEB-
INF\classes directo ry. N ow w e're read y to pu t th is n ew Java class to w ork for u s,
an d th at's com in g u p n e xt.
[ T eam L iB ]

[ T eam L iB ]

Using a Compiled Java Class


O u r n ew Java class, ch06_01, is n ow in stalled — h ow do y ou u se it in a W eb pa g e?
You can start off by im p ortin g th at class into ou r JS P p ag e w ith th e pa g e directive
(th at you first sa w in D a y 1). T h e pa g e directive's im p ort attrib ute en a bles you to
im p ort a Java class to m ake it ava ilable to you r JS P cod e. H ere's ho w you can im p ort
th e ch06_01 class:

<%@ page import="ch06_01" %>


<HTML>
<HEAD>

Week 1 – Page 199


<TITLE>Using a JavaBean</TITLE>
</HEAD>
<BODY>
.
.
.
</BODY>
</HTML>

N ow you can create a n ew object of th is class. T h is tim e th e code w ill call this n ew
object messager. T h is object w ill en able u s to call th e msg m eth od to g et th e "Hello
from JSP!" m e ssa g e:

<%@ page import="ch06_01" %>


<HTML>
<HEAD>
<TITLE>Using a JavaBean</TITLE>
</HEAD>
<BODY>
<H1>Using a JavaBean</H1>

<% ch06_01 messager = new ch06_01(); %>


.
.
.
</BODY>
</HTML>

N ow you h av e an ob ject of th e ch06_01 class, so you can call th e msg m eth od to get
th e m e ssa g e a n d display it, as y ou see in Listin g 6.2 .

Listing 6.2 Calling a Method (ch06_02.jsp)

<%@ page import="ch06_01" %>


<HTML>
<HEAD>
<TITLE>Using a JavaBean</TITLE>
</HEAD>
<BODY>
<H1>Using a JavaBean</H1>

<% ch06_01 messager = new ch06_01(); %>

The message is: <%= messager.msg() %>

</BODY>
</HTML>

Y ou can see th e resu lts in Figu re 6.1 , w he re ou r call to th e msg m eth od w as


su ccessfu l.

Week 1 – Page 200


Figure 6.1. Calling a compiled Java method.

A t th is point, w e'v e b e e n a ble to create an d com p ile a Java class, in sta ll it w h ere th e
JS P serv er can fin d it, an d call a m eth od in th at class.

N ote th at w e h ad to spe cifically im p ort th e class. A ctu ally, w e


can m ak e th in g s a little easier on ou rselves if w e pu t ou r class
in to a Java pa ck age, an d th at's co m in g u p n ext.
[ T eam L iB ]

[ T eam L iB ]

Creating a Package
Java provides an easy w ay of org an izin g you r classes u sin g Java p acka ges. A n d if
you u se a Ja va p acka ge , you w on 't h ave to u se th e page directive to im p ort you r
classes in JS P.

For exa m p le, you can p u t th e Java cod e ju st d e velop ed into a n ew class th at's p a rt of
a Java packa g e . In th is case, th e packa g e w ill be n a m ed beans. You ca n create th is
pack a g e in a .java file w ith th e package state m e nt, as you see in Listin g 6.3 .

Listing 6.3 Creating a Package (ch06_03.java)

package beans;

Week 1 – Page 201


public class ch06_03
{
public String msg() {
return "Hello from JSP!";
}

public ch06_03()
{
}
}

N ow w h en y ou com p ile th is n ew file, ch06_03.java, y ou'll get ch06_03.class— b u t


th e pu b lic class in th is .class file is n o long er ch06_03. In stead , it's beans.ch06_03,
beca u se it's in th e beans packa g e. T h at's h ow y ou m u st refer to it n ow — as
beans.ch06_03. A n d y o u ca n't pu t it into th e classes directo ry an y m o re ; y ou m u st
pu t it into a directo ry n a m e d classes\beans:

webapps
|____ch06
|____WEB-INF
|____classes
| |____beans
|____lib

In th is w ay, th e disk o rg an ization of you r Ja v a classes reflects th e p ack a ge y ou'v e


pu t you r classes in . Y ou sep a rate p ack a ge n a m es w ith a dot ( .). Fo r ex a m p le, if w e
created a pack a ge n a m ed these.are.my.beans like th is

package these.are.my.beans;

public class ch06_03


{
public String msg() {
.
.
.

th en w e'd store ou r ch06_03.class file in th e directory


classes\these\are\my\beans:

webapps
|____ch06
|____WEB-INF
|____classes
| |____these
| |____are
| |____my
| |____beans
|____lib

Week 1 – Page 202


N ow th at w e've placed ou r n ew class in a pack a ge n a m ed beans, h ow d o w e access
th at class? T h at's com in g u p n ext.
[ T eam L iB ]

[ T eam L iB ]

Using a Package
A s fa r as ou r JS P p ag e goes, all th at's ch an g ed is th e n a m e of ou r class; in stead of
ch06_03, it's n ow beans.ch06_03. T h at m ea n s all you h ave to do is u se th at as th e
class n a m e, as you see in Listin g 6.4 .

Listing 6.4 Using a Package (ch06_04.jsp)

<HTML>
<HEAD>
<TITLE>Using a Java Package</TITLE>
</HEAD>

<BODY>
<H1>Using a Java Package</H1>

<% beans.ch06_03 messager = new beans.ch06_03(); %>


The message is: <%= messager.msg() %>

</BODY>
</HTML>

N otice th at th e page dire ctive w e u sed in ou r e a rlier n on -pack a ge exa m p le


ch06_02.jsp is gon e. N ow th at w e'v e p u t ou r Java class into a p acka g e, th e n ew
directory stru ctu re (sp e cifically, th e beans sub d irectory of th e classes directo ry) tells
To m cat w h e re to fin d ch06_03.class. W e d on't n ee d to im p ort an y class at all;
To m cat w ill do th at for u s a uto m atically. Y ou ca n see th e resu lts in Figu re 6 .2 — n ow
w e're org a n izin g ou r Jav a classes into packa g es.

Figure 6.2. Using a class from a Java package.

Week 1 – Page 203


[ T eam L iB ]

[ T eam L iB ]

Passing Data to a Constructor


S o fa r, ou r con stru ctor h as n't don e a n yth in g , bu t it's tim e to ch an g e th at. U su ally
you u se a Ja va class's con stru ctor to con figu re an object w h en y ou cre ate it, an d
w e'll do th at h ere. F or e xa m p le, w e can p a ss th e strin g w e w a n t th e msg m eth od to
retu rn to th e con stru cto r, sto rin g th at strin g in tern ally.

H ere's h ow it m igh t loo k — in th is case, th e con stru cto r for th is class tak es a String
arg u m e n t an d stores it in an intern al variable n a m e d msg. T h e msg m eth od rea ds th e
text an d retu rn s it w h en you call th is m eth o d; y ou can see ho w it all loo ks in Listin g
6.5 .

Listing 6.5 Returning Text from a Method (ch06_05.java)

package beans;

public class ch06_05


{
String msg;

public ch06_05(String message)


{
msg = message;
}

Week 1 – Page 204


public String msg() {
return msg;
}
}

N ow you can p ass d ata to th is n ew con stru ctor w h en you create a n ew object of th is
Java class, a s y ou can see in Listin g 6.6 .

Listing 6.6 Using a Constructor (ch06_06.jsp)

<HTML>
<HEAD>
<TITLE>Using a Constructor</TITLE>
</HEAD>

<BODY>
<H1>Using a Constructor</H1>

<% beans.ch06_05 messager = new beans.ch06_05("Hello from JSP!");


%>

The message is: <%= messager.msg() %>


</BODY>
</HTML>

A n d th at's all th ere is to it— n ow you 're able to con figu re th e objects y ou create fro m
Jav a classes w ith a con stru cto r. Y ou can see th e resu lts in Figu re 6.3 .

Figure 6.3. Using a constructor.

Week 1 – Page 205


A ctu ally, th e Java classes w e'v e be en d ev elopin g so far are n ot techn ically
JavaB ea n s, th ey're ju st classes. A Jav a B ean m u st also exp o se pro pe rtie s.

JS P m ak es it easy to in tera ct w ith Java classes an d JavaB ea n s u sin g th e


<jsp:useBean> ele m en t. You can u se th is ele m e n t to creat e objects fro m Java B e an s
(an d th en set an d g et p ro p erty valu es u sin g th at object), an d an in -de pth look at th is
ele m en t is co m in g u p n ext.

[ T eam L iB ]

[ T eam L iB ]

Using <jsp:useBean>
You 'v e seen th at you ca n create obje cts from Ja va classes w ith ou t an y special effort.
B u t you can also u se th e <jsp:useBean> ele m e n t to do th e sa m e th in g . T h e
<jsp:useBean> ele m en t is a con v en ien ce elem e n t in JS P th at en a bles y ou to create
an object of a Java class an d give it an ID . Y ou can th en u se th at ID w ith tw o oth er
ele m ents, <jsp:getProperty> an d <jsp:setProperty>, to g et an d set pro p erty
valu es.

Let's tak e a look at th e sy ntax of th e <jsp:useBean> ele m ent. A s disc u ssed in th e


Introd u ction , th is boo k u ses th e con v ention s of Java do cu m e ntation for sy ntax su ch
as th is— h ere, | m ea n s "or," ite m s in bold are d e fau lt setting s, item s in squ are
brack ets ([ an d ]) are o ption al, an d you m u st select on e item of th ose th at ap p ear in

Week 1 – Page 206


cu rly braces ({ an d } ):

<jsp:useBean id="ID"
scope="page|request|session|application"
{
class="package.class" [ type="package.class" ]|
beanName="{package.class | <%= expression %>}"
type="package.class" |
type="package.class"
}
{ /> | > other elements </jsp:useBean> }

Let's tak e a look at th e attributes of th is elem e nt:

 id="ID"— A va ria ble th at iden tifies th e b ean . Y ou can u se th e va riable n a m e


in expression s or scriptlets in th e JS P pa g e. If th e bean h a s already b e en
created b y a n oth er <jsp:useBean> ele m ent, th e valu e of id m u st m atch th e
valu e of id u sed w h en th e bean w as create d .
 scope="page|request|session|application"— T h e scop e in w h ich th e
bean exists. T h e d e fa u lt valu e is page. W e'll see m o re on scop e tom orro w .
T h e p ag e scop e m e an s you can u se th e b ean w ith in th e JS P pa ge. T h e
req u est sc ope m ean s yo u can u se th e b ea n fro m an y JS P pa g e p rocessin g th e
sa m e re qu est. T h e session scop e m ean s y ou ca n u se th e be an fro m an y JS P
pa ge in th e sa m e session as th e JS P p a ge th at created th e b ea n , as you 'll see
tom o rrow . T h e a p p lica tion scop e m ea n s y ou ca n u se th e be an fro m an y JS P
pa ge in th e sa m e a p p lication as th e JS P pa g e th at created th e b ea n , a s you 'll
see tom orrow .
 class="package.class"— C reates a bea n fro m a class. T h e class m u st h ave
a pu b lic no -arg u m e n t con stru ctor.
 type="package.class"— If th e bean alrea dy e xists, th is gives th e be a n a
data type oth e r th an th e class it w as created from . T h e typ e m u st be a class
or interfa ce th at th e b e a n is already based on .
 beanName="{package.class | <%= expression %>}"
type="package.class"— C re ates a bean fro m a class. W h en you u se
beanName, th e b ean is created by th e java.beans.Beans.instantiate
m eth od, w h ich w e're n o t goin g to cover h ere.
 other elements— Y ou can in clud e oth er elem e nts in side th e body of
<jsp:useBean>, su ch a s th e <jsp:getProperty> an d <jspSetProperty>
ele m ents.

H ere's an exa m p le th at puts <jsp:useBean> to w ork. W e'v e already see n th is cod e ,


w h ich creates an obje ct from ch06_03.class an d calls th at object's msg m eth od:

<% beans.ch06_03 messager = new beans.ch06_03(); %>


The message is: <%= messager.msg() %>

H ere's h ow to d o th e sa m e th in g w ith <jsp:useBean>. In th is case, you can create a


n ew be an w ith th e ID bean1 fro m th e sa m e class, ch06_03.class (intern ally, Java
actu ally u ses th e new op erator to create th is n ew obje ct). T h en you can refer to th at

Week 1 – Page 207


bean w ith th at ID — for e xa m p le, you can call th e b ean 's msg m eth od as bean1.msg,
as y ou see in Listin g 6.7 .

Listing 6.7 Using a Bean (ch06_07.jsp )

<HTML>
<HEAD>
<TITLE>Using &lt;jsp:useBean&gt;</TITLE>
</HEAD>

<BODY>
<H1>Using &lt;jsp:useBean&gt;</H1>

<jsp:useBean id="bean1" class="beans.ch06_03" />

The message is: <%= bean1.msg() %>


</BODY>
</HTML>

Y ou can see th is W eb p a ge in Figu re 6.4, w h ere w e'v e u sed <jsp:useBean> to create


a n ew Jav a object.

Figure 6.4. Using the <jsp:useBean> element.

T h e <jsp:useBean> elem e n t is design ed to b e u sed w ith tw o oth er elem e nts — th e


<jsp:getProperty> an d <jspSetProperty> elem e nts, w h ich en a ble y ou to w ork

Week 1 – Page 208


w ith bean pro p e rties. W e'll loo k at h ow to create a p ro p erty in a JavaB e an n ext.

[ T eam L iB ]

[ T eam L iB ]

Creating a Read-Only Property


A pro p erty is a data item th at you store in a Ja vaB ea n . Fo r exa m p le, sup p ose you
h ave a p ro p erty n a m e d color. Y ou can store va riou s strin g s, su ch as red, blue, an d
so on in th e color prop erty , an d th e be an can u se th at pro p erty's valu e to con fig u re
th e H TM L it retu rn s fro m othe r m eth o ds.

To sup p ort a Java B ea n pro p erty , y ou u se get a n d set m eth od s. F or ex a m p le, for th e
color pro p erty, you'd a dd getColor an d setColor m eth od s to th e b ea n . N ote th at
you capitalize "color" in getColor an d setColor, even th ou g h th e actu a l pro perty
n a m e is color— Java w ill expect th e se m eth ods to exist, so it can w ork w ith th e
color pro p erty. If y ou r pro p erty w as n a m ed myFavoriteProperty, y ou w ou ld u se
th e get an d set m etho d s getMyFavoriteProperty an d setMyFavoriteProperty.

In th is ca se, you can ad d a prop e rty n a m ed message th at retu rn s ou r m essa ge fro m th e


bea n . Y ou can sta rt by on ly ad d in g a get m eth o d, w h ich m ean s th is p rope rty w ill
be read-o n ly (th ere's n o set m eth od to set its valu e). In p articu lar, th is cod e w ill
en a ble Java to read th e valu e of th is pro p erty w ith a m eth od n a m ed getMessage, as
you see in Listin g 6.8 .

Listing 6.8 Reading a Property Value (ch06_08.java)

package beans;

public class ch06_08


{

private String message = "Hello from JSP!";

public String getMessage()


{
return message;
}

public ch06_08()
{
}
}

N ote th at in a ddition to th e getMessage m eth od , th e cod e h as also de clared a


variable w ith th e sa m e n a m e as th e p ro p erty , message. Java w ill exp ect to fin d a
variable w ith th e sa m e n a m e as th e p ro p erty th is w ay, b e ca u se th at tells Java w h at

Week 1 – Page 209


th e data type of th e p ro p erty is.

You m ig h t also n ote th a t th e code h as d eclared th e strin g variable message to b e


private h ere. T h at m ea n s it's n ot accessible outside objects of th is class— in stea d,
you m u st a ccess its valu e w ith th e getMessage m eth od. If you m a d e th is variable
public in stead (su ch as th is: public String message = "Hello from JSP!";),
you can access it in JS P cod e directly as object.message, as in th is cod e:

<% beans.ch06_05 messager = new beans.ch06_08; %>


The message is: <%= messager.message %>

H o w ev er, th is gives th e JS P cod e direct access to th e message va riable, w h ich m ea n s


it can ch an g e th at varia ble's valu e. T o av oid su ch ta m p e rin g , it h as bec om e sta nd ard
in Java B ean s to u se get an d set m eth ods to create a w ell-defin ed w ay of accessin g
pro p erty valu es— for ex a m p le, if som e JS P cod e tried to set a pro pe rty n a m e d
height to a n egative va lu e, th e pro p erty's set m eth od can detect th at an d n ot s tore
th at valu e in th e pro p erty.

T h at's all w e n ee d to let Java read th e valu e of th is pro p e rty. H ow d o y o u read th at


valu e in JS P? You u se th e <jsp:getProperty> elem ent.
[ T eam L iB ]

[ T eam L iB ]

<jsp:getProperty> : Getting a Property Value


You u se th e <jsp:getProperty> ele m en t to retu rn th e valu e of a p ro p erty . H ere's
th e sy ntax for th is elem ent:

<jsp:getProperty name="ID" property="propertyName" />

H ere are th e attributes of th is ele m ent:

 name="ID"— T h is refers to th e n a m e of th e b ea n as de clared in a


<jsp:useBean> ele m en t.
 property="propertyName"— T h e n a m e of th e bean p rop e rty w h ose va lu e
you w ant. T h e p ro p erty is declared as a va riable in a bean an d m u st h av e a
corresp on d in g get m eth od.

H ere's h ow you can u se <jsp:getProperty> to get th e valu e of th e message


pro p erty — all you h ave to do is u se <jsp:useBean> to create an obje ct n a m e d, say,
bean1, an d th en g et th e valu e of th e message p ro p erty , a s y ou see in Listin g 6.9 .

Listing 6.9 Getting a Property Value (ch06_09.jsp)

<HTML>

Week 1 – Page 210


<HEAD>
<TITLE>Getting a Property Value</TITLE>
</HEAD>

<BODY> element> element> element>


<H1>Getting a Property Value</H1>

<jsp:useBean id="bean1" class="beans.ch06_08" />

The message is: <jsp:getProperty name="bean1" property="message" />


</BODY>
</HTML>

You can see th e resu lts in Figu re 6.5 .

Figure 6.5. Getting a property's value.

N ow w e can g et th e valu e of a p ro p erty in a JavaB ea n . It's w orth n otin g th a t you can


also u se <jsp:getProperty> in sid e a <jsp:useBean> ele m ent:

The message is:


<jsp:useBean id="bean1" class="beans.ch06_08">
<jsp:getProperty name="bean1" property="message" />
</jsp:useBean>

N ote, ho w ever, th at th is w ill on ly w ork if th e en closin g <jsp:useBean> elem e n t


creates th e obje ct y ou're accessin g w ith <jsp:getProperty>; if th e object alread y
exists (th at is, w as cre a ted by an oth er <jsp:useBean> elem e nt), th e elem e nts in th e

Week 1 – Page 211


<jsp:useBean> ele m en t are n ot ex ecu ted.

T h at's ho w to get th e va lu e of a p ro p erty — n ow w h at a bou t settin g a p rope rty's


valu e?
[ T eam L iB ]

[ T eam L iB ]

Creating a Read/Write Property


To let Java set th e valu e of a p rop e rty, you can u se a set m eth o d. F or exa m p le, to let
ou r JS P cod e set th e m e ssage ou r bean w ill retu rn , w e can ad d a m eth o d n a m e d
setMessage to set th e v alu e of th e message pro p erty . Y ou can see w h at th at m ig h t
loo k like in Listin g 6.1 0 .

Listing 6.10 Creating a Property (ch06_10.java)

package beans;

public class ch06_10


{

private String message = "Hello from JSP!";

public void setMessage(String msg)


{
this.message = msg;
}

public String getMessage()


{
return this.message;
}

public ch06_10()
{
}
}

N ote th e keyw ord this h ere. In Ja va, th is keyw ord a lw ays refers to th e curre n t
object. In oth er w ords, this.message refers to th e private va ria ble message created
an d stored in th is object:

private String message = "Hello from JSP!";

public void setMessage(String msg)


{
this.message = msg;
}

Week 1 – Page 212


Th e this keyw ord is a h an d y on e to kn ow n ow th at you 're creatin g Java obje cts —
you can alw ays u se it in cod e to refer to th e curren t object. A s you 've see n , it's n ot
techn ically n ecessa ry to u se th e this keyw ord w h en you 're referrin g to an obje ct's
data from cod e in th at object (in fact, Java w ill u se it auto m atically if you om it it),
bu t you'll so m etim es se e it don e for clarity. It can also preve n t a m b ig u ity w h en a
fun ction arg u m e n t h as th e sa m e n a m e as a va riable.

To a ctu ally set th e valu e of th e m e ssa g e p ro p erty in JS P cod e, you can u se th e


<jsp:setProperty> ele m e nt.
[ T eam L iB ]

[ T eam L iB ]

<jsp:setProperty> : Setting Property Values


You u se <jsp:setProperty> to set p ro p erty valu es in JS P. Y ou can p a ss you r ow n
valu es, or auto m atically pass valu es fro m th e request obje ct. H ere's th e sy ntax of
th is elem e nt:

<jsp:setProperty name="ID"
{
property="*" |
property="propertyName" [ param="parameterName" ] |
property="propertyName" value="{stringLiteral| <%= expression %>}"
}
/>

H ere are th e attributes of th is ele m ent:

 name="ID"— T h e n a m e of a bean th at h as alrea dy b e en created or located


w ith a <jsp:useBean> elem ent.
 property="*"— S to res all of th e valu es of request obje ct p ara m eters in
bean p rop e rties. T h e n a m es of th e b ean pro pe rties m u st m atch th e n a m es of
th e request pa ra m eters. N ote th at th e requ est para m eters a re alw ays
string s, so Java con v erts th em to th e type of y ou r p rop e rty w ith m etho d s
su ch as Double.valueOf(String) auto m atically.
 property="propertyName" [ param="parameterName" ]— S ets on e b ean
pro p erty to th e valu e of on e request p ara m eter. If th e b ean p ro p erty an d th e
req u est p a ra m eter h ave differen t n a m es, y ou m u st sp e cify both property
an d param. If th ey h av e th e sa m e n a m e, you ca n specify property an d om it
param.
 property="propertyName" value="{string | <%= expression %>}"— S ets
on e b ean p rop erty to a specific valu e. T h e valu e can b e a String or an
exp re ssion th at is evalu ated at runtim e. If th e v alu e is a String, it is
con v erted to th e b ean p ro p erty's d ata type a uto m atically.

H ere's an exa m p le th at puts <jsp:setProperty> to w ork u sin g th e set m eth od


setMessage th at w e've ad d ed to ou r exa m p le. In th is case, w e'll first display th e

Week 1 – Page 213


defa u lt m essa g e th at th is pro pe rty h olds, an d th en u se <jsp:setProperty> to set it
to a ne w m essa ge, as y ou see in Listin g 6.1 1 .

Listing 6.11 Setting a Property Value (ch06_11.jsp)

<HTML>
<HEAD>
<TITLE>Setting a Property Value</TITLE>
</HEAD>

<BODY>
<H1>Setting a Property Value</H1>

<jsp:useBean id="bean1" class="beans.ch06_10" />

The message is: <jsp:getProperty name="bean1"


property="message" />
<BR>
<jsp:setProperty name="bean1" property="message" value="Hello
again!" />

Now the message is: <jsp:getProperty name="bean1"


property="message" />
</BODY>
</HTML>

A n d th at's all it tak es— y ou can see th e resu lts in Figu re 6.6 , w h ere w e see th at w e
w ere in d ee d able to set a bean 's p rop e rty.

Figure 6.6. Setting a property value.

Week 1 – Page 214


[ T eam L iB ]

[ T eam L iB ]

Creating Private Methods


H ere's on e m ore th in g w e sh ou ld n ote in p assing . W e'v e stored ou r p rope rty u sin g a
private varia ble in ou r Java code — doin g so h elps h ide th at d ata fro m ex tern al
ta m p erin g . Y ou can also create private m eth o d s th at are pu rely intern al to th e
cu rren t object, an d can n ot be called fro m outside th e obje ct. T h is is a goo d idea if
you 're u sin g m eth ods th at you on ly w a n t to call from in side th e object. S u ch
m eth ods m ig h t h elp in p erform in g intern al calcu lation s, for exa m p le. U sin g private
m eth ods ca n h elp orga n ize you r objects, w ra pp in g u p all th eir fun ction ality into a
self-contain e d entity.

H ere's an exa m p le th at sh ow s h ow th is w ork s — in th is case, you ca n ju st add a


private m eth od n a m ed privateMessage th at w ill retu rn th e object's m e ssa g e , an d
call th e m eth od in th e message pro p erty's get m eth od, a s y ou see in Listin g 6.1 2 .

Listing 6.12 Using a Private Method (ch06_12.java)

package beans;

public class ch06_12


{

Week 1 – Page 215


private String message = "Hello from JSP!";

public void setMessage(String msg)


{
this.message = msg;
}

public String getMessage()


{
return privateMessage();
}

private String privateMessage()


{
return this.message;
}

public ch06_12()
{
}
}

Y ou can see a JS P pa g e th at u ses th is n ew class in Listin g 6.1 3 .

Listing 6.13 Calling a Private Method (ch06_13.jsp)

<HTML>
<HEAD>
<TITLE>Calling a Private Method</TITLE>
</HEAD>

<BODY>
<H1>Calling a Private Method</H1>

<jsp:useBean id="bean1" class="beans.ch06_12" />

The message is: <jsp:getProperty name="bean1"


property="message" />
<BR>
<jsp:setProperty name="bean1" property="message" value="Hello
again!" />

Now the message is: <jsp:getProperty name="bean1"


property="message" />
</BODY>
</HTML>

You can see th e resu lts in Figu re 6.7 — n ow w e'v e created p rivate m eth o d s pu rely
in tern al to a Java obje ct.

Figure 6.7. Using private methods.

Week 1 – Page 216


N ow th at you 're dig gin g into th e depth s of Jav a , it's a go od idea to tak e a loo k at th e
first of sev eral Java utility classes th at you 'll see th rou gh ou t th e b oo k . T h ese utility
classes are an im p ortan t part of Java pro gra m m ing . H e re y ou'll see th e Date class,
w h ich is in th e p acka g e n a m e d java.util.

[ T eam L iB ]

[ T eam L iB ]

Java Utility Classes: Working with Dates


T h e Date class en a bles you to create objects th at rep resen t a sp ecific in sta n t in tim e.
T h is class is a pop u lar o n e in Java pro g ra m m in g am o n g JS P p ro g ra m m e rs, b e ca u se it
en a bles you to keep tra ck of dates an d tim es. F or exa m p le, you can se e a JS P pa ge
th at displays th e date a n d tim e in Listin g 6.1 4 .

Listing 6.14 Using the Date Class (ch06_14.jsp)

<HTML>
<HEAD>
<TITLE>Using the Date Class</TITLE>
</HEAD>

<BODY>
<H1>Using the Date Class</H1>

Week 1 – Page 217


The date is: <%= new java.util.Date() %>.
</BODY>
</HTML>

You can see th e resu lts in Figu re 6.8 .

Figure 6.8. Getting the date.

B efore Java v ersion 1.1, you cou ld also u se th e Date class to get th e d a y of th e
m o nth , y ear, h our, an d so on sep a rately, b u t th at's gotten m ore co m p le x. N ow , th e
Calendar class sh ou ld be u sed to get th at kin d of in form ation . T h e origin al m eth ods
in th e Date class a re d e p recated, as you 'll see .

You sh ou ld kn ow th at th ere a re certain con vention s u sed to repre sen t m onth s, day s
of th e m onth , an d so on , in th e Date class:

 A m o nth is rep resented by an integer fro m 0 to 11; 0 is Jan u ary, 1 is


Febru a ry, an d so on , u p to 11, w h ich is D ecem b er.
 A date (day of m onth ) is rep resented by an intege r from 1 to 31.
 A n h ou r is re presented by an integer fro m 0 to 23. T h e h ou r from m idn igh t to
1 a.m . is h ou r 0, an d th e h ou r fro m n o on to 1 p .m . is h ou r 12 , an d so o n .
 A m inute is rep resen ted by an integer fro m 0 to 59.
 A secon d is rep resen ted by an integer from 0 to 61 (th e valu es 60 an d 61 do
occu r! B u t on ly for leap secon d s).

You can see th e Date class's m eth ods in Ta ble 6.1 .

Week 1 – Page 218


Table 6.1. Date Class Methods
M e th o d D o e s T h is
Date() C reates a Date obje ct a n d in itializes it to th e tim e it w as
created.
Date(int year, int D ep reca ted. R eplaced b y Calendar.set(year + 1900,
month, int date) month, date) or GregorianCalendar(year + 1900,
month, date).
Date(int year, int D ep recated. R eplace d b y Calendar.set(year + int
month, int date, hrs, 1900, month, date, hrs, min) or
int min) GregorianCalendar(year + 1900, month, date,
hrs, min).
Date(int year, int D ep recated. R eplace d b y Calendar.set(year + int
month, int date, hrs, 1900, month, date, hrs, min, sec) or
int min, int sec)
GregorianCalendar(year + 1900, month, date, hrs,
min, sec).
Date(long date) C reates a Date obje ct a n d in itializes it to th e given
nu m b e r of m illisecon d s sin ce Jan u ary 1, 1970,
00 :0 0 :00 G M T.
Date(String s) D ep recated. R eplace d b y DateFormat.parse(String).
boolean after(Date T ests if th is date is after th e sp ecified date.
when)
boolean before(Date T ests if th is date is befo re th e sp ecified date.
when)
Object clone() R etu rn s a copy of th is o bject.
int compareTo(Date C o m p a res tw o Dates for ord erin g .
anotherDate)
int compareTo(Object C o m p a res th is Date to a n oth er obje ct.
o)
boolean equals(Object C o m p a res tw o d ates for equ ality.
obj)
int getDate() D ep recated. R eplace d b y
Calendar.get(Calendar.DAY_OF_MONTH).
int getDay() D ep recated. R eplace d b y
Calendar.get(Calendar.DAY_OF_WEEK).
int getHours() D ep recated. R eplace d b y
Calendar.get(Calendar.HOUR_OF_DAY).
int getMinutes() D ep recated. R eplace d b y
Calendar.get(Calendar.MINUTE).
int getMonth() D ep recated. R eplace d b y
Calendar.get(Calendar.MONTH).

Week 1 – Page 219


int getSeconds() D ep recated. R eplace d b y
Calendar.get(Calendar.SECOND).
long getTime() R etu rn s th e nu m b e r of m illisecond s sin ce Janu a ry 1,
197 0, 00 :00 :0 0 G M T re p resented by th is Date object.
int D ep recated. R eplace d b y
getTimezoneOffset() Calendar.get(Calendar.ZONE_OFFSET) an d
Calendar.get(Calendar.DST_OFFSET).
int getYear() D ep recated . R eplaced b y
Calendar.get(Calendar.YEAR) - 1900.
void setDate(int date) D ep recated. R eplac ed b y
Calendar.set(Calendar.DAY_OF_MONTH, int date).
void setHours(int D ep recated. R eplace d b y
hours) Calendar.set(Calendar.HOUR_OF_DAY, int hours).
void setMinutes(int D ep recated. R eplace d b y
minutes) Calendar.set(Calendar.MINUTE, int minutes).
void setMonth(int D ep recated. R eplace d b y
month) Calendar.set(Calendar.MONTH, int month).
void setSeconds(int D ep recated. R eplace d b y
seconds) Calendar.set(Calendar.SECOND, int seconds).
void setTime(long S ets th is Date object to rep rese n t time m illisecond s
time) after Ja nu ary 1 , 1970 0 0:00 :0 0 G M T.
void setYear(int year) D ep recated. R eplac ed b y
Calendar.set(Calendar.YEAR, year + 1900).
String toGMTString() D ep recated. R eplaced b y DateFormat.format(Date
date), u sin g a G M T tim e zon e.
String D ep recated. R eplace d b y DateFormat.format(Date
toLocaleString() date).
String toString() C on verts th is Date obje ct to a String.
long UTC(int year, int D ep recated. R eplace d b y Calendar.set(year + int
month, date, int hrs, 1900, month, date, hrs, min, sec) or
int min, int sec) GregorianCalendar(year + 1900, month, date,
hrs, min, sec), u sin g a U TC tim e zon e, follow ed by
Calendar.getTime().getTime().

A s y ou can see in Table 6.1 , m an y of th e Date class's m eth ods th at let you g et th e
h ou r, d a y, m inute, an d so on a re n ow d ep recated in fav or of th e Calendar class. T h e
rea son is th at th e Date class w as n't p rep ared fo r intern ation alization . U sin g th e Date
class togeth er w ith variou s Calendar classes, o n th e othe r h a nd , en a bles you to
w ork w ith tim es in an y intern ation al locale.

Week 1 – Page 220


You don 't actu ally u se th e Calendar class directly, you u se a
class de rived fro m it for spe cific locales. C urrently, th ere's
on ly on e su ch class, GregorianCalendar. S ay, for exa m p le,
th at you w an t to get th e cu rre n t y ear. Y ou can d o th at by
creatin g a GregorianCalendar obje ct an d passin g its setTime
m eth od a Date object. T h en to g et th e year in th at Date
object, y ou can u se th e GregorianCalendar ob ject's get
m eth od, p a ssin g it th e Calendar.YEAR field like th is:

GregorianCalendar calendar = new GregorianCalendar();


Date date1 = new Date();
calendar.setTime(date1);
out.println("Calendar.YEAR is " + calendar.get(Calendar.YEAR) +
"<BR>");

T h e fields of a class a re its data m e m b e rs — th at is, variables availa ble p ub licly or to


classes based on th e cu rren t class. W h en a field n a m e is in capital letters (like YEAR),
th at's a Java co n vention — it m ea n s th e field is a con stant, an d its valu e can 't be
ch a ng e d (th ese a re static data m e m be rs, a n d y ou d e clare th e m in Java w ith th e
static keyw ord). You can see th e fields of th e C alen d ar class in Table 6.2 . Y ou can
also set th e tim e in a GregorianCalendar obje ct u sin g th e set m eth od su ch as in
th e follow in g, w h ere th e cod e is settin g th e tim e to 23 :59 (on e m inute b efore
m idn ight) on 11 /31 /20 05:

calendar.set(2005, 11, 31, 23, 59);


Table 6.2. Calendar Class Fields
F ie ld M e a n in g
int AM V alu e of th e AM_PM field for th e p eriod of th e da y from
m idn igh t to ju st before n oo n .
int AM_PM Ind icates w h eth e r th e HOUR is befo re or a fter n o on .
int APRIL V alu e of th e MONTH field for A p ril.
int AUGUST V alu e of th e MONTH field for A u g u st.
int DATE U se in get an d set for th e day of th e m onth .
int DAY_OF_MONTH U se in get an d set for th e day of th e m onth .
int DAY_OF_WEEK U se in get an d set for th e d ay of th e w eek.
int U se in get an d set for th e nu m b e r o f th e d a y of th e
DAY_OF_WEEK_IN_MONTH w eek w ith in th e cu rre n t m o nth .
int DAY_OF_YEAR U se in get an d set for th e d ay nu m b e r w ith in th e
cu rren t year.
int DECEMBER V alu e of th e MONTH field for D ecem b e r.
int DST_OFFSET U se in get an d set for th e d ay ligh t sav in g s offset in
m illisecond s.

Week 1 – Page 221


int ERA U se in get an d set for th e era (su ch as A .D . o r B .C . in
th e Ju lian calen d ar).
int FEBRUARY V alu e of th e MONTH field for th e secon d m onth of th e
yea r.
int FIELD_COUNT T h e nu m b e r of distin ct fields recog n ized by get an d
set.
protected int[] fields T h e field valu es for th e cu rrently set tim e for th is
calend ar.
int FRIDAY V alu e of th e DAY_OF_WEEK field for Frid ay.
int HOUR U se in get an d set for th e h ou r of th e m orn in g or
aftern oo n .
int HOUR_OF_DAY U se in get an d set for th e h ou r of th e da y.

protected boolean[] T h e flags th at tell w h ethe r a sp ecified tim e field for th e


isSet calend ar is set.
protected boolean True if th e valu e of tim e is valid.
isTimeSet
int JANUARY V alu e of th e MONTH field for Jan u ary.
int JULY V alu e of th e MONTH field for Ju ly.
int JUNE V alu e of th e MONTH field for Jun e.
int MARCH V alu e of th e MONTH field for M a rch .
int MAY V alu e of th e MONTH field for M ay .
int MILLISECOND U se in get an d set for th e m illisecon d w ith in th e
secon d .
int MINUTE U se in get an d set for th e m in ute w ith in th e h o u r.
int MONDAY V alu e of th e DAY_OF_WEEK field for M ond ay.
int MONTH U se in get an d set for th e m onth .
int NOVEMBER V alu e of th e MONTH field for N ov em b e r.
int OCTOBER V alu e of th e MONTH field for O ctob er.
int PM V alu e of th e AM_PM field for th e p eriod of th e da y from
n oo n to ju st be fore m idn ight.
int SATURDAY V alu e of th e DAY_OF_WEEK field for S atu rd ay .
int SECOND U se in get an d set for th e secon d w ith in th e m inute.
int SEPTEMBER V alu e of th e MONTH field for S epte m b e r.
int SUNDAY V alu e of th e DAY_OF_WEEK field for S u n d ay.
int THURSDAY V alu e of th e DAY_OF_WEEK field for T hu rsd ay.

Week 1 – Page 222


long time T h e cu rrently set tim e for th is calen d ar, exp ressed in
m illisecond s after Jan u a ry 1, 1970, 0:00 :0 0 G M T.
int TUESDAY V alu e of th e DAY_OF_WEEK field for T u esd ay .
int UNDECEMBER V alu e of th e MONTH field for th e th irtee nth m onth of
th e year.
int WEDNESDAY V alu e of th e DAY_OF_WEEK field for W edn e sday.
int WEEK_OF_MONTH U se in get an d set for th e w ee k n u m b er w ith in th e
cu rren t m onth .
int WEEK_OF_YEAR U se in get an d set for th e w ee k n u m b er w ith in th e
cu rren t year.
int YEAR U se in get an d set for th e yea r.
int ZONE_OFFSET U se in get an d set for th e offset from G M T in
m illisecond s.

H ere's an exa m p le p uttin g th ese fields to w ork — you can fin d th e cu rre n t year,
m o nth , an d so on an d th en reset th e Calendar object to 23 :5 9 on 11 /3 1/20 05 an d
display th e variou s Calendar fields again , as y ou see in Listin g 6.1 5 .

Listing 6.15 Using the Calendar Class (ch06_15.jsp)

[View full width]

<%@ page import="java.util.*" %>


<HTML>
<HEAD>
<TITLE>Fields of the Calendar Class</TITLE>
</HEAD>

<BODY>
<H1>Fields of the Calendar Class</H1>
<%
String dateString = new String();

GregorianCalendar calendar = new GregorianCalendar();


Date date1 = new Date();
calendar.setTime(date1);

dateString += "Calendar.YEAR is " + calendar.get


(Calendar.YEAR) + "<BR>";
dateString += "Calendar.MONTH is " + calendar.get
(Calendar.MONTH) + "<BR>";
dateString += "Calendar.WEEK_OF_YEAR is " + calendar.get
(Calendar.
WEEK_OF_YEAR) +
"<BR>";
dateString += "Calendar.WEEK_OF_MONTH is " + calendar.get
(Calendar.
WEEK_OF_MONTH)
+ "<BR>";

Week 1 – Page 223


dateString += "Calendar.DATE is " + calendar.get
(Calendar.DATE) + "<BR>";
dateString += "Calendar.DAY_OF_MONTH is " + calendar.get
(Calendar.
DAY_OF_MONTH) +
"<BR>";
dateString += "Calendar.DAY_OF_YEAR is " +
calendar.get(Calendar.DAY_OF_YEAR) +
"<BR>";
dateString += "Calendar.DAY_OF_WEEK is " + calendar.get
(Calendar.
DAY_OF_WEEK) +
"<BR>";
dateString += "Calendar.DAY_OF_WEEK_IN_MONTH is "
+ calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH) + "<BR>";
dateString += "Calendar.AM_PM is " +
calendar.get(Calendar.AM_PM) + "<BR>";
dateString += "Calendar.HOUR is " +
calendar.get(Calendar.HOUR) + "<BR>";
dateString += "Calendar.HOUR_OF_DAY is " + calendar.get
(Calendar.
HOUR_OF_DAY) +
"<BR>";
dateString += "Calendar.MINUTE is " +
calendar.get(Calendar.MINUTE) + "<BR>";
dateString += "Calendar.SECOND is " +
calendar.get(Calendar.SECOND) + "<BR>";
dateString += "Calendar.MILLISECOND is " + calendar.get
(Calendar.
MILLISECOND) +
"<BR>";

dateString += "Resetting the date!<BR>";

calendar.set(2005, 11, 31, 23, 59);

dateString += "Calendar.YEAR is " +


calendar.get(Calendar.YEAR) + "<BR>";
dateString += "Calendar.MONTH is " +
calendar.get(Calendar.MONTH) + "<BR>";
dateString += "Calendar.WEEK_OF_YEAR is " + calendar.get
(Calendar.
WEEK_OF_YEAR) +
"<BR>";
dateString += "Calendar.WEEK_OF_MONTH is " + calendar.get
(Calendar.
WEEK_OF_MONTH)
+ "<BR>";
dateString += "Calendar.DATE is " +
calendar.get(Calendar.DATE) + "<BR>";
dateString += "Calendar.DAY_OF_MONTH is " + calendar.get
(Calendar.
DAY_OF_MONTH) +
"<BR>";
dateString += "Calendar.DAY_OF_YEAR is " + calendar.get
(Calendar.
DAY_OF_YEAR) +

Week 1 – Page 224


"<BR>";
dateString += "Calendar.DAY_OF_WEEK is " + calendar.get
(Calendar.
DAY_OF_WEEK) +
"<BR>";
dateString += "Calendar.DAY_OF_WEEK_IN_MONTH is "
+ calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH) + "<BR>";
dateString += "Calendar.AM_PM is " +
calendar.get(Calendar.AM_PM) + "<BR>";
dateString += "Calendar.HOUR is " +
calendar.get(Calendar.HOUR) + "<BR>";
dateString += "Calendar.HOUR_OF_DAY is " + calendar.get
(Calendar.
HOUR_OF_DAY) +
"<BR>";
dateString += "Calendar.MINUTE is " +
calendar.get(Calendar.MINUTE) + "<BR>";
dateString += "Calendar.SECOND is " +
calendar.get(Calendar.SECOND) + "<BR>";
dateString += "Calendar.MILLISECOND is " + calendar.get
(Calendar.
MILLISECOND) +
"<BR>";
out.println(dateString);
%>
</BODY>
</HTML>

You can see th e resu lts in Figu re 6.9 , w h ere y ou see th e y ear, m onth , d ay, an d so
on .

Figure 6.9. Fields of the Calendar class.

Week 1 – Page 225


[ T eam L iB ]

[ T eam L iB ]

Summary
Tod ay you lea rn ed h ow to create Jav a classes, a n d Java B ean s th at sup p ort
pro p erties.

In p a rticu lar, y ou learne d h ow to u se th e Ja va class state m en t to create Java


classes. Y ou also sa w th at you can place a con stru ctor into a class , a n d th at you can
pass data to th at con stru ctor.

T h e <jsp:useBean> elem e n t en a bles you to cre ate an object from a Ja v a class or


JavaB ea n . W e'v e seen th at you can u se th is elem e n t to n a m e an object w h en it's
created, so th at it's accessible elsew h e re in yo u r code .

T h e <jsp:getProperty> ele m en t en ables you to get th e valu e of th e prope rty of a


bea n .

T h e <jsp:setProperty> ele m en t en ables you to set th e valu e of a b ea n's p rop e rties,


in clu din g lettin g you set pro p erties of th e sa m e n a m e as re qu e st para m eters

Week 1 – Page 226


au to m atically.

Fin ally, th e Date class e n a bles you to store d ate s an d tim es. To a ccess th e in divid u al
day, m o nth , year, an d o th er fields in a Date object, you u se a class b a sed on th e
Calendar class, su ch as th e GregorianCalendar class.

[ T eam L iB ]

[ T eam L iB ]

Q&A

Q1: A s a JS P p ro g ra m m e r, d o I n e ed to u se Ja v a B e a n s?

A1: N o. You can g et alon g fin e w ith ou t th e m , bu t w h en you r code gets past a
certain size, it's aw k w a rd to st ore in a W eb pa g e. Ja v aB ea n s h elp you
org an ize you r cod e, an d gives you ea sier a ccess to Java directly.

Q2: C a n I u se th e request o b je ct in a J a v a B e a n ?

A2: N o, th at obje ct is n ot accessible in a JavaB ean b y defau lt. H o w e v er, you


can p ass th e request object to a Java B e an if y ou set u p a m eth od in th e
bean to a ccept th at object— see th e E xercises for today.

[ T eam L iB ]

[ T eam L iB ]

Workshop
T h is w ork sh op tests w h eth er y ou un d erstan d all th e con cepts y ou learn ed tod a y. It's
a goo d idea to m a ster today 's con cepts b y h on in g you r kn ow led g e he re before
startin g tom o rrow 's m aterial. Y ou can fin d th e a n sw ers to th e q u iz q u estion s in
A pp e n d ix A .

Quiz

1: W h at a re tw o access sp ecifiers y ou can u se in Java classes?

2: H o w do you in vok e th e Java co m p iler?

3: W h at is th e n a m e of th e directo ry in w h ich you place .class files so th at


th ey're a ccessible from JS P?

4: You can in clu d e <jsp:getProperty> an d <jspSetProperty> ele m ents

Week 1 – Page 227


in side a <jsp:useBean> elem e nt. U n d er w h at circu m sta n ces are th o se
ele m ents n ot execute d?

5: W h y w as th e Date class dep recated?

Exercises

1: C reate a n ew Ja v aB e an an d pass th e request o bject to a m eth od of th a t


bean (th is object is an object of th e Java
javax.servlet.http.HttpServletRequest cla ss). U sin g th e
request.getParameter m eth od, recov er so m e text fro m a text field an d
pass it back to a JS P pa ge u sin g an oth er m eth o d , an d display th at text.

2: U sin g Date an d Calendar obje cts, p u t togethe r a JS P pa g e th at displays th e


nu m b e r of day s rem ain in g un til you r n e xt birth d ay. (H int: th e DAY_OF_YEAR
field w ill be u sefu l h ere.)

[ T eam L iB ]

[ T eam L iB ]

Day 7. Tracking Users with Sessions


and Cookies
Tod ay you 'll learn ab ou t on e of th e m ost p op u la r u ses of JS P — tra ck in g u sers w ith
session s a n d cookies. T rack in g u sers is a pe ren n ial pro ble m ; w h en a u se r look s at
you r W eb p ag e , h as th a t u ser b e en the re b e fore ? W ill you be re m e m be rin g
som eth in g a bou t h er? W ill you re m e m b er he r presen t pu rch ases an d be ch eck in g
th em out, displayin g the ir total cost? W ill you be cu sto m izin g h er W eb p age in w ays
th at sh e's sp ecified in th e past? T oday you'll see several w ays of trackin g u sers,
in clu din g th e follow in g :

 H id d en text— U sin g h idden con tro ls in a W eb p age is th e easiest w a y o f


associatin g som e in form ation w ith th e u ser th at's n ot directly accessible to
h im . H o w ever, th e h id den text can b e seen if th e u ser looks at th e H T M L for
th e W eb pa ge directly.
 C ookies— T h is is pro b a b ly th e m ost com m on w a y of tra ck in g u sers on th e
Inte rn et. Y ou can sto re in form ation in a u ser's com p uter u sin g cookies, an d
retrieve it w h en y ou ne ed it. Y ou can also sp ecify h ow lon g th e cookie sh ou ld
exist before b ein g deleted by th e brow ser.
 S ession s— S e ssion s a re som eth in g th e serv er offers u s to sup p o rt u ser
track ing , an d th ey're great, alth ou g h th ey can take u p a lot of resou rces on
th e serv er. S ession s let you preserv e data b etw ee n a ccesses to a W eb pa ge
by th e sa m e u ser.
 A pp lication s— A p p lication s a re m u ch like se ssio n s, as you 'll see, bu t th ey're

Week 1 – Page 228


m o re g en e ral— you can sh are d ata betw een all th e JS P pa g es in a site u sin g
ap p lication s. In othe r w ords, un like session s, a p p lication s can be u sed to
track m u ltiple u sers at th e sa m e tim e.
 S ession s, a pp lication s, a n d Java B ean s— Y ou ca n also set Ja va B ea n s so th ey'll
be in clu ded in a session or ap p lication . N orm ally, th e data in a JavaB e a n is
reset ea ch tim e th e u se r accesses a p ag e a n d creates an obje ct fro m th at
bea n , b u t y ou can in clu de th e b ean in a session or a p p lication so its data is
preserv ed b etw een acce sses by th e sa m e u ser.

T h e first step is to u se H T M L h id d en controls.


[ T eam L iB ]

[ T eam L iB ]

Using Hidden Controls


U sin g H TM L h id d en con tro ls is an ea sy w a y to store data in a W eb pa g e . For
exa m p le, in th is JS P p a ge, th e code w ill let th e u ser set th e text to store in a h id d en
control in a text field:

<HTML>
<HEAD>
<TITLE>Reading Hidden Controls</TITLE>
</HEAD>

<BODY>
<H1>Reading Hidden Controls</H1>
<%
String text = "";
if(request.getParameter("TEXT1") != null) {
out.println("The hidden text is:" +
request.getParameter("TEXT1"));
text = request.getParameter("TEXT1");
}
%>
.
.
.

Th e cod e stores th e text th e u ser typ e s in th e h id d en c ontro l, as you ca n see in


Lis ting 7 .1 .

Listing 7.1 Reading Hidden Controls (ch07_01.jsp)

<HTML>
<HEAD>
<TITLE>Reading Hidden Controls</TITLE>
</HEAD>

<BODY>

Week 1 – Page 229


<H1>Reading Hidden Controls</H1>
<%
String text = "";
if(request.getParameter("TEXT1") != null) {
out.println("The hidden text is:" +
request.getParameter("TEXT1"));
text = request.getParameter("TEXT1");
}
%>
<FORM ACTION="ch07_01.jsp" METHOD="POST">
<INPUT TYPE="TEXT" NAME="TEXT1">
<INPUT TYPE="HIDDEN" NAME="HIDDEN"
VALUE="<%= text%>">
<INPUT TYPE="SUBMIT" VALUE="Set Hidden Text">
</FORM>
</BODY>
</HTML>

Y ou can see th is pa ge in Figu re 7.1 , w h ere th e u ser h as entered so m e te xt an d is


abo u t to click th e S et H id d en T ext button .

Figure 7.1. Setting hidden text.

W h en th e u ser clicks th e button , th e JS P cod e stores th e text sh e's en tered in a


h idden control an d displays th at text, a s y ou se e in Figu re 7.2 .

Week 1 – Page 230


Figure 7.2. Getting hidden text.

T h e u ser can also ta ke a loo k at th e d ata in th e h id d en field directly — all sh e h as to


do is to view th e H T M L source of th e p a g e you see in Figu re 7.2 (u sin g th e V iew ,
S ou rce m en u item in Intern et E x plorer, or th e V iew , Page S o urce m en u item in
N etscap e N av igator). H e re's w h at th at H TM L sou rce loo ks like — n ote th e h id d en
control's text:

<HTML>
<HEAD>
<TITLE>Reading Hidden Controls</TITLE>
</HEAD>

<BODY>
<H1>Reading Hidden Controls</H1>
The hidden text is:Hello there!

<FORM ACTION="hidden.jsp" METHOD="POST">


<INPUT TYPE="TEXT" NAME="TEXT1">
<INPUT TYPE="HIDDEN" NAME="HIDDEN"
VALUE="Hello there!">
<INPUT TYPE="SUBMIT" VALUE="Set Hidden Text">
</FORM>
</BODY>
</HTML>

H id d en controls are fin e as fa r a s the y go , bu t th ere a re a nu m b er of o b viou s

Week 1 – Page 231


pro ble m s h ere — you can 't store data in a secu re w ay, a n d you ca n't store data
betw een session s. H o w ever, y ou can g et a ro u n d t h ose pro ble m s w ith cookies.

You m ig h t n ot be su rprised to learn th at the re's a class y ou u se to w ork w ith cookies


in JS P — th e cookie class.

[ T eam L iB ]

[ T eam L iB ]

The Cookie Class


C ookies— you eith er lov e th e m or h a te th e m . T h ey're sm all text string s you sto re on
a u ser's co m p ute r. In th e early days of cookies, peo ple w ere very su spiciou s of th e m ,
bu t th e truth is th at th e y're sim ply text an d can 't ca u se p ro ble m s (un less there are
secu rity pro ble m s in th e u ser's brow s er th at h av e n ot yet be en exploited by
h ack ers).

Tip

A lth ou g h cookies are w idely reg a rded as safe, m a n y u sers are still w ary of
th e m , an d h av e in stru cted th eir b row sers n ot to accept th e m . If you ca n't
set a coo kie in th e client bro w ser you 're w orkin g w it h , you m ig h t try
an oth er m eth od of storin g d ata, su ch a s h id d en controls. T echn ically, a
bro w ser is ex pe cted to sup p ort 20 coo kies for ea ch W eb server; ab o u t 3 00
cookies total— a n d m igh t lim it th e size of ea ch coo kie to 4K B of text.

A cookie's valu e ca n id en tify a u ser, so the y are co m m on ly u sed for session


m a n a ge m e nt. C ookies h ave a n a m e a n d a valu e , an d y ou can u se m eth ods of th e
Cookie class (th e fu ll n a m e, in clu din g th e Java p acka g e, is
javax.servlet.http.Cookie) to get access to th at data. Y ou can also in clu d e
com m e nts in cookies an d set th eir m ax im u m po ssible ages.

You r JS P code sen d s co okies to th e b ro w ser by u sin g th e


HttpServletResponse.addCookie m eth od . T h is m eth od stores d ata in th e H TTP
respon se h ea d e rs it sen d s to th e b row ser, in clu din g th e cook ies you 're creatin g .

T h e b ro w ser retu rn s cookies to y ou by sto rin g data in H TTP req ue st he a ders. Y ou can
get cookie data u sin g th e HttpServletRequest.getCookies m eth od , a s y ou'll see in
th e up co m in g exa m p les .

You 'll see ho w th is all w ork s in detail in toda y's w ork. Y ou can see th e m eth ods of
Cookie obje cts (th at is, th e javax.servlet.http.Cookie class) in Table 7.1 .

Week 1 – Page 232


Table 7.1. javax.servlet.http.Cookie Methods
M e th o d D o e s T h is
Cookie(java.lang.String name, C reates a cookie w ith a given n a m e a n d
java.lang.String value) valu e.
java.lang.Object clone() R etu rn s a copy of th e cookie.
java.lang.String getComment() R etu rn s th e cookie's com m e nt, or null if
th e coo kie h as n o co m m ent.
java.lang.String getDomain() R etu rn s th e do m ain n a m e for th e cookie.
int getMaxAge() R etu rn s th e m ax im u m a ge of th e cookie,
in second s. A valu e of -1 in dicates th e
cookie w ill exist un til brow ser shutd ow n .
java.lang.String getName() R etu rn s th e n a m e of th e cookie.
java.lang.String getPath() R etu rn s th e p ath on th e serv er so th at
th e bro w ser retu rn s th e cookie.
boolean getSecure() R etu rn s true if th e bro w ser is send in g
cookies on ly over a secu re p ro tocol.
java.lang.String getValue() R etu rn s th e valu e of th e cookie.
int getVersion() R etu rn s th e v ersion of th e p roto col for
th e coo kie.
void setComment(java.lang.String S ets a co m m e n t th at d e scribes a cookie's
comment) pu rpose.
void setDomain(java.lang.String S p ecifies th e do m ain for th e cookie.
domain)
void setMaxAge(int expiry) S ets th e m ax im u m a ge of th e cookie in
secon d s.
void setPath(java.lang.String uri) S ets th e path for th e co okie (th at is, th e
path by w h ich th e bro w ser w ill sen d th e
cookie).
void setSecure(boolean flag) Ind icates to th e brow ser if cookies sh ou ld
on ly be sen t u sin g a secu re p ro tocol
(su ch as H T TP S ).
void setValue(java.lang.String A ssig n s a n ew valu e to a cookie after th e
value) cookie is created .
void setVersion(int version) S ets th e version of th e cookie p roto col
for th e cookie.

S o h ow do you create a cookie? Y ou u se th e addCookie m eth od of th e


HttpServletResponse class, an d th at class is com in g u p n ext.

Week 1 – Page 233


[ T eam L iB ]

[ T eam L iB ]

The HttpServletResponse Interface


To create cookies, y ou n ee d to u se th e addCookie m eth od of
javax.servlet.http.HttpServletResponse interfa ce. W h at's
a Java interface? Y ou ca n th in k of an interfa ce a s a class th at
defin es m eth od n a m e s, bu t n ot th eir cod e. Y ou can 't create
objects directly u sin g an interface. In stea d, you m u st base a
class on th at interface — th e interface on ly de fin e s w h at d ata
m e m b e rs a n d m eth o ds th at class w ill h av e. A s w e'll see in D ay
11 , "C reatin g M ore Pow erfu l JavaB ea n s," u sin g in terfaces is as
close a s y ou can co m e in Java to b a sin g a class on m ore th a n
on e othe r class (in obje ct-oriented p ro g ra m m in g term s,
in terfaces repre sen t Jav a's sup p ort for m u ltiple inh eritan ce, as
w e'll see in D ay 13 , "C reatin g M ore P ow erfu l S e rvlets").

S o w he re d oe s th at leave y ou ? F ortun ately, th e serv er h a s don e all th e w ork y ou'll


n ee d h ere— on e of th e b u ilt-in objects ava ila ble to y ou in you r JS P cod e is th e
response obje ct (see "T h e JS P P ro g ra m m in g E n viro n m e n t" in D ay 2, "H an d lin g D ata
an d O p e rato rs"), an d th is is a pre -bu ilt object b a sed on th e
javax.servlet.http.HttpServletResponse in terfa ce.

Ju st as y ou u se th e request obje ct to see w h at data th e u ser h as sen t to y ou , y ou can


u se th e response object to sen d data back to th e u ser. In th is case, y ou 'll u se th is
object to sen d cook ies b ack to th e b row ser, w h ich w ill store th em . Y ou can see th e
fields of th e javax.servlet.http.HttpServletResponse interface in Table 7.2 , an d
th e m eth od s of th is inte rface in Ta ble 7.3 . B eca u se th e response object is bu ilt
on th is interface, it sh ares all th e m eth ods of th e interface, an d you'll see h ow to pu t
th em to w ork in th e n ex t topic, creatin g you r ow n cookies w ith th e addCookie
m eth od. Y ou u se th e va riou s field valu es in Table 7.2 if you w an t to sen d a sta tu s
rep ort b a ck to th e b row ser, a s w ith th e sendError or setStatus m eth ods (w h ich w e
w on't d o he re).

Note

T h e con v ention for fields is th at if its n a m e is in ca pital letters, it's a re a d -


on ly con sta n t w ho se valu e do esn't ch a n g e.

Table 7.2. HttpServletResponse Fields


M e th o d D o e s T h is
int SC_ACCEPTED Ind icates th at a requ est w as a ccepted
for p rocessin g , bu t w as n ot co m p leted.

Week 1 – Page 234


int SC_BAD_GATEWAY Ind icates th at th e H TTP serv er received
an in valid respon se fro m a server it
con su lted w h en a ctin g as a p rox y or
gatew ay.
int SC_BAD_REQUEST Ind icates th e req ue st sen t by th e clien t
w as in correct.
int SC_CONFLICT Ind icates th at th e requ e st cann ot b e
com p leted b ecau se of a con flict w ith th e
cu rren t state of th e reso u rce.
int SC_CONTINUE Ind icates th e clien t can co ntin u e.
int SC_CREATED Ind icates th e req ue st su cceed ed an d
created a n ew resou rce on th e serv er.
int SC_EXPECTATION_FAILED Ind icates th at th e serve r cann ot m e et
th e req u est in th e Expect requ est
h ea de r.
int SC_FORBIDDEN Ind icates th e serve r can n ot co m p lete
th e req u est.
int SC_GATEWAY_TIMEOUT Ind icates th at th e serve r did n ot receive
a respon se fro m a gate w ay or p roxy
serv er in tim e.
int SC_GONE Ind icates th at th e resou rce is n o long er
available.
int SC_HTTP_VERSION_NOT_SUPPORTED Ind icates th at th e serve r do es n ot
sup p ort th e H TTP p roto col version u sed
in th e req u est.
int SC_INTERNAL_SERVER_ERROR Ind icates an error in side th e H TTP
serv er.
int SC_LENGTH_REQUIRED Ind icates th at th e requ e st cann ot b e
h a n dled w ith o u t a specified conten t
length .
int SC_METHOD_NOT_ALLOWED Ind icates th at th e m eth od sp ecified in
th e R eq ue st-Lin e is n ot allow ed.
int SC_MOVED_PERMANENTLY Ind icates th at th e resou rce h as m ov ed
to a ne w location .
int SC_MOVED_TEMPORARILY Ind icates th at th e resou rce h as
tem po rarily m oved to a n oth er location .
int SC_MULTIPLE_CHOICES Ind icates th at th e resou rce corresp on d s
to an y on e of a set.
int SC_NO_CONTENT Ind icates th at th e requ e st w as
su ccessfu l b u t th ere w a s n o n ew conten t
to retu rn .
int Ind icates th at th e m eta in form ation sen t

Week 1 – Page 235


SC_NON_AUTHORITATIVE_INFORMATION by th e b ro w se r did n ot com e fro m th e
serv er.
int SC_NOT_ACCEPTABLE Ind icates th at th e resou rce identified by
th e req u est w as n ot a ccepta ble.
int SC_NOT_FOUND Ind icates th at th e requ e sted resou rce
w as n ot a vaila ble.
int SC_NOT_IMPLEMENTED Ind icates th e H TTP serv er do es n ot
sup p ort th e req u e st.
int SC_NOT_MODIFIED Ind icates th at a GET op e ration foun d
th at th e resou rce w a s a vailable an d n ot
m o dified.
int SC_OK Ind icates th e req ue st su cceed ed.
int SC_PARTIAL_CONTENT Ind icates th at th e serve r h as fu lfilled th e
partial GET requ e st.
int SC_PAYMENT_REQUIRED R eserved for future u se.
int SC_PRECONDITION_FAILED Ind icates th at th e preco nd ition given in
a req u est h ead e r field failed.
int Ind icates th at th e clien t m u st
SC_PROXY_AUTHENTICATION_REQUIRED auth en ticate itself w ith th e p roxy .
int SC_REQUEST_ENTITY_TOO_LARGE Ind icates th at th e requ e st entity is
larger th a n th e server can process.
int SC_REQUEST_TIMEOUT Ind icates th at th e requ e st tim ed out.
int SC_REQUEST_URI_TOO_LONG Ind icates th at th e R eq u est-U R I field is
too long .
int Ind icates th at th e serve r cann ot serv e
SC_REQUESTED_RANGE_NOT_SATISFIABLE th e req u ested data ran g e.
int SC_RESET_CONTENT Ind icates th at th e agen t w ill reset th e
display of th e d ocu m ent.
int SC_SEE_OTHER Ind icates th at th e resp o n se to th e
req u est can be fou n d u n d er a differen t
U R I.
int SC_SERVICE_UNAVAILABLE Ind icates th at th e H TTP serv er is
ov erloa ded.
int SC_SWITCHING_PROTOCOLS Ind icates th e serve r is sw itch in g
pro to cols.
int SC_TEMPORARY_REDIRECT Ind icates th at th e req ue sted resou rce is
tem po rarily at a differen t U R I.
int SC_UNAUTHORIZED Ind icates th at th e requ e st ne eds H T TP
auth en tication .
int SC_UNSUPPORTED_MEDIA_TYPE Ind icates th at th e requ e st is in a form at

Week 1 – Page 236


n ot sup p o rted b y th e re qu ested
resou rce.
int SC_USE_PROXY Ind icates th at th e requ e sted resou rce
m u st be a ccessed th ro u gh th e p roxy .

Table 7.3. HttpServletResponse Methods


M e th o d D o e s T h is
void addCookie(Cookie cookie) A dd s th e given cookie to th e resp on se.
void addDateHeader(java.lang.String A dd s a respon se h ea d e r w ith th e given
name, long date) n a m e an d date.
void addHeader(java.lang.String A dd s a respon se h ea d e r w ith th e given
name, java.lang.String value) n a m e an d valu e.
void addIntHeader(java.lang.String A dd s a respon se h e ad e r w ith th e given
name, int value) n a m e an d integer valu e.
boolean containsHeader R etu rn s a B oolean valu e in dicatin g if a
(java.lang.String name) respon se h ea d e r h as b e en set.
java.lang.String encodeRedirectUrl D ep recated. A s of servlet sp ecific ation
(java.lang.String url) version 2.1, u se encodeRedirectURL
(String url) in stead.
java.lang.String encodeRedirectURL E n cod es th e spe cified U R L for u se in
(java.lang.String url) th e sendRedirect m eth od.
java.lang.String encodeUrl D ep recated. A s of servlet sp ecification
(java.lang.String url) version 2.1, u se encodeURL(String
url) in stead.
java.lang.String encodeURL E n cod es th e spe cified U R L by in clu din g
(java.lang.String url) th e session ID in it.
void sendError(int sc) S en d s an error respon se to th e clien t
u sin g th e given statu s field valu e.
void sendError(int sc, S en d s an error respon se to th e clien t
java.lang.String msg) u sin g th e given field valu e an d text.
void sendRedirect (java.lang.String S en d s a te m p o ra ry redirect resp on se
location) to th e b row ser u sin g th e given U R L.
void setDateHeader(java.lang.String S ets a resp on se h ea d er w ith th e given
name, long date) n a m e an d date.
void setHeader(java.lang.String S ets a resp on se h ea d er w ith th e given
name, java.lang.String value) n a m e an d valu e.
void setIntHeader(java.lang.String S ets a resp on se h ea d er w ith th e given
name, int value) n a m e a n d integer valu e.
void setStatus(int sc) S ets th e statu s cod e for th is resp on se.
void setStatus (int sc, D ep recated. A s of servlet sp ecification

Week 1 – Page 237


java.lang.String sm) version 2.1, u se setStatus(int) to
sen d an error w ith a description .

[ T eam L iB ]

[ T eam L iB ]

Creating a Cookie
T h is n ext ex a m p le w ill pu t all th is n ew techn olog y to w ork. H ere, th e cod e w ill create
a cookie an d place som e text in it, an d a n oth er pag e w ill read th e cook ie an d display
th at text. T o create th e cookie, you u se th e Cookie class's con stru ctor, passin g it th e
n a m e of th e cookie (w h ich w ill be message he re) an d th e text in th e coo kie (w h ich
w ill ju st be "H e llo!" in th is case). You can also set th e len gth of tim e th e cookie w ill
exist on th e u ser's co m p uter w ith th e setMaxAge m eth od, w h ich you pa ss a valu e in
secon d s to— to m ak e th e cookie last for a da y, you can pa ss a valu e of 24 * 60 * 60
th is w ay:

<HTML>
<HEAD>
<TITLE>Setting a Cookie</TITLE>
</HEAD>

<BODY>
<H1>Setting a Cookie</H1>

<%
Cookie cookie1 = new Cookie("message", "Hello!");
cookie1.setMaxAge(24 * 60 * 60);
%>
.
.
.

Th at creates th e cookie, bu t doesn't in stall it in th e bro w ser — to d o th at, y ou u se th e


response obje ct's addCookie m eth od th is w ay:

<HTML>
<HEAD>
<TITLE>Setting a Cookie</TITLE>
</HEAD>

<BODY>
<H1>Setting a Cookie</H1>

<%
Cookie cookie1 = new Cookie("message", "Hello!");
cookie1.setMaxAge(24 * 60 * 60);
response.addCookie(cookie1);
%>

Week 1 – Page 238


.
.
.

T h at in stalls th e cookie in th e b row ser. Y ou can also in clu d e a lin k to th e pa ge th at


w ill read th e cookie, a s you see in Listin g 7.2 .

Listing 7.2 Setting a Cookie (ch07_02.jsp)

<HTML>
<HEAD>
<TITLE>Setting a Cookie</TITLE>
</HEAD>

<BODY>
<H1>Setting a Cookie</H1>

<%
Cookie cookie1 = new Cookie("message", "Hello!");
cookie1.setMaxAge(24 * 60 * 60);
response.addCookie(cookie1);
%>

<A HREF="ch07_03.jsp"/>Read the cookie</A>


</BODY>
</HTML>

Y ou can see th is pa ge in Figu re 7.3 , w h ere it's a lrea dy set its cookie in th e b row ser.
T h e ne xt step is to read th at cookie's in form ation b ack in .

Figure 7.3. Setting a cookie.

Week 1 – Page 239


[ T eam L iB ]

[ T eam L iB ]

Reading a Cookie
To sto re a cookie in th e u ser's co m p uter, y ou u se th e request object's getCookies
m eth od. T h is m eth od retu rn s an array of Cookie obje cts (or null if th ere are n o
cookies) S o h ow do you read th e cookie n a m ed message? Y ou sta rt w ith th e
getCookies m eth o d , creatin g an array of Cookie obje cts:

<HTML>
<HEAD>
<TITLE>Reading a Cookie</TITLE>
</HEAD>

<BODY>
<H1>Reading a Cookie</H1>

<%
Cookie[] cookies = request.getCookies();
.
.
.

Week 1 – Page 240


Tip

A re you pa ssed all th e coo kies on th e com p ute r ? N o, you 're on ly passe d th e
cookies th at ca m e fro m th e sa m e d o m ain as th e pag e you 're u sin g th e
getCookies m eth od in .

T h is retu rn s an arra y of cookies, w h ich you can loo p ov er to fin d th e message cookie.
H ere's w h at th at loo p m igh t loo k like:

<HTML>
<HEAD>
<TITLE>Reading a Cookie</TITLE>
</HEAD>

<BODY>
<H1>Reading a Cookie</H1>

<%
Cookie[] cookies = request.getCookies();

for(int loopIndex = 0; loopIndex < cookies.length; loopIndex++)


{
.
.
.
}
.
.
.

In side th e b o dy of th e loo p, you can g et th e n a m e of each cookie w ith t h e Cookie


class's getName m eth od, an d its valu e w ith th e getValue m eth od . If th e cod e fin d s
th e message cookie, it d isplays th at cookie's valu e. Y ou can see w h at th at loo ks like
in Listin g 7.3 .

Listing 7.3 Reading a Cookie (ch07_03.jsp)

<HTML>
<HEAD>
<TITLE>Reading a Cookie</TITLE>
</HEAD>

<BODY>
<H1>Reading a Cookie</H1>

<%
Cookie[] cookies = request.getCookies();

Week 1 – Page 241


for(int loopIndex = 0; loopIndex < cookies.length; loopIndex++)
{
if (cookies[loopIndex].getName().equals("message")) {
out.println("The cookie says " +
cookies[loopIndex].getValue());
}
}
%>
</BODY>
</HTML>

N ow th is pa ge is a ble to read th e cookie set in ch07_02.jsp. Y ou can se e w h at th e


resu lts are in Fig u re 7.4 , w he re th e cod e w a s a b le to recover an d displa y th e cookie's
text.

Figure 7.4. Reading a cookie.

N ow you 're settin g a n d rea din g cookies u sin g JS P!


[ T eam L iB ]

[ T eam L iB ]

Setting and Reading a Cookie in the Same Page


T h e p reviou s exa m p le set a cookie in on e p a g e an d read it in a n oth er, b u t som etim es
you m ig h t w an t to set a n d read a cookie in th e sa m e pa g e. Fo r exa m p le, if y ou r
h o m e p ag e allow s th e u ser to cu stom ize so m e a spects of th e p ag e , su ch as its

Week 1 – Page 242


back g roun d color, y ou can store th at in form atio n in a coo kie. T h e n ext tim e th e u ser
open s y ou r h o m e p ag e, you r code can read th at cookie a n d display th e correct
back g roun d color.

H ere's an ex a m p le to sh ow ho w th is w orks — in th is case, th e cod e w ill set a cookie


n a m e d color to cyan, a n d th e n ext tim e you load th e sa m e pa g e, th e JS P code w ill u se
th at cookie to ch an g e th e ba ck g ro un d color of th e pa g e to cya n . W h en th e p age loa ds,
it w ill ch eck fo r th e cookie n a m ed color, an d if it's foun d , u se its valu e to set th e
back g ro un d color of th e W eb pa g e. H ow ev er, if th at cookie isn't foun d , th e code w ill set
a B oolean va riable n a m ed foundCookie to false, w h ich m ean s it w ill h ave to
create th e cookie:

<HTML>
<HEAD>
<TITLE>Setting and Reading Cookies</TITLE>
</HEAD>

<BODY
<%
Cookie[] cookies = request.getCookies();
boolean foundCookie = false;

for(int loopIndex = 0; loopIndex < cookies.length; loopInd ex++)


{
Cookie cookie1 = cookies[loopIndex];
if (cookie1.getName().equals("color")) {
out.println("bgcolor = " + cookie1.getValue());
foundCookie = true;
}
}
.
.
.

If foundCookie is false th e code w ill set th e color cookie. You can test if
foundCookie is false w ith an if statem e n t a n d th e JS P n ot op erator. ! (discu ssed
in D ay 2), w h ich flips th e B oo lean sen se of its a rgu m en t like th is

if(!foundCookie)

w h ere th e body of th e if statem en t is ex ecu ted if th e color cookie w asn't foun d . In


th at case, th e cod e crea tes th e cookie a n d store s it as you see in Listin g 7.4 .

Listing 7.4 Setting and Reading Cookies in the Same Page


(ch07_04.jsp)

<HTML>
<HEAD>
<TITLE>Setting and Reading Cookies</TITLE>
</HEAD>

Week 1 – Page 243


<BODY
<%
Cookie[] cookies = request.getCookies();
boolean foundCookie = false;

for(int loopIndex = 0; loopIndex < cookies.length; loopIndex++)


{
Cookie cookie1 = cookies[loopIndex];
if (cookie1.getName().equals("color")) {
out.println("bgcolor = " + cookie1.getValue());
foundCookie = true;
}
}

if (!foundCookie) {
Cookie cookie1 = new Cookie("color", "cyan");
cookie1.setMaxAge(24*60*60);
response.addCookie(cookie1);
}
%>
>
<H1>Setting and Reading Cookies</H1>
This page will set its background color using a cookie.
</BODY>
</HTML>

W h en y ou load th is pa g e th e first tim e, it sets th e color cookie, an d th e pa ge


back g roun d w ill be w h ite. W h en y ou load th e p a ge fro m th en on , until th e coo kie
expires, th e p age re ads th at cookie an d u ses it to tu rn th e pa ge b a ck g ro un d cya n , as
you see in Figu re 7.5 .

Figure 7.5. Setting and reading a cookie using the same page.

Week 1 – Page 244


T h at gives y ou a g oo d foun d ation on h ow to u se cookies. Y ou've see n h ow to set
cookies an d read th e m back in , u sin g separate pa ges or th e sa m e pa g e . You 'v e seen
h ow to sp ecify h ow lon g th e cookie sh ou ld exist, w h at its n a m e sh ou ld b e, an d w h at its
valu e sh ou ld be. A s you can see , cookies a re g reat for tra ck in g in dividu al u sers —
after all, you're sto rin g data on th e u ser's com p uter; h ow m u ch m ore track in g do
you ne e d?

It tu rn s ou t th at you m igh t ind ee d ne e d m o re track in g — you m igh t w an t to p reserv e


th e data in variou s varia bles in you r code b etw ee n u ser acc esses to th e pa g e .
C ookies can sto re data as text on th e u ser's co m p uter for you , bu t w h a t if you w a n t
to store y ou r data in objects — a n d h ave th ose objects retain th eir valu e betw ee n
pa ge loa din g s? For so m eth in g su ch as th at, you can u se session s.
[ T eam L iB ]

[ T eam L iB ]

Using Sessions
T h e H T T P proto col is by its very n atu re stateless— th at is,
w h en you load a p a ge a nu m b er of tim es in su ccession , th e
serv er starts an e w e ach tim e. If you w an t to tra ck, say, th e
nu m b e r of tim es th e u s er h as acc essed th e pa g e, you n ee d to
specifically store th at d a ta so m ew he re, a s in a coo kie.

T h is is very diffe ren t fro m w ritin g a stan d ard progra m , w h ere y ou're intera ctin g w ith

Week 1 – Page 245


th e u ser w h ile th e pro g ra m is runn ing , so you can store data in variables an d coun t
on it n ot bein g reset to its defau lt valu es th e ne xt tim e you look at th at data. U sin g
session s, y ou a ctu ally can do th e sa m e th in g in JS P — y ou can interact w ith th e u ser
as th ou g h y ou h ave a session going .

W h at does th at m e an ? D u rin g th e tim e a session is active, you can store data in th e


session , a n d it'll be pres erved on th e serv er in b etw een tim es th e u ser a ccesses y ou r
pa ge. Y ou can set y ou r variables in on e pa ge a c cess, an d th ey'll h old th e sa m e data th e
n ext tim e y ou see th e p ag e , as lon g as th e session h as n't tim ed ou t (se e " S ettin g
S ession T im eo uts " later today). T h e d efau lt tim e T o m cat allow s betw een pa ge
accesses in a session is 30 m in utes.

You can a ccess th e curren t session u sin g th e b u ilt-in JS P


session obje ct, w h ich is based on th e
javax.servlet.http.HttpSession interface. T h e d ata you
store in a ses sion is stored as session attrib utes. Y ou can u se
th e session object's setAttribute m eth od to store data , an d
th e getAttribute m eth od to recov er th at d ata, as lon g as th e
session is active. E a ch s ession is given its ow n ID valu e, an d
w h en a session first b eg in s, th e session obje ct's isNew
m eth od w ill retu rn a valu e of true.

Note

You sh ou ld realize th at it m ig h t n ot be possible for T o m cat to set u p a


session w ith th e bro w se r. T om cat u su ally u ses coo kies to sto re session
in form ation , bu t th e bro w ser m a y h av e cookies tu rn ed off, for exa m p le (in
th at case, T o m cat tries to en cod e th e n eede d in form ation in U R Ls, bu t
som etim es th at is n ot su ccessfu l). If T om cat is n ot able to create a session
w ith th e bro w ser, th e isNew m eth od w ill kee p retu rn in g true every tim e
th e pa ge is accessed, a n d th e session ID w ill b e differen t for e ach pa g e
access. Y ou can also u s e th e isRequestedSessionIdFromURL an d
isRequestedSessionIdFromCookie m eth od s to see h ow T om cat is sto rin g
session in form ation — se e Table 4.2 .

T h ose a re ju st a few of th e m eth od s of th e javax.servlet.http.HttpSession


in terface— you can see th em in Table 7.4 .

Table 7.4. javax.servlet.http.HttpSession Methods


M e th o d D o e s T h is
void addCookie(Cookie cookie) A dd s th e sp ecified cookie to th e respon se
object.
java.lang.Object getAttribute R etu rn s th e object of th e given n a m e in
(java.lang.String name) th is session .

Week 1 – Page 246


java.util.Enumeration R etu rn s a Java Enumeration of String
getAttributeNames() objects contain in g th e n a m es of all th e
objects in this session .
long getCreationTime() R etu rn s th e tim e w h en th is session w a s
created (m eas u red in m illisecond s sin ce
m idn igh t Janu ary 1, 197 0 G M T).
java.lang.String getId() R etu rn s a strin g contain in g th e iden tifier
for th is session .
long getLastAccessedTime() R etu rn s th e last tim e th e clien t sen t a
req u est in w ith th is session , as th e n u m b e r
of m illisecon d s sin ce m idn igh t Jan u ary 1,
197 0 G M T .
int getMaxInactiveInterval() R etu rn s th e m a xim u m tim e, in second s,
w h ich th e server w ill kee p th is session
open b etw een clien t accesses.
ServletContext R etu rn s th e ServletContext to w h ich th is
getServletContext() session belon g s.
HttpSessionContext A s of servlet sp e cification version 2.1, th is
getSessionContext() m eth od is dep recated .
java.lang.Object D ep recated. A s of servlet sp ecification
getValue(java.lang.String name) version 2.2, th is m eth o d is replaced by
getAttribute(java.lang.String).
java.lang.String[] D ep recated. A s of servlet sp ecification
getValueNames() version 2.2, th is m eth o d is replaced by
getAttributeNames().
void invalidate() In valid ates th is session .
boolean isNew() R etu rn s true if th e clien t does n ot yet
kn ow ab ou t th e session .
void putValue(java.lang.String D ep recated. A s of servlet sp ecification
name, java.lang.Object value) version 2.2, th is m etho d is replaced by
setAttribute(java.lang.String,
java.lang.Object).
void R e m o ves th e obje ct w ith th e sp ecified
removeAttribute(java.lang.String n a m e fro m th is session .
name)
void removeValue(java.lang.String A s of servlet sp e cification version 2.2, th is
name) m eth od is replaced by
removeAttribute(java.lang.String).
void C onn ects an object to th is session , u sin g
setAttribute(java.lang.String th e given n a m e.
name, java.lang.Object value)
void setMaxInactiveInterval(int S p ecifies th e tim e, in second s, betw een
interval) clien t requ e sts b efore th e server w ill

Week 1 – Page 247


in valid ate th is session .

[ T eam L iB ]

[ T eam L iB ]

Creating a Session
T h is is all best see n in an exa m p le. T h is n ext ex a m p le w ill sh ow h ow to store th e
nu m b e r of tim es th e u s er h as acc essed th e pa g e in th e curren t session , as w ell as
h ow to get th e session ID , w h en th e session w a s created, an d th e last tim e th e p ag e
w as acc essed in th e cu rren t session . T h is ex a m ple starts w ith th e page directive first
discu ssed in D ay 1, "G e ttin g S tarted!," w ith th e directive's session attribu te set to
true:

<%@page import = "java.util.*" session="true"%>

T h is m ak es su re th at op en in g this pa ge starts a n ew session if su ch a session doesn 't


already exist. T ech n ically sp eak in g , th is page directive is n ot n ecessa ry , beca u se th e
defa u lt for th e session attribute is true, bu t it's in clud ed h e re ju st for com p letene ss
(y ou can o m it it in you r ow n session -b ased cod e ).

T h is exa m p le w ill kee p track of th e nu m b e r of tim es th e u ser h as view e d th e curren t


pa ge in a session attrib ute n a m e d counter. T h e first th in g to do is see if th is
attribute h as already be en set in a form e r pa g e access in th is session , w h ich you can
do w ith th e getAttribute m eth o d.

H ere's so m eth in g to n ote — y ou can 't store th e b asic d ata types su ch a s int in
session attrib utes— you can on ly sto re Java obje cts, w h ich are ba sed on th e
java.lang.Object class (all Java obje cts a re b ased on th e sa m e class). String
objects are fin e to store as attributes — b u t w h at abou t integer valu es su ch as ou r
counter valu e? Java h a s a class to m atch all th e basic data typ es — Integer for int
valu es, Double for double valu es, an d so on . Y ou can create an object u sin g th ese
classes by p assin g a strin g (like 3) to th e class's con stru cto r, or by p assin g a valu e of
th e correspon d in g d ata type to th e class's con stru cto r (for exa m p le: Integer
integerObject = new Integer(3) or Double doubleObject = new
Double(3.14)). You ca n recove r th e data in th e corresp on d in g b asic data form w ith
th e intValue m eth od of th e Integer class, doubleValue m eth od of th e Double
class, an d so on .

T h e counter varia ble w ill be stored a s an Integer obje ct, so h ere's ho w you can
read its valu e fro m th e session obje ct u sin g th e getAttribute m eth o d :

<%@page import = "java.util.*" session="true"%>


<HTML>
<HEAD>
<TITLE>Using Sessions</TITLE>

Week 1 – Page 248


</HEAD>

<BODY>
<%
Integer counter =
(Integer)session.getAttribute("counter");
.
.
.

If counter h as n ot b ee n set before, getAttribute w ill retu rn a v alu e of null. T h at


m e an s you can create th e counter valu e, or in cre m en t it if it already exists, an d
store th e n ew valu e in th e session object like th e follow in g:

<%@page import = "java.util.*" session="true"%>


<HTML>
<HEAD>
<TITLE>Using Sessions</TITLE>
</HEAD>
<BODY>
<%
Integer counter =
(Integer)session.getAttribute("counte r");
if (counter == null) {
counter = new Integer(1);
} else {
counter = new Integer(counter.intValue() + 1);
}

session.setAttribute("counter", counter);
.
.
.

Th at w ay y ou can sto re an d retrieve data in th e session obje ct. Y ou ca n also get th e


cu rren t session ID w ith th e getID m eth od. You get th e tim e th e session w as created
w ith th e getCreationTime m eth o d, a n d y ou get th e tim e th e session w a s last
accessed w ith th e getLastAccessedTime m eth o d. Y ou can see all th is at w ork in
Lis ting 7 .5 .

Listing 7.5 Creating and Using a Session (ch07_05.jsp)

<%@page import = "java.util.*" session="true"%>


<HTML>
<HEAD>
<TITLE>Using Sessions to Track Users</TITLE>
</HEAD>

<BODY>
<%
Integer counter =
(Integer)session.getAttribute("counter");

Week 1 – Page 249


if (counter == null) {
counter = new Integer(1);
} else {
counter = new Integer(counter.intValue() + 1);
}

session.setAttribute("counter", counter);
%>
<H1>Using Sessions to Track Users</H1>
Session ID: <%=session.getId()%>
<BR>
Session creation time: <%=new Date(session.getCreationTime())%>
<BR>
Last accessed time: <%=new
Date(session.getLastAccessedTime())%>
<BR>
Number of times you've been here: <%=counter%>
</BODY>
</HTML>

Y ou can see th e resu lts in Figu re 7.6 , w he re th e u ser h as op en e d th is p age a n d


reloaded it a nu m b e r of tim es.

Figure 7.6. Creating and using a session.

U sin g session s su ch as th is is great for storin g a n d recov erin g d ata — it p ro vides y ou


w ith an en viro n m e n t m u ch like a stan d ar d p ro g ra m , w h ere you interact w ith th e u ser
w ith ou t h avin g to w orry abou t h av in g you r data reset.

Week 1 – Page 250


[ T eam L iB ]

[ T eam L iB ]

Setting Session Timeouts


You can u se m eth o d s of th e session object to set th e m a xim u m tim e b etw een pa g e
accesses b e fore th e server en d s th e session :

 getMaxInactiveInterval()— R etu rn s th e m ax im u m tim e interval, in


secon d s, for w h ich th e server w ill kee p th is session open betw een acces ses.
 setMaxInactiveInterval(int interval)— S p ecifies th e tim e, in second s,
betw een u ser req ue sts befo re th e servlet conta in er w ill in v alidate th is session .

If y ou set th e lifetim e of a session to -1, th e session w ill n ever expire.

T h e d efau lt tim eo u t betw ee n u ser a ccesses for session s in To m cat is 3 0 m in utes. Y ou


can ch a ng e th is in T o m cat's web.xml file (sto red as jakarta-tomcat-
4.0.3\conf\web.xml). A ll you h ave to do is ch an g e th e tim e stored in th e
<session-timeout> elem e nt:

<!-- ==================== Default Session Configuration


================= -->

<!-- You can set the default session timeout (in minutes) for all newly
-->
<!-- created sessions by modifying the value below.
-->

<session-config>
<session-timeout>30</session-timeout>
</session-config>

B esides session s, you can als o u se ap p lication s.


[ T eam L iB ]

[ T eam L iB ]

Using Applications
A session en a bles you to tra ck on e u ser at a tim e — an a p p lication en a bles you to
track all JS Ps in th e sa m e site, n o m atte r h ow m an y u sers are u sin g th e m . To access
th e curren t ap p lication , you can u se th e bu ilt -in JS P application object. Like th e
session obje ct, th e application obje ct is bas e d on th e
javax.servlet.http.HttpSession interface. In th e p reviou s exa m p le, you saw h ow
to create a session attribu te n a m e d counter, w h ich stores th e nu m b e r of tim es th e
u ser h as visited th e pa g e in th e curren t session . In th e sa m e w ay, y ou can create an

Week 1 – Page 251


application attribute n a m ed applicationCounter th at h olds th e total nu m b e r of
tim es an yon e in th e sam e a pp lication h as view ed a JS P pa ge:

Integer applicationCounter =
(Integer)application.getAttribute("applicationCounter");
if (applicationCounter == null) {
applicationCounter = new Integer(1);
} else {
applicationCounter = new Integer(applicationCounter.intValue() +
1);
}

application.setAttribute("applicationCounter", applicationCounter);

You can see th is at w ork in Listin g 7.6 , w h ere th e code su pp o rts a counter for th e
nu m b e r of visits in th e cu rren t session , a n d in th e curre n t a p p lication .

Listing 7.6 Using the Application Object (ch07_06.jsp)

[View full width]

<HTML>
<HEAD>
<TITLE>Using the Application Object</TITLE>
</HEAD>

<BODY>
<H1>Using the Application Object</H1>
<%
Integer counter = (Integer)session.getAttribute("counter");
String heading = null;
if (counter == null) {
counter = new Integer(1);
} else {
counter = new Integer(counter.intValue() + 1);
}

session.setAttribute("counter", counter);

Integer applicationCounter =
(Integer)application.getAttribute(
"applicationCounter");
if (applicationCounter == null) {
applicationCounter = new Integer(1);
} else {
applicationCounter = new
Integer(applicationCounter.intValue() + 1);
}

application.setAttribute("applicationCounter",
applicationCounter);
%>

You have visited this page <%=counter%> times.

Week 1 – Page 252


<BR>
This page has been visited by all users <%=applicationCounter%>
times.
</BODY>
</HTML>

In th is exa m p le, th e session counter k ee p s tra c k of th e nu m b e r of tim e s a u ser h as


visited th e p a ge , an d th e ap p lication counter ke eps track of th e nu m b e r of tim es all
u sers h av e a ccessed th e pa ge . T h is isn't particu larly easy to see on th e sa m e
com p ute r, b ecau se T o m cat w ill coun t you as th e sa m e u ser. H ow ev er, y ou can g et
aro un d th at if you h a p p en to h a ve diffe ren t bro w sers. Fo r exa m p le, you can op en it
in Intern et E xplorer an d reload a fe w tim es, as you see in Figu re 7.7 . If you th en
open it in an oth er b row ser, su ch as N etsca p e N a v igator, you 'll see th at th e
ap p lication cou nter is in dee d keepin g track of u sers a cross session s, a s sh ow n in
Figu re 7.8 .

Figure 7.7. Using the application object.

Figure 7.8. Another user using the application object.

Week 1 – Page 253


[ T eam L iB ]

[ T eam L iB ]

Using Sessions, Applications, and JavaBeans


It tu rn s ou t th at you ca n in stru ct To m cat to sav e Java B ea n s in
a session object a s w ell as in attrib utes. In fact, y ou can
store Ja v aB ea n s in ap p lica tion s as w ell. Y ou do th is w ith th e
<jsp:useBean> ele m en t's scope attribute, w h ich you can set
to on e of the se valu es:
scope="page|request|session|application". T h e term
scop e ind icates w h e re a d ata item is "v isible" (m e an in g it m ay
be referre d to by n a m e) in you r code . T h e d efa u lt scop e for a
bean is p age scope, w h ich m ea n s th e b ea n exists on ly for th e
pa ge scop e. H ow ever, if you set th e scop e of a bean to
session , it is store d w ith th e rest of t h e session's data.

T h e b ean y ou see in Listin g 7.7 m aintain s a pro p erty n a m e d counter th at JS P cod e


can in cre m en t— w e'll se e th at u sin g pa ge scop e , counter is reset to 1 each tim e th e
pa ge loads, b u t u sin g session scop e, counter w ill in cre m en t to 2, 3 , 4 , an d so on as
you reload th e p ag e, be cau se th e b ea n is sto re d in th e session's data.

Week 1 – Page 254


Listing 7.7 A Bean That Maintains a Usage Counter (ch07_07.jsp)

package beans;

public class ch07_07


{

private int counter = 0;

public void setCounter(int value)


{
this.counter = value;
}

public int getCounter()


{
return this.counter;
}

public ch07_07()
{
}
}

You can see a JS P pag e th at u ses th is bean w ith pag e scope in Listin g 7.8 .

Listing 7.8 Using Page Scope for Beans (ch07_08.jsp)

<HTML>
<HEAD>
<TITLE>Using Beans and Page Scope</TITLE>
</HEAD>

<BODY>
<H1>Using Beans and Page Scope</H1>

<jsp:useBean id="bean1" class="beans.ch07_07" scope="page" />


<%
bean1.setCounter(bean1.getCounter() + 1);
%>
The counter value is: <jsp:getProperty name="bean1"
property="counter" />
</BODY>
</HTML>

A n d you can see th at W eb pa ge at w ork in Figu re 7.9 — n o m atte r h ow m a n y tim es


you reload th is pa ge, th e counter w ill rem ain set to 1, b ecau se th e b e a n h as p a ge
scop e, so it's created an ew each tim e y ou load th e p ag e .

Figure 7.9. Using a bean with page scope.

Week 1 – Page 255


H o w ev er, if y ou give th e b ean session scop e, a s in Listin g 7.9 , it's stored w ith th e
rest of th e session , w h ich m ea n s th e counter valu e w ill be preserved betw ee n pa ge
accesses.

Listing 7.9 Using Session Scope for Beans (ch07_09.jsp )

<HTML>
<HEAD>
<TITLE>Using Beans and Session Scope</TITLE>
</HEAD>

<BODY>
<H1>Using Beans and Session Scope</H1>

<jsp:useBean id="bean1" class="beans.ch07_07" scope="session"


/>

<%
bean1.setCounter(bean1.getCounter() + 1);
%>
The counter value is: <jsp:getProperty name="bean1"
property="counter" />
</BODY>
</HTML>

Y ou can see th e resu lts of givin g th e bean session scop e in Figu re 7.1 0 .

Week 1 – Page 256


Figure 7.10. Using a bean with session scope.

[ T eam L iB ]

[ T eam L iB ]

Summary
Tod ay you lea rn ed h ow to tra ck u sers w ith coo k ies an d session s in JS P. Ev eryth in g
started by u sin g H T M L h idd en contro ls to sto re data in th e W eb p a ge sen t to th e
bro w ser a n d th en sen t b ack to th e server. A ltho ug h sto rin g data in h idd en controls
w orks, it's n ot v ery secu re, an d th e data sto red in th ose contro ls is visible if th e u ser
view s th e pa g e's H T M L sourc e.

You learn ed th at you ca n u se cookies to store text d ata on a p erson 's com p uter,
u sin g Cookie objects an d th e response object's addCookie m eth od. Y ou can retriev e
th ose obje cts w ith th e request obje ct's getCookies m eth o d.

T o sup p ort a session , you u se th e session object. A s you 've see n , you can get th e
session's ID , creation tim e, last accessed tim e, an d m o re u sin g session m eth ods.
S ession s let y ou esta blish a w ork able conn e ction w ith th e u ser's brow s er, lettin g you
store data betw ee n pa g e accesses.

You can also u se application obje cts to store data; an a p p lication is b ro a d er th an a


session , b e ca u se session s deal w ith a sin gle u ser, b u t an a p p lication in clud es all th e
u sers u sin g JS P pa ges o n you r site.

Fin ally, you learn ed th at you can store b ean s in sess ion s an d a p p lication s if you set

Week 1 – Page 257


th e scope attribute <jsp:useBean> to th e ap p ropriate valu es.
[ T eam L iB ]

[ T eam L iB ]

Q&A

Q1: A re th e re a n y d ra w b a c k s to u s in g s e s sio n s ?

A1: Yes, th ey pu t a con side rable strain on th e resou rces of th e serv er if th ere
are m an y session s run n in g at th e sa m e tim e. T h ey can also b e b rok en
un expectedly if th e u se r's conn e ction fails. A ll in all, in pro fession al JS P
ap p lication s, you m u st be p rep a red for cases w h en u sin g a session w ith
th e u ser d o esn 't w ork.

Q2: C a n I sto re o th e r d a ta in co o k ie s b e sid e s th e c o o k ie 's n a m e ,


m a x im u m a g e , a n d v a lu e ?

A2: Yes, you can also u se th e Cookie obje ct's setComment an d getComment
m eth ods to sto re a co m m e n t— a String obje ct— in th e cookie. T h is
com m e n t can expla in th e pu rp ose of th e cookie, for exa m p le.

[ T eam L iB ]

[ T eam L iB ]

Workshop
T h is w ork sh op tests w h eth er y ou un d erstan d all th e con cepts y ou learn ed tod a y. It's
a goo d idea to m a ste r today 's con cepts b y h on in g you r kn ow led g e he re before
startin g tom o rrow 's m aterial. Y ou can fin d th e a n sw ers to th e qu iz qu estion s in
A pp e n d ix A .

Quiz

1: W h at a re th e n a m es of th e Cookie object m eth o ds you u se to fin d a


cookie's n a m e an d value ?

2: W h at is th e defa u lt tim e o u t for a session in th e To m cat server?

3: H o w do you kn ow if T om cat can 't establish a session w ith th e u ser's


bro w se r?

4: W h at possible scope s ca n you u se w ith JavaB e a n s in JS P?

5: W h at is th e defa u lt settin g for th e page directive's session attrib ute?

Week 1 – Page 258


Exercises

1: C reate a sa m p le h o m e p age th at accepts a p erson's n a m e an d birth d ay


u sin g text fields (u se te xt fields for th e n a m e, b irth m onth , an d birth day)
an d stores th at in form ation u sin g a cookie th at lasts a yea r. T h en u se th e
Date an d Calendar classes y ou saw in D ay 6, "C reatin g JS P C o m p on en ts:
JavaB ea n s," to display a greetin g to th e p erson on h is birth d ay.

2: T ry repeatin g th e Java B ean exa m p le in th e topic " U sin g S ession s,


A pplica tions, an d Ja va B ean s ," bu t th is tim e, give th e b e an ap p lication scop e
to create a W eb p a ge coun ter th at u ses th e cou nter in th e bean to in dicate
th e total nu m b er of tim es th e p a ge h as b ee n access ed by an y on e, an d th en
test it out. A lso, u se th e application object's setMaxInactiveInterval
m eth od to set th e ap p lica tion tim eo u t to a secon d or tw o an d w atch w h a t
h a p p en s to th e counte r as th e a p p lication tim es ru n ou t ov er repeated p age
reloads.

[ T eam L iB ]

Week 1 – Page 259

You might also like