Sei sulla pagina 1di 49

13/05/2014

1
JavaServerPages
Aprettierformof
servlet!
1
Servlets
SunexpectedServletstoreplaceCGI
Basically
Theydidn't.
Theywerepopularwithbanks,insurancecompanies,
andotherhighendapplications
Butwereunappealingtoamateurdevelopers
SmallISPsandwebhostingcompaniesunwillingto
deployJavaserverside
2
ASP&PHP
Microsoft'sActiveServerPagetechnology
provedmorepopular thoughlimitedto
MicrosoftIISserver
PHPcamefromnowhereandeasilyoutgrew
servlets innumberofsites,ifnot
importanceofsites
3
ASP&PHPadvantage
Amateurdevelopersmostlydeveloping
webapps withlotsofmarkupandlittle
processingcode
ComposeapageasHTML
Embedlittlescrapsofcodethatsupplydynamic
content
4
Sun'sresponse
JavaServerPages
BasicallyaHTMLdocument
Embedded
Directives
Actions
Scriptlets
Theseembeddedelementsinvokeprocessing
ReturndatastringsthatgetembeddedintotheHTML
5
JSP&Servlets
JSPisaservlettechnology
JSPpage"compiledintoaservlet"beforeuse.
Oftencombinedwithotherservlets
Servletsdothe"heavylifting",resultsleftinshared
datastructures
ServletforwardscontroltoJSPpage
JSPpageaddsthe"pretties
Dataextractedfromshareddatastructuresandembeddedin
amongstthepretties
Ascommentedpreviously,servlet/JSPcombinationissimilartothemorerecentlydevised
PHPscript/Smartycombination
6
13/05/2014
2
Beans
Typically:
Servlet,alongwithapplicationspecificclasses
implementingbusinesslogic,performtheoperations
requiredbythewebrequest
Adddatatopersistentstore
Retrieveotherdata
Servletpackagestheretrieveddataandreportsinto
structlikeclasses,andforwardsthesetoaJSPfordisplay
Thosestructlikeclassesmustcomplywithcertain
namingconventionsiftheyaretobeusedintheJSPs
TheseconventionsinventedearlierwithJavaBeans
7
Beans
LittlelumpsofpureconcentratedJavacoffee
Beanterminologyhadbeenintroducedinto
Javaearlier.
SunenviedMicrosoftssuccesswithGUIbuilder
wizardsandwantedtoprovideJavawithfeatures
thatwouldallowconstructionofsimilar
sophisticatedGUIbuilders.
Sunadded
Javareflection theabilityforcodeatruntimeto
examinetheinterfaceofaclassandinvokethemethodsof
aninstanceofthatclass
Beannamingconventions primarilyforaccessor and
mutator functions(gettersandsetters)
AgainSunbuiltenablingtechnologyandexpectedotherstobuildthewizardsthatusedit.
8
Beanclasses
Importanttofollownamingconventionsfor
anylittlestructlikeclassesusedtopassdata
aroundamongstservletsandJSPs.
Nottoohard NetBeans knowstheconventions
willhelpyouwhenyoucreatetheclasses
Youspecifythedatamembers
YouletNetBeans generatethegettersandsetterswith
appropriateBeanconventionnames
9
Theadventuresfirst,
explanationstaketoomuchtime
10
TheGuru
Abetterclassof
HelloWorld
Program
11
TheGuruisafortunecookieprogram.
Itmakesarandomchoicefromacollectionof
aphorismsandprintsthisasitsadvice.
Aphorism:awiseorwittysaying
12
13/05/2014
3
Advice.jsp&Guru.java
JSP
Usingscriptlets smallfragmentsofJavausedto
invokeoperationsofanobject
AsimplesemibeanclassGuru
Onlyonemethoddefined StringenlightenMe()
NoXMLdeploymentfileneeded(well,notinsimple
cases)
13
Advice.jsp
14
Advice.jsp
Pagedirectives
Theseprovideinformationtothecodegeneratorthat
willcreateaworkingservletfromtheJSPpage
Codegeneratorrunswhenthewebappisdeployed,creates
anewservlet itisthisservletthatactuallyruns
Twopagedirectiveshere
contentType specifyreturnpagetypeandcharacter
encoding
import specifyanyimportdirectivesthatwillhaveto
beputintothegeneratedservlet;hereneedto
explicitlysaythatwillbeusingaclassfromthe
mystuff packagedeployedwiththisJSP
15
MostlystandardHTMLmarkup
MostofaJSPwillbestandardHTML
HTMLtags
Fixedcontenttext
(JSPdocumentationusesthetermtemplatetext)
JSPshouldbeeditableinyourfavouriteHTML
editor
16
Scriptletcode
Scriptlet code
EmbeddedcodeinthefashionofASPandPHP
Javacode thoughthespecificationdidallowforotherlanguagestobeused!
Scriptlet code uhm!
AtemporaryexpedientwhenJSPs firstintroduced
Rarelyusedlater(aftertheintroductionofusefulsetsofactiontags)
Usenow?
Onlyforquickprototyping!
Whydisfavoured?
CodeinamongstHTML
alwaysatriskfromenthusiasticwebdesignerswantingtoimprove
appearanceofpage
Mixingofverydifferentgenres
DeclarativestyleHTMLmarkup
Proceduralstylecode
17
Scriptingelements
Scriptlet
<%
someJavacode
%>
Thecodeisdroppedintothegeneratedservlet.
Canincludevariabledeclarations theyaredefinedaslocal
variablesoftheservicefunction.
Expression
<%=Javaexpression %>
getstranslatedintosomethinglikeout.print(Javaexpression )
Declarations

18
13/05/2014
4
Guruclass
Aninstanceoftherandomnumbergenerator
Acollectionofaphorisms
Afunctionthatreturnsarandomlyselectedaphorism
19
Itworks!
20
Buthow?
packageorg.apache.jsp;
importjavax.servlet.*;
importjavax.servlet.http.*;
importjavax.servlet.jsp.*;
importmystuff.Guru;
publicfinalclassAdvice_jsp extendsorg.apache.jasper.runtime.HttpJspBase
implementsorg.apache.jasper.runtime.JspSourceDependent {
privatestaticfinalJspFactory _jspxFactory =JspFactory.getDefaultFactory();
privatestaticjava.util.List<String>_jspx_dependants;
privateorg.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
publicjava.util.List<String>getDependants(){ return_jspx_dependants;}
publicvoid_jspService(HttpServletRequest request,HttpServletResponse response)
throwsjava.io.IOException,ServletException {

}
}
Ageneratedservlet
21
Servicemethod
publicvoid_jspService(HttpServletRequest request,HttpServletResponse response)
throwsjava.io.IOException,ServletException {
PageContext pageContext =null;
HttpSession session=null;
ServletContext application=null;
ServletConfig config =null;
JspWriter out=null;
Objectpage=this;
JspWriter _jspx_out =null;
PageContext _jspx_page_context =null;
try{

}
catch(Throwable t){}
finally{}
}
Initializehostofvariables
Dothework
22
Doingthework
try{
response.setContentType("text/html;charset=UTF8");
response.setHeader("XPoweredBy","JSP/2.2");
pageContext =_jspxFactory.getPageContext(this,request,response,
null,true,8192,true);
_jspx_page_context =pageContext;
application=pageContext.getServletContext();
config =pageContext.getServletConfig();
session=pageContext.getSession();
out=pageContext.getOut();
_jspx_out =out;
_jspx_resourceInjector =(org.glassfish.jsp.api.ResourceInjector)
application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");

out.write("\n");
}
Justalittlemoreinitialization
Nowstartoutputtingtheresponsepage
23
Doingthework
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<!DOCTYPEhtml>\n");
out.write("<html>\n");
out.write(" <head>\n");
out.write(" <meta httpequiv=\"ContentType\" content=\"text/html; charset=UTF8\">\n");
out.write(" <title>The Guruconfersadvice</title>\n");
out.write(" </head>\n");
out.write(" <body>\n");
out.write(" <h1align=center>\n");
out.write(" <fontcolor=red>\n");
out.write(" Todaysadvice fromthe Guru\n");
out.write(" </font>\n");
out.write(" </h1>\n");
out.write(" ");
GurutheGuru =newGuru();
out.write("\n");
out.write(" <p>\n");
out.write(" ");
out.print(theGuru.enlightenMe());
out.write("\n");
out.write(" </body>\n");
out.write("</html>\n");
out.write("\n");
out.write("\n");
Oooh lookwhatithasdone!
Itswrittenallthosetiresomeout.print()statements
Andithasembeddedthescriptlet codeintothebodyof
theservicemethod
write/print??Ifargumentstringisnull,printprintsnull,
butwritehasanexception 24
13/05/2014
5
Justabunchofout.write statements
Andreally,thatisallthereistoJSPs.
Thecodegeneratorwritesallthoseoutput
statementsthatweresotiresomewhenyou
workedwithservletsdirectly.
25
Sunsviewofscriptlet code
ProceduralcodeinamongstthedeclarativeHTML
notthebrightestidea(eventhoughitsworkingfor
PHPandASP)
Couldntsomemoredeclarativestylebeadopted.
Sundecidedtoaddactiontags
LikeXMLmarkup
Action~verbe.g.createobject,printvalue,
Parameters~adverbsandadjectives
Referencetoaclassinstance,~noun,thethingbeing
manipulated
26
Sunsapproach
1. Buildanenablingtechnology
2. Providealimitedproofofconceptimplementation
3. Leaveittootherstocreateworkinginstances
Enablingtechnology
Taglibraries
Limitedproofofconcept
jsp:taglibrary
27
Actiontagstyle
SlightmodificationoftheGuruclassisneeded
CanthenbuildaversionoftheAdvice
applicationusingSunsjsp:taglibrary
Theresultsmaynotseemthatimpressive
Thedifferenceinclarityofthedeclarativeaction
tagapproachonlyreallyshowsinlargerexamples
28
ActiontagJSPpage
jsp:taglibrary
Providedbydefault,dontneedtoconfigureor
installanything
29
JSPpagewithjsp:tag
jsp:useBean
Createinstanceofspecifiedclass
Giveinstanceanidentifier
jsp:getProperty
Get,asaString,thevalueofaspecifiedproperty
ofachosenobject
Property whichproperty
Name whichobject
IneverdidfindwhyitsidinuseBean butnameingetProperty 30
13/05/2014
6
ModifiedGuruclass
31
Beannamingconventions
jsp:getProperty
enlightenment
Objectmusthavea
getEnlightenment()method
32
Again howdiditwork?
Ageneratedservlet
ThetranslatorthatcreatesservletsfromJSPs
withscriptlet codesimplyembedsthatcodein
theservicemethodofthegeneratedservlet.
Tags?
Theyareabitlikemacros
Thetranslatorcanexpandthemoutto
appropriateJava:
33
Service()
useBean i.e.createit,addittopage
getProperty
Thesegenerated files arefound in places like:
C:\ProgramFiles\glassfish3.1.1\glassfish\domains\domain1\generated\jsp\Guru2\org\apache\jsp
34
Defineyourowntagclass
Sundidntexpectyoutousejustthe
limitedjsp:taglibrary
35
Definingowntags
Sunsjsp:taglibrarywasquitelimited
Createinstanceofclass
Usegetters/settertochangedatamembers
Youneededscriptlet codetodoanythingmoreelaborate
withclassinstances suchascallmemberfunctionsother
thangettersandsetters
Dealwithforwardandinclude samefacilitiesas
alreadyexistedinservlets
Hopingthatotherswoulddevelopmore
sophisticateduses,Sunprovidedsomebase
classesthatcouldbeusedtodefineowntag
classes
36
13/05/2014
7
Yourowncustomactionelements
Anactionelement(tag)appearsinaJSPas
somethinglike
<alib:thing1parameters,moreparameters>
Blockoftext
</alib:thing1>
Thisblockismappedintocodeinthegeneratedservletthat
is(conceptually)alongthelines
import alib.*;

alib.Thing1 t001 = new alib.Thing1(params);


t001.getStarted();
t001.handleBodyText(Block of text);
t001.finishUp();
Inpractice, thegeneratedcodeisalot moresophisticatedandcomplex.
37
Yourownactions(tags)
Youhavetodefineyouralibtaglibrary(~Javapackageof
tagclasses)
Youhavetodefineclassesthatdowhateverspecialprocessing
yourrequire.
Theseclassesmustextendvariousbasetagclassesthatareprovided
aspartoftheJSPsystem.
Typically,processingoccursmostlyatendtag,
theregenerateblockofHTMLtextderivedfrominformation
inparametersandbodydata.
Laterreleaseofservlettechnologyincludedawayofcreatingcustomtagsusinga
declarativestyleratherthanbycodingJavaclasses.(Translatorcreatestheclass
fromthesupplieddeclarations.)Supposedly,thisstyleamenabletowebdesigners
withnoprogrammingexperience.
38
Deploymentofowntags
Moderatelycomplex
Buildyourtaglibrarywithyourtagclasses
Createadescriptivedeploymentdocument
Associatestagswithclasses
Specifiestheparameterstheytake(andwhetherthese
aremandatory)
Placedescriptivedocumentinappropriatesub
directoryofWEBINF
Addtaglib pagedirectivestoJSPs
39
Classes
Twobaseclassesininitialrelease(othersaddedlater)
Tag
Yousimplywanttohaveablockofcodeexecutedwithparameter
datapassedinfromtheJSPpage
BodyTag
Thiswasforconstructingthingslikeloopsusingmakup tags
Tagstart Ihavethiscollectionofrecordsretrievedfromadatabase,
processthemonebyone
Body HereiswhatIwantyoutodowitheachone:composearowina
HTMLtableinsertingdatamembersfromrecordlikethis
Endtag Alldone,goaheadandoutputthetable
CodingofaBodyTag wasalittleelaborate
Youhadtomanipulateatemporaryoutputbufferthatyourcodefilledin
(e.g.abuffertoholdtextofthatHTMLtable)
Atendtag,youhadtoarrangefortexttobecopiedfromyourbufferinto
JSPpage
40
Mysimpleexample:DateStamper
Ivedecidedthatitwouldbeusefultohaveatagthat
couldaddadatestamptoageneratedpage.
ItshouldappearinJSPasatagthatcontainsa
comment
ItshouldgeneratetextforthefinalHTMLpage
41
Mysimpleexample:DateStamper
ThisversionisusingSimpleTagSupportasabaseclass;thiswasintroducedlater
andslightlysimplifiesthecodingcomparedwithoriginalTagbaseclass.
42
13/05/2014
8
Taglib descriptor
ThedeploymentcomponentthattranslatesJSPs
intoservletsmustsomehowdiscovertherelation
between
<mytag:DateStamper
andtheclassthatIdefinedinsomepackage.
Itmustalsodiscoverthenamesofthe
parameters(likemycommentparameter)and
whetherthesearemandatoryoroptional
(commentismandatory)
ThisinformationsuppliedinaXMLdeployment
file thetaglibrarydescriptorfile
43
mytag.tld
Thisisthemytag libraryand
hereareitstags(onlyone
DateStamper).
TheDateStamper classis
definedinpackagemytags;
itdoesntprocessanybody
text;itdoeshaveonerequired
parameteroftypeString
namedcomment.
44
NetBeans assists
Youusedtohavetocomposethetaglibrary
descriptor.
NowNetBeans offersTagHandlerasoneof
thefiletypesthatyoucanaddtoawebapp
ItisjustaJavaclass,butNetBeans willsetthe
baseclassandaddtheappropriatemarkuptothe
tld file.
45
Referencingyourtaglibrary
YourJSPrequiresataglib directivetoloadatag
library(equivalenttoaincludedirectiveforabean
class)
theprojecthastohavethecorrectarrangementof
filesanddirectories
46
Sunsapproachmaybenotthebest
jsp:taglibrary
Toolimited
Othersdeveloperscreateusefullibraries
Butlotsofrivalincompatibletaglibrarieseachattempting
todosimilarwork
Manipulatebeans
Handleselectionanditeration
E.g.whenprintingaHTMLtablepresentationofacollectionofdataitems
SQL
Doyourdatapersistenceusingmarkuptags!?!
Bizarreandhighlyspecializedcodingskillsforwritingtag
libraryclasses
47
Buttagsdoevolvetosomethinguseful
Bestofbreedcompetitionamongsttaglibraries
strutsfromtheApachegroup
Firstreallygood,widelyacceptedtaglibrary~2000
JavaStandardTagLibrary(JSTL)~2003
ThroughJavacommunityprocess
Combineexperiencefromstrutsandothergoodtag
libraries
Defineanewstandard(muchsuperiortojsp:library)
thetaglibrarythatshouldhavebeeninfirstrelease!
48
13/05/2014
9
Microsoftdiditbetter
MicrosoftreviewedJSPanditsearlytaglibrarieswhen
developingideasfordotNet
Followedthesamebasicidea
UseXMLliketagstodefinecomponentswithassociated
codewithinconventionalHTML
Diditbetter
GUIeditorstyledevelopmentofpages
Componentframework
AddaHTML<select>inapage;codegeneratorcreatesinstanceofa.NET
SelectionclassthathasacollectionofOptionobjectsanda(setof)
integer(s)identifyingselectedoptions
Wizardscreatingmuchofthecode
C#/VisualBasicclassesautogeneratedwithstubfunctionswhere
youinsertanyapplicationspecificcode
49
OK,timetogetmoretechnical
ThingsyourfindinJSPpages
Beans
ScopesforBeans
Sessions
etcetc
50
Pagecontents
Directives
Actionelements
Scriptingelements
Templatetext
51
AJSPpage
<%@pagelanguage="java"contentType="text/html"session="false"%>
<jsp:useBean scope="request"id="userInfo"class="SubscriberRecord">
<jsp:setProperty name="userInfo"property="*"/>
</jsp:useBean>
<%if(!userInfo.isValid()){%>
<jsp:forward page="badInput.jsp"/>
<%}%>
<%if(userInfo.createInDatabase()<1){%>
<jsp:forward page="NoDB.html"/>
<%}%>
<html><head><title>Thankyouforregistering</title></head><body>
<h1>Thankyou</h1>
<p>Yourmembershipnumberis
<jsp:getProperty name="userInfo"property="id"/>
</body></html>
Directive
Actiontag
Scriptlet
Template
text
52
Directives
Essentially,theseprovideinformationtothe
componentthatgeneratestheservletfromtheJSP
page.
pageattributes
IsaSessiontobeusedforstatemaintenance?
Howareoutputdatabuffered?
Isthereapagethatcanbeinvokedifanexceptionoccurs?

includes
Fragmentsofpreparedtextfromotherfiles
taglib
Specifylibrarycontainingcustomactionelementsthatsupplement
thestandardJSPtags
53
Actionelements
ThesearetheXMLliketagsthatcanappear.
Thereisastandardsetofactionelements providedvia
thejsp tags
Thesestandardtagssupport
commonactionsonbeans
someactionsontheservletrequest,andresponseobjects.
Controlcollaborationwithotherjsp pagesand/orservlets
Standardactionelementsinclude:
<jsp:useBean>
<jsp:getProperty>,<jsp:setProperty>
<jsp:include>,<jsp:forward>
<jsp:param>
54
13/05/2014
10
Standardlibrariesofactions
JSTLwillbeillustratedthroughlaterexamples
AJSPusingJSTLwillsimplyneedacoupleof
pagedirectivesthatspecifywhichpartsof
JSTLarerequired(itsabiglibrary,usuallydont
needitall)
JSTLlibrarycodeneedstobeaddedtoproject
butnospecialconfigurationdataneeded
55
Scriptingelements
Scriptlet
<%
someJavacode
%>
Thecodeisdroppedintothegeneratedservlet.
Canincludevariabledeclarations theyaredefinedaslocal
variablesoftheservicefunction.
Expression
<%=Javaexpression %>
getstranslatedintoout.print(Javaexpression )
Declarations

56
Scriptingelementscontd.
Declarations
Youcandeclareinstancedatamembersandmember
functionsforthegeneratedservlet.
Whatmightyouwant?
Supposethatyoudecidedthattheservletshouldownadatabase
connection,andthatthiswouldbeopenedatinitializationtime
andclosedanddestroytime
Thenyouwoulddefine
java.sql.Connection dbConnection;
publicvoid_jspInit(){/*connecttodatabase*/}
publicvoid_jspDestroy(){/*closethatconnection*/}
57
Scriptingelementscontd.
Declarationsappearas
<%!
java.sql.ConnectiondbConnection;
publicvoidjspInit(){

}
//etc
%>
58
Templatetext
AllthestandardHTMLandcontenttextfragmentsin
theJSPpagearereferredtoastemplatetext.
Thesetextfragmentsaresimplypackedintoalarge
numberofoutputstatementsinthegenerated
servicefunction.
out.print(bitmorehtml);
out.print(bitmorecontenttext);
out.print(morehtml);
out.print(andstillmorehtml);
59
AJSPpage
<%@pagelanguage="java"contentType="text/html"session="false"%>
<jsp:useBean scope="request"id="userInfo"class="SubscriberRecord">
<jsp:setProperty name="userInfo"property="*"/>
</jsp:useBean>
<%if(!userInfo.isValid()){%>
<jsp:forward page="badInput.jsp"/>
<%}%>
<%if(userInfo.createInDatabase()<1){%>
<jsp:forward page="NoDB.html"/>
<%}%>
<html><head><title>Thankyouforregistering</title></head><body>
<h1>Thankyou</h1>
<p>Yourmembershipnumberis
<jsp:getProperty name="userInfo"property="id"/>
</body></html>
Directive
Actiontag
Scriptlet
Template
text
60
13/05/2014
11
Directives
<%@directiveNameattr1=valueattr2=value%>
include
URIforfiletoinclude
CanincludechunksofHTML/contenttextfromotherfiles
taglib
Prefix
Groupnameforthetags,equivalenttojsp:
URIfortaglibrary
TaglibraryshouldbeintheWEBINFdirectoryandshouldbe
describedmoreintheweb.xmlfile
61
Pagedirective
<%@page%>
Lotsofattributes!
Canusemorethanonepagedirective.
Attributes(somelessimportantonesfirst):
language
DefaultstoJava,andformostsystemsthereisonlyJava;someJSP
implementationsallowJavascriptcodefragmentsinstead
extends
Youcandefineyourownservletbaseclass,arefinementofHttpJspPage;but
itwouldbeunusualtowanttodothis
info
TextdescribingyourJSPpage(foruseinsophisticateddevelopment
environment)
isThreadSafe
Settofalseifreallywanta"singlethreadmodel"servlet
62
Pagedirective
Moreattributesofapagedirective
isErrorPage(true/false)
Errorpagehas"Exception"objectdefined,scriptreports
errorsasencodedinthisobject
contentType
Usedtosetcontenttype("text/html",orifyouareambitious
"img/gif")
import
Referencejavapackageusedincodeinpage
session(true/false)
DefaultisJSPpagesarepartsofsession,withcookieusedto
carrysessionid
63
Pagedirective
Stillmoreattributes
errorPage
URLofJSPerrorpage
autoflush(true/false)
buffer (buffer=nkb,default8kb)
64
Pagebuffering
OutputfromJSPnormallybufferedbeforebeingsent
toclient
Allowsyoutostartgeneratingoutput,thenmaybe
modifyaheader(can'tchangehttpheadersifoutput
"committed"bysomeofitbeingwrittentobacktoweb
serverandthencetoclient)
Bydefault,outputbuffersflushandthencanbe
refilled,
canchangesothatbufferfullcausesanerror
exception(devicetopreventgenerationofexcessiveoutput)
65
Session
DefaultisforJSPpagestocheckforsession,andstart
asessionifnonedefined.
Sessionreliesoncookiebasedsessionidentifier,
youshouldexplicitlyencodesessionidentifierintoall
URLsinordertocaterforclientswhodon'tlike
cookies.
Turnoffsessionsifnotreallyneeded(manyinformationalpagesdon'tneedsessionsupport)
Mostexamplesthatyouwillseeassumethatclientshavecookiesenabledand
dontbotherwiththemessyextrasofmodifyingalllinkstoholdsessionidsfor
cookieless customers. 66
13/05/2014
12
jsp:actions,
useBean
<jsp:useBean/>
Or
<jsp:useBean>body</jsp:useBean>
Basically,instantiatebean;parameterssetproperties.
Bodycodewouldberelatedinitializationsteps
Scriptletstyle
Invocationofotheractiontags
(Canhavesometemplatetext,justbecomesmoreoutputsto
responseoutputstream)
67
jsp:useBean
Parameters
class
Stringwithfullyqualifiednameforbeanclass(ifbeanisclass
definedinWEBINF/classes,thennopackagenamequalification
needed)
id
Variablenamefortheobjectthatisbeingcreated(forusein
scriptlet codeetc)
scope
Page,request,session,application
Also
beanName
type
Beanscopeisimportant,
moreshortly!
68
useBean
Checksscopespecifiedforinstanceof
specifiedclassassociatedwithidentifier
Ifalreadyexists,returnreference
Elsecreateobject
(Objectcouldexist somethingboundto
sessioncouldhavebeensetbyanyother
servlet/jsppageinvolvedinsamesession)
69
jsp:getProperty
<jsp:getPropetyname=property=>
Parameters
name
Objectsname,asspecifiedin<jsp:useBeanid=..
property
Propertyname,rememberingrulesregarding
capitalization,matchinggetfunctionetc
70
jsp:setProperty
<jsp:setProperty name=property=
param=value=/>
Parameters
name,property objectidentifierandproperty;
param value
Alternativewaysofspecifyingvalue;
param datacomesfromaHttpRequest parameter,eitheruse
param=tospecifyparameterorfollowdefaultsofmatching
names
value datacomesfromabitofscriptlet code
71
jsp:setProperty
setXXX(XType)
UsuallywillhaveaStringvaluefromform
parameter,soneedStringtoXTypeconverstion
Boolean.valueOf(String)
Integer.valueOf(String)

72
13/05/2014
13
jsp:forward
jsp:include
<jsp:forwardpage=>
Discardanybufferedpartialresponseandbounce
requesttospecifiedpage
<jsp:includepage=>
Flushbufferwithpartialresponse(committing
andsendingheaders)
Invokeotherpage,lettingitoutputsomedata
Resumeprocessing
73
Beanscope
Beanisjustanobjectinstantiatedfromspecifiedclass.
Howisbeanobjectdefined?
LocalvariableofdoService()functionofgeneratedservlet,
thisispagescope andisthedefault
Actually,itisabitmorecomplex,explanationlater.
VariableaddedtosessionobjectusingsessionssetAttribute function,
thisissessionscope;
variablecanberetrievedfromsessionbyotherservletsorjsps in
relatedgroup
VariableaddedtoHttpRequest objectusingitssetAttribute function,
thisisrequestscope,
getspassedwithrequestifJSPforwardsorincludesotherservlets
VariableaddedtoservletcontextobjectusingitssetAttribute function
thisisapplicationscope.
74
Beanscope
Amechanismforspecifyingwhetherashared
datastruct (beaninstance)was:
AttachedtotheHttpRequest object
Usedwhencreatingabeaninoneservlet/jsp and
forwardingittoanother
StoredinthecurrentHttpSession object
Theubiquitousshoppingcart
Storedinthewebapp widecontextdata
DataliketheratestablefromAcmeEmployeesexample
Orjustsomethingbelongingtothispage
75
Beanscope
Codegeneratedintheservletforusingabean
wouldbealonglines
Findcontainer
Ifscopeisrequestthencontainer=httprequest elseif
scope=sessionthencontainer=httpsession elseifscope=
Containerhashashmapofname/objectpairs
setAttribute/getAttribute (asseenwhencoding
servlets)
askcontainerforrequiredbean
mybean=(typecast)container.getAttribute(beanname)
76
Pagescope
Forconsistency,jsp beansthatarepagescopedcannotbe
simplevariableoftheservicemethod,
theymustbeaddedtoaPageContextobject(setAttribute)
andaccessedthroughthis
jsp:usebean Createtheobject
Addreferencein
PageContext
77
UsingJSPs alone
JSP(+applicationspecificentityclasses)
Scriptlet codeandactiontags
78
13/05/2014
14
JSPs alone
InitialhopeforJSPs wasthattheywouldsuffice
forapplicationdevelopment.
WebApp
JSPusingapplicationdefinedbusinessclasses
Coding
Amixofscriptlet andactiontagsasneeded
Astaglibrariesevolved,theamountofscriptlet codedecreased
Stillavalidapproachfortinywebapps andfor
prototyping
79
Memberformexample
Simpleexamplebuilttoillustrateapproach
Fillinaform(staticHTML)withpersonaldetails
SubmittoaJSP
Takesdatafromformandsetsvaluesinabean(this
beanisactuallyanEntityclassforadatabase)
Validatebean
Ifinvalid,diverttoerrorJSP
Ifvalidwritetodatabase
ExamplebuiltinstagestoillustrateJSP
features
80
StaticHTMLform
81
Thetable
82
Persistence
NotusingJPAherebecause:
HadseveralissuesintryingtouseEntityManagers etc
fromamemberfunctionofaJSP
Cannotuseresourceinjectiontogettransactionandentity
managerfactory(resourceinjectionnotsupportedbyJSP);
alternatives(JNDIlookupofresourcessuchas
java:comp/UserTransaction)shouldwork
Mainproblem,neverresolved:
Transactionwritinganewrecordsuccessfullycompleted
withoutexceptions
butnonewdatainthedatabase!
83
Instead:
Asimpleentityclassmanuallyconstructed
Defineaclasswithjustprivatedatamembers
LetNetBeans addconstructors
Needonethatinitializeseverythingapartfromidfield(whichhasto
bedeterminedbydatabase)andanothernoargumentconstructor.
84
13/05/2014
15
Addgettersandsetters
85
Simpleversionofwebapp
FirstversionofJSPpagewillsimplyreaddata
fromformandsetfieldsinaninstanceof
membersclass;
thenprintsacknowledgementpage
Thisusesjustjsp:taglibrary
86
TheJSPprocessingpage
87
Useofjsp:
useBean
Defaultispagescope
getProperty
Returnindividualpropertyvalue
setProperty
Couldsetaspecificproperty,specifyingthatvalue
camefromaparameter
ButsetProperty(property=*)ismoreautomated
88
<jsp:setProperty name="memberdata"
property="*"/>
Iteratethroughthelistofname=valuepairsintheinput
Foreachname,X,checkforafunctionsetX()intheclassoftheobject
whosepropertiesarebeingset
Ifnosuchfunctionexists,ignorethatinput
IffindasetX function,checktheargumenttype
IfnotString,useappropriateJavafunctiontoconvertstringfrom
formintorequiredtype(e.g.useInteger.parseInt(str)ifneedan
int)
InvokesetX functionwithargument
89
Plusses
Nowwasntthatmuchneaterthanoldservlet
codewithits:
String gnstr = request.getParameter(givenname);

Members datastruct = new Members();


datastruct.setGivenname(gnstr);
90
13/05/2014
16
Troubles
Ifthereareinvaliddata,theremaybetroubles
Youreallydontwanttosendthatkindof
exceptionreporttoauser!
Integer.parseInt()
wontlikethis
91
errorpage
JSPs haveastandardizedschemefordealing
withanyunhandledexceptionsinthe
generatedservlet.
AJSPcanspecifyanotherJSPasanerror
page
Ifanexceptiondoesoccur,theappengine
(glassfishorother)willreturnthiserrorpage
ratherthanaHTTP500serversideerrorreport
TheexceptionhandlingJSPispassedthe
exceptionsothatitcanreportwhatwentwrong
92
AddinganerrorsJSP
Thispage,whichisntan
errorshandlingpage,is
linkedtoanerrorshandling
pageatexceptions.jsp
Thispageisanerrors
handlingpage;
itprintstheexception
93
Workingwithanerrorpage
94
Errorspage
Bydefault,aJSPisNOTanerrorspageso
thereisnoneedtohaveisErrorPage=falsein
allpagedirectives.
Thereisnoneedfortheerrorspageto
actuallyprintouttheexception userswill
notunderstandsuchreports.
95
Goingbeyondjsp:
IfyouwantyourJSPtoactuallydosomework,
youneedmorethanjustthejsp:taglibrary
Choices:
Findataglibrarythathasaprocessingoptionthat
exactlymatchesyourneeds
Therearelotsoftaglibraries someevendomoderately
usefulprocessinglikesubmitaSQLselectqueryandputthe
datafromtheresultsetintoaHTMLtable
Writeyourownhighlyspecializedtagclass
Usescriptlets
Uglybuteasy
96
13/05/2014
17
Memberswebapp validation
Nextversion
StaticHTMLform enterdata
Members.jsp
FillininstanceofMembersrecord
Askmembersrecordwhetheritisvalid(scriptlet)
Ifnotvalid,forwardtheinvalidrecordtoaJSPthatwillreportwhyitis
invalid
Displaydataentered
SinceMembersrecordmaynowbeusedbyotherJSPs,
changethejsp:useBean tagtocreatetherecord
attachedtotherequestobject(ratherthanhaveit
pagescopeasbefore)
97
Members.java
Anextradatamemberthatwillholdalistoferrorsifvalidationfailed:
98
Simplevalidation
Fieldslikegivenname mustnotbenull.
Birthyear wellapplysomerestrictions;dont
wantpersonsclaimingtheywerebornin1890
or2022etc
Email dosomeformofregex check
Sun,inoneoftheJavaexamples,suppliesaregex
patternthatismeanttomatchemails
Sunspatternexcludesuppercaseletters
99
Member.isValid()
100
Members.jsp
Beanattachedto
HttpRequest object;
notPageContext
Scriptlet code
Scriptlet code
101
Scriptlet code:ugly
YoucanseewhySunwasnthappywithscriptlet
coding
Lookatthis
Everygood(SISAT)ITgraduateworkingasaweb
designerwillinstantlyremovethisextraneousguff
thatyoutheprogrammerputin justtrashlittering
her/hisprettypage
Ofcourse,therewillthenbeacompilationerrorwhenthe
deploymentprocesstriestocompilethegeneratedservlet
code anditwillbeyourfault
102
13/05/2014
18
myerrorreport.jsp
PickuptheMembersrecordthatwillhavebeenforwardedattachedas
anattributeoftherequest;
printitserrormessagestring
103
OKdataentered
104
Invaliddata
105
Persistingdata
Needadatasource connectiontoMySQL
Needafunctiontosavetherecord
Openconnection
Preparestatement
Binddata
Execute
Runanotherstatementtogetrecordnumber
106
DeclaringcodeinJSP
Need:
Datamemberfordatasource
Overridden_jspInit
OwnsaveRecord function
Also
Alargenumberofimportstatements
107
JSPdeclaration
Declaration<%!%>
108
13/05/2014
19
Savefunction
109
JSPscriptlet code
110
Itdoeswork
Actiontagsandscriptlets
DoingalltheworkintheJSP
Yesitworks
Butugly
111
Model2
JSPs introduced~1998
InitialadopterstrieddoingalltheworkofawebappinJSP
By2000,verdictin
JSPs maybebetterthanservletsforformattingHTML(you
dontneedallthoseannoyingout.print statements)
Buttheyarentthathotfordoingtherealworkofaweb
app
Sonewmodel
Dotheworkinaservlet
UsetheJSPforfinaloutput
112
Model2
InModel2JSP
Essentiallynouseofscriptlet code
Usenewtaglibraries(fromApacheandothers)
thathaveactiontagsthatareusefulfor
conditionaldatadisplay,iterationetc
Manycompetinglibraries
BestfeaturescombinedintoJSTL~2003
113
ThenewModel2MembersProject
114
13/05/2014
20
Model2Members
Form
WillforthisexamplekeepthestaticHTMLforms
Formspostdatatoservlet
Servlet
UseJPAfordatapersistence
Doworkofwebapp
Or,generallybetter,justcontrolsequencingofworkdoneby
applicationspecificclassesthatembodybusinesslogic
Collectdatathatshouldbedisplayedasresponse
ForwardtoJSP
JSP
Displaydata,usingJSTLtaglibraries
115
Memberswebapp
StillhaveMembersform
Reportisjustthemembershipnumbersonot
interesting
Haveaseparatelistmembersrequest
Thiswillillustrateiterativeactiontag
116
ThenewModel2MembersProject
Javacode
classMembers:
Entityfromdatabase(JPA)class
classMembersServlet
Acceptsforminput
CreatesMembersrecord,setsitsfields
Asksitifvalid
Ifnot,sendreasonwhydatanotacceptabletoanerrorreportJSP
Iflooksvalid,saveittodatabase(gettingdetailsofmembernumber
automatically)
ForwardtoanotherreportingJSP
classListingServlet
Acceptforminput
RunJPArequest
ForwardresulttoJSP
117
ThenewModel2MembersProject
JSPs
Index.jsp
Welcomepagewithlinkstoforms
addmemberreport.jsp
Reportssuccessfuladditionofarecord
listreport.jsp
ListofrecordsinHTMLtable
myerrorreport.jsp
Reportonerrorsinprocessing
118
ThenewModel2MembersProject
StaticHTML
ListForm.html
MembersForm.html
OfcoursethesecouldbeasJSPs
119
The(autogenerated)Entityclass
120
13/05/2014
21
Validationframework
JPA2linksintoavalidationframework
Notehowthedatamembersinthegeneratedclass
aretaggedwithannotationsrelatingtochecks;
therearechecksfornotnull,checksonlengthofa
stringetc.
Thesewillbeappliedwhenanentityispersisted!
Soyoucangetvalidationexceptions
Theexceptionhasamemberdatastructurewhichisasetof
descriptionsforalltheconstraintsthatwereviolated
Inthisexamplethough,wewanttodoourownvalidation
andreportproblemsratherthanpickupexceptions.
121
Validationframework
NotethatthereisaNotNull annotationonthe
id member
Buttheidisforanautoincrementfield
handledbyMySQL anditshouldbeNULL!
Bestremovethatannotation.
122
Ownvalidation
Willcontinuetodoourownvalidation
(thoughautovalidationwillapplyaswell)
AddavalidationfunctiontotheJPAclass
Callfunction
Itreturnstrueorfalse
Iffalse,theclasshasaStringdatamemberthatwill
containanerrorreport
Thismemberisnotpersistent!
123
Members.java
YoucanaddextradatamemberstoanEntityclass
butmustmarkthemasTransient(otherwisethe
persistencemechanismwillgetconfusedwhen
tryingtostorerecords)
124
Ownvalidation
125
MembersServlet
126
13/05/2014
22
MembersServlet.doPost
127
MemberServlet.doPost
Firststage:
Getparameters
Createandsetmembersofentity
Askifvalid
Ifnot
Getstringdescribingproblem
Attachittorequestobject
ForwardtoerrorreportingJSP
128
ReportJSP
ServletaddscompletedMembersobjecttorequest
andforwardstoJSPfordisplay.
jsp:librarywillsuffice
129
addmemberreport.jsp
130
ErrorreportingJSP
Pickupstringwitherrormessagefrom
request,andprintit
jsp:librarywillsufficehere justwanttopickupdatapassedwithrequest(simple
Stringdata)andprintit
131
Ownerrorchecking
132
13/05/2014
23
TriggeringaJPAValidationerror
Enteredtoolonganameinthenamefield
(browsersmaxlength checkremovedfirst)
133
ListingServlet
134
Listingservletresults
ListingservletcreatesalistofMemberobjects
satisfyingrequiredconstraints
Listisaddedtorequest
RequestforwardedtoJSP
JSPprocessing:
Ifcollectionisempty,reportthis(simple
<p></p>output)
Ifcollectionhasmembers,createaHTMLtable
listingtheirdata
135
listreport.jsp
Hereneedconditionaltestsanditeration
providedastags
UseJSTLlibrary
ifthenelse
Actually,thesyntaxis
choosewhenotherwise
foreach
(syntaxisforeach!)
136
listreport.jsp
137
listreport.jsp
Datawereattachedtoforwardedrequest soarea
memberresultsoftherequestScopeobject
requestScope.results
NamingstyleissimilartoJavascript
JSTLhasabuiltintestfunctionthatcanapplytoa
collecton empty
emptyrequestScope.results
Werewepassedanemptycollection?
138
13/05/2014
24
listreport.jsp
JSTLforeach
Workingvariableandcollection
var=memberitems=
Withinforeach canaccessmemberobject,again
Javascriptstyleaccessitsindividualfields
member.id,member.givenname,
139
listreport.jsp
140
JSTL
ClassesimplementingJSTLtagsmaybepartofthe
servletcontainerslibrary noneedforextra.jar
filesinapplication.
Ifneeded(aswithourGlassfishAppserver)addJSTL
librariestoproject
RefertoJavatutorialfordetails
foracompletelistoftheJSTLtagsandtheir
attributes.
Ominous Oracleseemstohavelettheonlinelinkstothedocumentationgobad.
141
JSTL
Core:
Variabledefinitionandmanipulation
Flowcontrol
URLrelated
SQL
Connectionsandqueries
Internationalization
Numberanddateformatting,messagestrings
XML
142
143
JSTLcore
<%@taglib uri="http://java.sun.com/jsp/jstl/core"prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt"prefix="fmt"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/sql"prefix="sql"%>

<c:set var="foo"scope="session"value="..."/>

<c:forEach var=Item"begin="0"items="></c:forEach>

<c:if test="${!emptyparam.CustomerName}"> </c:if>


144
13/05/2014
25
JSTL
Intentisthatstandardtagswillreplaceuseofin
houseand3
rd
partytaglibrariesforroutine
operations.
SQLtags intendedtoquickprototyping,adviceis
nottousetheminrealapplications
<sql:queryvar="books"dataSource="${applicationScope.bookDS}">
select*fromPUBLIC.bookswhereid=?
<sql:paramvalue="${bid}"/>
</sql:query>
145
Expressionlanguage
Previouslycouldhavefragmentsofscriptlet code
usedintags e.g.codetoaccessdatamemberof
somebeanattachedtorequest,orcodetogetan
iterator forthestrutslogic:iterate taglibrary:
<logic:iterate id="sg"collection="<%=theLeague.games()%>">
Expressionlanguage alternative,supposedly
simplerscriptinglanguagethatcanbeusedforsuch
purposes(claimisELiseasierforwebdesignersto
usethanscriptlet code)
<c:if test="${sessionScope.cart.numberOfItems >0}">
...
</c:if>
146
ExpressionLanguage
SupposedlyidenticaltoJavascriptonthose
partsthatoverlap.
147
EL
${ELcode }
Codeaccessingdatamembersofobjects,
performingrelationaltestsetc;manyimplicit
objects
servletContext,session,request,response,param,

Onecommonuse accessingparameterswith
formdata
148
EL examples
<c:setvar="bid"value="${param.bookId}"/>
PicksupforminputfieldbookIdandplacesvaluein
bid
<sql:queryvar="booksdataSource="${applicationScope.bookDS}">
select*fromPUBLIC.bookswhereid=?
<sql:paramvalue="${bid}"/>
</sql:query>
<c:forEachvar="bookRow"begin="0items="${books.rowsByIndex}">

RunningSQLquerythenprocessingresultswithin
JSPpage
149
JSTL:SQL
Uhm
150
13/05/2014
26
Itried,ashaveothers
ButallIgotwasexceptions nosuitable
driverfound
Thedatasource wasbeingusedsuccessfullyin
servlets
Iamnotalone
DozensofcomplaintsonGoogleovermanyyears
Applyingtodifferentservletcontainers itsnota
glassfishissue
151
Itworks
Poordocumentationeffort!
Consideringthatpeoplehavebeenposting
problemsonwebfor10+yearsyouwouldhave
thoughtthatSun/Oraclewouldhaveclarified
thingsalittle.
Datasource nameintagisnotinterpretedas
theactualdatasource name
Itssimplyanameforadatasource usedbythis
program
152
Sowhereisthedatasource
Therealdatasourcehastobeidentifiedinthe
configurationfiles.
Web.xml
Includeareferenceentryforthedatasource asnamed
intheSQLtag
Sunweb.xmlorglassfishweb.xml
(Forus glassfishweb.xml)
Thishasanentrymappingthedatasource nameas
usedintheSQLtagtotherealJNDInameofthe
deployeddatasource
153
Anotherexample
AJSPpageusingSQLtags:
Myrealandapplicationdatasource namesareidentical,butImuststatethisinthemappingfile
154
Someconfig files web.xml
155
Moreconfig files glassfishweb.xml
156
13/05/2014
27
Itruns
157
butanyway
InallthediscussionsthatGooglefinds
concerningsuchproblems(andgenerally
fixesthatdontfixtheproblems),someone
willinject
Youshouldntaccesspersistencestorage
fromthedisplaylevel
Quiteso
Iguessitisntabug,theexceptionaboutnotfindingthedriverisafeatureaddedto
discouragenavedevelopersfromusinginappropriatedesigns.
158
struts
A(verybrief)introductiontostruts1
themodelviewcontrolframework
forservlets
(~2000)
159
Twostruts
Apache.org says:
TheApacheStrutsProjectofferstwomajorversionsof
thethe ApacheStrutswebframework.
Struts1isrecognizedasthemostpopularweb
applicationframeworkforJava.Struts1isthebest
choiceforteamswhovalueprovensolutionsto
commonproblems.
Struts2wasoriginallyknownasWebWork 2.The2.x
frameworkisthebestchoiceforteamswhovalue
elegantsolutionstodifficultproblems.
Somedifferencessummarizedathttp://www.javasamples.com/showtutorial.php?tutorialid=200
160
Webapplication?
By~2000,Javawebapplicationscouldbebuilt
usingservletsandapplicationbeanstodothe
work,andJSPs todisplayresults.
Webapplication?
Therewasnocoherentapplication
Whatyouhadwasasetofservlets(andbeans)
thatimplementedindividualusecases
SamesetofproblemsasdiscussedwhenintroducingZend framework PHPs
somewhatlatervariantonbuildingacoherentwebapplicationwitha
ModelViewControlarchitecture
161
Well,youcoulduseEJB(~1998)
Nowitwaspossibletousea4tierarchitecture:
Client,webserver,ejbengine(applicationserver),
database
ratherthana3tier(client,web,database)architecture
The4tierarchitectureallowedyoutobuilda
sessionbeanthathadallthebusinesslogicthat
wasotherwisescatteredoverdifferentservletsand
applicationbeans.
But4tierarchitecturesdidntappealtoall
(AfewofyoumaylearnsomethingabouttheminCSCI398)
162
13/05/2014
28
Buildingarealwebapplication
Servletcontainersdiddoalittleofthework
Authenticationandauthorizationmanagedcentrally
Lifecyclemanagement
(Later,resourcemanagementlikepooleddatabaseconnections)
Canonereplaceasetofservletsbyasingleapplication?
Therewillhavetobe
Elementsthathandlethevariousdistinctusecases
Somecentralizeddispatcherthatdetermineswhatworkistobe
done
JSPs canhandlethefinaldisplay
justneedtopackagedynamicdatainstructs andforwardtotheJSPs
163
Amodelviewcontrolarchitecture?
JSPs arefineforaviewcomponent.
Control
Itwouldbeniceifonecouldhaveasingle
dispatcherthatreadconfigurationdatadescribing
anapplication
Actionrequired,persistentdatamanipulated
Conditionalcontroltransferdescription
Dothisnextifactionsucceeded
Dothisnextifactionfailed
164
Birthofstruts
Apachesstrutsprojectwasanattempt
(successful)tobuildsuchanarchitectureontop
ofservlets.
strutshasasacoreelementaclassActionServlet
Thisisitsdispatcher,orindesignpatternterminology
itsFrontController
Servletshadbeencreatedwiththatservletmappingwebxmlfeature
thatspecifiedhowaURLinarequestgotmappedtoaservlethandler.
Thisservletmappingprovidedtheroutingmechanismforstruts
AllURLsusedinstrutsgeneratedpageswillidentifytheactionsrequested
withnamesthatendwith.do
Theservletmappingrule*.domapsallsuchrequestsintotheActionServlet
165
NetBeans viewofstruts
166
ActionServlet
1. GetandPostrequestswillarriveattheActionServlet
2. TheActionServlet caninspecttheactualrequest
pathname
Thiswillbeusedtokeyintoadatastructurethatithasbuilt
frominformationinaconfigurationfile
Theconfigurationdatawillidentifyabeanclassforthedataand
aclassthatperformstheprocess
3. TheActionServlet willcopyparameterdataintoan
instanceoftheappropriatebeanstructure(usingreflection
aswithJSPs jsp:setproperty beanpropertyvalue)
ActionFormkindofabaseclassforthesebeans
4. TheActionServlet
167
ActionServlet
4. TheActionServlet will(usually)instantiatean
Action(instanceofasubclassofframeworkAction
class)thatwillperformbusinesslogicoperationson
thebean(ActionForm)
5. ProcessingresultsinaActionForward objectthat
identifiesthenextprocessingstep
Usually,thiswillsimplyidentifyeitherasuccessreport
JSPorafailreportJSP.
6. AppropriatedataforwardtoJSP(asattributesof
request),JSPpresentsresults
168
13/05/2014
29
NetBeans viewofstruts
169
SimilartoZend Framework?
Well,kindof.
Differentorganisation
ActionForms possiblycorrespondtoZendFormclass
Action
Zend FrameworkhasControllersthathavemultipleactionmember
functions
HerehavemanydifferentActionclasses
Butatthenextstepstrutsgetsmoresophisticatedand
morecomplex(andhasanevenhigherlearningcurve
barrier).
Muchofstrutsisbasedondeclarativestylesof
development
CreatingapplicationsdefinedintermsofcomplexXMLdocuments
thatareinterpretedbytheActionServlet
170
Tryforahelloworldexample
Howaboutlistingmembernameschosenbygender
shouldntbetoocomplex.
SocreateanewNetBeans Javawebappspecifying
useofstruts
171
NetBeans strutsprojectstarter
NetBeans createsaprojectthatisaworking
webapplication
Letusseewhatitconsistsof
(AtleastitdidntjustsayHelloWorld)
172
Justafewlibrariesthat
makeupthestruts
framework
A.propertiesfile samerole
asZend Frameworks
application.ini
AcoupleofJSPs
AfewXMLfileswith
datadefiningthe
application
173
index.jsp
Startwithsomethingeasy index.jsp shouldbea
goodplacetostart
WTF
Ohok,itsjustredirectingustoWelcome.do
Asthatisa.doURL,itwillgotothethe ActionServlet
Ascanbeseenfromtheweb.xml file:
174
13/05/2014
30
strutsconfig.xml
SowhatistheActionServlet todowiththisrequestforwelcome.do
ItwilldeterminetheActionfromdataoriginallyinthestrutsconfig.xml
file
Thiswillhavebeenparsedandbuiltintoaruntimedatastructurewhenthisweb
appfirststarts;strutsdoesntexpensivelyreparsetheXMLoneachrequest.
Thereisntmuchinthedefaultstrutsconfig.xml file butthereisaan
actionmappingforwelcome
Sohereitissimple:
Noneedtocreateanybeanstructure,noneedtorunanyvalidationofdata,
noneedtodoanyprocessing
SimplyforwardtowelcomeStruts.jsp
175
welcomeStruts.jsp
176
welcomeStruts.jsp
Importstrutsowntaglibraries
tagsbeans:
Thingsthatjsp:librarycoulddoplusafewmoreoperations
tagshtml:
?Waitandsee
tagslogic:
Conditionaloperationsanditeration,precursortoJSTL
corelibrary
177
welcomeStruts.jsp
logic:notPresent
Conditionaltest
Herecheckingwhetherthereisamessageforthisactionin
applicationScope
Wehaveseenthecoderunanditdidntreportan
errorsoobviouslythemessagedatawasfound.
178
welcomeStruts.jsp
bean:message
SomewhatsimilartoJSTLc:out;findsomedatatoprintas
aString
Here,thedatashouldbefoundinapplicationScope witha
keyasspecified.
179
Whoputthemessagedataintoapplication
scope?
Thatwasdonewhenthewebappwasinitiallyloaded
TheActionServlet wouldhaveloadedthedatafromthe
ApplicationResource.properties file
Remember,servletsremaininmemoryonceloaded;itisOKtodoalotofworkatinitialloadtime,
itwillsavetimelater.
welcome.message
180
13/05/2014
31
Caneditthepropertiesfile
Anewmessage
181
Makingarespectableapplication
Howaboutanotherversionofthemembers
application.
Canconvertthestruts1welcomeframeworkintoa
realapplicationbyaddingJSPs andJavaclassesand
configurationdata.
Thisversionofmemberswillsimplyhavea
formtoentergenderrequiredinlisting,andthe
codetogofromtheretoalistofmembernames.
182
StrutsMembers1
Startwiththevanillaisntshebeautstrutsproject
1. EditthatstrutsWelcome.jsp
2. Changesomemessagesinthepropertiesfile
3. AddanewJSPforasearchform
183
<html:tags >forform
Createtheformusingstruts<html:tags
184
Createapagethatcanshowresults
ShowResults.jsp
Datawillbeinabean
Usestrutslogiciterateetctodisplaycontent
Noteanoddityhere. TheShowResults.jsp isplacedintheWEBINFfolder,belowthe
normalWebPagesfolder. ThiscanbedoneinanyJavaWebapp,notjuststruts.
Why?ServletcontainerswillnotreturnsuchpagesforaGETrequestwithaURL;this
eliminateschanceofinquisitiveuserreachingpagestheyshouldntgettodirectly. 185
Usingmembersclass
ApplicationusesthatsimpleMembersclass
illustratedearlier
SuccessfulactionwillattachanArrayList<Members>tothe
request
186
13/05/2014
32
Apageforerrorreports
strutsprovidesforActionMessages (ActionErrors)thatcanbe
usedtoreportproblems theygetattachedtotherequest
object.
Canforwardtoanerrorpresentationpage.
Special<html:errors />tag becomescodetoiteratethrough
errormessagecollection.
187
ActionForm class
Next,needaclassthatwillholdthedatasubmittedinthe
form
Thestrutsframeworkwillallfillitsdatafieldsfromformparameters
(muchlikejsp:setProperty did)
Netbeans hasastrutscategoryinitsnewfilesmenu want
strutsactionbean
188
Usualautogeneratedplaceholders
Generatedclasshasautogeneratedint andStringmembers
justtoremindyouhowtheyaredone.
Replacethesebymembersthatcorrespondtothefieldsin
theinputform(andwhichhaveappropriatenamesforthe
beanstyleconventions)
189
Createownmembersandvalidation
190
Anaction
Next,addanActionsubclass
Thiscanworkwiththeformbean validatingit,thenin
Action.execute()processingthedata.
ActionclasshastohavelotsofconfigurationdataintheXML
Fortunately,NetBeans handlesmostoftheworksettingthisup
Actionpathtomatchentry
inthehtml:form tagofthe
SearchForm.jsp
191
Action
Identifydatabeanthatitworkswith
Bitoddlynamed,theinputresource
istheerrorspageiftheformbeanfails
tovalidate.
(Imusingoneerrorspageforalltypesoferror.)
192
13/05/2014
33
Anactionadded
Astubclassgenerated,anXMLdeploymentstatementadded
193
Execution
Gotothedatabase,retrievetherecords
194
Execution
Pickupparametersfromthe(nowvalidated)
formbean:
Returneddatawillbelistofmembers
try{}catch{}finally{rememberalwaysclosedbconnection}
Ifexceptions,createanerrorreport,addittosystemserrors,and
failurereturn
Errorreportscanbeparameterized.
195
Searchcode
UseDataSource (configuredintoglassfishinearlierexample)
Runquery
CollectresultsmanuallycraftingMembersobjects
196
Onexceptions
197
DefineforwardrelationsinXML
198
13/05/2014
34
Itworks!
199
Cantriggererrorhandling
ChangevalidationcodesothatOTHERnotallowed
andpickOtherinform:
MakeanerrorinSQL
200
Validation
strutshasmechanismsfordataentryvalidationthatareas
sophisticatedasthelaterZend frameworkversions,
butwhichareconfiguredverydifferently.
AswithZend,thereareeffectivelyanumberofpredefined
validator classes;
youcandefinenewclassesandfitthemintothisframework;
oryoucanletthestrutsframeworkdoitsownvalidation
usingitsclassesandthensupplementthechecksina
validate()methodthatiscustomdesignedforyourformdata.
InstrutsvalidationisdefinedlargelythroughXMLdeployment
descriptors
(BitmoresophisticatedthanZends inlinecodeinvokingoperationsofinstancesofZend
validtor classes)
201
Validation NetBeans
NetBeans includesvalidatorrules.xml and
validation.xml inthestrutsprojectsthatitbuilds
validatorrules.xml
Definitionsofvalidationtestssuchasrequired,date,
email,match(yousupplyregex),
Youwouldonlychangethisifdefiningyourownvalidator
classes
validation.xml
Youeditthistodescribethefieldsinyourformandthe
validationchecksthataretoapply
Itcontainstwoexampleformspecifications,youcanremove
these
202
ValidationNetBeans
Youhavetouseadifferentbaseclassforyourform
class thereisasuperclassoptioninthedialogfor
creatingaFormActionBean
Example aformfordataentryofanothermember:
203
strutsvalidationexample
Addtostrutsprojectthecomponentsnecessaryto
handlerecordcreation:
addForm.jsp theformpagefordataentry
usingstrutsHTMLtags
AddResult.jsp reportsuccessful
creationofrecord
AddAction.java theActionclasswhose
executemethodsavestherecordtoMySQL
AddForm.java theActionFormbeanclass
Updatedconfig
Checking
requirements
204
13/05/2014
35
addForm.jsp
<html:errors />div:
explainedshortly
Formmarkupusingstruts
htmltags
205
AddForm subclassofValidatorForm
Validation?
Dowhatparentclassdoes.
Couldaddapplication
specifictestshereifneeded.
206
AddAction
207
AddAction
PickupdatafromthevalidatedValidationForm bean.
208
AddAction
InsertdataintoMySQL,then
pickuprecordnumber(whichis
insertedintoanextramembernumber
fieldintheformbean)
209
AddResult.jsp
Limitedreportpage justshowingthatthingsdowork
210
13/05/2014
36
Demo
211
Baddata?
Getbacktheform
submissionpagewith
dataasenteredand
errormessages!
212
Magichappened
Itsallintheconfigurationdata
Propertiesfile:
Lotsofcustomizederrormessages
strutsconfig.xml
Newelements
Elementfortheaddformhasdifferenterrorhandlersfor
validationerrorsandactionerrors
Validationerrorsgobacktodataentryform
Actionerrorstotheerrorpageillustratedbefore
validation.xml
Definitionoftheformlistingthevalidationteststhatapply
toeachfield
213
Properties
Lotsofmodificationsofexistingerrormessagesand
additionsofmoremessages
Changedprefixstyleto
enhanceerrormessages
Addedmessagesthat
getreferencedin
thevalidationtests.
214
strutsconfig.xml
Twoformbeans
areidentified
Addaction:
onvalidationerrorgobacktoaddForm.jsp (input)
onsuccessgotoAddResult.jsp
onactionerror,usesameerrorspageassearchaction
215
Validationrequests
Testgivennamedataentered:
itsrequired,ithasamask(regex)
testthatsaysitmustconsistonlyof
letters
216
13/05/2014
37
Validationrequests
Testfamilynamedataentered:
itsrequired,ithasamask(regex)
testthatsaysitmustconsistonlyof
letters,hyphens,andapostrophes
Testgenderdataentered:
itsrequired,ithasamask(regex)
testthatsaysitmustbethestring
MALEorthestringFEMALE
217
Validationrequests
Testbirthyeardataentered:
itmusthaveavalueinrange1920
to200
Testemaildataentered:
itmustmatchstrutsownregex
forvalidemails
218
struts
219
struts
Assophisticated(andcomplex)asZend
Differentindetail,butoverallthesamestyle
ModelViewControl
FrontController
Formobjectsthatgetloadedwithdatafrominput
Suppliedvalidationclasses
Routingtodifferenttemplateresponsepages
accordingtosuccess/failureofvalidationand
subsequentactions.
220
Declarativev.inlinecode
Majorstyledifferenceisstrutsistoa
significantdegreedeclarative
SpecifywhatyouwantinXMLtemplatefiles
Zend reliedmuchmoreoninlinecoding
Gettheform
Grabdatafromfield
Createvalidator
Applyvalidator todata
.
221
andthereisyetanotherway
Brief(!)introductionto
JavaServerFaces
acomponentbasedframework
222
13/05/2014
38
JavaServerFaces:Cautions
JavaServerFaceshasversions1&2withsubstantialdifferences
Makesurethattheonlinetutorialthatyouarefollowingisintendedforyour
version!(AlmostalwaysshouldbeusingJSF2now).
JSF2:
Uhm inmanyplacestherearetwodifferentwaysofaccomplishingatask
(e.g.injectionofaresource)
Amoretraditionalway,similartoJSF1,andworkingwithavarietyofapplicationengines
Anewapproach,CDI,onlyonmoremodernappservers
Generally simplerfor the developer to use
JSFpagesusealmostthesameexpressionlanguageasJSPs butthereare
differencessuchasthetimeatwhichanexpressionisactuallyevaluated
JSFusedtouseJSPs forallthepresentationlayer butnowmainlyuse
facelets,anewertechnologyforbuildinguppages
Soyouarelikelytobequiteconfusedbytheveryvariedexamplesthatyou
willencounter
223
JavaServerFaces
Adifferentkindofframework.
AnattempttocreatesomethingmoresimilartoaJava
Swing/AWTapplication
Componentsliketextboxes,lists,tables
Renderedonthescreen thoughinverydifferentways
Swing/AWTrenderingisthroughGraphicsanddrawingoperations
JSFcomponentsrendereddowntoHTML!
Componentscanhaveeventlistenerswaitingforactionsby
theuser
Buttheactionhandlercodeisintheserver(whereaswith
Swing/AWTdisplaycodeandeventhandlercodearepartofthe
sameprogram)
Codeinapagemayappeartomakedirectuseof
objectsthatmustexistintheserver
SomeconceptualsimilaritiestoMicrosoftsWebForms(ASP.Net)thatprecededJSF1by~3years
224
Theadventuresfirst,
explanationstaketoomuchtime
225
TheGuru
Abetterclassof
HelloWorld
Program
Doyouthink that youmayhaveseenthisbefore?
Wait tillyouget toCSCI398.
226
Aphorismserver
Awebpage,andabeanclass
Andnotanawfullotofconfigurationdata
Anothertaglibraryinuse
jsf/htmltags.
.xhtml well,kindof;supposedtobealmost
XMLcompliant
227
TheGurucode
Nothingspecial justtheodd@Namedannotation
228
13/05/2014
39
DeploymentXML
Prettysimple,agreed?
Reallynothingthereapart
fromanindicationthat
anotherofthose
FrontControllerobjects
isinvolved something
calledFacesServlet
229
MoredeploymentXML
Prettysimple,agreed?
230
So,allmagicagain
ButitdoesntseemthatmuchdifferentfromJSP
Ok,wedidnthavetosayweweregoingtousean
instanceofourGuruclass(nojsp:usebean),
wejustusedit
ObviouslytheJSFframeworkdoessomethingsensiblelike
lookforanexistinginstance(insomedefaultcontext,
probablyJSPs sessionScope)andifitdoesntfindoneit
createsone.
Maybeyouarenttooimpressed.
Thenjustwait,theresmore!
231
First,implementamoresophisticatedGuru
ThisGurucanbetoldtomovethroughitscollection
ofknowledge
Havealsochosentogiveitanexplicitnametheguruand
tosayexplicitlythatwewantitinsessionScope
implementsSerializable?
Justarequirementforasessionscopevariable Illrevealmorein
CSCI398
232
AmoresophisticatedGuru
233
Amoreelaborateindex.xhtml page
234
13/05/2014
40
Butlookwhathappenswhenyoupressthe
buttons!
0
1
2
3
1
0
1=110
2
235
Impossible!
Youarepressingbuttonsinthebrowserand
thestateofanobjectintheserverchanges!
Thatisimpossible.
Itmustbemagic.
236
Magic?ToomuchHarryPotterinyourpast
Itsnotmagic.
ItsjustHTML(andsometimes,atleastwithMicrosofts
version,someJavascript)
LookatthesourceoftheHTMLpage:
237
Pagesource
Thosebuttons theyare<inputtype=submit/>
238
Howdiditwork?1
Eachtimeabuttonwaspressed,theformwas
submitted
Hiddendatafields:
TheseholdinformationthatletstheFacesServletidentify
theobjectthatistobemanipulated.
Namedsubmitbuttons
TheFacesServlet willstillhavetheinformationthatmaps
thesetotheactionfunctions(#{theguru.move()}
ELusing$getsevaluatedjustonceaspageiscomposedintocode
aswhenaJSPiscompiledintoaservlet
ELusing#getspreservedandreevaluatedeverytimethe
expressionsareneeded
239
Howdiditwork?2
TheFacesServlet invokedthemove()operationof
thetheguruobjectinsessionScope.
TheFacesServlet thanhadtorecomposethe
responsepage
SoitagaininvokedthegetEnlightenment()methodof
theguruobject gettinganewchoiceofaphorism
Thecompletepagewasreturnedfordisplayin
thebrowser
240
13/05/2014
41
Completepagereplacement?!
ThedefaultoperationsofJSF(andMicrosofts
ASP.Net whichwastheoriginalrealizationofthis
approach)involvescompletepagereplacement.
Actionsinthebrowsertriggerpostoperations
offormdata
Lotsofhiddendatafieldsintheformcontaindata
thatallowserversideto(re)createobjects,orfind
existingobjects,andestablishthecorrectviewstate
Serverhandlespostrequest,andreturnsthe
updatedpageasaresponse.
Costly?
241
Interactionbycompletepage
replacement
Acostlystrategy
Entirepagebeingreplaced
(MyGuruconsultationpageisquitesimple,butimaginethisonareal
pagewithacomplexstructure).
Itsactuallyquitereasonableforaninhouseapplication
workingoveranintranet
Allowsforthecreationofinteractiveapplicationsthatworkin
conventionalbrowsers easierforpeoplesuchasclerkstolearn
assosimilartootherwebusage.
Itisntagoodideaforanapplicationthatrunsoverthe
Internet
(Obviously,AJAXcouldbe,andsometimeis,usedforthe
interactionsratherthancompletepagereplacement butAJAX
isalateradditiontotheseframeworks)
242
Youwantsomethingmorethanhelloworld(orguru)
OK
Youaretodevelopawebappthatistoallowauserto
selectafacultygettingaviewofthesubjectsofferedby
thatfaculty,andthenselectasubjecttogetfulldetails.
SubjectdataarestoredinaMySQL table:
243
Illustrationofoperations:
welcomepage
Selectafaculty
244
Illustrationofoperations:
facultyselected
Pickasubject
245
Illustrationofoperations:
subjectselected
246
13/05/2014
42
NetBeans project
Asyoumightexpect,thereisarequiredstructureforJSF
Thingslikecss stylesheets,Javascriptfilesetc,havetobelocatedin
subdirectories(JSFusesthetermlibraries)ofaresources
directoryinwiththewebpages.
247
Javacode
Subject
Alittlestructholdingsubjectcodeandother
data
SubjectData
AJSFManagedbeanclass
Responsibleforgettingthedata(acollectionofSubject
objects)fromthedatabaseandmakingthemavailable
totheJSFpage
248
Subject.java
249
SubjectData.java
Shouldhavebeenpossibleto
useresourceinjectiontoset
upthedatasource. It failed.
I couldnt bebotheredto
searchonGooglefor likelycause.
Sothedatasourceis set upusing
explicit JNDI lookups.
Datamembersmadeavailableto
JSF:
faculties listoffacultynames
chosen nameofcurrently
selectedfaculty
facultyofferings collectionof
Subjectinstances
chosenSubject selectedinstance
250
SubjectData.java
Constructor
Getdatasource
Usedatasourcetogetaconnectionandusethis
toretrievenamesoffacultiesandstorethesein
anArrayList<String>
Setsubjectdatatonull
Whenfacultyisselectedinwebpage:
Againgetconnectionfromdatasource
UsethistocreateacollectionofSubjectobjects
251
SubjectData.java
Accessandstatefunctions:
State?
Hasafacultybeenpicked?
Hasaspecificsubjectbeenselected?
Theseareneededtocontrolselectivedisplayof
elementsinthepage.
Access
Givemeacollectionoffacultynames
Givemethecurrentchosenfaculty
Givemethesubjectsofferedbythatfaculty
Givemethesubjectrecordforachosensubject
252
13/05/2014
43
SubjectData.java
Getfacultynames
selectdistinctfacultyfromsubject
Initialization
253
SubjectData.java
state
Hasafacultybeenselected?
Hasasubjectbeenselected?
254
SubjectData.java
access
Getselectedsubject,subjectsofferedbyafaculty,
listoffaculties,chosenfaculty
255
SubjectData.java
Choosingafacultyinformpage
1. Mutator setChosen
Nothingspecialaboutthis
2. Event
Alsospecifyachangeevent
Worktobedoneifthereisachangeofchosenfaculty(inthiscase
loadsubjectsforanotherfaculty)
Operationisdistinctfromsimplysettingthedatamemberchosen
Eventstyle:
WellIthinkitwasoriginallyMicrosoftsidea(Isaw it first in.Net stuff)
Itmakeswebprogrammingverysimilartowritingan
interactivenativeapplication(WebForms~WinForms,
JSF~Java+swing)
256
SubjectData.java
changeevent
RunSQLquerytoretrievethesubjectsofferedbyfaculty
257
JSFpage
Conceptuallyequivalenttoamore
conventionalpagewiththree<div>sections
and(CSS)controloverwhich<div>sare
displayed.
Alwaysshow<select>withchoiceoffaculties
Ifafacultyhasbeenselected,showatablewith
subjectcodesandtitles
Codesarelinkstogetdetailsofsubject
Ifasubjecthasbeenselected,showlecturerand
description
NotactualHTML<div>sectionsandcontroloverdisplaydoneinserverandonly
selectedpartssentinresponsepage
258
13/05/2014
44
259
JSFpage
<div>forfaculty
selectionform
<div>forfaculty
details nameand
tableofsubjects
offered;onlyshown
iffacultyselected.
<div>forsubject;
onlyshown
(rendered)ifa
subjecthasbeen
selected.
260
JSFpage
JSFform:
h:selectOneMenu mapsintoHTMLmenu(~select,justalwayssize=1);
f:selectItems JSFcoretags,takesacollection,generatessetofHTML
<select>items canspecifyvalueaswellaslabel;
onchange action donthaveanexplicitsubmitbuttoninthisform;if
thevalueoftheHTML<select>ischanged,thebrowserwillexecute
standardsubmit;valuespecifiesthatthesetChosen()methodofthemanaged
beanwillgetcalledwiththenewchosenfacultyname
valueChangeListener functionthatisalsotobecalledforthischangeevent
261
JSFpage
h:outputText renderediffacultyChosen()methodofmanagedbeanreturnstrue;it
showstextwithstringfromgetChosen()methodofmanagedbean.
h:datatable generatesHTMLtablethatwilldisplaydataincollectionretrievedby
getFacultyOfferings;usessomeCSSstyles;
tabledefinedbytheh:columnentriesthatspecifyfacets(likeheadertitlesfor
column)anddatatobedisplayedincolumn;
theentriesinthesubjectcodecolumnarecommandLink(i.e.submitbuttons) 262
CSS
263
Areyouimpressed?
Thatwasprobablythemostsuccinct,neatest
bitofwebcrudding thatyouhaveeverseen.
AsleekJSFpage
Justaverysimplemanagedbeanandastruct
ButprobablywonthavemuchappealtoyourSISATgraduate
colleagueswhoaredesigningthecompanyswebpresence
Theyarentgoingtomakemuchofthosetrulyweirdh:andf:tags
264
13/05/2014
45
Whynovisualpagebuilder?!!
WhenwelookatMicrosoftsversion,wewillsee
apagethatiscreatedusingaGUIstylepointand
clickeditorwithapaletteoftools(e.g.inserttable)
Picktool,addelement,uppopsdialogaskingfor
parameters(e.g.whatcollection?Anyrenderingcontrol?)
ThereusedtobeasimilarsysteminNetBeans
butnetbeans.org apologises theysimplydont
havetheresourcestomaintainit
AlsothereareanumberofstillmorespecialisedextensionstoJSFthatarecompeting
andwhichwouldrequirevariededitors
EclipsedoeshaveavisualdesignermoduleforJSF
265
Componentframeworks
Components?
Theyarethoseuserinterfaceelementslikethetable,
theactionbuttonsetc.
ItisalotclearerwiththeMicrosoftschemewhere
youcanactuallyusethesamevisualeditortocreate
eitheraWinForms application(equivalenttoaJava
applicationusingswing)oraWebForms applications
(browserasrenderer,eventssenttoserverside
application justaswithJSF)
TagsenteredastextinaJSFpage?
Doesntreallyseemlikedefininganinteractiveeventsource
component(asinaJavaswingprogram)
Butitisdoingjustthat
266
Thereareonly2webapps
Rememberthatthereareonlytwoweb
applications
1. Retrievesomedata
2. Addnewdata
Havedemonstratedwebapp1,sohowabout
aJSFversionofadataentryformthatadds
datatopersistentstorage
267
Lookma nohands!
Membersagain butthistimetryintruly
automatedstyle
NetBeans newJavawebproject,andyesituses
JSF
FirststepcreateanEntityclassfromdatabase(will
beusingJPAforthisexample)andapersistenceunit.
268
Almostwhatiswanted
ThisisforaMySQL database
Autoincrementprimarykey
Insertrecordswithanullvaluefortheprimarykey
Bestfixthegeneratedcodethatsaysitmustnotbenull
269
Next onebuttoncreateallcode!
NewJSFpagesfromentityclass
270
13/05/2014
46
Yourapplicationdelivered:
CRUDapplicationondemand:
271
Itruns:
Paginateddisplayofmemberdata
272
Wecanedit
273
Wecandelete
RemoveReTest;
274
Butwecannotquitecreate(yet)
Createformgeneratedhasafieldfor
id,butforthistabletheidisanauto
incrementintegerandshouldntbe
setbytheuser.
Also,thereisonlylimitedvalidation
doneondataentry wehaveabusiness
constraintthatthebirthyearbeinthe
range1920to1993;
wewouldalsolikechecksonemailand
names,
andfinallywouldpreferthatthe
Genderfieldbeaselectbox.
275
Bestlookatthegeneratedcode
OnlyCreate.xhtml
276
13/05/2014
47
Create.xhtml
Justasetofh:inputTextcomponentswith
accompanyingh:outputLabeltagsarrangedina
h:panelGrid
Theinputfieldsarealltaggedrequired=true,andhave
requiredMessage attributes
E.g.
requiredMessage=#{bundle.CreateMembersRequiredMessage_e
mail}
Alittleeditingisneeded
277
Messages?
Apropertiesfilewithmessageswasgeneratedalong
withtherestofthecode
Canmodifytomakemorerelevantandaddown
278
ModifyingCreate.xhtml
Removethefieldfortheid
Editotherrecordstoaddvalidators
OfcourseJSFhaspredefinedvalidator classes:
Checknumbers
Checkagainstaregex

Sodefineafewvalidators ontheinputfields
AlsochangethegenderentrytoselectOneMenu
withacoupleofitemfacets
279
Create.xhtml
f:validateRegexfacetsaddedtothegivennameandfamilynameinputs,
validatorMessage attributesaddedreferencingerrormessages(MyErrors_xxx)
addedtothemessagesbundlefile.
h:selectOneMenuwithtwof:selectItementriesforthegenderinput
280
Create.xhmtl
Yearofbirthentryfieldgetsanintegerrangecheck,emailfieldgetsaregex
checkwithafairlysimpleversionofemailregex
TheJPAclassalsohasitsownchecks,soifthenamesaretoolongwewillgeta
persistenceerror. Ithasanoptionalemailcheck onethatdoesntallow
capitallettersinemailaddresses.
281
Itworks!
282
13/05/2014
48
Itreportsanyinputerrors
283
Likemagic!
Nowthatwaseasywasntit.
Acompletecrudy applicationwithjusta
coupleofmouseclicksandsomeminor
editingtoaddvalidationtests.
Nowyouask
WhydidntyoujustshowusJSFinsteadof
draggingusthroughZend Framework,
servlets,JSPs,andstruts?
284
YouarentIS/ITstudents
StudentsinInformationSciences/Information
Technologydegreescanbeallowedtobelievein
magic
TheycanbeshownjustJSF(or,farmorelikely,the
Microsoftversion)andtoldthatallthatisrequiredto
createawebapplicationisacoupleofmouseclicks
andmaybesomeminorediting.
YouareCSstudents.
Youaresupposedtounderstandhowthings
actuallywork
285
BackingComponents
IfyoudelvefurtherintoJSFyoucanlearn
aboutBackingComponents
Theseareclassesthatyoudefinetomodelinyour
Javaapplicationapartof,ormaybetheentiretyof
adatainputform.
TheJavacodewillworkwithUIInput objectsthat
canrepresentinputelementsintheform.
Givesyoumoresophisticatedcontroloverthe
handlingofinputdata butitsrelativelyrare
toreallyneedsuchclasses.
286
JSF lotstolearn
JSF
Itsbig
6taglibraries
Core,HTML,Facelets (userinterfaceelements),composite
components,(partsof)JSTL,andJSTLfunctions
AndthatswithouttheAJAXextensions
287
JSFextensions
288
13/05/2014
49
Javawebapps
Diverse!
Threeorfourtier:
4tier(CSCI398)(browser,webcontainer,applicationengine,database)
ServletandJSPinthewebcontainer
BusinesslogicinEJBsessionbeansintheapplicationengine
Automateddatapersistence(JPA)
3tier(browser,webcontainer,database)
Basics:
Servlet,JSP,JPA
Advanced usingvariousextensiontechnologies
Numerous!
289
Javawebapps
3tierextensiontechnologies:
Struts1and2
JSFanditsextensions
Others
Tapestry,wicket,
JRuby
Googlewebtoolkit
ComponentframeworkusingAJAXratherthanpagepostback

290
Companychoosestechnology
IfyoubecomeaJavawebdeveloperyouwill
notmeetthemall
Someoneincompanywillhavechosenthe
technologystackthatistobeemployed
Youwillhavetospecializeinthat
291
Mostefficientwebtechnology?
ProbablyoneoftheJavavariants
Persistenceofservercomponentsandprecompiledcode
InJava,serversidecomponentsarecreatedatdeploymenttimeorat
firstusetime
Donthavetorecreateobjectsasyoudowiththescriptingtechnologieslike
PHPand,atleasttosomedegree,withMicrosoft
Javawillhavebeencompiledto.classfilesbeforeoratdeployment
time;compilernotneededatruntime(whereasscripting
technologiesrecompile)
ServersideJavacompilationwillconvertmoreheavilyusedcodeto
actualmachinecoderatherthanbytecode
Kicksinonlyafteraburnintimetoidentifyheavilyusedcode canmake
measurementofJavaperformancetrickyasgetsfasterasyourunit
Myguess:a4tierversionwithEnterpriseJavaforthebusiness
logic
292

Potrebbero piacerti anche