Академический Документы
Профессиональный Документы
Культура Документы
Backin1997
Webapplication
JavaServlets
ManystaticHTMLformpages Eachgettingorpostingtoadifferentaction
Action?
Cprogram Shellscript Perlscript probablymostpopularatthattime ASPscript(ActiveServerPages) rapidlygainingpopularity, shortlytobecomefavouriteforsmallwebsites PHP3script(rare)
Javaservlets
ServletsareatthecoreoftheJavaweb technologies Othertechnologies JavaServerPages, frameworkslikeStruts,JavaServerFaces,etc all buildontheservlettechnologies. ServletswillformpartofanyJavawebsolution butitisrareforservletsalonetobeusednow
GenerationoffinalHTMLpageisbetterdonewithsome othertechnology.
Servletsaregoodforcodingtheapplication,butnotgoodatgenerating prettydisplays!
Chaotic!
Webapplicationswereessentially unstructured
AdirectoryfullofHTMLpages,scriptfiles,odd picturesetc
OrmaybetheHTMLfilesetcwereinonedirectory,atthe scripts/executablesincgibinoranotherdirectory
NothingtorelateaHTMLpagetoascript Get?Post?
Noconsistencyinusage,justsomestylesuggestions
Iflotsofdatausepost, Onlyusegetifrequestsimplyreadsbutdoesnotupdatedata
Amaturetechnology
Thedefinitionofservletsdidhaveaminorupdatein ~2008,butreallytheyaretheoldestofthe technologiesthatwediscuss datingbackto~1997. Atthattime,servletswereinnovative
Amuchcleanerconceptualizationofhowawebserver shouldwork Contributedgreatlytodevelopmentofthenowstandard applicationserver/businesscomponentmodelusedin mostenterprisecomputing.
Redundantrepetitiouscoding
Webapplicationsallrequiresimilarfeatures
Authentication
Whoareyou?Nameandpasswordplease.
Authorization
Iknowy you, ,y youareallowedtop performtheseactionsand accessthissubsetofdata
Databaseusage
Establishadatabaseconnection,use,release
7/02/2013
Configuration/deploymentdatain code
Thecodingstyleswouldhavehadthingslike databasedetailshardcodedinthesource code
Ifyouneedtoredeploy, deploy e e.g. g changethedatabase password,youneededtoeditthesource(and
mayberecompileandrebuildifaCbasedapplication)
Anundisciplinedmess!
Backin1997,webapplicationswere undisciplinedandmessy. There h mustbe b ab betterway! !
Enter servlets
Processcreation
Technologiesinuseweremainlybasedaroundforking servermodel
Newrequest?
Createnewprocess(fork) Loadrequiredprogram(exec)
Mightbecompiledcode therewereafewapplicationsthatusedC but usually ll that h meantfirst f loading l d the h interpreterthen h l loading d and dcompiling l a scriptfile
Servletconcept~1997:1
Awebapplicationisasingledeployable entity
Allfilescomprisinganapplicationmustbeorganizedina standard,definedmannerandbepackagedasa deployablearchivefile
Runthecode
Awebapplicationencompassesmanyuse cases
Eachusecaseishandledbyaseparateelement aservlet inthewebapp
Sessionstate
Maintenanceofsessionstateproblematic
Maintainstateonclient
Hiddenfieldsinformswerepopular Cookiesusedalittle Notecostoftransferringstatedatawitheachrequest andresponse(andgreatervulnerability)
Servletconcept~1997:2
Eachservletisaremotelyaccessedserverthat handlestherequestmessagesdefinedbytheHTTP protocol
Get,Post, AlsoOptions,Head,Put,Delete,
Maintainstateonserver?
Filesystemmainly Orintemporarydatabasetables
Maintainedinmemory
Nocosttoreload,recompile Ifmemorygetslow,servletcanberemoved
Itwillgetrecreatedifneededagainlater
7/02/2013
Servletconcept~1997:3
Servletsshouldbethreadsafeandbecapable ofhandlingmanyconcurrentusers. Authenticationandauthorizationshouldbe handledcentrallyanduniformly
Thedatadefiningpermissionsfordifferentclasses ofusersshouldbeseparatefromcodeandshould beeditablebyasystemsadministratordeploying theapplication.
Anewmodel
Thereisaserverengine
Itsmorethanjustawebserver,itisamulti threadedenginethatsupportsbusinessobjects
Multithreading geasierforJavathanCbackin1997
Javahasthreadsaspartoflanguagedefinition, Cthreadlibrarieswereplatformdependent
Higherconceptuallevelthanthealternativeofthetime
ASP,modPerl,(modPHP)
Letusextendthewebserverbyincludingthecodeofourinterpreter; thenwehandlereturnofscriptfilesdifferently,werunthemrather thanjustreturningthem
Servletconcept~1997:4
Servletmodelshouldprovideefficientbuiltin supportforsessionstate
Sinceservletspersistinmemory,theycan maintainpersistentdatainmemory
Serverengine
Responsibilities:
Configurationof,andlifecyclemanagementofthe servlets(businessobjects)andtheirassociated data( (sessions, ,etc) ) Handlingcommontasks
Authenticationandauthorization
(Managementofdatabaseconnections wasntpartoftheservlet containerdefinition; itcamewithEnterprise JavaBeansthefollowing year;servletcontainers arenotobligedtoprovidesuchservices.)
Servletconcept~1997:5
Application 2 Servlet1 Servlet2 Servlet3
Serverengine
Multithreaded
Inearlyimplementations,thiswouldbethread perrequest
Onreceiptofrequest(viaHTTP)createanewthread (ortakereusablethreadfromthreadpool)anduseit toruntherequest
i.e.executetherequestedmethodoftheservlet
Servletcontainer
Servletcontexts separated, noncommunicating
Application1
Servlet1 Servlet2 Servlet3
7/02/2013
Servlet
Servlet
AbusinessobjectrespondingtoGet,Post,Put
Businesslogic
Simpleapplication
Theservletdoeseverything
Gettheinputdata Checkit diverttoerrorhandlingpageifdatainvalid Composerequeststodatabase Runthem Workthroughresults Formataresponsepagewiththeappropriatedatafrom thedatabase Returnresponsepage
Servlet
Potentially,multiplesimultaneoususerseach usingownthread
Dontstorerequestspecificdataininstance variables variables
Localvariablesdeclaredwithinfunctionsarethread specificandquitesafe
Businesslogic
Complexapplication
Theservletitselfhandlesonlycontrol
Createadataobject tellittoloaditselffromthe submitteddata Askitwhetheritisinvalid? Ifsodivertittoanerrorhandler. Ifthedataobjectishappy,letitdoworkwiththedatabase (eitherprovidingitwithadatabaseconnectionorwiththe dataitcanusetomakeadatabaseconnection) Askitfortheresults Maybehandlefinalresponsepagepreparationormaybeuse anotherhelperobject
Mightyouhaveinstancedata(datamembersof servletclass)?
Sometimes,butavoidifpossible
Servlet instancedata
Databaseconnection?Logfile?
Somedatabasedriversarethreadsafe
Canhavemultipleselectorinsertorupdaterequestsrunning onsamedatabaseconnection Ifthreadsafedatabasedriver,itissensibletohaveservletmaintaina databaseconnectionasaninstancemember open p itjust j onceand keepusingit. Uhm howdoyouknowifthedriverthatyouwillbeusingisthread safe.
Servletasacontroller
Initiallyjustaprogrammingidiom
Thisisthebestwaytodealwithcomplexbusiness logic
Laterbecomesmoreformalizedwithextension librariesandframeworkssuchasstruts
Struts(~2000)isaMVCframeworkwithsupport scriptsandtools
Providesakindofstandardizedactioncontrollerservlet, andautomaticallydefineddataobjects, Youdefinedactionclassesandviewtemplates
7/02/2013
Servletsandfrontcontroller
Originalmodelforservletswasthateachhandledone usecase(or,sometimes,apartofoneusecase) Somedevelopers(strutsandothers)laterchangedthis tohaveasingleservletthatactedasadispatcherto applicationspecificclasses
Allrequestsroutedtotheoneservlet Itdeterminedthespecificcontrollerandactionrequired Toolscreatedtosupportthismodele.g.automatedcode generators
Still,itisgetParam()
Servlets(atleastwithoutextensionlibraries)dont offeranythinglikethestyleyouvejustlearntwith Zend_Form intheZend framework
Givemetheformobject Formobject,givemeareferencetotheselectobject namedcountry Selectobject,tellmewhichcountrytheuserpicked
Actually,thisstylereallycomesfromMicrosoftwho popularizeditwhenintroducing.NET
Ourservlets
Wewillnotbeusinganyoftheframeworks justtheclassicmodelwithourownservlet classesmakinguseofhelperobjects (instancesofclassesthatwewilldefinefor ourselves)
ItisJava! Hence,classesandclasshierarchies
Ofcourseeverythingisbasedaroundclasses hastobebecauseitsJava. p being gtaught g aboutclass Youvekept hierarchiesbutprobablyhavemostlybeen shownrubbishexampleslikeBankAccount withsubclassesChequing,Saving,Mortgage etc Timetomeetusefulhierarchies!
Serverengine/servletcommunication
ServerenginehidesmuchofthelowlevelHTTP stuff; offerstheservletarequestobjectanda responseobjectwithwhichtowork
Servlet l canask kthe h requestobject bj for f the h value l of fa parameter(doesnthavetoscrabblethroughthe encodedrequeststring)
Canalsoaskforvaluesofaccompanyingcookies,detailslike browserinuseetc
Servletclasshierarchy
Backin1997,Sunwasproposingtowritea servletenginethatwouldruntheseservlet businessobjects
Theyhavetobecreated,configured,toldtosave themselvesifabouttobedestroyed, y maybe y asked aboutloggingdataetc. IfworkingwithHTTP,theyhavetobetoldtohandle Get,Postetcrequests
Sunmadeallowanceforotherprotocolsenteringuse(hasnt happenedyet)sosomekindsofservletmighthavetohandle differentrequests
Servletcangetanoutputstreamfromresponse objectandaddoutputdata.
Actually,atthistimeMicrosoftsASPofferedsimilarrequestandresponseobjectsthoughtherest ofanASPscriptwasmuchlessobjectbased
7/02/2013
How?
Defineahierarchy!
Aninterfacespecifyingfunctionalitythatallserverobjects hostedinacontainermusthave. Apartiallyimplementedabstractclass
Addssomemorefunctionsignatures Provides P id someli limited it d(overridable) ( id bl )i implementation l t ti of fsomeof f functions
Sun:servletproposal
SunsapproachwasdifferentfromMicrosoft
Microsoftownsatechnologyanddoesitsbest tostymiepotentialcompetitors Sunsapproach
Wedefinethestandard(possiblywithhelpfromwider community) Weprovideareference implementation Othercompaniesencouragedtocreate(higher performance)implementations
Weprovideacertificationservicethatcheckswhetheragiven implementationfullymeetsthedefinedstandard.
Obviouslywrongapproach; Sunisdead,Microsoftstillwellalive!
AclassforhandlingHTTP
Adispatcher ifrequestisgetcalldoGet()elsif requestispost calldoPost()elsif DonothingemptyhandlersfordoGet etc.
Serverenginecannowbewritten
Callstothesedefinedmethodsofservlets
Servletclasses
Servlet(interface)
init(),destroy(),get (config,info),service()
Configuration
Sunsproposalincludeddetailsofhowservlets weretobeconfiguredanddeployed
Ideawasthatcouldbuildaservletapplicationand thendeployontodifferentimplementations
IBM,BEA,Sunenterprise,othercompanies
GenericServlet(abstract)
Addslogging,parameters, context,
HttpServlet(abstract)
doGet(),doPost,do
Configurationdataweretobeseparatefrom code
Needtobeeditablebysysadmindeployingthe application
MyServlet!(concrete)
doGet()doPost()
Originally,followedthefashionofthetimes
Noconsistencyinusage,justsomestylesuggestions
Iflotsofdatausepost, Onlyusegetifrequestsimplyreadsbutdoesnotupdatedata
Configurationdata
Dataforconfigurationinseparatetextfilesthat mustbeincludedinthedistributablearchivefile alongwithcompiled.classfilesetc. Format?
XML
Itwasjustbecomingfashionablebackin1997
doPost()
Checksubmitteddata
Ifinvalid,redisplayentryformwithpartialdataanderrormessages
web.xml file
Aservletapplicationwillhaveaweb.xml configuration file.
Basically,similardatatothatwhichyousawwithZends application.ini file.
Ifdatavalid,continuewithallotherprocessingsteps.
Examplesthatfollowmayvary;most(all?)usetheshowform/handleformidiom
7/02/2013
Howtobuildit(in1997)?
Sunproposedthreeapproaches
Standaloneservletcontainers Inprocessservletcontainers Outofprocessservletcontainers
"Servletcontainers"
Outofprocessservletcontainers
Webserverhas"module"orplugin(notJava)ofsome form Havesecondserverprocessthatprovidesservlet environment Webserverhandlesstandardpagerequests(andanyCGI orscriptingthatmightalsobesupported) Servletrequestsroutedviaplugin tosecondprocess (TCP/IPlink,possiblyUnixratherthanInternetprotocol) Significantcostsbutadvantageofscalability
"Servletcontainers"
Standaloneservletcontainers
Javabasedwebserver
HandlesgetrequestsfornormalHTMLfilesetc DoesnothaveanythinglikeApache'srangeofoptions f serverside for id i includes, l d CGI CGI,etc
Servletcontainers
Standaloneandoutofprocessprovedthemore popular Wewillberunningastandaloneserver Glassfish Inreal lindustrial d lscale l d deployments, l itistypical ltohave h Apacheasafrontend
Apacheconfiguredwithaservlethandlerelementthat forwardsrelevantrequeststoanapplicationserversuchas IBMsWebSphere,Oraclesappserver,oranenterprise versionofGlassfish(alsofromOraclethesedays).
"Servletcontainers"
Inprocessservletcontainer(directcompetitorto modperl,php)
webserverplugin
JVMinsidethewebserver's server saddressspace RequestthatinvolveaServlet,passedviapluginto servletcontainer&JVM multithreadedsingleprocessservers goodperformancebutlimitedscalability.
1997 whathappenednext
Theservletmodeldelightedthebigenterprise companiessuchasbanks
Disciplined,secure,softwareengineeredapproach suitedtheirneeds Widespread Wid dtake t k upb bylarger l companies i
Java
Javaswitchesfrombeingaclientsidelanguage (Appletsinbrowsersandlocalhostedapplications)to beingpredominantlyaserversidelanguageforbig business
ThenewCobol
7/02/2013
1997 whathappenednext
Servletenginesstarttobecreated
Sundidprovideone Apacheprojectcreatedabetterone(Tomcat); otherse.g. e g Axiscreatedlater later. IBMadoptsthistechnologyandextensively promotesit(Oraclealso,thoughstartingalittle later)
Backinthosedaysmanyothersoftwarecompanies existedandtherewereotherofferings.
Netbeans glassfish:problems
IfNetbeans/glassfishsystemgetsshutdownimproperly,itmay leaveworkfilesinthesedirectories(holdingdatalikeprocess numbers) AsubsequentrestartofNetbeans/glassfishmaythenfail(itjust hangs)
Ifthishappens,delete allthedirectories thatwerecreatedandstartagain creatinganewdomain domain
Netbeans/glassfishsetupsometimesfailstoshutdownOracle databaseconnectionsproperly
Oracleknowsthatyouarentthere Oraclewontletyoustartanewsessionbecause itsangrythatyoudidntsay goodbyelasttime Onlysolution seeyuan 3.228thedatabaseadministratorwhoistheonly personwhocanshutthoseoutstandingconnections
Ouruse
Glassfish
VariantofaSunEnterpriseJavaapplication server(supportsbasicWebandmoreadvanced EJBservices)
Nowtosomedegreeopensource Hasbasicedition(free)andpaidforenterpriseedition
Applicationserveradministration
Netbeans installercreatesaglassfishwhere anonymouslogintotheserveradministration consoleispermitted
Itisnotwisetoleavethisdefaultsetting
1. Loginasanonymous 2. Usetheadminconsoleapplicationtocreatean administratoraccountwithpassword. 3. Logoutofadminconsoleapp(endinganonymous session) 4. Logbackinusingnewaccountandremovetheoption foranonymouslogin!
Netbeans glassfish
Netbeans installationincludesGlassfishapplication server
Serverrequiresmanyconfigurationfilesetc
Installincludesaproductionconfigurationownedbyroot obviouslyyoucannotusethatone. WhenfirstaskNetbeans tocreateaWeborEnterpriseproject,it willcreateaprivatesetofconfigurationfilesforyou yourown domain
Directorieswillinclude.netbeans,.netbeansderby,.netbeans registration,mydomain, Atsametime,scriptswillchooseportnumbersfortheglassfishserver HTTPandHTTPSports(cannotuse80etcasthesebelongtoroot) OtherportsusedbyGlassfishe.g.CORBAconnection, admin consoleetc.
Anotherproblem
Thisonemayonlyrelatetomoreadvancedusein CSCI398
Someconfigurationfiles,includingthoserelatingto CORBAconnectionsetc,includethenameandIP numberofthecomputer. Soifyoucreateconfigurationdataononelab computer,thentryworkingonanothercomputeryou mayfindthatyoucannotconnecttotheserver.
7/02/2013
Windowsusers
Dontplaceanyofyourfiles,orthe NetBeans/Glassfishfiles,indirectoriesthat haveaspaceinthename(e.g.Program Files,MyDocuments) ManyoftheJavadeploymenttoolswillfall overonencounteringaspace aspacemarks theendofthestringwithafilename; soinsteadoflookingforafilenamed
C:\\DocumentsandSetting\xyz\MyDocuments\NetBeans Projects\WebApp1\dist\webapp1.jar
Squarerootservlet
Servlet
AbusinessobjectrespondingtoGet,Post,Put
doPost
ShowmetheresultofprocessingthedatathatIentered
i.e.numericsquarerootorerrorreportifdatainvalid
ItlooksforC:\\Documents
Derby
ThefreedevelopereditionofGlassfishcomeswith theDerbydatabase
Derby(alldoneinJava)isafreeSQLrelationaldatabase systemnowmanagedbyApachegroup(thoughoriginating f from IBM)
NoparticularadvantageoverMySQL oranyoftheothers.
Squarerootservlet
AspecializedsubclassofHttpServlet
Yourfirstservlet
Netbeans IDE Glassfishserver
7/02/2013
HttpServlet
protected voiddoDelete(HttpServletRequest req,HttpServletResponse resp) Calledbytheserver(viatheservicemethod)toallowaservlettohandlea DELETErequest. protected voiddoGet(HttpServletRequest req,HttpServletResponse resp) Calledbytheserver(viatheservicemethod)toallowaservlettohandleaGET request. protected voiddoHead resp) d H d(HttpServletRequest (Htt S l tR t req,HttpServletResponse Htt S l tR ) ReceivesanHTTPHEADrequestfromtheprotectedservicemethodandhandles therequest. protected voiddoOptions(HttpServletRequest req,HttpServletResponse resp) Calledbytheserver(viatheservicemethod)toallowaservlettohandlea OPTIONSrequest.
doGet()~showForm()
HttpServlet
protected void doPost(HttpServletRequest req,HttpServletResponse resp) Calledbytheserver(viatheservicemethod)toallowaservlettohandle aPOSTrequest. protected void doPut(HttpServletRequest req,HttpServletResponse resp) Calledbytheserver(viatheservicemethod)toallowaservlettohandle aPUTrequest. protected void doTrace(HttpServletRequest req,HttpServletResponse resp) Calledbytheserver(viatheservicemethod)toallowaservlettohandle aTRACErequest. protected long getLastModified(HttpServletRequest req) ReturnsthetimetheHttpServletRequest objectwaslastmodified,in millisecondssincemidnightJanuary1,1970GMT. protected void service(HttpServletRequest req,HttpServletResponse resp) ReceivesstandardHTTPrequestsfromthepublicservicemethodand dispatchesthemtothedoXXX methodsdefinedinthisclass. void service(ServletRequest req,ServletResponse res) Dispatchesclientrequeststotheprotectedservicemethod.
doGet()~showForm()
ResponseContentType:
response.setContentType("text/html;charset=UTF-8");
Contenttypes
Typically,servletsreturnHTMLpagessotheresponsetype istext/html Occasionally, Occasionally youwillhaveaservletthatreturnsdatafor animage,andtheresponsetypewouldbeimage/png or image/gifetc(dependingonhowtheimagedatawere encoded). But,forsomeoddreason,thedefaultresponsetypeis text/plain
ThebrowserwilldisplayalltheHTMLmarkupetc Soyouhavetosettheresponsetypeexplicitlyeverytime.
doGet()~showForm()
Outputstream
PrintWriter out = response.getWriter();
HttpServletResponse
Providesaccesstotheoutputstream,
andmethodsforaddingheaders,forsendingredirectionresponses, changingstatuscodesetc.
10
7/02/2013
HttpServletResponse
void addCookie(Cookie cookie) Addsthespecifiedcookietotheresponse. void addDateHeader(String name,long date) Addsaresponse headerwiththegivennameanddatevalue. void addHeader(String name,String value) Addsaresponse headerwiththegivennameandvalue. void addIntHeader(String name,int value) Addsaresponse headerwiththegivennameandinteger value. boolean containsHeader(String name) Returnsaboolean indicatingwhether thenamedresponse headerhasalreadybeenset. String encodeRedirectURL(String url) Encodes thespecified URLforuseinthesendRedirect method or,ifencoding isnotneeded, returnstheURLunchanged. String encodeURL(String url) Encodes thespecified URLbyincludingthesessionIDinit,or,if encodingisnotneeded, returnstheURLunchanged.
out.println()
NotthebestwayofformattingaHTMLpage
Problems
Youreallycannotgetmuchofanideaforwhatthepage willlooklikefromthesestatements Itscode!
Yourwebdesignercolleaguewillnotbeabletoprettyit up
IalwaysforgettoincludeaDOCTYPE directiveatstart.Ishouldputthemin!
HttpServletResponse
StringgetHeader(String name) Getsthevalueoftheresponse headerwiththegivenname. java.util.Collection getHeaderNames() <String> Getsthenamesoftheheadersofthisresponse. java.util.Collection getHeaders(String name) <String> Getsthevaluesoftheresponse headerwiththegivenname. intgetStatus() Getsthecurrentstatuscodeofthisresponse. voidsendError(int sc) Sendsanerrorresponse totheclientusingthespecified status codeandclearsthebuffer. voidsendError(int sc,String msg) Sendsanerrorresponse totheclientusingthespecified statusand clearsthebuffer.
out.println()
Notasbadasitlooks
TheJavacompileroptimisesthisthroughtheuse ofaStringBuffer object
SodontreallykeepallocatingnewStringobjectsinthe heap
HttpServletResponse
voidsendRedirect(String location) Sendsatemporaryredirectresponse totheclientusingthe specifiedredirectlocationURLandclearsthebuffer. voidsetDateHeader(String name,long date) Setsaresponse headerwiththegivennameanddatevalue. voidsetHeader(String name,String value) Setsaresponse headerwiththegivennameandvalue. value voidsetIntHeader(String name,int value) Setsaresponse headerwiththegivennameandintegervalue. voidsetStatus(int sc) Setsthestatuscode forthisresponse.
doPost()~processdata
Typically
1. RetrieveposteddatafromtheHttpRequest object 2. Validateinputs
Onerror
Simplysendaredirectresponsereferencingastandardizederror reportpage(lazy) Generateadynamicresponsepagewithappropriateerrormessages (tiresome) GeneratearesponsewiththesamesubmitformasobtainedbydoGet Acceptableinputsfromsubmissionusedtoinitializevaluesof inputfields Errorcomments andhighlightingoffieldswheredatarejected (thepreferredprofessionalapproach)
3.
Favouredvariant justcreateaninstanceofaspecialized dataclass,fillitsmembers with inputdatareceived,askittovalidateitself.
11
7/02/2013
doPost()~processdata
Typically
3.
HttpServletRequest
InterfaceHttpServletRequest extendsServletRequest
Thereisanimplementingclass HttpServletRequestWrapper (ofnointeresttomost programmers) Many M methods th d defined d fi dat tServletRequest S l tR t
Originally,Sunthoughtthattheremightbeotherprotocolsusing servlets,andsoprovidedmethodsallwoulduse,andmethods specifictoHttp
OnlyHttpusedinpractice
Performingdataprocessingoperations
Useprivateauxiliaryfunctionsthatyouaddtoyourservlet
4.
GenerateresponsewithappropriateHTMLheadetc
Ofcourse,thesquarerootservletisalittle simplerthanthetypicalservlet
GrabinputvaluefromHttpRequest, processit(viahelperfunction), slotresponseintoblockofstandardHTMLoutput
doPost()~processdata
(justsomeofthemethodsof)ServletRequest
ObjectgetAttribute(String name)
ReturnsthevalueofthenamedattributeasanObject,ornullifnoattributeofthe givennameexists.
EnumerationgetAttributeNames() <String> ReturnsanEnumerationcontainingthenamesoftheattributesavailabletothis
request.
StringgetCharacterEncoding()
Returnsthenameofthecharacterencodingusedinthebodyofthisrequest.
intgetContentLength()
Returnsthelength,inbytes,oftherequestbodyandmadeavailablebytheinput stream,or1ifthelengthisnotknown.
StringgetContentType()
ReturnstheMIMEtypeofthebodyoftherequest,ornullifthetypeisnotknown.
ServletInputStreamgetInputStream()
RetrievesthebodyoftherequestasbinarydatausingaServletInputStream.
StringgetLocalAddr()
ReturnstheInternetProtocol(IP)addressoftheinterfaceonwhichtherequestwas received.
SevletRequest.getParamater(paramname)
String datastring = request.getParameter("data");
(justsomeofthemethodsof)ServletRequest
LocalegetLocale()
ReturnsthepreferredLocalethattheclientwillacceptcontentin,basedonthe AcceptLanguageheader.
EnumerationgetLocales() <Locale> ReturnsanEnumerationofLocaleobjectsindicating,indecreasingorderstartingwith
thepreferredlocale,thelocalesthatareacceptabletotheclientbasedontheAccept Languageheader.
StringgetLocalName()
ReturnsthehostnameoftheInternetProtocol(IP)interfaceonwhichtherequest wasreceived.
intgetLocalPort()
ReturnstheInternetProtocol(IP)portnumberoftheinterfaceonwhichtherequest wasreceived.
StringgetParameter(String name)
ReturnsthevalueofarequestparameterasaString,ornulliftheparameterdoesnot exist.
Map<String,getParameterMap() String[]> Returnsajava.util.Map oftheparametersofthisrequest.
String[]getParameterValues(name)
Formultivaluedparameters.
12
7/02/2013
(justsomeofthemethodsof)ServletRequest
Enumeration<getParameterNames() String> ReturnsanEnumerationofStringobjectscontainingthenamesoftheparameters
Servlet3:Async
Servlet3specificationaddedmethodslike isAsyncSupported(),startAsync()
Theseexisttosupportweirderuseswithserver push thingslikeCOMET Theconnectiontoclientiskept p open p andfurtherdata canbesent
containedinthisrequest.
String[]getParameterValues(String name)
ReturnsanarrayofStringobjectscontainingallofthevaluesthegivenrequest parameterhas,ornulliftheparameterdoesnotexist.
StringgetProtocol()
Returnsthenameandversionoftheprotocoltherequestusesintheform protocol/majorVersion.minorVersion,forexample,HTTP/1.1.
BufferedReadergetReader()
RetrievesthebodyoftherequestascharacterdatausingaBufferedReader.
StringgetRemoteAddr()
Exotic
MayserveasalternativetoAJAXinsome circumstances WebSockets willeventuallyofferalternativefor situationswhereasync mighthavebeenuseful
(justsomeofthemethodsof)ServletRequest
RequestDispatchergetRequestDispatcher(String path)
ServletRequest
ServletRequest hasmethodsappropriatefor anyrequestprotocol
Getdetailsofremotemachine Getdetailsofrequest q format Assumingrequestisgoingtoincludeasetof parameter/valuepairs,getthevalueofa parameter
Returnsthenameoftheschemeusedtomakethisrequest,forexample,http,https, orftp.
StringgetServerName()
Returnsthehostnameoftheservertowhichtherequestwassent. intgetServerPort() Returnstheportnumbertowhichtherequestwassent. ServletContextgetServletContext() GetstheservletcontexttowhichthisServletRequestwaslastdispatched. booleanisSecure() Returnsabooleanindicatingwhetherthisrequestwasmadeusingasecurechannel, suchasHTTPS. voidremoveAttribute(String name) Removesanattributefromthisrequest. voidsetAttribute(String name,Object o) Storesanattributeinthisrequest. voidsetCharacterEncoding(String env) Overridesthenameofthecharacterencodingusedinthebodyofthisrequest.
Anold interface
Datesbackto1997 notetheuseof EnumerationratherthanIterator asin getParameterNames()andgetLocales()
Ifyouneedthese these,havetostepthroughcollections usingmethodsofEnumeration
Locales
Forcustomizingresponses Internationalization
(justsomeofthemethodsof)
HTTPServletRequest
booleanauthenticate(HttpServletResponse response)
UsethecontainerloginmechanismconfiguredfortheServletContextto authenticatetheusermakingthisrequest.
StringgetAuthType()
Returnsthenameoftheauthenticationschemeusedtoprotecttheservlet.
String
Cookie[]getCookies()
longgetDateHeader(String name)
Returnsthevalueofthespecifiedrequestheaderasalongvaluethatrepresentsa Dateobject.
StringgetHeader(String name)
ReturnsthevalueofthespecifiedrequestheaderasaString.
Enumeration< String>getHeaderNames()
Returnsanenumerationofalltheheadernamesthisrequestcontains.
objects.
13
7/02/2013
(justsomeofthemethodsof)
intgetIntHeader(String name)
HTTPServletRequest
Extras
HttpServletRequest
AccesstoCookies,HttpHeaders, SupportforHttpauthentication Supportforsecurityrolesetc etc.
Returnsthevalueofthespecifiedrequestheaderasanint.
StringgetMethod()
ReturnsthenameoftheHTTPmethodwithwhichthisrequestwasmade,for example,GET,POST,orPUT. StringgetPathInfo() ReturnsanyextrapathinformationassociatedwiththeURLtheclientsentwhenit madethisrequest. StringgetPathTranslated() Returnsanyextrapathinformationaftertheservletnamebutbeforethequery string,andtranslatesittoarealpath. StringgetQueryString() ReturnsthequerystringthatiscontainedintherequestURLafterthepath. StringgetRemoteUser() Returnstheloginoftheusermakingthisrequest,iftheuserhasbeen authenticated,ornulliftheuserhasnotbeenauthenticated. StringgetRequestedSessionId() ReturnsthesessionIDspecifiedbytheclient. StringgetRequestURI() Returnsthepartofthisrequest'sURLfromtheprotocolnameuptothequery stringinthefirstlineoftheHTTPrequest.
(justsomeofthemethodsof)
StringBuffergetRequestURL()
HTTPServletRequest
HttpServletRequest :Servlet3
Servlet3specificationaddedsomenewelementsto HttpServletRequest,mostnotablebeingsupportforfile uploads
Oddly,Sunhadomittedthisfromoriginalservletspecificationeven thoughfileuploadalreadywidelyused Developershadtohackouttheirownsolutions gettheinputstream, parseitforyourself, Eventually,Apache.org createdaproject(ApacheCommons)to supplystandardsolutionstogapsinSunsJava(servletwasonlyone exampleofwheretherewereanomalies) MostfileuploadexamplesthatyouwillseeforJavaservletswilluse Apachecommons.
PartgetPart(String name)
ReconstructstheURLtheclientusedtomaketherequest.
StringgetServletPath()
Returnsthepartofthisrequest'sURLthatcallstheservlet.
HttpSessiongetSession()
Returnsthecurrentsessionassociatedwiththisrequest,oriftherequestdoesnot haveasession,createsone. HttpSessiongetSession(boolean create) ReturnsthecurrentHttpSession associatedwiththisrequestor,ifthereisno currentsessionandcreateistrue,returnsanewsession. PrincipalgetUserPrincipal() Returnsajava.security.Principal objectcontainingthenameofthecurrent authenticateduser. booleanisRequestedSessionIdFromCookie() CheckswhethertherequestedsessionIDcameinasacookie. booleanisRequestedSessionIdFromURL() CheckswhethertherequestedsessionIDcameinaspartoftherequestURL. booleanisRequestedSessionIdValid() CheckswhethertherequestedsessionIDisstillvalid.
GetsthePartwiththegiven name.
Collection<Part>
getParts() GetsallthePartcomponentsofthisrequest,providedthatitisoftypemultipart/formdata.
(justsomeofthemethodsof)
booleanisUserInRole(String role)
HTTPServletRequest
doPost()~processdata
voidlogout()
14
7/02/2013
Processinputforsquarerootservlet
web.xml
BuiltasaprojectinNetBeans
NetBeans alwaysaddsindex.jsptoaJavaWeb project
Inthisexample,canusethispagetoholdalinkthatwill invokethesquarerootservlet
Servletmapping
URLtoservletname
web.xml
Servlet
Servletnamemappedtoservletimplementationclass
Oneuseofmappings
youalreadyhavepublishedlinkswithaURLlikeinfo.htmlanddecideto makethisadynamicallygenerated pageratherthanstatichtml fine,justmaptheinfo.htmlurl totheservletthatgenerates dynamic content
Theweb.xml file
XMLfilewithSchema
Doesgetchecked,willnotdeployiffailsvalidationtests
Usedtobeaproblemindayswhenyoueditedweb.xml inatext editor,easytomakemistakeslikeputtingelementsinwrongorder NoproblemifconstructedusingNetBeans wizard wizard
web.xml
Sessiontimeout
Doesntapplyincaseofsquarerootservletwhere dontcreateanysessiondata. Itsetsadefaultvaluefortimeoutanddestruction ofsessiondataifthesearecreated
Ifnottouchedbyanyrequestfor30minutes,session datadestroyed
Purpose?
Inpart,similartoapplication.ini fileswithZend,it holdsconfigurationdatafortheapplication AlsodefinesURLmappings
15
7/02/2013
Webarchive
IfyouinvokecleanandbuildonJavawebproject,NetBeans willbuildawebarchivefile(.warfile)withadistributable copyofyourapplication
Oneofcoreobjectivesincreatingservletmodelwasthatapplicationscouldbe built,andtheresultingwebarchivecouldthenbedistributedtoproduction environments (possiblyusingdifferentservletcontainers)
Generalfeaturesofservlets
Lifecyclemethods,inputs,outputs, context,
Structureofwebarchive(.war)file
Toplevel AnystaticHTMLpages,JSPs; images,Javascriptfiles,CSSfilesetc cangointoplevel,butbetterifyou createsubdirectories forthese. METAINFdirectory Summarydetailsofcontents ofwar file WEBINFdirectory web.xml file librarysubdirectory ifusing speciallibraries otherelements suchastaglibrary descriptors classessubdirectory subdirectories forpackages,these contain.classfiles Standardized.AllJavawebcontainers usethissameorganization.
Lifecycle:init
init()(GenericServlet.init()oroverride)
Calledwhenservletloaded
Atypically,aservletmaybeloadedwhencontainerstarts
Simplyadd<loadonstartup/> toservletentryinxmlfile
Typically,servletloadedwhengetfirstrequest
Usetoreadparametersfromxmldeploymentfile
getInitParameter()(fromservletconfigurationorservletcontext)
Couldbeusedtoopenadatabaseconnection
Thiswouldbekeptinmembervariableofservlet, Shouldusesynchronizationlockforallworkusingconnection
Deployandrunonglassfish
Lifecyle:service(,)
Calledforeachrequest
OverriddeninHTTPServlettodispatchtoauxiliary functions
RequestandResponsearguments
Instancesofwrapperclasses
HoldTCP/IPinputandoutputstreamsforclient Provideotheraccesstowebserverdata
Threadperrequestorthreadpool(dependsonyour container)
16
7/02/2013
Lifecycle:destroy()
Containercandestroyaninactiveservlet
Timeoutconstraintscanbespecifiedincontainer configurationfile
HTTPServletsubclass
getServletInfo
Usefulonlyifemployingsomesophisticateddevelopment environmentthatallowsyoutomanipulateservlets, deploythemetc SingleStringusetodescribeservlet
StringgetServletName();
Lifecycleoddities
Extrathreadsdoingwork
JavaServletProgramminghasanexample
athreadcontinuallycalculatinglargeprimenumbers, clientscanconnectandbeissuedwithmostrecentlyfoundprime
Servlet
Also
ServletConfig getServletConfig()
Configurationdataforthisservlet
Morerealisticexample
Extrathreadhasconnectiontodatafeed(e.g.currencyexchange ticker) Processesdata,performingsomecomplicatedcalculation(identify pricedifferentialsforcurrencyspeculators) Clientsconnectagaintogetmostrecentdata
SevletContext getServletContext()
Configurationdataforagroupofservlets
Careneeded!
mustshutdownthesethreadsindestroy() MayneedlimitstopreventthreadsusingtoomuchCPU
publicabstractclassHttpServlet extendsGenericServlet
Providesanabstractclasstobesubclassedtocreate anHTTPservletsuitableforaWebsite. Youmustoverrideatleastonemethod,usuallyone ofthese:
doGet, ,iftheservletsupports pp HTTPGETrequests q doPost,forHTTPPOSTrequests doPut,forHTTPPUTrequests doDelete,forHTTPDELETErequests init anddestroy,tomanageresourcesthatareheldforthe lifeoftheservlet getServletInfo,whichtheservletusestoprovide informationaboutitself
ServletConfig
Configurationparameterdatafromweb.xmlfile
StringgetInitParameter(Stringname); EnumerationgetInitParameterNames();
17
7/02/2013
ServletContext
StringgetServerInfo()
Name,versionnumberetcofcontainer
Request
intgetServerPort() StringgetServerName() Lotsmore ServletInputStreamgetInputStream() BufferedReadergetReader() EnumerationgetParameterNames() StringgetParameter(Stringname) String[]getParameterValues(Stringname)
ObjectgetAttribute(Stringname)
Containermaydefineavarietyofimplementationspecific attributes Shoulddefinejavax.servlet.context.tempdir
StringgetInitParameter(Stringname)
Canhavesomecontextwideinitializationparameters
Request
Cookie[]getCookies() StringgetAuthType()
BASICetc ifHTTPauthenticationspecified
Outputs
Redirectionandforwarding Headers Responsecontent
EnumerationgetHeaderNames() StringgetHeader(Stringname)
AskforanyspecificHTTPheader:CHARSETACCEPTetc
SessiongetSession() StringgetQueryString()
Request
StringgetMethod()
GET,POST,PUTetc
Redirection
Errors
DontincludelotsofcodetoproduceHTMLerror pages,simplyredirectrequesttoastaticHTML p g page
StringgetRemoteUser
Assumeshttpauthentication
18
7/02/2013
Forwarding
Everythinghappensonserverside ServletAdoessomework
Constructsdatastructure Linksthistostructuretothesessionobjectorpossiblyto therequestobject Forwardstherequest,responseviaaRequestDispatcherto somethingelseonserver(anotherservlet,oraJSPpage)
Responsecontent
getServletOutputStream
forbinarycontent,
getWriter
text/html /h lortext/plain / l i content
ServletB(orJSPpageB)
Doesmorework,generatesfinalresponsetoclient(or forwardsagain)
Havesomecontrolsoverbuffering
Headers
Asusual,anyheadersmusthavebeensentbefore starttowritecontentviawebservercomponent ServletResponse
setStatus(int code) sendError(int code,Stringmsg) ThesesetthereturncodeinHTTPresponsefirstline ResponseclassdefinesconstantsSC_OK(200), SC_NO_CONTENT(204)etc (defaultisSC_OK)
Secondservletexample
Membership
Headers
HTTPServletResponse.setHeader(String headername,Stringvalue)
SetthingslikeLOCATION,EXPIRES,CONTENTTYPE (defaultstotext/html)
Servlet1
Membership
Verysimpleapplication
Enterpersonaldatainform Createnewmemberrecordindatatable Returnmembershipnumber
Servlet2
Viewdataofselectedmember
Cansendanauthenticateheader,thenpickup user,passwordetc
Illustrates
Servletparameters JDBCstyleconnectiontodatabase Useofadataobjectthatvalidatesitselfetc
19
7/02/2013
Membershipproject
Twoservlets,andaselfcheckingdataobject class+aJDBClibrary
NetBeans InsertCode
Remember NetBeans canhelpwhengenerating standardcode
sqlstuff
Forconveniencewhiledevelopingtheproject,Iplacedthe fileswithsql createtablestatementsintheproject;theyget includedthedistribution
Dontdothisinpractice,keepthemsomewhereelse;itjustadds potentialexposuretohackerattacks
MemberRecord
Errorsmember stringwherebuildupreportonvalidation errors. Examplesofaccessor/mutator (getters/setters)functions
MemberRecord
MemberRecord
Fieldscorrespondingtocolumnsoftable Functionality
Validation Erroridentification Loadandstorefromdatabase
MemberRecord validation
MemberRecord iscreatedbyservletcodeand populatedwithposteddata; thenaskedtovalidate
Eachmembershouldhavevalidationmethodusingregex orotherchecks
20
7/02/2013
Morevalidationchecks
Load
male.equals()??? wellthisworksevenifgenderisnull!
Overallvalidationmethod
JSP&HTML
NetBeans createsindex.jsp
Canturnthisintoawelcomepagewithlinkstoservlet
UsuallybettertojustgetridofitandcreatestaticHTMLwelcome page.
Save
JSP&HTML
OtherstaticHTMLpages thingslikemiscellaneouserror reports
21
7/02/2013
Theservlets
Commoncode(duplicated!)
init(),getDBConnection(),errReport()methods anddatamembersrelatingtodatabaseaccess
Pickingupinitializationdata
Drivername,usernamefordatabase,URL, passwordetc
Allconfigurationdatathatshouldbeeasily changedbypersondeployingapplication Servletscanpickupsuchdataininit()method
init()
Readparametersfromservletconfig data
22
7/02/2013
MebershipServlet.doGet()
Usualproblem whatdoesthepagelooklike?
MembershipServlet.doPost()
1. Readsubmitteddata convertstringsto numerics 2. Createrecordandpopulate y 3. Checkvalidity
Ifinvalidgenerateerrorreport
4. Connecttodatabase 5. Attempttosaverecord
Anydatabaseerrors?RedirecttostockHTMLpage
6. Savedok?Reportpagewithmembernumber
MebershipServlet.doGet()
Usualproblem whatdoesthepagelooklike?
Read,convertdata
MembershipServlets formpage
Lookslikethis
Create,populate,andvalidate selfcheckingrecord
23
7/02/2013
Customerrorreport
Canuseredirecttoerrorpagewhensimplywanting toindicateanerror;butifprovidingfeedback,need somekindofcustomizederrorreporting
Savingrecord
Establishdatabaseconnection
Getconnection
Failure redirectbrowsertostaticHTMLpage
Finalresponse
Gettingdatabaseconnection
ViewRecordServlet.doGet
Errorlogging youwouldprobablywantsomethingmoresophisticatedinproductionenvironment
24
7/02/2013
ViewRecordServlet.doPost
Getandvalidatedata; customerrorreport
Contextparameters
Canremovetheparametersfromthe individualservletsanddefinethemascontext parametersinstead
Errorreportsonfailures
ViewRecordServlet.doPost
Changetheservletcode
Justpickupdatafromthecontext
Config andContext
Config data servletspecific Herebothservletsneedthesameparameters
Servletconfig/context
Servletconfig objects withparameters from web.xml
Servlet1
Servlet2
contextparameters fromweb.xml
25
7/02/2013
TheDatasource approach
Theproblemswiththisapproach:
1. Youhavetohaveaprogramthatyoucanusetocreate DataSource objectscontainingrequireddata,andwhich canstorethemintherepository. 2 Any 2. A programusing i aDataSource D t S must tinclude i l d code d t to contacttherepositoryandlookuptheDataSource by name,andthendownloadit
ItisabitlikegettingaCORBAclientstubobject(infact,the repositoryandtheJavaNamingandDirectoryInterfaceJNDIare derivedfromCORBAsNameService andtheCOSNaming interfaces)
JDBCdriver/Datasource
MessyJDBCcode
Howdoyougetaconnection?
Class.forName(dbdriver); db = DriverManager.getConnection(dbURL,username,password);
UsingDataSources
DataSource objectsarejustplaininconvenientforsimple standaloneJavaSEprograms. Buttherearenoproblemswhenyouhavesomethinglike servlets,aservletcontainer,andanIDElikeNetBeans
Glassfishcan
ActastherepositoryfortheinitializedDataSource objects RunaJNDInamingservice Addelementstotheservletcontainerthatsupplyaservletwitha connectiontotheJNDIservice
JDBCDriverManagerapproach deprecated
Yearsago,Suntriedtogetprogrammerstoadopta morestructuredapproachtosettingupadatabase connection
Basicideaofnewscheme
1 1. 2. 3. 4. 5. Haveainitializeddatastructures, structures containingallinformation neededtosetupadatabaseconnection(URL,user,password, driverdetails) TheseDataSourceobjectsstoredinsomerepository,given suitablehumanreadablenames Programscontactrepository,requestresourcebyname ProgramsloadDataSource object ProgramsgettheirdatabaseconnectionsfromtheDataSource objectsthattheyhaveloaded
CreatingaDataSource object
NetBeans hasawizard
NewfileoftypeGlassFish/JDBCResource
26
7/02/2013
Addedtoproject
DetailsoftheDataSource (actuallyinformationon howtofinditinglassfish)appearina ServerResourcescomponentintheproject
JNDInameshouldbesomethinglikejdbc/aname
NetBeans helpers
IfyouhaveusedNetBeansServices/Database,youwillhave connectiondefinitionssetupthere. NetBeans knowstousetheseasmodelswhencreating datasources
Changestoproject
Theprojectnolongerrequiresthelibrarywiththe.jarfilefor thedriver.
WhenaprojectwithaDataSourcereferenceisaddedtoGlassfish, thelibrarywiththedriverisaddedtotheclasspath usedbytheweb container.
Connectionpools
NetBeans/Glassfishwillsetupconnections usingconnectionpools(providedthereisa suitableclassinthe.jarfileforthedatabase)
Glassfishwillopenseveralconnections Whenaprogramasksforaconnection,itgetsone ofthesepreopenedconnections Whenaprogramclosesaconnection,itisnt actuallyclosed;instead,itiscleanedupandput backinthepoolforreuse
Changestoproject
Theinit()andgetDBConnection()methodsareupdated:
27
7/02/2013
Caution SQLvariations
WithDataSources,adeployer couldchange thedatabaseusedsimplybychangingthe nameofthedatasource(jdbc/somethingelse) intheweb.xml web xml file
Yes,but
GiventhelimitedstandardisationofSQL,itislikelythat someoftheSQLstatementsareinadatabasespecific dialect.
Imagefromadatabase
Sometimesappropriatetostoreanimageina databaseasablob Maythenwanttoreturnitviaaservlet
Setreturntypetotypeforimage Loadbytesfromblobrecordindatabase Writebytestooutput(binary)outputstreamassociated withResponseobject
Returninganimage
public class ImageViewServlet extends HttpServlet { @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String imageid = request.getParameter("ident"); int idval = 0; try { idval = Integer.parseInt(imageid); } catch (NumberFormatException nfe) { return; } Connection conn = DBInfo.connectToDatabase(); PreparedStatement pstmnt = null; byte[] data = null;
Settingup pickingupparameters,openingdatabaseconnectionetc
Returningresponseslikeimage/jpg
Typically,aservletwillreturnaresponsepage thatisaHTMLpage(text/html) Sometimes,youwanttoreturnanimage
Image I data d t stored t din i adatabase d t b Imageisgeneratedprogrammatically
SimilartousingGDinPHP
try { pstmnt = conn.prepareStatement( Myexamplehadatable CARSinOraclewithablob "select pic from CARS" + calledpic " where carid=?"); pstmnt.setInt(1, idval); ResultSet rs = pstmnt.executeQuery(); if (!rs.next()) { return; } data = rs.getBytes(1); } catch (SQLException sqle) { return; } finally { try { conn.close(); } catch (Exception e) {} }
Loadingtheblobdataasbyte[]
28
7/02/2013
ImageServlet
JustadoGet()method returnsafixedimage
Returningthebytesasimage/jpg
Generatinganimage
SimilartoGD
1. Allocatespaceforimagebuffer
Awidthxheightarrayof4bytepixelrecords r,g,b,alpha
NotasgoodasGD
Traditionallymorelimitedchoiceofencoders
ImageIO library,arelativelyrecentaddition,hasimproved things
Lotsofpoorlydocumentedvariantsforstructureof imagebuffer!
SimpleGraphicWebApp
Drawoperations
index.jsp index jsp
Has<img >linkreferencingtheservlet
29
7/02/2013
Sessions
Youmustrememberthis
Outputofimage aspng
WhatfontscanIuse?
Ask:
Sessions
Yes,wewillusetheubiquitousshoppingcart exampletoillustratesessions. Ourapplication
Shoppingservlet
Letsyouadditemstoyourshoppingcart
Thereshouldbequiteafew:
Viewcart servlet
Letsyouseethecontentsofyourshoppingcart.
Everyclientwantshis/herownshoppingcart
So,thisisrepresentedassessional datalinkedto individualclientsessions
Headlessservers!
Youmightrunintoproblemsgeneratingimagesonaserver machinerunningvariantsofUnix/Linux
AWTlibraryusedbyJavahassomecodeoftheformGiveme detailsofthedisplaydevice Serversdonthavedisplaydevices! AWTcodefails nopicturedrawn. drawn
Sessionidentifier
Individualsessionsarekeptdistinctviasession identifiers Javasystemwillcreateasessionidentifierina mannersimilartoPHP
(Pickpseudorandomnumber number,MD5hideit)
InJava,thisidentifierisakeytoahashmapkept inmemorybytheapplicationserver
Eachuserrunningasessional applicationhastheir ownsessiondatakeyedbytheallocatedsessionid
Keywillbesenttobrowser
asvalueofacookienamedjsessionid
30
7/02/2013
Sessionstate
Javaservletsprovidesupportformaintaining sessiondatathatisgenerallysimilartoPHPs $_SESSION[]andsessionfunctionslike session_start() Coupleofdifferences
Servletenginestoressessiondatainmemory(notin filesasinPHP) MechanismthatsupportsURLrewritingisless automatedthanPHPs (youcodemustexplicitlymake provisionfortheneedtorewritetheURL)
Creatingasession
Yourservletcodecancheckwhethersessionstatehas beenestablished:
Therequestobjecthasamethodeffectivelyoftheform: getSession(boolean optionallyCreate)
Sotypically,inawebapponeoftheservletswould create t the th session i aspart tof fits it handling h dli of fadoGet() d G t()or adoPost()
Otherservletswouldsimplycheckthatthesessionhad beenestablishedandreportanerrorifitwasmissing
Example shopping
Ashoppingservletwouldcreateasession(fortheubiquitousshoppingcart)if itdidntalreadyexist,butuseanexistingsessionifalreadyestablished Acheckoutservletwouldcomplainaboutlackofasession(howdidyougetto thecheckoutwithoutdoinganyshopping)
Actualsessiondata
Thesessiondataobjectcreatedforaclientis itselfahashmapofkey/valuepairs
SessiondataobjecthasmethodslikegetAttribute andsetAttribute Key=string Value=instanceofapplicationchosenclass
TypeinAPIisObject Explicittypecastsmustbeusedwhenretrievingdata
Thatinterferingindex.jsp
JSPs bydefaultcreatesessions soifyour websitestartsatindex.jsp,youshouldhavea sessionfromtheoutset. SoinyourtypicalNetBeans application, application the index.jsp willhavetriedtoestablishasession
ThedirectivesinaJSPallowyoutospecifythataparticularstartingJSPdoesntwantsessions.
Paranoidcookieless customers
AsinPHP,URLrewritingisusedtodealwith clientsthathavecookiesdisabled.
URLrewritingembedsthesessionid intothepath namesusedinallthe(internal)linksinaresponse page
Iftheclientclicksonalink(ahref,img src,formaction,) therequesthasthesessionid embedded
Startingout
JSPwithlinkstotwoservlets stilltobe implemented
31
7/02/2013
Getbrowsertowarnoncookies
Wanttotrackcookiesforthisdemo
Dealingwithcookieless customersinaJSP
WhereyourJSPpagehaslinks,youmust somehowencodethesessionidentifierinto thelink
Canbedonewithclumsyscriptlets BestapproachistouseJavaStandardTagLibrary actiontags
Seethatcookie
Requesttoset cookieforJSP
Dealingwiththeparanoid
AddJSPactionstoURLencodesessionid
includetheJSTLtaglibrary
Pagesent
Pagewithsessionids embeddedinlinks
Applicationserverknowshowtoremovesuchsessionid datafromarequestURL
32
7/02/2013
Therestoftheapplication
Nowthatguaranteedtohavesessionidentifiers maintainedbybrowser,cancontinuewithrestof application!
Otherclasses
StockItem
Identifier,description,cost
Stock
Collectionofstockitems,methodstofindspecific items(byid)etc
Item
Identifier,number
Shopping
Collectionofitems
Servlets
ShopTillYouDropServlet
doGet
Displayaformpagewithalistofpurchasableitems
Listisfixedanddefinedindataforp program g simply p ybecauseI didntwanttoaddadatabaseelementtothisexample;of course,inrealapplicationthedataonpurchasableitems wouldcomefromarelationaltable
Data
BothservletscreateaninstanceofStock
Inarealapplication,bothservletswouldhave connectionstoadatabasetablewiththesedata
Sessiondata
Sessionobjectassumedtoexist(shouldhavebeen createdbytheindex.jsp welcomepage) ShopTillYouDropServlet addsaShoppingobjectas anattributecalledcart
doPut
Submitteddataidentifychosenitemsandquantities Addthesetocontentsofshoppingcart
ViewCart
doGet
Retrieveshoppingcartfromsessionstatedata Generateapagelistingcontentandtotalcost
StockItem
33
7/02/2013
Item
ShowTillYouDropServlet
Stock
ShopTillYouDropServlet.doGet
Generatingaformwithentriesforeachitem instock
Entriesaretextinputfieldsfornumbertobuy Entrynamesaretheproductidentifiers
Shopping
ShopTillYouDropServlet.doGet
34
7/02/2013
ShopTillYouDropServlet.doGet
Nosessionid?
ShopTillYouDropServlet.doPost
Becausecookiesarepresent!
ShopTillYouDropServlet.doPost
CheckforaShoppingobjectinsessiondata(create oneifnoneexists) Processsubmitteddata
Unusualform!
GetEnumerationwithnamesofsubmittedparameters
ThesenamesshouldbeStockItem identifiers,thevaluesarethenumber ordered
ShopTillYouDropServlet.doPost
Loop
Checktheidentifiers,ifnotrecognisedignorethatinput Checkorder ifinvalidornonnumericignorethatinput Addappropriateitemtoshopping
(Re)attachshoppingobjecttosessiondata Generateresponsepage
ShopTillYouDropServlet.doPost
Getparanoidaboutthis
35
7/02/2013
Startover
Servletinteractions
C Iset Can tacookie ki please? l ?
Ihavetakenthelibertyofputtingthekeyinthelinks,justincaseyou refusemycookies.
OK,nocookies
Servletinteractions
Sometimes,convenientforagroupofservletsina contexttosharework
OK,Illnotsetanycookies
Sharingdata Sharingprocessingofarequest
Datasharing
Usethedatabase Or,usecontextobjectmuchlikeasessionobject
Add,read,removedataobjects
ButIdoknowwhoyouare!
Stateinmemory
Appserver holdingsessiondatainmemoryis moreefficientthanPHPapproachwheredata areactuallystoredinfilespace. Butmayexacerbateproblemofscaling scalingout out andrunningapplicationonmultiplemachines
Reallydohavetohavesubsequenttrafficreturnto sameservermachine
PHP?Well,maybecouldhaveasharedfilespace thoughthatmightnotbetoopractical.
Sharingdataviacontext
Noclearguidelinesastowhenwouldprefer thisapproachtouseofdatabase. Basically
Shared Sh ddata: d t information i f ti to t be b displayed di l dby, b or utilizedinseveralotherservlets Controlservletthatcreatesthesedataandadds themasanattributeofcontext Userservlet(s)thatreaddatafromcontext
36
7/02/2013
Addingdata
ControlServlet.doPost()
Pickupdatafromformfilledinbyuserofcontrolservlet. Packagedatainsomestructure(classThing{}) Storeincontext,associatingdatawithsomeagreed attributename
Thing myThing = new Thing(request.getParameter(, ); ServletContext cntx = getServletContext(); cntx.setAttribute(theMagicData, myThing); }
Forwardingapartially processedrequest
publicvoiddoGet(HttpRequestreq,HttpResponseres)throws { Stringstr=req.getParameter(); Thingthing1=newThing(,,) req setAttribute(FirstThing thing1); req.setAttribute(FirstThing, Stringservlet2Name=/Servlet2; RequestDispatcherrd=req.getRequestDispatcher(servlet2Name); rd.forward(req,res);
Retrievingdata
Inotherservlets
ServletContext cntx = getServletContext(); Thing myThing = (Thing) cntx.getAttribute(theMagicData);
Requestdispatching
Possibleapproaches:including
Servlet1
Doessomeofprocessingofrequest,producingdataitems GeneratesapartoftheHTMLresponse Getsrequestdispatcherforanotherservlet Invokesotherservletviadispatcher,askingforitsoutputstobe includedinresponsebuffer
Servlet2
Isupposeitisquickerthangoingtoadatabase
Doessomeprocessing GeneratesmoreoftheHTMLresponse
Servlet1
Resumesprocessing,generatesremainderofresponse
Requestdispatching
Possibleapproaches:forwarding
Servlet1
Doessomeofprocessingofrequest,producingdataitems Attachesitsdataitemsasattributesofrequest ObtainsarequestdispatcherforServlet2 Forwardsrequest(withattributes)andresponseviarequest dispatcher
ExampleincludingotherServlet outputs
DukesbookstoreexamplefromSunsJavatutorials
BannerServlet.java
GeneratesafewlinesofHTMLdisplayingbookstoresname
Servlet2
Completesprocessing GeneratesHTMLresponse
37
7/02/2013
Dukebookstore: codefragments
publicclassCashierServletextendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest, HttpServletResponseresponse)throws { response setContentType("text/html"); response.setContentType( text/html ); PrintWriterout=response.getWriter(); out.println("<html><head><title>Cashier</title></head>"); RequestDispatcherdispatcher= getServletContext().getRequestDispatcher("/banner"); if(dispatcher!=null) dispatcher.include(request,response);
Uploadingfiles
Codefragments
publicclassBannerServletextendsHttpServlet{ publicvoiddoGet(HttpServletRequestrequest, HttpServletResponseresponse)throws {PrintWriterout=response.getWriter(); out.println( bodybgcolor=\"#ffffff\">" bgcolor \ #ffffff\ + out.println("<body "<center>"+"<hr><br> "+ "<h1>"+"<fontsize=\"+3\"color=\"red\">Duke's</font>"+ "<fontsize=\"+3\"color=\"purple\">Bookstore</font>"+ "</h1>"+"</center>"+ "<br> <hr><br>"); } publicvoiddoPost(HttpServletRequestrequest, HttpServletResponseresponse)throws {/*identicalcode*/}
Fileupload
OmittedbySunfromoriginalservlet specification
OmissionnotcorrecteduntilServlet3in~2008
Implementationscontributedbyothers primarilyApache/commonsproject
Dukebookstoreexample: otherfeatures
Useofservletcontext
Hascollectionofbookrecordsratherthanrealdatabase CatalogServlet arrangesforthistobeinstantiatedand savedasanattributeofservletcontext
Stillbitclumsy
Multipartformdatareadasacollectionof Parts
Allareasfiles Soifyouhaveformdataotherthanfiles(usual textinputsetc)theygetuploadedintoafile Togetparameters(otherthanrealfiles)youmust readthedatafromfile. Sigh
38
7/02/2013
Example
Formwillhavean<inputtype=file>fieldforafile, andan<inputtype=text>fieldforatagname Uploadfileintoaspecifieddefaultdirectory,givingit anamebasedonthetagname andthefiletype(as specifiedindatacharacterizinguploadedfile)
FileUploadServlet.doGet()
Showstheuploadform
FileUploadServlet
Needsanextraannotationthatmarksitasaservlet thatwillbeworkingwithmultipartformdata:
FileUploadServlet.doGet()
Remembertosettheenctype attributeontheform!
Andtheacceptattributeinthe<inputtype=file>element
@MultipartConfig
Arguments:
location:directorywherefileswillbecreated(this examplewasrunningonWindowshenceC:/tmp/) maxFileSize:largestuploadable file maxRequestSize:limitontotaldatauploaded(you mightbeuploadingseveralfiles) fileSizeThreshold:dataareloadedintomemoryon upload,butifexceedthislimitthensavedto temporaryfiles
FileUploadServlet.doPost()
GetsthePartsfromtherequest.
Forthosepart(s)thatcorrespondtosimpleform parameters
OpenaBufferedReader thatworkswiththe inputstream associatedwiththePart Readthedata
39
7/02/2013
FileUploadServlet.doPost()
Accesscontrolonwebapplications
Largeproportionofwebapplicationsrequire authenticationandauthorization. Servletconceptentailedthatthisverymuch y standardizedworkshouldbehandledmainly bytheservletcontainer
Avoidshavingsimilarcodeappearinginlotsof applications Allowsusersandgroupstobeadministeredat corporatelevel
Ratherthanhiddenineachapplication
FileUploadServlet.doPost()
Partsarenamedbyfield namesinform. Pickupthe(image)file data
Aspects
Users
Usernamesandpasswordsasisstandard
Storedinsomerepositorybelongingtotheservletcontainer,sothere aregoingtobeimplementationspecificdetails
Groups
Gettheinputforthe simple<inputtype=text name=tagname > Laboriouslyreadit!
Forconvenience,canallocategroupstousers
Dontthenhavetolistalluserspermittedaccesstoanapplication, justidentifythegroups
developer,sysadmin,clerical,management,external,
Roles
Applicationspecific
Personswhocanactinaspecificroleareauthorizedtoinvoke doGet/doPost/onspecifiedservlets Servletbehaviourmaydifferaccordingtoroleofuser
Implementationspecificschemeforassociating users(orgroups)androles
40
7/02/2013
Authenticationmethods
Ifaservlets web.xml doesspecifyaccess controls,containerwillinterceptinvocationsof methodsofthatservlet. Whenuserfirsttriestoaccessaservlet,theyget challengedtoidentifythemselves
Canusesimpleaccesstorealmdialogasisstandard forHTTPinbrowsers Applicationcandefineacustomloginform Canusemoresecuremechanismssuchasdigest authentication
Example:Acmeemployeesworkrecords
Acme(asmallwebdevelopmentcompany)hasasystem ofpayingemployeesbythehourforwork
Manydifferentworkcategorieswithdifferingpayrates
Employeesbelongtodifferentgroups
Boss, Boss managers, managers workers
Webapplication
servesallemployees Hasthreeservlets onerestrictedtouserswithspecificrole, twohavingbehavioursthatareroledependent
Inthisexample,rolesandgroupsareessentiallysynonymous(butthis onlytendstohappeninsimplesituations;usuallytherearerolesthat overlapseveralgroups)
Interceptingthefirstrequest
TheinitialGet/Postrequesttoacontrolledservletisintercepted Theapplicationserverdoesntrespondtotherequest,insteadit dealswiththelogin possiblysendingaformandreceivingareply withnameandpasswordthatitcancheck Ifloginissuccessful,applicationserverwilltrytoresumethat originalrequest
But,anydatathatwassentwiththatrequestmayhavebeenlost!
Example:Acmeemployeesworkrecords
Threeservlets
Recordworkdone
Specifynumberofhoursandworkcategory
Workcategoriesdependonroleoruser
Viewpaymentdetails d l
Anyonecanseehowmuchtheyareduetobepaid Personsinmanagerialrolescanalsoseehowmuchisto bepaidtotheirunderlings
Defineworkcategoriesandrates
Restrictedtotheboss
Customizingaservlets behaviour
ServletAPIcanretrievedetailsofthecurrent authorizeduser
Principal whoarethey Roles Roles cantheyactinroleX?
Ratesrecords
Obviouslybelongindatabase Butfrequentlyaccessedbydifferentservlets Notthatmuchdata maybetwentywork categories(namestrings)andrates(doubles) Socandidatetogoinsharedcontextdata
Whenfirstfindneedfordata,loaditfromdatabase Keepinacopyinmemoryspeedingaccess Ifratesrecordsarechanged,updatethedatabaseand destroymemorycopy anupdatedversionwillbe loadedwhennextneeded
Soasingleservletcangivedifferentresponses tousersindifferentroles.
41
7/02/2013
NetBeans andGlassfishimplementation
UseGlassfishadminconsoletocreateusersand assignthemgroups Whendefiningservlets,useweb.xmleditor wizardtodefinerolesandallowedservletusage. Beforedeploying,createanotherxmldeployment file
Thisisimplementationspecific(associatedwith glassfish) Itsdatamapgroups(orindividualusers)ontoroles
MySQL tables
Creatingusersinglassfish
Configuringlogin
Canusebasic
Workswithdefaultdialogonbrowser Lazy,unattractive
Generallyuseform form
CustomsitespecificloginanderrorHTML pages Formontheloginpage
Fieldnamesj_username andj_password Datapostedtoj_security_check (builtincomponentof appserver)
MySQL tables
Iagainhaveplacedthesql filesintheprojectdirectory ok fordevelopmentanddemos,butdontdothisonareal installation!
Configuringlogin
42
7/02/2013
Definingroles
Inthisexample,rolesareessentiallythesameas thegroups
Roles
Employee Manager M Boss
Mappingrolestousers/groups
Mappingtologingroups
Employee=acmeworker Manager=acmemanager Boss=acmeboss
Definingroles
Placingrestrictions
Addarestrictiontowelcomepage(index.jsp) Employee Thiswillbringuploginpageonfirstaccess(sodone beforegettinganywherewheremightbeposting data)
Mappingrolestousers/groups
Implementationspecific
needaglassfishdescriptorxmlfile
NowneedtologinwhengotoACMEsite
43
7/02/2013
Whereislogininfoheld?
Ifusingform,thedetailsoftheusernameare keptinsomeappserverrecordcollection indexedbysessionidentifier
TheACMEwebapp
RatesServlet bosschanges rates; RecordWorkServlet employee recordsclaimfor hoursworked; ViewRecordsServlet viewyourrecords(or recordsofsomeone thatyoumanage) ErrorReport servletthatdealswithforwarded errormessage.
TheACMEwebapp
Severalservlets
Noteduplicationofcodeamongservlets
(Thedesignofthisapplicationissimilartothatofmostearlyservletwebapps. Duplicationofcode wellthatwasoneofforcesthatleaddevelopersto createmoresophisticatedsolutionswheretheservletpartbecamemoreand morerestrictedtojustflowcontrol.)
Entityclasses:JobRecord
Severallittleentity yclasses
Theseareprogrammerdefined
Regularnatureoftheseclasseswasoneofforcesthatleadtocreationof automaticobjectrelationalmappingschemes
Databaseconnection
Allusecasesforthisappneedtoaccessthedatabase remember tocloseconnections!
Returnfromservletmethodwithconnectionopenleadstoproblems:
Connectionobjectbecomesgarbage Connectionwillclosewhenfinalize() invoked(part ofgarbagecollection process) Butifthereislotsofmemoryfree,GCwontgetrun soconnections leftopen Eventually runoutofconnections!
UsedtoholddatareadbackfromWorkdone databasetable
TheACMEwebapp
Databaseaccess
UsingaDataSource (andMySQL)
Entityclasses:RateRecord
Assumesthatcookiesareenabled
Code C d d doesnt include i l d statementsthat h add ddsession i identifiertolinks
44
7/02/2013
Entityclasses:RateRecord
Entitycollections
Frequentlyneedcollectionsofentityobjects, andneedoperationslikefindingentitiesin thiscollectionthathavespecificproperties. Goodapproachistoinvententitycollection classes
UseastandardJavautil Collectionclass Provideapplicationspecificaccessmethods
Entityclasses:RateRecord
EntityCollections:PayRates
AninstanceofPayRates isessentiallyaninmemory copyofthePayrates datatable
Methods
Loadallpayratedata Findspecificentry
Entityclasses:RateRecord
PayRates
45
7/02/2013
RatesServlet
Deployment
Restricttoboss
Auxiliarymethods
Forwardanerrormessagetoanerror reportingservlet
Allthreeofthemainservletswillneedtogenerate theodderrorpagewhensomethingamiss
Placeallthatcodeinalittleservletthatjustdisplays errormessages
doGet
Showform
Listwithallexistingjobcategoriesandtheirrates(+extra entryallowingnewcategory) Textboxfornewcategory Textboxforrate Submitbutton
doPost
Eithercreatenewrow,orupdateexistingrow;force replacementofinmemorycopyofratesdata
HTML5datalistwouldhavebeenconvenient here.
RatesServlet
Deployment
ErrorReport
Foronce,processRequestisappropriate!
MaybereportinganerrorduringdoGet orindoPost
RatesServlet
doGet,doPost,andsomeapplicationdefinedprivateauxiliary functions forwardanerrorreport,pickupthePayRates objectfromServletcontext,openadatabaseconnection
Auxiliarymethods
Getdatabaseconnectionfromdatasource
46
7/02/2013
Auxiliarymethods
AccessPayRates object(forceitscreationifit doesntalreadyexistinservletcontext)
RatesServlet:doGet
RatesServlet:doGet
RatesServlet:doPost()
Validateinputs,performinsertorupdate
RatesServlet:doGet
RatesServlet:doPost()
47
7/02/2013
RatesServlet:doPost()
RecordWorkServlet:doGet
Thisissegmentthatisroledependent:
Response
RecordWorkServlet
Deployment
CanbeusedbyanAcmeemployee
RecordWorkServlet:doGet
Customization
Formshowingworktypesvarieswithroleofuser
Worktypesforacmeworkersarethesoftwaredevelopmenttasks Managershavemostlymeetingsandclientcontact Bossdealswithallthemorehighlypaidwork
Socodethatchecksforuserrole
DuplicatecodefromRatesServlet
Getdatabaseconnection,getPayRates object (creatingincontextifnecessary),forwarderrorreport
RecordWorkServlet
RecordWorkServlet:doGet
Response
Colinsview(theboss)
48
7/02/2013
RecordWorkServlet:doGet
RecordWorkServlet:doPost
Samuelsview(manager)
Davidsview(employee)
RecordWorkServlet:doPost
GetUserPrincipal
identifieswhoisusingtheservlet(needtheirnamewhen creatingrecordinWorkDone table,alsoinresponse)
RecordWorkServlet:doPost
chainedmethod invocations (probablynotused muchinyourC++ andJavasubjects, butcommonin mostOOprograms)
Checkdata
forwarderrormessageifproblems
Createnewrecord(auxiliaryfunction) Generateresponse
(Makesureyouclosethedatabaseconnection)
Generate responsepage
RecordWorkServlet:doPost
Getuser
ViewRecordsServlet
Deployment
Anyacmeemployee caninvokedoGet;managerscanuse doGet anddoPost
Customization
doGet worksdifferentlyforacmeworkers and acmemanagers
Checkinputs
doPost
Handlessubmissionbymanagerbydisplayingrecordsofchosen person
49
7/02/2013
ViewRecordsServlet
ViewRecordsServlet:doGet
ViewRecordsServlet
Codeincommonwithotherservlets getdb connection,getpayrates,forwarderror Privateauxiliaryfunctions
showFormForManager reportWorkDone
ViewRecordsServlet:showFormForManager
doGet
Determinerole,calleithershowformorreport workasappropriate
doPost
Handlemanagersubmission
ViewRecordsServlet
ViewRecordsServlet:showFormForManager
50
7/02/2013
ViewRecordsServlet:reportWorkDone
AdvancedServlets
Apache+servletcontainer Filtersandlisteners (forwardreferenceto)struts
ViewRecordsServlet:reportWorkDone
Generateresponse page
Apachefrontendtoappserver
Appservers,suchasglassfishortomcat,canbe usedalonetoserverequestsdirectly
TomcatclaimsthatitsHTTPhandlingissogoodthat thereisnoneedforafrontendApache/IISevenif mostofyoursiteiscomposedofstaticdata; claim l isthat h only l need df frontend df forl load db balancing l andstickysessions Generallythough,afrontendApachewouldbe employed
Lesshackable WebsitestaysliveifTomcatservercrashesetc(losethose dynamicpagesthataregeneratedbyJavaapps)
ViewRecordsServlet:reportWorkDone
Frontendsetup
From:http://www.idevelopment.info/data/Programming/web/connecting_apache_tomcat/Web_Server_Connectors.shtml
51
7/02/2013
Frontendsetup
Apache(IIS)modulerecognisesrequestsfor servlet/jsp/andputsthemintoaseparatehandler
HandlerattemptstokeepopenTCP/IPlinkstoservletcontainer (tominimizecostofcreating/destroyinglinks) Communicationsuseadifferentspecializedprotocol(AJP)
Note:possibleextrasecurity
Canhaveanotherfirewallhere
Configuredonlytoallowrequeststoappserverportsandsettoinspectandfilter requeststoverifythattheyuseAJPprotocol Thisshouldhelptokeepoutscriptkiddiehackers
Listeners
Listeners
Interceptorsontheapplicationengineslifecycle actions
Canlistenforeventsinvolving
Requests Changingattributesonrequests Context Changingattributesoncontexts Sessions Changingattributesonsessions
Thestaticfileshandledbyfrontend Apache:
Putthemonafilesystemthatismountedreadonly(thenhackersshouldntbe abletoputtheirtagsonyourpages)
Whensuchaneventoccurs,appropriatemethodofa deployedListenerobjectisinvoked.
ConfiguringApache
Theapache.org sitehasdocumentationonhowto configureaconnectionthroughtoTomcat
Includessomedetailsofloadbalancing(andneedfor stickysessions)ifyouhavemultiplecomputersrunning copies i of fth theappserver(as ( would ldbe b typical t i lonalarger l site) http://tomcat.apache.org/connectorsdoc/ Consultdocumentationonyourappserverifusingsomething otherthanTomcat
Filters
Interceptincomingrequests,andoutgoing responses
Canadjustcontent Canblockprocessing
Filterchain
CanhavemanyFilterobjectsdeployed, Deploymentdescriptordefinessequence:
Requestarrives=>filter1=>=>filtern=>doGet/doPost ofservlet Responseleavesservlet=>outfilter 1=>=>backtoclient
Bewarenabgbiasandignorance!
Timetomeetlistenersandfilters
Featuresaddedinservletsversion~2.3 Allowforextracodetoberun;examples
Changeanincomingrequestoroutgoingresponse Extraactionafteraddinganattributetosession
FiltersandListenersSun/Oracle
Myproblem
Theexamplespresentedareneverconvincing!
Often,thesameworkcouldeasilybeincorporatedinservletcodeand noclearargumentisgivenforseparationofcodeintoseparate elementthatmustbedeployed
Seehttp://docs.oracle.com/cd/B15904_01/web.1012/b14017/filters.htm forofficialintro.
52
7/02/2013
Listenerexample
Fromhttp://www.informit.com/articles/article.aspx?p=170963&seqNum=7 ExampleisforaHttpSessionListener
WhateventsareimportanttoSessions?
Theygetcreated Theygetdestroyed.
Destructionisautomatic ifleftuntouched foradefinedperiod(usual container configurationgives them30minutes)
OK,IlltryListener
MyAcmeEmployees siteputsdatainto context,soIcantrackthis
Gettoldwhenadd/remove/replaceanattribute (likemypayrates) payrates )object ButwhatcanIdowhenImtoldthis?
Notmuch logamessageIsuppose
Solistenfortheseevents
HttpSessionListener interfacespecifiesmethods:
voidsessionCreated(HttpSessionEvent e) voidsessionDestroyed(HttpSessionEvent e)
Createyourownclassimplementing HttpSessionListener
Provideeffectivemethodsforthesemethods
Informits code
MyListener
Deployment
Web.xml filecontainsalistenersection
<listener> <listener-class> pkg.ConcurrentUserTracker </listener class> </listener-class> </listener>
Deployment
53
7/02/2013
Oooh lookinthelogs
Howaboutfilters?
Examplesat:
http://www.oracle.com/technetwork/java/filters137243.html
Compressingresponse
Iwouldhavethoughtthatwasresponsibilityofsomething likeanApachefrontend
CouldIhavedonethatintheServlet
Ofcourse Myservletcodecouldhaveprintedamessage whenitadded/removedthepayrates data structure Uhm
MyfilterinAcmesite
Possiblymodifyresponse
Ifuseristheboss(colin)appendGrovel,grovel,grovel paymemorepleasetoallresponsepages
Developershint appears
WhythenuseaListener?
Uhm .
Maybeyouthoughtabouthavingthisextralogging afteryouhadsuccessfullybuiltanddeployedthe servlet Youcouldaddthelistenerclass,avoidingany modificationstoworkingservletcode. Additionoflistenerappliestoallservletsinthesame webapp ifyouhadwantedtoaddloggingafterthe fact,youwouldhavehadtoeditallthreeservlets.
Filter(andauxiliaryclass)
ClassimplementingFilterinterface
Auxiliaryclassthathelpsmanipulationofresponse streams itisprovidedintheOracleguidetousingfilters
Notconvinced
54
7/02/2013
Filter.doFilter
Ifneedfiltering(itscolin),then
Replacetheoutputstreamthatwillbeusedfor responsebyastreamthatcreatesacharacter array. Invoketheoperation Pickupthecharacterarrayandinsertextratextat end(beforethe</body>tag) Writethecharacterarraytotherealoutput streamfortheresponse.
Struts
Datesfrom~2000(wellbeforeRubyonRails,Zend frameworketc)
By2000,mostJavawebdevelopmentsutilizedboth servletsandJSPs
JSPs forfinalpresentationofpages(view) Servletsforcontrol Model
embodiedinapplicationdefinedbusinessclasses,suchasentity objectsthatcouldfirstvalidatethemselvesandthenloadand storethemselves(usingJDBC),andentitycollectionobjects
Otherwisejustinvokemethodasnormal
Filter.doFilter
Centralizeddispatcher
StrutsprovidestheServlet
Yes,afrontcontroller;liketheZend applicationobject ThisActionServlet(theclassimplementationisinthe strutslibrary)readsfromanapplicationconfigurationfile
FileentriesessentiallydefineamappingofrequeststoAction objects(bitlikeZend controllersbuteachhasonlyasingleaction) whoseexecutemethodsperformprocessing
Typically,makeuseofActionFormobjectsthatholdsubmitteddata (?Zend_Form)
Deployment
Editweb.xml
Addthefilter
Specifyclass Providesymbolicname forlaterreference
NetBeans viewofstruts
Addfiltermappings
Identifywherefilter applies
Glitch:NetBeans editdialogimpliesthatyoucanenterURLsorservletnames;onlyURLswork
55
7/02/2013
Deferonstruts
StrutsutilizesJSPs extensively
Muchoftheautomationofformhandlingandall thefinaldisplaydependsonJSPs
SobriefintroductiontostrutswillfollowJSP section.
56