Professional Documents
Culture Documents
- ~--
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
¾
()f
a
~ l!t,~
II
~I~
:, ~
~essit\ ~ }
Request
processing
phase
expressions or scriptlets.
316 AdvancedJava Programming
Example
<%!
private int counter = 0 ;
private String getAccount( int accountNo) ;
%>
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
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
scop e. (~ea
<tit
//Example of JSP Session Scope . . .
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
<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
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
'"\.,
//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 - ., ;_
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'
.. 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>
~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>
~)
£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 - ~
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" />
l. How JSP is different from Servlets? Explain advanta ges of JSP over
0ther server side
.
scriptin g languag es.
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 . ·
□□□
. . ' ... _