You are on page 1of 20

-JAVA SERVER PAGES

with suitable~ ...


,plain worksdlft~P.

ms with suitable map


code and brief de9Jirl:

rvlet Interfare (311 kat


. - .

- ~--
A5?ExplainWUI~--:
.,f reads nUJll
er comprehensive study of this chapter, you will be able to:
To compare JSP with Servlets and other server side technologies
To demonstrate different tags used in JSP ·,
boX, ,,.LI ~ To explain different implicit objects provided by JSP
•_:..in2 !JC"' ~
t coJ\taU"';i ii~ To process HTML forms using JSP
~n save bl1 ,. To access databases using JSP
..;.; , To handle exceptions and sessions using JSP
,~JBi!t _..m l To used java beans with JSP
1\'let·? ,11
,,ti·te dO"·
;iot\S·
314 Adv11 nccd J11v11 l't\ )~l'llllHHin:1,
~-- -·· ... -
IZ.l BASIC OF JAVA SEllVER PAGE i

Java Serv('r Pngl'R (JSP) is a ~rvcr-aid c programming technolog y that enables the creation of •
dynamic, plntform-indl•pcn dcnt method for building Web-based applications. JSP have access
to th(' entire family of Java APls, including the JDBC API to access enterpris e databases. It can
be thought of as an extension to scrvlct bt..-cause it provides more functionality than servlet. A
JSP page consists of HTML togs and JSP tags. The JSP pages are easier to maintain than serviet
because we can ~ raratc designing and development.
Web develope rs write JSPs as text files that combine HTML or XHTML code, XML elements,
and embedde d JSP actions and commands. JSP tags can be used for a variety of purposes, such
as retrievin g infom,at ion from a database or registering user preferences, accessing JavaBeans
compone nts, passing control between pages and sharing informat ion between requests, pages
etc. oser se~d
JSP engtr'-'
12.1.1 Advantages of JSP
'fhe Web
Followin g is the list of other advantag es of using Java Server Pages over other technologies:
to the JSP
JSPvsA SP If the JSP
The advantag es of JSP are twofold TheJSP e
• The dynamic part is written in Java, not Visual Basic or other MS specific language, so The serv1
it is more powerful and easier to use.
origmal I
• It is portable to other operating systems and non-Microsoft Web servers.
i The serv
JSP vs Servlet s methods
There are many advantag es of JSP over servlet. They are as follows: passed b
• Extension to Servlet JSP technology is the extension to servlet technology. We can use ~ The wet
all the features of servlet in JSP. In addition to, we can use implicit objects, predefined content.
tags, expressio n language and Custom tags in JSP, which makes JSP development easy. lITI'P re
• Easy to maintain: JSP can be easily managed because we can easily separate our Typically, the J!
business logic with presentat ion logic. In servlet techn~logy, we mix our business logic wt-ether the mo
with the presenta tion logic. &enerated servlE
• Fut Develop ment If JSP page is modified, we don't need to recompil e and redeploy ~ generated. 1
the project. The servlet code needs to be updated and recompil ed if we have to change ' PHI>) and the

~-~
the look and feel of the application.
• LeH code than Servlet In JSP, we can use a lot of tags such as action tags, custom tags
etc. that reduces the code.
~~fiv e 1
12.1.2 JSP Access Model 'l'fess1on ta~
When a user goes to a web site that is develope d by using JSP and tries to access JSP page by 12.2.1Decl
using a web browser, following steps are performe d to process the request and return result to ~
tag allows

,~d
~\>
the user:
ill~~%! ilnd i

\VitJ

.
1
0?\s or ,

Java Server Pa11es o - -~ 315
j '...~ ° Chapter l ZJ

~
!

Jsp
d
a.~
hqv ol\
Transialion
phase

' -1~ i:\ti\b


:Y th<\l)
:-tt¾l ~l
I! ii

¾
()f
a
~ l!t,~
II
~I~
:, ~
~essit\ ~ }
Request
processing
phase

!n_ l' g fa\'~


eql.lests Fig. l l .1 JSP Architedure.
'P<l~ ·
user sends JSP request to the Web server through web browser to the web server with
1. .
JSPengme. _
.t
echno10 gies: required is JSP fil e, therefore passes the JSP file
2. The Web server. recognizes that the file
to the Jsp Engme. ·
ise go to step 5.
3. If the JSP fil~ has been called the first time, the JSP file is parsed, otherw
The JSP engme generates a special servlet file from the JSP file.
ecific langua so then forwards the
ge,
4. The servlet file is compiled into a executable class file. JSP engine
ers. original request to a servlet engine and the servlet is instantiated.
init and service
5. The servlet engine loads the servlet class and executes it by calling
format, which is
methods. During execution, the servlet produces an output in HTML
. passed to an HTTP response.
of static HTML
11ology. We can use 6. The web server forwards the HITP response to browser in terms
page inside the
content. Finally web browser handles the dynamically generated HTML
objects,preclefiMI
HTIP response and results are displayed on the web browser.
development easy. file already exists and
Typically, the JSP engine checks to see whether a servlet for a JSP
?asily separate oor whether the modification date on the JSP is older than the servlet
? If the JSP is older than its
and that servlet file is
rour!n,m,,lli generated servlet, the JSP container assumes that the JSP hasn't changed
with other scripting languages (such
not generated. This makes the process more efficient than

mpile and ~ as PHP) and therefore faster.


: wehavetocharf

tags are: Declaration tags,


~n tags,cUSIOIII"' There are five main tags that all together form JSP syntax. These
Expression tags, Directive tags, Scriptlet tags, and Action tags.
l2,2,1 Declaration tag ( <0/o! 0/o>)
we _must
This tag allows the developer to declare variables or methods. Before the declaratio~
ents placed m this tag
have<%! and at the end of the declaration, we must have %>. Statem
lllUst end with a semicolon. Declarations do not genera
te output so are used with JSP

expressions or scriptlets.
316 AdvancedJava Programming
Example
<%!
private int counter = 0 ;
private String getAccount( int accountNo) ;
%>

12.2.2 Expression tag ( <%= %>)


%'
This tag allows the developer to embed any Java expression. It is the short hand form of ~ctiO
statement "out.printlnQ" written in servlets. A semicolon should not appear at the end of the ,,.z,S
statements wriiten inside the tag. For example, to show the current date and time, we can write V" ·oJl tags ;
1 aeti gs suPf
Date : <%= new java.util . Date() %>
1; ~forWard
12.2.3 Directive tag ( <%@ directive ... %>) 1J
<J·sp ••ft
It is a JSP directive that gives special information about the page to the JSP Engine. It usually
has the following form: <%@ directive attrib1,1te="value" %>. There are three main types of 11,2,6JSP C
directives:
g,cou........r11ents
· I
- Page Directive - P!OCessing information for this page. ~when we
- Include Directive- files to be included. g,coaunents:
Tag library Directive- tag library to be used in this page. . <%-- T
Directives do not produce any visible output when the page is requested but change the way
the JSP Engine processes the page. For example, we can make session data unavailable to a
page by setting a page directive (session) to false►-- • --

Page directive: This directive has 11 optional attributes that provide the JSP Engine with
¥•J
11m are sevei
special processing information. Some of the attributes are: ct;ectsareava
<%@ page language= "java" %> !mig explicitl)
llire implicit ol
<%@ page extends= "com.taglib_ %>
<%@ page import = "java.util. *" %>
• out o'b
Print'-'
Include Directive: It allows a JSP developer to include contents of a file inside another. File is reque!
included during translation phase. Examples are given below: used iJ
<%@ include file= "include/privacy.html" %>
respo1
<%@include file• "navigation.jsp" %> the JSJ
The first example includes the privacy.html file residing in include directory into the JSP page COnfi@
and the second example includes navigation.jsp file in current directory into the JSP page canhE
I
Tag Lib directive: A tag lib is a collection of custom tags that can be used by web developers in
~~
the current. It uses following syntax:

Example
<%@ taglib uri • "tag library URI" prefix• "tag Prefix"%> ::1
thew
<%@ taglib uri="http://www.javatpoint.com/tags" prefix••■yta1• I> Ccln})E
Sessic
can~
f
Java Server Pages -.
4 scriptlet tag ( < OJ.o ••• 0!lo:> ) O Cha
" 1
i,...~• ~tz) m
p ;ava code can be written . .
JJl Js ' d 01 tns1de the .
L..tween <% an ,o> tags. This cod Jsp page u .
i,i;•·. • bl . e can acces smg the script! t
..;nt a vana e, we can write scriptl t s any variabJ e tag. Code is written
P•... · <% e as below: e or bean d ec lared. For example, to

String username - "


- Suman" .
out.println ( use '
rname) ;

12.2.s Action tag


The action tags are used to control the fl ow between
action tags supported by JSP are: 1·sp:forw d . .· page~ and to use Java Bean. Some of the
ar , )Sp.include Jsp·
PEn · tag that f orward s t o anoth er JSP page is given
• below: ' .param etc. An example of action
gtne. It Usi,,1t
hree rn,,;_ -"'lllf <jsp:forward page="printdate.jsp" />
-"llll ~ ~

12.2.6 JSP Comment


JSP comments marks text or stateme~ts that the JSP cont amer .
• should ignore. A JSP comment is
useful when we want to hide or "comment out" part of our JSP page. Fo11owing
· 1s· the syntax of
JSP comments:
<%-- This is JSP comment--%>
but change ~ 1\'il
lata unavailable to;

the JSP Engine Iii There are several obj~ts that are. automatically available in JSP called implicit objects. These
objects are available to developers in each page and developer can call them directly without
being explicitly declared. JSP Implicit Objects are also called pre-defined variables. There are
nine implicit objects defined in JSP container. These objects·are described below:
• out object- This object is used for writing any data to the buffer. It is the object of
PrintWriter class.
• request object- This is the object of HttpServ~etRequest class. This object is normally
thet·frti
if\sideaf\O used in looking up parameter values and cookies.
• b" Thi · th obiect of HttpServletResponse class. Through this object
response o Jed- s 1s e , od
d w cookies or date stamps, HITP status c es etc.
the JSP programmer can a d ne . . . . .
• • • nf" Ob' t is an instantiation of ServletConfig class. This object
conf1g ob1ect- The co 1g iec • JSP
can be d t t . .tialization parameter for a parttcu1ar page.
use O ge uu . . . plicit object of Throwable class. This object can be
• exception object- exception is an un
used to print the exception. . f ServletContext class and is created only once by
• Application object- It is an nu:ta::noor project is deployed on the server. This object
the web container when ap.pbca t r from configuration file (web.xml). ··
. "ti lizatton parame e
can be used to get uu a . . . bject of type HttpSession. The Java developer
■ • . . an unpbc1t o . . inf .
8 ess1on object- session lS ve attribute or to get session ormation. .
can use this object to set,get or remo
p;
311 Advanced Java Prog ramm ins f
. This obje ct is assig ned to the ~ r
Page obje ct- page is an impl icit obje ct of type Obje ct class

refer ence of auto gene rated serv let class.
l
I

icit obje ct of type Page Con text class. The


• page Con text object- page Con text is an impl
remo ve attri bute from obje ct scopes.
page Con text object can be used to set, get or l
---..,.-.....-.r-..-.~--
J
ed as
a part icula r plac e of the appl icati on is defin
The avai labil ity of a JSP object for use from e in
ted in a JSP page will have a scop e. Obje ct scop
the scop e of that JSP object. Ever y object crea
page , requ est, sess ion and appl icati on.
JSP is segr egat ed into four part s and they are
ct can be acce ssed only from with in the
• Page Scop e- page scop e mea ns, the JSP obje
obje cts out, exce ption , resp onse ,
sam e page whe re it was crea ted. JSP impl icit
e'.
page Con text, conf ig and page have page scop
//Example of JSP Page Scope
n" scope="page" />
<jsp:useBean id="employee" class="EmployeeBea
requ est scop e can be acce ssed from any
• Req uest Scop e- A JSP object crea ted usin g the
serv e a sing le requ est. Implicit
pages that serv es that requ est. Mor e than one page can
obje ct requ est has the requ est scop e.
//Example of JSP Request Scope
n" scope="request" />
<jsp:useBean id="employee" class="EmployeeBea {/Se,
SP obje ct _is· acce ssibl e from page s that belong /Ip~·
• Sess ion Scop e- sess ion scop e mea ns, the _J
Impl icit obje ct sess ion has the sessi on
. to the sam e sessioi:1 from whe re it was crea ted. d!t111'.

scop e. (~ea
<tit
//Example of JSP Session Scope . . .

oyeeBean" scope="session• /> </h,


<jsp:useBean id="employee" class="Empl
g the appl icati on scop e can be accessed
(~
• App licat ion Scop e- A JSP obje ct crea ted usin (fon
icit obje ct appl icati on has the
from any page s acro ss the appl icati on. The. Impl
appl icati on scop e.
//Example of JSP app lica tion Scope
n" scope="application" />
<jsp:useBean id="employee" class="EmployeeBea
//Ex amp le-- -Fir st JSP Exa mpl e--- firs t.jsp
File
<html>
<head>
<tit le> Firs t JSP Example</title> f
</head>
,~ 0
<body>
<font size=3> <t~n
<br><br><center><h2> (Jf
<%-- Display by using exp ress ion tag- -%>
<%= "Fi rst JSP Example"%>
<hr colo r=b lue size=3> '
f
:~ '
Java Server Pages O Chapter 12) 319
by using script let tag- -%>
iSP l aY
<V D
~ tln("Hello WebApp developer .•... Welcome to JSP")·
< priO ,
rjJt '
~)
~2>
(((enter>
(/fOnt>
(/'oodY>
(/ht111l>
~
~ Int 1il blmple IC

I>
Fint JSP Eumple
~ fnnnany
st. Imp~ Hello WebApp developer.....Wekome to JSP

l.,
;that~
//Second Example-Printing Message 18 times
It\e551(11
. //print.jsp File
<html>
<head>
<title>Repetition< /title>
on· /> </head>
<body>
eaccsed <font size=3>
<br><center><h2>
<X-- Display by using expression tag --X>
<X: •Print 10 Times" X>
</h2>
<hr color=blue size=3> .
<X-. Display by using script let tag - -X>
<X

for (int i=0;1<10;i++)


b out.pr intln(" Lalitp ur Nepal<br>");

<center>
</font>
</body>
</ht1111>
320 Advanced Java Programming
Output

Print 10 Times

Lalitpur Nepal
Lalitpur Nepal 1·
Lalitpur Nepal j
Lalitpur Nepal l '
Lali1pur Nepal
La1itpur Nepal · 1 I ~
Lalitpur Nepal ~
Lalitpur Nepal r ._,
Lalitpur Nepal
La1itpur NCJNU

·1z:s-l'OUI PaOCESSINoiN·JsP~"'?~~.-:~~:~~-~ ~="". ,--~~~-----~-~---~ _____...,._-...--__l


:• I
I

r ~
J..._,,.....,

Form processing in JSP is similar to form processing in Servlets. We can use request object to
read parameter values from lITML file or another JSP file. Methods supported by request
object are similar to methods used in dervlets.
//process.jsp File
-
-- ..
<html>
<head>
<title>For111 Processing</title> cump
</head> l/f/f1
<body> (hW.i
(body
<font size=3> (h2>p
<br><br><center><h2> (hr c
Processing HTML Form (form
<hr color=red size•3> '-:
(inpu
<%
~x:
int x=Integer.parselnt(request.getParameter(" first")); (inpu
int y=Integer.parselnt(request.getParameter("se cond")); (br>s
int z=x+y; <sele
out.println("Sum="+z); <o
.: • . -➔ <o
%>
<o
<h2> <o
<center> <o
</font> <o
</body> t <~
'i~1
</html>
.. d ~
I
Java Serv
oiitput er Pages 0
Ch~ 321

~ I

...,.., ~ Form Ptvcessing

'"\.,

can use IPn--,11!11 '


. HTML Form
Processmg
ds supported ~)
. _Sum=14

Example with more elem ents


1/myform.html File
<html>
<body>
<h2>Please Tell me about yourself</h2>
<hr color =red size=3>
~for~ a~tion="myfrom. jsp" method="post">
~me. <inp ut type ="te xt" name="firstName">
<input type ="te xt" name="lastName"><br> le
S~x: <inp ut type ="ra dio" checked name="sex" value="male">Ma
<input type ="ra dio" name="sex" value="female">Female
;br>S elect Your Country:
selec t name="country">
<option value="Nepal">Nepal</option>
t'))i <option value="India">India</option>
•))i <option value="China">China</option>
<option value="Pakistan">Pakistanc/option>
<option value="Bangladesh">Bangladesh</option>
<option value-"Bh utan">Bhutan</ option>i
< . - il ka</opt on>
< optio n value ="Sr ilank a">S r an
/sele ct>
<br>
<input type="submit">
I! 322 AdvancedJava Programming
</form>
</body>
</html>

//myform.jsp File
<html>
<body>
<%
String fn = request.getParameter("firstName");
String ln = request.getParameter("lastName");
String sex= request.getParameter("sex");
String country= request.getParameter("country");

<br><br><br>
<center>
<h2>Hello, <%=fn+:• "+ln+" I"%>
I see that you are <%=sex%> and from country
<%=country%> - -: ---- c~ . .·. • '
</h2> ' ..·_ t:.: ·_ C - ., ;_

</center> · · -'-~- · '·· ·


</body>
</html>
Output

Please Tell me about younelf

Sec • Male O Female


- - -. .
Sekct Your Cammy: Nepal ·J
tJ&ii9exu
I . ' .

Hello, Arjun Saud! I see that yoa are male and from country Nepal
- · · ·· Jav
:.a.6 DATABASE ACCJtss .,.__ a Server Pages
0
~ w,r . . . . dSp Chap~r l ~ 323
We also access database by using }Sp . -·· _.,
-Aes related to database access . h.' AU JDBc APJ
CV" W1t tn the scan be ace
//oddbOOll • html Fi.Le expression tag. essed from JSP. We have put all
<htnil>
<head>
<Title> E-book Store </Title>
</head>
(t,Ody>
<br><Center>
<h2>Adding New Book</h2>
<hr color=blue size=3>
<form action="addbook.jsp" method="post">
<table>
<tr>
<td> ISBN </td>
<td><input type=text name=ISBN></td>
</tr>
<tr>
<td> Book Title </td>
<td><input type=text name=title></td>
</tr>
<tr>
<td> Authors</td>
<td><input type=text name=authors></td>
</tr> -
<tr>
<td> Price </td>
<td><input type=text name=price></td>
</tr>
<tr>
<td> Publisher </td>
<td><input type•text name•pub></td>
</tr>
<tr>
<td colspan•2 align•cen1er>,. Add sook" >
<input type•"submit" va ue•
<ltd>
</tr> fl
</table> •
</form>
</body>
</html>
,~
~
324 Advanced Java Programming
1/addboo k.jsp File
<html> f tO
<body>
<%
~~or~
String ISBN= request.g etParame ter("ISBN "); r.l Ji•,i:il
String title= request.g etParame ter("title "); ll1"'tl
1'

String auth = request . getParam eter("auth ors "); f ~"'t,le


int price= Integer.p arseint(r equest.g etParame ter("pric e")); f 10 ~1
String pub=requ est.getPa rameter(" pub"); #\e
<h2><center> ~:ej.j
<font face="Tw Cen MT" color=blue> i/ifl ac1
<%@ page import= "java.sql .*" %>
<%
.i~
' rfll
table>
Connection con =
~r>
DriverMa nager.get Connecti on("jdbc: mysql://l ocalhost/ ebook",_ "root" J
<td>~
"arjun"); _ <td>~
Statemen t stmt = conn.crea teStatem ent();
String sql . ="insert into books values ( "'+ISBN+ _ "','"+titl e+ i1tr>
••,••+aut h+"', +price+" ,'" +pub+"')" ;
0
!. · . -·· - .- rtr>
stmt.exec uteUpdat e(sql); · <td>~
out.print ln("Book is Addes Successf ully");
<td> ◄
%>
</font><center><h2> - (/tr>
</body> rtr>
</html> - <td
Output <inp
</td

.. e
'
'1 a.
~ -1• ,"l>,,- ,.<; •
l *:•
Sm,m....,,-»_,.-_;•~~-~..I,,.... ~• ~~·
• .•
• -... ,,• ...._ • ._' ' •
(/tr>
(/form>
IIProce
Adding New Book ~ pa I

Strj
Boakldle --··-···· ------ --- l StrJ
Audm 1. .. . _ _____ __]
Price int
Publiaber i int
' ttta j int
0ut
I>

look is Aclcle1 Successfully


I:,, ,:,, -;;, ,,,,,. .-:.:11-i '.J '-,. ~~-,;, ; t m
~ HANDLING IN.JSP . > ;

~crrt•"" "' n11r~lly _a n ot?'" t ,.,,,r1rn ~t , ,,, ... rr"t 1-J~,,.,,•,on H~~.:r~ " t:: ':
1•,:,t ,.
'flit tn handle thr. ru nt,r~ l'f'f(trft, l};r.. rr,.;,r { ~ f l J f rH-,l'il'KI .-f ~!''l t.f!''. If) 'I'd •,wf,J'?
~ ti""· So hand ling MCN'J>fit,n- ,- a tt.:,f1-, ftY~ f,,, tt-- Wffi ~(..YI",,...,. r _R 1/·f~ U.-" ,,;,-:or
e~) ) . ,!1'1" ·ty ErTOf Page for eMh J',J'. Wt-"-r~,~ ,,..,. V"rr tt-,,,,.,,.. ~n -:-/o-,1':on, ~-' Y-R <fl'f;A:!'~
I
ro 'f"-'°t,cally invoke111 the error pa,~- A• WI! lcrwrlf, 1(/1',-Y;on ,. 3n kr,-~:nt ,;,~ <A t:/~
, 11""":ble da."8. This obj(.-ct can ~ U.¥!d to prrr,t ,.,. (,;'/rr,l' 'i on, ~Jt i t ~ ,,r Jr ~ ~ lt1 ~-,,r
ni:-
;"e-·
To tel up an er,c,r page, u~ the<%~ P,,?ft t:Tt'"~"rr·, rn p.p• 14> t!,;1~,;·f~.

f.s'O'lple
u,dCK .jsp Ff.Le
~~ action••process.jsp•>
,uble>
<tr>
,td>First Nu•ber</td>
BN+ ,td><input type••text• na.e••n1• / ></td>
,/tr>
<tr>
<td>Second Nuaber</td>
<td><input type••text• na.e-•n2• / > </ t d>
</tr>
<tr>
<td colspan•2 align-center>
<input type-•sublltt• value--•dtvide·/>
</td>
</tr>
</fora>
1/process.jsp FiLe
~ page errorPage••error.jsp• S>
~
String nU111•request.getParaaeter( •n1• );
String nU112•request.getParaaeter(•n2• ) ;
int ••Integer.parselnt(nual);
int b-Integer.parseint(nua2);
int C•l/b;
-'- i S •. • ♦C ) ,,•
out .print(•dtvision of nu-.,ers
¥>

1/trror.j•p
<t@ Pille isErrorPage-•true• I>
<h3 >Sorry an exception occuredl</h3>
E)(ctption is: <S- exception.getfilessage() I>
328 Advanced Java Programming
Outp ut

~~u9~~~~~~~e~~:"~~~-=-~~~7
_©• ltt-;;~
l:!!i! Wltf,./ ,-......, /Aq,,tl IC
?"_"'___;:c: - - -
·~
Fint Nmnber 10
Second Nmnber S
[Iiiiiil
/'
~,.,,,t
~J)
;,>
<fOr' a

-----
'-!,8 ~!Arj un/pro c<>S.jsplnl:lO&nZ:~
d"put
d"put
cli,,waa ofmab essis: 2
.~rt>
;rtf>
i111l>

fwtLCOIIC
itll>
"'1>
l!l a.a,r,na art -:\,jul ll x
'+\• ~ _,Arjun/
'<..:,.,-- . . . String
FinrN aibu :10 __ ·-· _ _ __1 oot.pr
SermdNmnbor O __ ._ _ j

~
sessi]
1
ref,.•
Ih

~Y>
~)

Sony u aapd oa ocan dl

mcepli aail: /1,y.-o


- .. Java Server Paoes
~ -
- --
O Chaptc;:--12) 371
~ ~-SUSION TilACJUNc
-JSP
Jtt '
session is an implicit object of ty H
-b pe ttpSession Th J
~ or remove attn ute or to get sessio . f . · e ava developer can use this object to
s,et,s H . n tn ormation B d f .
. · Y e ault, JSPs have session tracking
.
'-led and a new ttpSess1on obJ'ect • .
ettaL' . k' is mstanhated f
Di~t,ling session trac mg requires explicitly tu . . or each new client automatically.
· ·t,ute to false as follows: rntng it off by setting the page directive session
attn
<%@page session="false" %>

£XOIIPLe
//index.htaL FiLe
<htal>
<bOdY>
<forlll action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</for-.>
</'oody>
</ht■l>

II wLcoae.jsp File
<ht■l>
<body>
<I
String name=request.getParameter("uname");
out.print(•welcome "+name);
session.setAttribute("user",name);
l>
<a href••second.jsp">second jsp page</a>
</body>
</ht■l>

llsecond.jsp Fi.Le
<ht■b
<body>
<' tAttribute("userN);
String name•(String)session.ge
out.print(•Hello •+name);
l>
</~-.. .
uuay>
</ht1111>
d flt
~ -di
328 Advanced Java Programming t,vil
tl'et
Output
~Jl'
~-:;;~;~~~~ ,eti.,
-~ • I\t loolhost:8000/ AIJUI\I ' Java .
tOvl
'
A,jun
-
p 1
etC·
cajl .'
collll
J1i1'i
, ajld

writ
etC,
tong
Waccae Aijun second jsp page ifllP
tecli
creci
dati

ii.i•'l F

javaBeans •
application
Hello.Asjaa Following;
- Itr
It!
- It 1
- It l
lavaServe1
language I
pron-.&.:
r---~ues
Frameworks are large bodies of pre-written code to which you add your own code in order to
solve a problem. You make use of a framework by calling its methods, inheritance, and l•p:uaeJ
supplying callbacks, listeners, or other implementations of the patterns. A framework will often lheUs,81
dictate the structure of an application. Some frameworks even supply so much code that you ~Pting
have to do very little to write your application. Three major java web frameworks are briefly In the Jsp
discussed below. ·· ·
• Struts: Struts 1s· a Java-based open-sourced framework that helps in deve-1opm · g web
application in J2EE. It e~tends the Java Servlet API and promotes the Model, Vie:
Controller (MVC) architecture. This makes the web applications develo~ 1
standard technologies like JSP, JavaBeans, and XML, more maintainable, exten51b e,
~
I '
and flexible . The fram
.
t,ui1dmg, to dep loying, t
ework is des i
other features to make w obrnaintainin
. gne
Java Server Pages O - ~

• d to strearnl"me the full d l


g applicatio
Chapter l ZJ 32 9
eve
and POJO actions, Tag Sue develoPm ns over time Struopment cycle, &om
spnn·~ S . . PPOTt, AJAX support
ent eas ier for th · ts provide various
• er pn ng IS a powerful l'gh e developers such as POJO form
. . , easy Integration and m s
ava En I twe igh t .
J ·d t nse Edition vm:E
erp
'-- ) · In a wa y app
any
prov.;:
etc.
;up po rt to Various fra me wo
·t •lication development framewo
r~ I : a framework of framewo
rks
rk used for
because it
am ew ork in a bro ade r sense
subec as ~truts, Hibernate, Tapestr
can solve ma ny technical y, EJB, JSF
hen problems ycan defined as a stru .
compre s.
tve tool for sup por tin g . liOU . can ctu re usm g which you'
• say that the Spring Framework
• Hibernate: Hib ern ate is a fr app cations usin J is a
and han d} . g ava programming language.
.
es the imp lem ent atioam ew ork m Java which
ns . comes wit .
writing a que ry for CRUD OnP h an abstraction lay er
r ti mtemally. The imp
lem ent atio ns include tasks like
etc. Hioemate dev elo ps perr-· a ons or establishin
s· t g a connection wit h the databases
longer use. It is lightweight and is ence logic which st
Obj . ' d
---- +,:a flf- hr . ores an processes the dat a for,
"U r'& ,_.
an ection-relational Mapping (ORM)
techniqueIY.,thaope n-source wh ich gives it tool and mo st
t ma ps th bj ed
ae a~ ma ni . an ge ove r oth er frameworks. IORM is a
ti e o ect sto red m the database.
databases. An ORM tool simplifies dat a
pu1a ~ and acces.s. It internally use
s the Java API to interact wit h the

- DM.. . . . . . . . . . . ·--~------.,.--- - -~-:r- ,--~-. . ---~,----. -. '


~
I
J a v ~components are Java classes tha
t ~ be
app . • Any Java class that follows certain _easily reused and composed together into
design conventions is a JavaBeans
Following are the uni que characteristic com pon ent .
s tha t distinguish a JavaBean from oth
er Jav a classes:
- It must provide a def aul t, no- arg
um ent constructor.
- It should be ser iali zab le and imp
lem ent the Serializable interfac
e.
- It may have a number of pro per ties
wh ich can be rea d o; written.
- It may have a number of "getter'
and "setter• me tho ds for the pro
perties.
lavaServer Pages tec hno log y directly
sup por
language elements. We can easily create ts usi ng JavaBeans components wit h sta nda rd JSP
and initialize bea ns and get and set the val ues
P,operties. of the ir

ja p: u. Be u
The IIMBan action declares a JavaBean
for use in a JSP. Once dec lare d, the
ICripting variable tha t can be access bea n bec om es a
ed by both scr ipti ng ele me nts and oth
in the JSP. The full syntax for the use er cus tom tags used
Bean tag is as follows:
<jsp: useBean id••beans name• cla
ss••class name• scope=ubeans sco
pe»/>
Here values 1. the ttribute cou ld be pag e, req ues t, session or applica
requirement.,or scope
1ne value ofathe id attr ibu te may be al tion based on our
any v ue as a 1ong as 1t. 15 .
a uru
.
que nam e
ilrlong other useBean declarations
in the same JSP.
330 Advanc edJava Program ming
Examp le
<html>
<head>
<title>u seBean Examp le</titl e>
</head >
<body>
<jsp:us eBean id•"dat e" class•" java.ut il.Datc .. /> •
<p>Th e date/ti me is<%• date %>
</body >
</html >
Outpu t
This would produc e followi ng result: The date/time is Thu Sep 30 11:18:11 GST 2010
jsp:set Proper ty and jsp:getProperty
Along with <jsp:us eBean. .. >, we can use <jsp:ge tPrope rty/> action to access get
method s and
<jsp:se tPrope rty/> action to access set method s. Here is the full syntax;
<jsp:u seBea n id=•be ans id• class• "class name• scope• •beans scope•>
<jsp:s etProp erty name=•beans id" prope rty="p ropert y name•
value= "value "/>
<jsp:g etProp erty name="beans id• prope rty••p ropert y name" />

</jsp:u seBea n> ....


The name attribu te referen ces the id of a JavaBe an previ_o usly introdu ced to the JSP
by the
useBea n action. The proper ty attribu te is the name of the get or set metho ds
that should be
invoke d. · ·
Ev.ample
//Stud ent.Ja va File
public class Studen t implem ents java.i o.Ser ializa ble .
{
priva te String firstN ame • null;
priva te String lastName • null;
priva te int age• 0;
public Stude nt() { }
public String getfirs tName ()
{
return firstN a•e;
}
public String getLas tName ()
{
return lastNa me;
}
public int getAg e()
Java Server Pa ~-
{ &es O Chapter 12) 331
return age;
}
public void setFirstName(st i .
{ r ng firstName)
this . firstName _ fi
- rstName·J
}
public void setLastName(st
{ ring lastName)
thi~.lastName = lastName ·
J
10
1 -}
public void setAge(Integer age)
{ . . '
;et lllethods il\l this.age= ag~;
}
.' ..
i scope'> }
ne"
//Student.jsp File .
1e" /> <html>
<head>
<title>get and,_ set p~ope~ties .Example</title>
</head> · ,.
the JSP by !rt
<body
that should re
<jsp:us~Be~n ·id="st" ·c1ass="Student">
<jsp:setProperty name="st" property="firstName" value="Aagaman"/>
<jsp:setProperty name="st" property="lastName" value="Saud"/>
<jsp:setProperty name="st" property="age" value="S"/>
</jsp:useBean>
<p>Student First Name:
<jsp:getProperty name="st" property="firstName"/>
</p>
<p>Student Last Name :
<jsp:getProperty name• "st" property• "lastName"/>
</p>
<p>Student Age:
II "/)
<jsp:getProperty name• "st" property• age
<Ip>
</body>
</htmb
~
'Ibis Would produce following result:
Note• u _,__ S 'labl ,·n CLASSPATH and try to access above ]SP.
• 0 ·uuu: tudents.class ava, e
332 Advanced Java Programming

l. How JSP is different from Servlets? Explain advanta ges of JSP over
0ther server side
.
scriptin g languag es.

2. Explain JSP access model with suitable diagram.

What is meant by implicit objects? Explain differen t implicit objects provide d by


]SP
3.
briefly.

4. Write a JSP script that reads value from a textbox and identifie s whethe r it is odd or even.

5. List the different tags availabl e in JSP. Explain each of the tag with brief description and
syntax.

6. What is meant by scope of objects? Explain differen t scopes of JSP objects briefly with
example .

7. Write a JSP script that that demons trates use of select and insert operatio ns with suitable
example .

8. How JSP can be used for enabling and .disbling session? Explain with suitable JSP script.
. . - -

9. How exceptions can be handled in JSP scripts? Explain with suitable JSP script.

10. What is meant by Java Bean? How it c_a n be used in JSP scripts? Explain with suitable
example . ·

□□□

. . ' ... _

You might also like