rl - perisastry.com · 592 programmiig in java nequest: tl:rr:r.r:t: :l!;,: r...

9
< servlet _ class >Authenticate</servlet _ class > </servlet> < servlet-mapping> < servlet - name>authenticate</servlet _ name> <ur1 - pattenn >/auth/authenticate</ur1 _ pattenn > < ui.ebr"?q > Vsenvlet -maPPing> +="f-*.#' -.,<servlet> < senvlet - name>showAuthenticatlonDetails< /servlet _ name> <servlet - class >ShowAuthenticationDetalls<,/servlet _ class > </servlet> < servlet -mapping> < servlet _ name>showAuthenticationDetails</servlet _ name> <ur1 -pattern>/auth/showAuthenticate</ur1 _ pattern> </servlet -mapping> <servlet> < servlet _ name>showmessage</servlet _ name> < servlet - class>ShowMessage</servlet _ class > </servlet> < servlet -mapping> < servlet - name>showmessage</servlet _ name> < urI - pattern >,/auth/showmessage</u11 _ pattenn> </servlet -mapping> <servlet> < servlet - name>signout</servlet _ name> < servlet - cl.ass >Sign0ut<,/senvlet _ clas s> <,/senvlet> < servlet-mapping> < servlet - name >s ignout<,/servlet - name> <u11 -pattern>/auth/signout</ur1 - pattern > <fi1ter> <fi lten - name>noCacheFilter</fi lter- name> <fi1ter - class >NoCacheFilter< /fi1ter - c1a ss > </filter> <fi1ter-mapping> <fi lter- name>noCacheFilter</fi lter- name> < ur1 - pattern> / + < / url - pattenn> </fi1ten-mapping> <fi}ter> <filter- <fi}ter- </fi1ter> <fi1ter-r <filte* <ur1-g <u11-p </fiIter< </web-4 16.5 lNTROIrll Java sen eml)edfu code rl exeoset an equiv. using JII conteilfi advaffit JSPd delimlr andiBg recd casettl' TheLIR| t1/ Fig.16.21 #iPl

Upload: others

Post on 25-Mar-2021

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: rl - perisastry.com · 592 Programmiig in Java nequest: tl:rr:r.r:t: :l!;,: r .i::rues"p.6Bfqe..':: application session pageContext The above code uses out object which is a predefined

< servlet _ class >Authenticate</servlet _ class >

</servlet>

< servlet-mapping>< servlet - name>authenticate</servlet _ name><ur1 - pattenn >/auth/authenticate</ur1 _ pattenn >

< ui.ebr"?q > Vsenvlet -maPPing>

+="f-*.#'-.,<servlet>

< senvlet - name>showAuthenticatlonDetails< /servlet _ name><servlet - class >ShowAuthenticationDetalls<,/servlet _ class >

</servlet>< servlet -mapping>

< servlet _ name>showAuthenticationDetails</servlet _ name><ur1 -pattern>/auth/showAuthenticate</ur1 _ pattern>

</servlet -mapping>

<servlet>< servlet _ name>showmessage</servlet _ name>< servlet - class>ShowMessage</servlet _ class >

</servlet>

< servlet -mapping>< servlet - name>showmessage</servlet _ name>< urI - pattern >,/auth/showmessage</u11 _ pattenn>

</servlet -mapping>

<servlet>< servlet - name>signout</servlet _ name>< servlet - cl.ass >Sign0ut<,/senvlet _ clas s>

<,/senvlet>

< servlet-mapping>< servlet - name >s ignout<,/servlet - name><u11 -pattern>/auth/signout</ur1 - pattern >

<fi1ter><fi lten - name>noCacheFilter</fi lter- name><fi1ter - class >NoCacheFilter< /fi1ter - c1a ss >

</filter>

<fi1ter-mapping><fi lter- name>noCacheFilter</fi lter- name>< ur1 - pattern> / + < / url - pattenn>

</fi1ten-mapping>

<fi}ter><filter-<fi}ter-

</fi1ter>

<fi1ter-r<filte*<ur1-g<u11-p

</fiIter<</web-4

16.5 lNTROIrll

Java seneml)edfucode rlexeosetan equiv.

using JIIconteilfiadvaffit

JSPddelimlrandiBgrecdcasettl'TheLIR|

t1/

Fig.16.21 #iPl

Page 2: rl - perisastry.com · 592 Programmiig in Java nequest: tl:rr:r.r:t: :l!;,: r .i::rues"p.6Bfqe..':: application session pageContext The above code uses out object which is a predefined

I o t * duoiti;d.ii:it i'

<fiIter>- " .ir.". - n,me>checkLoginF ilter< /fi"::::i:"'<filter-class>ntread}logingFilten</fiIter.c1as5>

</fiIter>

<fi1ter-maPPing>- " .ii.". - i'me>checkLoginF ilten< /fir,te1 - nlme>

.rii - p"at""n>/auth/ shor'rmes sage< /url - pattern>

<ur1 - pattern>/auth/ showAuthenticate< /ur1 - pattern >

</fiIter -maPPing>

</web-aPP>

16.5 INTRODUCTTON TO JAVA SERVER PAGES

Javaserverpages(JSP),incontrasttoservlets,isbasicallyapagethatcontainsJavacodeembedded *r#;h;, iags. Servlet i, "-,,'" ,'"Sram wlr=e htmllags are

1mf=e.aded in Java

code or html responses are *.o"ru,.u ti'ffiiu'"u' lsp mes have an extension '3sp and they

execute within alSP contain.r rr".tii'lit'3 *tt'"*er lris container translates the ' jsp into

u, .q.,i,,I,nt;*,;. il"tr,o *o,a,, l"sp i, u ,"*r"t i* tt," uu"tg'ound, The basic purpose of

using JSp * ui* 'u-" u. ,t u, or r#"r,1."., ," process. the reque-st and Benerate dynamic web

contenr for the client. The obvious ;il;'* arises is wtty is JSP required? Does it offer an

advantage over a servlet?

JSPoffersasignificantadvalageoveraservlet.JSPisembeddedinhtmlwithsomespecialdetimiterswhichiookliketags.trnt;;;t;;il T:I:f*t*aservletvourBedtolearnJava

and its progru.*irrg sryles *ht"l-I i. ;;;itt. .utt in JSP' Moreover' JSP pages are automatically

recompitea wtren r"luired, which ir';;th" ;te witt' se'utets" Servlets have to be recompiled in

case they are changed. So as soon a, ,",,"a.,t, yoor lsr page, changes made to it are reflected'

The URlp/apping requirea i, *"u.J*ini" n" servlets is not required in the case of JSP'

J 16.s.1 Jspltlg!rygg .r r-.:--r-i+/\ rsnserviceg, an(

]1,;im" *m *"t1:3'' jsprnito'-5g3'Y-'"o' and

#il:*:ffi,xffiffi""i sprnit ( ) metf'oa iJsimitarto the iniit I method of a servlet or an applet'

It is called ""il;; ardng the entire iirr"ytt" and is used to initialize

variables unA ot3"'tt tftat cair be used tbroughout the JSP'

-jspservicetl metnoa is automatically called and is used to generate

rcEo,nse 6#el"*r, This method delegates request tojlgg5l| or

: ^&9

methodof ageneratedsewlet'

i isoDesuovo;";;;;tautomaticallycalledwhentheJSPpageterminates<--L-----:1{- r n -- ^l^^.^;-a +lra re(rirrrces held by the JSP'

,,r.1"::l : :' r"," noffiT*,;;u i"' creaning the resources herd bv the rsp'

Page 3: rl - perisastry.com · 592 Programmiig in Java nequest: tl:rr:r.r:t: :l!;,: r .i::rues"p.6Bfqe..':: application session pageContext The above code uses out object which is a predefined

; ffi :'.F.rbWm*tn g i n:,1 av o

16.5.2 Steps in JSP Page ExecutionThe following steps are followed during execution of a JSP page:

o user sends request for a JSP page to the webserver through a web browser.. Webserver accepts the request and passes it to the JSp container.r If the JSP file has been called for the first time then the JSP container parses the' converts it into a servlet, and compiles the servlet.

r The container loads the servtet class by instantiating it and calling the isprnitll_jspService( ) methods of the JSP life cycle.

. If JSP page is called for second or nth time, the container checks whether the JSPis newer than its class and if yes, the translation of JSP to servlet takes place andit is compiled, instantiated, and loaded again; otherwise the most updated ialready running.

. The generated HTML is displayed on the user's web browser.

16.5.3 JSP ElementsJSP has three types of components namely

o Directives . Expression, scriptlets, and declarations o Actions

Directives

Directives are specific instructions to the container informing it how to process the JSp pagaThere pre three types ofdirectives in JSP: page, include, and taglib. The syntax for addiqdirective to a JSP page is

<@ directive-name attribute-name="va1ue" ..., >

(a) page, as the name suggests, is used to speciff attributes for the page, for example, whdclasses to be imported for the servlet or what will be the content type for the generatedresponses by the servlet and so on. Some of the attributes is provided in Table 16.8.

Table 16.8 Attributes of the Page Directive

Ifyanin yourJ

or its xn

(b) inclrshon

or its xu

(c) tagli

or its

Expres

To ermexpressi

Note drThe I

is adder

<I ='the clis

ntryS"FIf a nrnare gnc

exampl

out-l

d=rn

out-i

out-,

foro{rt-

%>

Page 4: rl - perisastry.com · 592 Programmiig in Java nequest: tl:rr:r.r:t: :l!;,: r .i::rues"p.6Bfqe..':: application session pageContext The above code uses out object which is a predefined

lntrodaction to Advanced Jawa

IfyouwanttouseDateclassinyourJSPpageyouwillhavetoimportthejava'utilpackagein you. JSP Page as shown below:

<T@ Page imP#t="iava' util' *" %>

or its xml equivalent tag can also be used as shown below:

<jsp:dlrective'page import ="java'uti1'*" />

(b) include directive is used to add the contents of another file into a JSP page' It is used as

shown below:

<%@ include fiIe="includedirective'htm1" %>

or its xml equivalent tag can also be used as shown below:

<jsp:dinective'include fiIe="includedirective'htm}" />

(c) tagrib directive is used while creating user defined tags' It can be used as:

<7"@ taglib uri=" " Prefix="" I

or its xml equivalent can also be used as shown below:

xmlns:Prefix="tag libnarY ur1"

ExPressions

To execute Java expressions like (a+b*c), we make use of {sP;loression

syntax' The result of

expression is air""iry .rntedded in the ltml

page. Expressions are enclosed within <%= "' %> '

Note that "*pr",'io* "t" '* terminated with;lsemicolonI?] !*u*Ott'

The result of 2 + 2 - 2 is <x= (2+2-2) %> ' The expression in <% %> is evaluated and answer

is added to the html'

<%=,,IntroductiontoTSP,,%>.Thestring..IntroductiontoJSP,,isaddedtothehtmlsenttothe client. It is similar to the out ' prinrn( ) statement'

ScriptletsIf a number of statements have to be executed, scriptlets is the right place' Note that scriPtlets

are enclosed within ,r, ,", d"ii^iters and ,..i"oior. are used to terminate statements' For

example,

<%

out.println("This following text is visibtre through a Scriptlet <bt'");

d=new Dateo t

;;;';;;;;ti'0"' rhe current Date is: "+d+"<br>");

out.println("<br><b> A Sample for Loop</b"bt> ");

for (int i=0;i<5;i++)

out.printtn("Iteration No :" +i+"<br>");

%>

591.gt"

.:Er"

Page 5: rl - perisastry.com · 592 Programmiig in Java nequest: tl:rr:r.r:t: :l!;,: r .i::rues"p.6Bfqe..':: application session pageContext The above code uses out object which is a predefined

592 Programmiig in Java

nequest: tl:rr:r.r:t: :l!;,: r .i:

:rues"p.6Bfqe..'::

application

session

pageContext

The above code uses out object which is a predefined object in JSp. println and print mmethods of this out object which are responsible for sending rr.i"g, io the client. In other*cmmmth:^tf'*t passed as parameter values in print methods areaddeJ to the generated html. Tab[e16.9 lists all implicit objects.

Table 16.9 tmpticit Objects in JSp

<jsp: useBean>

<j sp: include>

<j sp: forward>

<j sp: getProper!

<js,p: setPropertl

[!!!!,wewiud

16.5.4 F

The onll'sholrl iathe \\EB.

After pi

follogins

ht:

Let u-i fqdJ spEleme-

declaradsmost r-rf fr

X*u'*$vap iht'*6. a#=*6t'*e..fu{1tg;,..:rpr,,:r:q+re t;.,i:* r.

ActionsActions are JSP elements that use, create or modifu other objects and they follow strict XMLsyntax. Table l6.l0lists the JSp actions.

&

t-

Declarations

If you wish to declare any item it should be done here. Note that declarations are enclosedwithin <%l %> ' Avariable can be declared in scriptlet as well. The difference between declaringa variable in scriptlet and through declarations ls trrat att the scriptlet code goes into the servicemethod of the JSP page (when it is converted to servlets) and ail declarations reside on top ofthe service method within the class. semicolons are allowed while declaring a variable or objectin a JSP page. For example,

<%! Date d;%>

Page 6: rl - perisastry.com · 592 Programmiig in Java nequest: tl:rr:r.r:t: :l!;,: r .i::rues"p.6Bfqe..':: application session pageContext The above code uses out object which is a predefined

Introduction to Ad;vanced "Iav*-

'593

(jsP:::use8€an>. .

<jsp: include>

<jsP:for5aqd> '. ':

<j sP: getProPertY>

i <jspisetProPentYT

Table 16.10 Actions in JSP

To set proPerties ofa bean'

T.o'usEb-cgns,tn,J$.Erage ri ":'.:.r.;i:rr,'.', i' . ,, .,,,,.Similar to include directive'

'f,,f"*aa.there[uesrts'$g o,lsPpageor ser'v-let'

To get properties of a bean'

ElEIl.wc *itt .ois*rss

si:me actioni'later wrren we discuss .Java b'eans,

Apache software foundation

16.5.4 Placing your JSP in the Webserver

TheonlythingthatyouneedtodoistoplaceyourJSPaccordingtothedirectoryStructureshown in Fig. 16.22. Asis evident from the figure, all html and jsp.files are placed parallel to

the wEB-INF directory within the root directoiy oithe web application (i'e', login in our case)'

AfterplacingvorrrlipiriteappropriatedirectorystructureasshowninFig' 16'23,typethe

foito**g in the address bar to see the output as in Fig' 16'23'

http : //localhost : 8080/login/JspElements' j sp

Let us put all that we have discussed into practice and create a simple JSP page' We will call it

]spElements.:sp. wewillbecreatingahtmltabletodisplaydirectives,expressions,Scriptlets,

declarations, actions, and important implicit objects in a single JSP page' and try to show how

most of them can be used in a JSP page'

IhrbhG

dd

Tomcat 7.0

1ib

webapPs

t^lEB- INF

JspElements ' jsP

includedi.rective. html

[LFig.16.22 Directory Structure for lspElements' jsp

Page 7: rl - perisastry.com · 592 Programmiig in Java nequest: tl:rr:r.r:t: :l!;,: r .i::rues"p.6Bfqe..':: application session pageContext The above code uses out object which is a predefined

*,iY,:j#..P,t;t;11.,7!!:;ul

<Html><Head >

<title> lntroduction to ISP </title></Head>.Loayr.tz, Three components of JSP </h2>

<o1><ti> Dinectives</Ii><1i> Expression, scriptlets and declarations</1i><1i> Actions</li>

< /o1>npr"i t"", this ISP contains implicit objects'

<table border=1><tr><td><h3> Directives </h3></td>

<td><h3> ExPressions </h3></td><td><h3> ScriPtlets </h3></td><td><h3> Declarations </h3>

</td><td><h3> Actions </h3></td><td><h3> Some Important' Implicit Objects </h3></td></tr>

ll!]rn""" are three types of directives:<br><em>page' include and tagrib'</

em><br>The +offowing l!*i it i"n""ated. using a include directive' <br>

.;;;.%@ include filel"includedirective'htmI" %></em>

.Z@ p"i" import="java'util'*" %>

</td>.iJ, rn" result of 2+2-2 ls : <%= (2+2-2) %><br>---.2=

"fnt.oduction to ISP Elements" %>

l{ll"t a numben or statements have t9 P"."'ftYlld:::i::t:::'is the

right p1ace. <ur>rne-ioii"'i'g scniptlet includes a print statement'

statement to instantiate a Daie object and'a for 1oop.

<!-- Starting of scriPtlet -->

<% r !L-^..^L^€-hi

out.println(..Thisfotlowingtextisvisible.throughaScriptlet<br>.,);d=new Dateo;out.println("<br> The Current Date is: "+d+"<br>");

out.println("<br><b> A Sample for Loop</b><br> ");for (int i=0;i<5;i++)out.printfn(;'It"t'tion No :" +i+"<br>");

%>

<l-- Ending of ScriPtlet --></td><td>

If you wish to declane anY itemherl which is instantiated in a

<%lDete di%>

</td><td >

&It; jsP: useBean&gt; <br>

it shoutd be done here'<br> we are declaring a Date

scriptlet.

&lt;jsP:inclr&It; jsP:forr&lt; jsP:getfir&It; jsP: setPr<ltd><td>request<br>resPonsecF'lsession<br>aPPlicatiordout(br><ltd></tr></table><h5> ISTE: I

<em>

ISP contailscniPtletslava code Imethod is r

</em></body>

. </Html>

Output

Page 8: rl - perisastry.com · 592 Programmiig in Java nequest: tl:rr:r.r:t: :l!;,: r .i::rues"p.6Bfqe..':: application session pageContext The above code uses out object which is a predefined

Introduction to Advanced Java 595

&tt; j sP: include&gt; <br>

&It; j sP: forward&gt; <br>

&It; jsP: getProPertY&gt; <br>

&1t; jsP: setProperty&gt; <br>

</td><td >

request< br >

res ponse< br>sess ion<br>applic ation< br >

out< br >

</td>< /tr>< /tab1e >

<h5> N0TE:. </h5><em>

]SPcontainercreatesaservletautomaticallyforeveny]SPpage.TheexpreSSion,scriptlets and html found in the lsPpage i's used by ISP container to create the

Java code for the automatica:.ry generated--isps""ui."O method of the servlet' This

method is analogous to senviceO method of the servlets

</ em>

< / bodY>

< /Html >

Output

Fig. 16.23 Snapshot of the Browser Showing the JspElements' jsp Page

ExPlanation

rn" uUor. "-*n* .t.urty shows Java code being^ file is not html' The meaning of all tais used in the

embeddedinhtrnlfi1..,]'i#il;iu.--"*r","?examp1eisshowninTableI6.l1.

i a Date

Page 9: rl - perisastry.com · 592 Programmiig in Java nequest: tl:rr:r.r:t: :l!;,: r .i::rues"p.6Bfqe..':: application session pageContext The above code uses out object which is a predefined

Table 16.11 Htmt and JSp TagsHtmI and {!P}Ss'used in examptes D:€$criptionHtml

Head

titlebodl

ol

-:I1

table

Roor tag of html Iite.

Header: of'"rhe atml.fi le,

Used for speci$,ing title ofthe page. It is used u,rth:r ::Disptayable porrion of ine ntmt.

Used for creating ordered (i.e., numbered) list (see .,- :Used lor creating list items olrhe ordered (ol) or uir,,::.(ul ) isee code).

Used for depicting dataand columns.

Rcrv creation afa taUt;,

a tabular format. A

is,done usingftis tag"

Columa creation of a table is done using

Used"for

Similar to

Used for displaying less than sign in

tag.

<).

ht,:.h2,,;'.h3 j,] h4,

<2"@inciude fiIehtntl " %>

-<Iq@, p-age.',iillront :.r .ljava, utij;,*i ,%>

<.Y= (Z+Z-Z) %><br>

<%;j,I.:l In:tn*duc t ion !.o :SR, E 1ements,", %>, :' , .: ., :a : r . l :. ,. :., ,. . ,

<%

followi.ng text isScniptlet<br>");

Used for displaying greater than sign in html (i.e., >)

Uie* Ar.heaarugs,:hf ii:rt e biggesf and h6 is thesrxailesr.JSP include directive is used to incluclc Ihe conren::includedirective.html flle within the JspElements.page.

J$P page d#ee&.rs &ea to impor uti 1 pasftagsl.,:JSP expression is used to evaluate the expression and sendresulr to the client embedded in the generated html.

lii,:l,L:::": li|s-.! tose ir:rt sdaihe, etob"dd..ur the generared html.JSP scriptlei is used to depict a number of statement can :;embedded iu html. predeflned object ot rt is used in this scriprieto write strings to the client. The output of all these statemenr i.embedded in the generated html sent to clienr.

out. pnintln ( ',Thisvisible through a

d=new Dateo;out,pnintln("<bn>"+d+"<br>" );out.println('.<br><b> A Sample fonLoop</b><bn> ");

fon (int i-0;1<S;i++)out.println(,. Itenation No :,,

+1+"<$n>"); ly

.h6. .": : ,, ,.r

" includedirective.

The Cument Date