Professional Documents
Culture Documents
Week 1 (Day 1 To Day 7)
Week 1 (Day 1 To Day 7)
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 ]
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 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 ]
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.
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 ]
Week 1 – Page 4
Caution
[ T eam L iB ]
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
Week 1 – Page 5
The Tomcat Directory Structure
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
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
Starting Tomcat
Tip
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 .
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
C:\WINDOWS;C:\Program Files;C:\jdk1.4\bin
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.
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
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
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
/tomcat/jakarta-tomcat-4.0.3/bin/startup.sh
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 .
Tip
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 ]
Week 1 – Page 12
Tip
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 .
<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
.
.
.
jakarta-tomcat-4.0.3
|__webapps
|__ch01
|__WEB-INF
|__classes
|__lib
|__ch02
|__WEB-INF
|__classes
|__lib
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.
[ T eam L iB ]
[ T eam L iB ]
HTML
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>
JavaScript
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>
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. )
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
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!
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
import java.applet.Applet;
import java.awt.*;
C:\>javac ch01_04.java
<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 .
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.
Java Servlets
Week 1 – Page 20
n a m e servlet is m ea n t to im p ly).
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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:\>SET CLASSPATH=C:\tomcat\jakarta-tomcat-4.0.3\common\lib\servlet.jar
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
Week 1 – Page 22
Tip
JSP
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
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 .
Tip
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.
[ T eam L iB ]
[ T eam L iB ]
<HTML>
<HEAD>
<TITLE>A Web Page</TITLE>
</HEAD>
<BODY>
<% out.println("Hello there!"); %>
</BODY>
</HTML>
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:
out.println("<HTML>");
.
.
.
[ T eam L iB ]
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
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:
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
<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>
Directives
Week 1 – Page 29
an d D ay 10 , C reatin g C u stom Ta g s."
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
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
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 :
[ T eam L iB ]
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.
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) :
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 :
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
[ 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.
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.
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
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.
[ T eam L iB ]
[ T eam L iB ]
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
[ 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.
<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 .
<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>
[ T eam L iB ]
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.
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.
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);
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
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 ]
<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 .
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).
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.
<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>
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>
[ 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.
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 ]
<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;
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
<HTML>
<HEAD>
<TITLE>An Automatic Data Conversion</TITLE>
</HEAD>
<BODY>
<H1>An Automatic Data Conversion</H1>
<%
double double1;
float float1 = 1;
double1 = float1;
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.
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.
<HTML>
<HEAD>
<TITLE>Casting to a New Type</TITLE>
</HEAD>
<BODY>
<H1>Casting to a New Type</H1>
<%
float float1;
double double1 = 1;
Week 1 – Page 47
out.println("float1 = " + float1);
%>
</BODY>
</HTML>
Note
[ 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 .
<HTML>
<HEAD>
<TITLE>Creating a String</TITLE>
</HEAD>
<BODY>
<H1>Creating a String</H1>
<%
String greeting = "Hello from JSP!";
out.println(greeting);
%>
</BODY>
</HTML>
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:
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.
[ 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 :
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 eam L iB ]
Week 1 – Page 52
objects in Table 2.3 .
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.
[ T eam L iB ]
<HTML>
<HEAD>
<TITLE>Getting String Length</TITLE>
Week 1 – Page 53
</HEAD>
<BODY>
<H1>Getting String Length</H1>
<%
String s1 = "Hello from JSP!";
Week 1 – Page 54
ch aracters y ou can esca pe:
[ T eam L iB ]
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.
<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 .
<HTML>
<HEAD>
<TITLE>Creating an Array</TITLE>
</HEAD>
<BODY>
<H1>Creating an Array</H1>
<%
double accounts[];
accounts = new double[100];
accounts[3] = 119.63;
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;
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};
Tip
<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;
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 .
<HTML>
<HEAD>
<TITLE>Using Operators</TITLE>
</HEAD>
<BODY>
<H1>Using Operators</H1>
<%
int operand1 = 23, operand2 = 4, product;
Week 1 – Page 60
T h e follow in g operato rs are ava ilable in Java:
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 ( >>>=)
[ 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;
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:
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 ]
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 .
<HTML>
<HEAD>
<TITLE>Incrementing and Decrementing</TITLE>
</HEAD>
<BODY>
<H1>Incrementing and Decrementing</H1>
<%
int value1 = 0, value2 = 0;
value2 = value1++;
out.println("<BR>");
out.println("value3 = " + value3 + "<BR>");
out.println("value4 = " + value4 + "<BR>");
value4 = ++value3;
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 ]
<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>
Caution
[ T eam L iB ]
[ T eam L iB ]
Week 1 – Page 66
2.1 3.
<HTML>
<HEAD>
<TITLE>Addition and Subtraction</TITLE>
</HEAD>
<BODY>
<H1>Addition and Subtraction</H1>
<%
int operand1 = 15, operand2 = 24, sum, difference;
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).
<HTML>
<HEAD>
<TITLE>Using Relational Operators</TITLE>
</HEAD>
<BODY>
<H1>Using Relational Operators</H1>
<%
int temperature = 70;
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.
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:
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
[ 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 .
<HTML>
<HEAD>
<TITLE>Using Logical Operators</TITLE>
</HEAD>
<BODY>
<H1>Using Logical Operators</H1>
<%
int temperature = 70;
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.
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.
[ T eam L iB ]
double value;
value = 10 + 24 / 2;
Week 1 – Page 71
out.println("The value = " + value);
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.
<HTML>
<HEAD>
<TITLE>Checking Operator Precedence</TITLE>
</HEAD>
<BODY>
<H1>Checking Operator Precedence</H1>
<%
double value;
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.
++ — ~ !
* / %
+ -
&
&&
||
?:
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.
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
[ 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?
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
[ T eam L iB ]
[ T eam L iB ]
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;
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.
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;]
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.
<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 .
E x e c u tin g C o m p o u n d S ta te m e n ts
<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>
T h e else S ta te m e n t
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).
<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>
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).
<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 .
<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.
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.
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
}
<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>
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;
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 .
<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>
[ 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.
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.
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 .
Week 1 – Page 89
<HTML>
<HEAD>
<TITLE>Using the for Statement</TITLE>
</HEAD>
<BODY>
<H1>Using the for Statement</H1>
<%
int loopIndex;
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 .
<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;
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.
<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>
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 .
<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;
Week 1 – Page 93
</HTML>
while(condition)
statement
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 .
<HTML>
<HEAD>
<TITLE>Using the while Loop</TITLE>
</HEAD>
<BODY>
<H1>Using the while Loop</H1>
<%
int value = 5;
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 .
<HTML>
<HEAD>
<TITLE>Finding a Factorial</TITLE>
</HEAD>
<BODY>
<H1>Finding a Factorial</H1>
<%
int value = 6, factorial = 1, temporaryValue = value;
Week 1 – Page 95
}
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.
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:
do {
test = 5 * values[index++];
} while (test < 15);
<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 .
<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;
<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;
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.
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.
<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.
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 ]
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:
<HTML>
<HEAD>
<TITLE>Creating a Method</TITLE>
</HEAD>
<BODY>
<H1>Creating a Method</H1>
<%!
int addem(int op1, int op2)
{
.
.
.
}
%>
</BODY>
</HTML>
<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.
<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 .
<HTML>
<HEAD>
<TITLE>Declaring Multiple Methods</TITLE>
</HEAD>
<BODY>
<H1>Declaring Multiple Methods</H1>
<%!
int addem(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>
<HTML>
<HEAD>
<TITLE>Using jspInit and jspDestroy</TITLE>
</HEAD>
<BODY>
<H1>Using jspInit and jspDestroy</H1>
<%!
int number;
<%
out.println("The number is " + number + "<BR>");
%>
</BODY>
</HTML>
Recursion
int factorial(int n)
{
if (n == 1) {
return n;
}
.
.
.
}
int factorial(int n)
{
if (n == 1) {
return n;
}
else {
return n * factorial(n - 1);
}
}
<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);
<%
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.
Scope
<%!
int number;
<%!
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
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:
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 .
<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;
}
<%
int array[] = {1, 2, 3, 4, 5};
doubler(array);
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.
<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>
<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;
<%
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.
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
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 ]
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
Exercises
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 ]
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
[ 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
[ T eam L iB ]
[ T eam L iB ]
<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
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
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 .
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.
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.
[ 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 .
<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 .
<HTML>
<HEAD>
<TITLE>Back From the Server</TITLE>
<BODY>
<H1>Back From the Server</H1>
You clicked the button!
</BODY>
</HTML>
[ T eam L iB ]
<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">
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 .
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 ]
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.
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.
<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>
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 .
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"):
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
<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
[ T eam L iB ]
[ T eam L iB ]
<HTML>
<HEAD>
<TITLE>Submitting Text Fields</TITLE>
</HEAD>
<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>
[ T eam L iB ]
[ T eam L iB ]
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 .
<HTML>
<HEAD>
<TITLE>Inserting Text into Text Fields</TITLE>
</HEAD>
<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>
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.
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 {
Tip
[ T eam L iB ]
[ T eam L iB ]
<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.
<HTML>
<HEAD>
<TITLE>Reading Text Areas</TITLE>
</HEAD>
<BODY>
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"));
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 .
<HTML>
<HEAD>
<TITLE>Reading Text Areas</TITLE>
</HEAD>
<BODY>
<H1>Reading Text Areas</H1>
You typed:
<BR>
<%
StringBuffer text = new
StringBuffer(request.getParameter("textarea1"));
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 .
[ T eam L iB ]
[ T eam L iB ]
<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>
<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.
[ T eam L iB ]
<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!">
<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>
[ 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.
<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>
<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.
[ T eam L iB ]
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;
<HTML>
<HEAD>
<TITLE>Using Buttons</TITLE>
</HEAD>
<BODY>
<%
if(request.getParameter("buttonName") != null) {
%>
You clicked
<%= request.getParameter("buttonName") %>
<%
}
%>
<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>
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 ]
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.
<HTML>
<HEAD>
<TITLE>Using Multiple Forms</TITLE>
</HEAD>
<BODY>
<H1>Using Multiple Forms</H1>
<%
if(request.getParameter("buttonName") != null) {
%>
You clicked
<%= request.getParameter("buttonName") %>
<%
}
%>
<HTML>
<HEAD>
<TITLE>Using Multiple Forms</TITLE>
</HEAD>
<BODY>
<H1>Using Multiple Forms</H1>
<%
if(request.getParameter("submit") != null) {
%>
You clicked
<%= request.getParameter("submit") %>
<%
[ T eam L iB ]
[ T eam L iB ]
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 .
[ T eam L iB ]
Q&A
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 ?
[ T eam L iB ]
[ T eam L iB ]
Quiz
Exercises
[ T eam L iB ]
[ T eam L iB ]
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
[ T eam L iB ]
[ T eam L iB ]
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 .
<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>
<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 {
if(request.getParameter("check3") != null) {
out.println("Checkbox 3 was checked.<BR>");
}
else {
out.println("Checkbox 3 was not checked.<BR>");
}
%>
</BODY>
</HTML>
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 ]
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 .
<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.
<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 {
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 ]
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.
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";
}
<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";
}
}
%>
[ T eam L iB ]
[ T eam L iB ]
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>
<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>
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.
<HTML>
<HEAD>
<TITLE>Reading Select Controls</TITLE>
</HEAD>
<BODY>
<H1>Reading Select Controls</H1>
You selected
<% out.println(request.getParameter("select1")); %>
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.
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 ]
<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
<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>");
}
[ T eam L iB ]
[ T eam L iB ]
<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>
<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>
[ 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:
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 .
<HTML>
<HEAD>
<TITLE>Uploading Files</TITLE>
<BODY>
<FORM ACTION="ch05_13.jsp" METHOD="POST">
<INPUT TYPE="FILE" NAME="filer">
<BR>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</BODY>
</HTML>
<HTML>
<HEAD>
<TITLE>Uploading Files</TITLE>
</HEAD>
<BODY>
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.
[ 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 .
<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>
<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>
[ 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:
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>:
Tip
[ T eam L iB ]
[ T eam L iB ]
<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>
<%
int x = Integer.parseInt(request.getParameter("imagemap.x"));
int y = Integer.parseInt(request.getParameter("imagemap.y"));
%>
<%
if(x > 98 && x < 209
&& y > 104 && y < 126) {
%>
<jsp:forward page="ch05_19.html" />
<%
}
%>
<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.
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
<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"));
%>
[ T eam L iB ]
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.)
<HTML>
<FRAMESET ROWS="70%, 30%">
<FRAME SRC="ch05_25.html">
<FRAME NAME="frame2">
</FRAMESET>
</HTML>
<HTML>
<HEAD>
</HEAD>
<BODY>
<FORM NAME="form1" ACTION="ch05_26.jsp" TAR GET="frame2"
METHOD="POST">
<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>
Tip
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 ]
<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">
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.
<HTML>
<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.
[ T eam L iB ]
[ T eam L iB ]
<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 .
<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>
[ T eam L iB ]
[ T eam L iB ]
Reset Buttons
<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>
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
[ 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.
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 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 ]
[ 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
Exercises
[ T eam L iB ]
[ T eam L iB ]
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
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 .
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
[ T eam L iB ]
[ T eam L iB ]
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:
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:
[ 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 .
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 ]
C:\ch06>javac ch06_01.java
Tip
[ T eam L iB ]
[ T eam L iB ]
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 ]
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:
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 .
</BODY>
</HTML>
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.
[ 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 .
package beans;
public ch06_03()
{
}
}
webapps
|____ch06
|____WEB-INF
|____classes
| |____beans
|____lib
package these.are.my.beans;
webapps
|____ch06
|____WEB-INF
|____classes
| |____these
| |____are
| |____my
| |____beans
|____lib
[ 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 .
<HTML>
<HEAD>
<TITLE>Using a Java Package</TITLE>
</HEAD>
<BODY>
<H1>Using a Java Package</H1>
</BODY>
</HTML>
[ T eam L iB ]
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 .
package beans;
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 .
<HTML>
<HEAD>
<TITLE>Using a Constructor</TITLE>
</HEAD>
<BODY>
<H1>Using a Constructor</H1>
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 .
[ 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.
<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> }
<HTML>
<HEAD>
<TITLE>Using <jsp:useBean></TITLE>
</HEAD>
<BODY>
<H1>Using <jsp:useBean></H1>
[ T eam L iB ]
[ T eam L iB ]
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.
package beans;
public ch06_08()
{
}
}
[ T eam L iB ]
<HTML>
[ T eam L iB ]
package beans;
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:
[ T eam L iB ]
<jsp:setProperty name="ID"
{
property="*" |
property="propertyName" [ param="parameterName" ] |
property="propertyName" value="{stringLiteral| <%= expression %>}"
}
/>
<HTML>
<HEAD>
<TITLE>Setting a Property Value</TITLE>
</HEAD>
<BODY>
<H1>Setting a Property Value</H1>
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.
[ T eam L iB ]
package beans;
public ch06_12()
{
}
}
<HTML>
<HEAD>
<TITLE>Calling a Private Method</TITLE>
</HEAD>
<BODY>
<H1>Calling a Private Method</H1>
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.
[ T eam L iB ]
[ T eam L iB ]
<HTML>
<HEAD>
<TITLE>Using the Date Class</TITLE>
</HEAD>
<BODY>
<H1>Using the Date Class</H1>
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 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.
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 .
<BODY>
<H1>Fields of the Calendar Class</H1>
<%
String dateString = new String();
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 .
[ 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.
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 ?
[ 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
Exercises
[ T eam L iB ]
[ T eam L iB ]
[ T eam L iB ]
<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");
}
%>
.
.
.
<HTML>
<HEAD>
<TITLE>Reading Hidden Controls</TITLE>
</HEAD>
<BODY>
<HTML>
<HEAD>
<TITLE>Reading Hidden Controls</TITLE>
</HEAD>
<BODY>
<H1>Reading Hidden Controls</H1>
The hidden text is:Hello there!
[ T eam L iB ]
[ T eam L iB ]
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.
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 .
[ T eam L iB ]
Note
[ 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);
%>
.
.
.
<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);
%>
<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);
%>
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 .
[ 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();
.
.
.
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();
<HTML>
<HEAD>
<TITLE>Reading a Cookie</TITLE>
</HEAD>
<BODY>
<H1>Reading a Cookie</H1>
<%
Cookie[] cookies = request.getCookies();
[ T eam L iB ]
<HTML>
<HEAD>
<TITLE>Setting and Reading Cookies</TITLE>
</HEAD>
<BODY
<%
Cookie[] cookies = request.getCookies();
boolean foundCookie = false;
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)
<HTML>
<HEAD>
<TITLE>Setting and Reading Cookies</TITLE>
</HEAD>
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>
Figure 7.5. Setting and reading a cookie using the same page.
[ 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
Note
[ 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:
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 :
<BODY>
<%
Integer counter =
(Integer)session.getAttribute("counter");
.
.
.
session.setAttribute("counter", counter);
.
.
.
<BODY>
<%
Integer counter =
(Integer)session.getAttribute("counter");
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>
[ T eam L iB ]
<!-- 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>
[ 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
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 .
<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);
%>
[ T eam L iB ]
package beans;
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 .
<HTML>
<HEAD>
<TITLE>Using Beans and Page Scope</TITLE>
</HEAD>
<BODY>
<H1>Using Beans and Page Scope</H1>
<HTML>
<HEAD>
<TITLE>Using Beans and Session Scope</TITLE>
</HEAD>
<BODY>
<H1>Using Beans and Session Scope</H1>
<%
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 .
[ 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.
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
[ 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.
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
[ T eam L iB ]