You are on page 1of 30
Prosrererenerrerasind sae ae alt sn pees sat sri ene Snecma usu tom mt Stave re ‘The structure ts le/pagefcom ‘esr aco le test Sinkpoee tree ye prorsmming pore cetctnpaerdpenrecar ecard a = hovignntaneainiainaiintensnt code prose seate amc wee pageanaing oth 2 ‘eae casa en a Pon oye coe ee eo pe) Hwboue et “Getexspseerel an [eras ine ‘pismo i Tenet = ined an ‘SipoetladmennSeD| rcoce pee “aint ned ist sot \ Seren tein) Te | . Donic mcbnge ott po — ‘Seg an S23 rocauret ee and del hpcomos bans en bapa ‘epi cea epoment areca ara viet esi eens) eee Tinraateecate 92 soy weapon ony Esp Inder to cat tomwshmebpe eer 93) rere se ‘hectamen-hone\s\ omens fhe roa sce ee apie a cmp te pure tthe “ehenteinnre bec oni Beep Tre to hc iweb opto. iro ieee Teac ” csonetol ang papier eta deat eommutpona chit tare eens ou te motto done ip gear? ‘ml foremryrnsition one mp gue itermy anne Pegs ‘hind ondnewoetwilbecetebne herent So te edatani ‘tec sy ovtrentypes tests programming (wo estes) (alma ‘Stucco andy pet tbopene ith chpero cigar -shgwesn Sint ab ers Parente onfgapoiin, (a eich seit “vst rt "Sai “Souther simi obi >free bien be. ecco ou ere cycle methods beeen pp pe itera “strcmp oe io pos eceaton tng may prrced Ser coo mesh pcr ene rents nd cle te cle etots ect ros Noltecre meted ‘lnsutiton ete when contr ces JS ds be asst ser see mee troup Sere eee mead Inkerttont) tes onlin or gran ie ination ‘opening con ce pokes prety sera te hd ion "Sper wenrepecto ice Segue groceing event “rates hitachi anh oc ron Scie aparotes ears ne cjemsted roses ‘ntinntngpueetng nan rome erare £2) betrcon een “Sres wir eweren Senso atm ety “tninr nied -ppDmsvy tats eee hads ‘iron Sevediteyce mab tee say) metas ate oo lace Fraga ete viene ‘evconeibeconsbiet| promo) ope contin estat pe ote etn ns ene tse names mid names ‘renteeorted bythe opammer tewarels cdr cota ‘im tomcat web server the JS cls for fist ip of spApp1 web application wil come in Eomest 9.n\wor\ catalina VoclostpApporgapache ip fer having names Tso ava [source cole) package name ‘ht jot (com coe)" [Web app mame. -=>Every JES class extend from Contaier supplied class and that class extends from HttpServlet (AC) > The superclass JS clas is Container specific Le wil change container to container = Incase of Tomcat server the superclass of JES class is orgapache jasper untime.HttpispBase By default every ES cass contains '8}_jspinit() method b) _jspDestroyl) method ¢)_spServiet-) method ‘ote: pint), jspDestroy() methods will come in JES class only when they are defined by prarammer in jsp fle ‘>The Template text placed injsp page goes to_jspServicel of outwrite() methods ‘= The java code placed in sritlet goes to_jopServicel) as itis. ‘© allimplic objs created in _jspServicel) method a Local variables. ‘> The java code that goes to_jpServicet.) wll automatically takes cae of exception handling using try -catch blocks. and becomes the argument values sant ‘ore ngage at veto tenet ies me ad apache espero aS Ana 1 ase name anit super classname se container specific Lather names ‘and package names wil change Based onthe Server/Container we use. cee el (ore-apach => The superclass ofS class contains servet life cyte methods definitations calling jsp ie ‘methods internally. and also jsp), jsplnit),spDestroy(,_jspDestroyl) methods with "Null Method defntations. (empty method defnitation to comple the flow). For Instantation event ‘container calls Integ) method on 15 las obj>since not therein JES cass the leg) ‘method JS superclass executes (http!spBase) —> the nite) method SES super class ‘alls jspnit{) and split) methods.-> jsp of JES class and jsplnit{) method of {ES Super calss(itplspBase) methods will execute. Forrequst processing event Container calls 1st sevice" method ServeltRequest ServietResponse object as args on JES clase object-> since not available in JES case wil search al the classes of inheritence hierochy ‘and finds it HtpServlet cass (super super class of JES cass) ~> Ist service.) of ttpServlet class ‘alls 2nd serie(;-) methods and itfinds it super clas of JES cass (ttplspBase cass) and this method interallyclls_jspServicel] method and _jspServicelr] of ES cass executes. For destruction event Container alls destroy} method on JES class obj —> since not available in ES class —> the destroy) method of JES superclass will execute -> and that internally cll jpDestory) and_jepDestroyl) methods —> spDertroyl of JES superclass executes and _jepDestroy} method (of ES clase will execute, “Two phases ofJep execution 2) Translation phase [Translates jp into an equalent Servlet comp sourcecode and byte code) >) Execution phase/request proccesing phase (the_jepService[;-] method of JS case will fexecite to process the request and to generate the response) “Translation phase. hrowsSEJOEL vm Extetion phase 1 (or) request processing response phe ‘The request elven to jsp page participates directly request processing phase/execution phase ifthe source code jp page is not modified before the request and the bytecode JS clas is already avslbleotheruse the request given xp page first participates translation and later paricpated in ‘request processing/execution phase. it we just delete soruce file of JES class. then alsonext request directly particpates in ‘execution phase, Sie Seetaieo)— Cvaae —) Sosa =a copious ot), eveite ruses te) CS REEEI, somes, oh ac ao mee 155 eistanatp (arses collection) = Castes) Tie njoar) ‘tbe neipbcen pte eo web pein {ENF an ones Ron oe ign wba semen aia vn I “ear a aT Ree on eae = beieorole meme ashi sees, | STs ane euamctnctnate tian mes "ante Neca anor camera, ©) cect pen epg hp we ns) siete conection rho noe? pncomneiaia sterarcgianeruaepor arty me Sopiyomete sie nero. Sree oes ‘tpn /tecp (mm dee fe wn ents? ats the antago place ip pagln pt ares? ‘Ansl> To rate sourcecode aces trom outsides we aplaton ar web eset iavecty ram endusrs) ‘Uretato hie te tcnnlogy of wed sppieation em ender. ‘ropetswtomate cand on nartp> advntger fn oul tpi r) tgp pe Sspinng request sop dt collected servlet comp then Set ees oi page wl ply "nl agus To avid his uly wes ‘cep Phot reno noone con ge diet request edt isp the sourcecode 5 sith thou compton) can ne ‘Can we place _jepinit),_jepServcel,-]and_jepDestroy) method definitations in the elration tag is poe?” Ans) Since same ae already avilable in IfS laze. So our methods (our_epke) become upleate methods in JES ass Java does nt suppor duplicate methods butt supports 26 public void jst 1% ‘can wo place srt fe cyte methos detrittions Inthe declaration tgs of kp Paes? es Jes class (ilsp8ab Incase of Tomest server and we cannot overide final methods sere ite cycle methods placed ciation goes 15 class becomes overriding methods sloth sper dae lat serge meods at te iret So tate deter of rein ey meta lonay een as fat Busing server ite cyte methods recy. with pubertal) we” ‘ote: we can use al he3 seipting tgs in one jsp pase in any order hong either standard or ‘al syntaxor both sytanes. ‘ramle App that wes a2 scripting ag togather in ingle ee nese scripting tags are 3) seriptlet, bjexpresion ledelaration tas, secondiso Gs public String generateWishtessapfstring ert etter date ana time avaut. calendar cabana. calendar actinstancel; eet eurrentnour ofthe day Int hou'=calget¥avti.Calendor HOUR_OF AY; Hesverste wish messoge ratio tg ‘ihour
stm SeganerateWisheseag(uname) > Procedure to develope ep page bared web application wsingeclipee sel cate are ot AeSnew Sayama, semen one eat svg | ‘noes ow ache pee prmpeciet {Sinai natenertic ie deco" pn mes ‘Smee ie sep mae sre that Tomeat serve che wth eclpa D.. steps) develop second sp and web xml fe. steps Run the web appiation op lett clk on the Projet» run as > choose sere" note we create Dynamic webProect after configuring server tothe IDE. then thereis na heed of adding servet-pir file to CLASSPATH/BuldPATH otherwise we needa ade Serve-apijer file to 8ULDPATH/CLASSPATH .explictly. note Eelpc 10s uses its own copy of Tomest server inthe workspace folder «The JES ass for elven) pge willbe generated in the folowing place of workspace oe ‘5\Worskpaces\advava\NTAV1118\ metadata plugns\orgelpseustsorvercor\tmpO\work catalina location ephopslonlapachelsp re PON [=2secondjepjave (JES source code) web application pkgname —|-sescond-jpclats UES comple code) Comments ins pase ‘Asp pecan ave 3 types of comments “Dhl comments comments fel= w= 2) STocommnen template and mlsytaxbare ip ago oo pose Ses comments ae recogied and rocsted by Ht iterpter Sree comment fe End ">To comment standard syrtax tag p page iovacommats [/f-singetine. n°] -maline) [-tocommentjava code of igtng ge |-Sthese comments ar recopited and processed by ave compiler “ml commanets fie page arcaled output comment bac they come to bronser longi the responce code/output cose. ‘Dien comme ae cad idon commants ce they visible ony inthe i pee, matin ‘ter oases of porcine Sievecomments ae eed siting comrinets beat theyareuslulto commento ode nce inserting eso pe viii to Reoure code nts oyode moet tee | "° ~ " memes | ve ‘ no fe ‘ns) Pose but at recmanded bez makes sp coe o pete the ouput by executing te cose and that utout ‘be commented. ‘cane comment hn codetemplate ext wth comms? ‘Ans poste ad ecomanded as. ‘an we use sritn/av commento commen Nn codes ado? “hn ot pons (ate about the i iy ota) a re reqs sopeopeciieto cach request “Visible rough out request) ‘Iseoton scope opie eachbrowser ofa ent machine} ‘appeation cope pect cach web appleation vise ‘web comps of web open] ‘ote ppliatinScope meane data iia in alla compsatwob “es icimplementing en wenew test) “Sy, Tren DDETIPE to TTS ood co request Jmraxserdet tp tseretecset reves response InvacsendethipittpsenetResponsel] | response] rea be Invalang.biet pase ce = seen Jmvocaeret nn Seal) seni cong Fnvenseret Seton) pace sealaon avast Seietcontent( spocaton oe Jivaeserde ap epretac) ee cxcention Tovaangthvowabe@) = notes wedontrete thermic ob, the opeoane ester them having Mae eference type en by sera p a avrg abe pe (sed onthe contaieroeser we ne ama th ference ype of request bjs tye ahaa Invocsersetntp.seretRequst) butts objet ype spe teach server Implementing "ipseretReques request ob class ame: rrequest gts) > ree request obclassrameclss ngapache cain connector Resuestfaade impeme Ms Hpserdeteuest) ‘ewes ob dss name ass ioundetouservet spec taser as Implement tpservitequsth Important observations {o) Esception haan is tons only forthe code tht goes to psec) OES das. For “emainingoae we ned perform exception hanling manual forthe code les | decloraton tage nedtopetrom aceon handing expictly besos code gee Ieoutae of encersee meses. © pct — vi pubieae ft ep een “nstomam oro drverorcebrr ‘ ) vi ot cchtaceationet oe } ‘ana fortamel eralabedier Oren) V% , neexeption ro ube old Jeserielreqestiows 8/04 ‘When Exception willbe ried? ‘ns| ull be raze for rum ie problems. nd causes sbeorma termination inthe “ection othe Aoplcaon, hati the meaning te handing exception? laine trfcten bloc forthe cade hat rene ctception cal excption hang “evthen aceon raise it wine terminate ie appieton ater onl goes ath ocean firmer teen lect. Whats the it fe checked exception ond unchecked exception? chekeed Exception (fetcing an horlingeazeton | eae Aedoringtheexepetin tobe von | if wat caugt ond hancled it propegates the Ismandatoryatherwisecases | exception ocaller (b)does not propagate the exception |() supports exception propagation ty default by tole mast exp enable) tht excepton's not caught ond hones ‘hs ning "tows (cl mese dassessub avec subcless | Tes asses are dtc or inset of volangeacepton Subesesof ava angmuntime cass. notes inane, wer unchecked etceptions mos of tine to enjoy exception propagation! esi In lyered eppicsione mae ‘bjecs vibe nal thee ole methods cee Servet comp oS ease itp void omni Sting dbuseroconiggtntParametrebuser imei Irelerence variable aan 7 “cone tefsne i eo nee ce cect ebestigrbmrecaienss mane > akan tar raemcmmearecbrentau ensue : oe feats ‘-uhen wean not acess Container eats abe in ny pare of Tap Senet camps using impli eterece vrs ane then town efrenevoriabesoecessbre them shown owes (fe). ome “irate test tnstead ot hard costing tecnicainout values directly nthe op page, wo can get ee ‘ham tom web le hough SrvetConfSerletCatex cb ‘ifthe tacialnputvaluerare specie one zee pomp then sein param totes the les don on ep page web le wil taker pace on ep page only when tht np pois requested throu pater. etherwse they wil a thes lcs “peramaomesdhunr ‘renee sot eramrelicr tag) ) using submit button (place sp fle name or ur patter as the “action” attribute value of
tag) ‘using javascript. (take the support of form.submi() method) note: sp to Db s/w communication we need to add jdbe cod sf coated jar file (ke ojd6.jar) in WEB-INF/lib folder. sp page.. by also keeping jdbe driver Dynamic web page ‘Account is opended/not ope (or) =| (henhl table) “home Sspappa-08 a |-Swebcontent ar logics for hypatink and subritin the ep page. nebo ») Collect jab properties from webxmi fleas init param values. for |—>bank account jsp ‘access SerletConfig object seperately in spnit() method [>wesanr * ¢) invovle all 3 jsp life cycle methods jspinit(), _jspService(-,-) and jspDestroy() d) avoid out.printin(-) completely from coding .. with the support of | PRESSpank accountjgp | directive contontType ‘aos speci reponse omen ype berating resetcntentype) mato Stet vee ul caretaso 22591 ‘ce: 6G page content Type="tert/pein™> on you ttle which willbe applied? “© response.etContentTypattoxt/himl"jsThee line code alway come after [Boe deci tg consntine ete boned response contre) Iethod, S2he expey cated respons setContents reise he sapges dete ap eepoone coment pe place the tmp et aforenonguages we ee ote te charactor ocean Mo page conantypeen/hemtchase UTES > oo esto - default yale ie "re™ ‘itdo not we use "sessiosn tracking” on our web application. itrealy bad ‘ractie to enable Session objet in those movies. ‘seutgnored Writing iova code in sp page isbad practice. we should avoid it or minimize it becoe the java code in sp page klls the redbility. bu to perform arithmetic and lopcl operations inks page we need java code. To overcome this use EL, to perform arithmetic and logical ‘operations. ‘syntax S(cexpre i: ttevaluesthe expression dipslaythe ‘outputon tothe browser. (tisexpression ag) 1 KO page Elgnoreda"true"%> stars) [> eg peor a te shettondsiloy9 exaust ives $45) as text ent. the defelt sof tisatibute Jose $0. S445) gves 9 trough @poge >is not inluded. ‘ss>allous to specify encoding charset forthe sp page: ==> Instead of writing charset alongwith contet type we can plac seperately ‘<6epaae pasetncosings uth" contetType="tet/tm™ > 5) Sor lokats directive include /Static include is tagis given to include the code of dest web comp to the JESclass of source jsp page ‘>This tag performs code inclusion ..not the output inclusion. 2. jsp ava (jsp equalent serviet comp) bsp (dest web comp) public cass jp extends Include code from bisp » Hise code o = ¥ [1 Sspservicel-) Mielass =n directive include , we can not take servlet comp asthe destination comp becoz ifthe seviet source code or byte code is included to the_jspServicel--) of source jsp page them it becomes illegal code, => we lfm files,spfles as destion comps. if destisp page is having declaration tag s code they will be going to outside of _ispServce(-in source sp's JES cls, = This code inclusion i called statie binding / compiletime binding..becor code the Inclusion takes place at translation phase. Jspf\pp3-Directivelnclude In directive the destionation htmsp files will |-Swebcontent rot executed, but their code willbe included. [raisp.bise to JES source code of source jsp page [-SWeBINe [pert SBaatoteiepct>
a
Se ir ‘Stone vette) > Sendotaianci>- on request url: http:/flocelhest3030/s9pApp9-Directvelnelude/aisp Inote:: No JES class will be generated for b jsp. butts code wil be include to the JES class code of ajsp page. (Le code inclusion is taking place) ‘note::In one source jsp page we can place multiple directive includes as needed. this Includes the content of multiple destination comps to the JES lass of source jsp page note: ifthe dest jp. html comp files in private area ofthe web applicaton.. hem we need to pass their complete path in <%@include fle=".."% ‘acminerane ree] Site ‘ince ae erecta tp ora Seon wes cnane savanna ees (Seton (mentor) 1 mrt nite stot tnpsitee sae sptor on pe neon ge “Seorieyeernarete gota enn a rae ae ‘ature bo tpi ot a a ee. ‘I suemenoe fr mug pene mailers one (esi repent (SES pe saatsen met et a et mater eal neces fence ona ae rnsiinocngo cman cece ao — pm eis) Clperacareetonmgret materia |) nian ane mmcepera animes asencone | bln ning snap whom forecceneres (ome eerewteeron sopremop irene! |“puctarepaaseeereinntsa ns io | eedistist eee, (recep SS | gpeenn segs orngonpcam rarest 1 meses pte and dest wa cop ae tare inthe ew pesto sndwingsoneteg sche (hens nee or cenour fe dbtnal cent peant Tic cion sac” fowpevon pe “Fesapend corso rng nation Sais as Sangh ery Lome nei ont: ‘Sitienaeone cece apy wanna imal ar a ‘sSeton sey eon ava tanea race reg cet Sheen coma bition meee obese ee EINE rreiern ere ecm Papecontat attibtoe ‘instead of ang 4 ferent objects ke paperaquestsesionappliation to create & scopes of aeibutes ‘we can use dng pagaContert object to create athe 4 scopes fates baco pageContent bj olds alte imple oof Tocrestepagecontnt tribes pageContert etree ata" "val ‘ocreates "ot attbute having aE scope ogecontoxt seraribtel't2" "val" pageContet 10n score oa cba Sort accor RT cre Te may usm ro e Pact SESON SOE metommaebeel ea odie peop ened tea pagecontot statute at2, ala" pageContext SESSION. SCOPE: ~> modes the sesion cope pageContetatibur "at" ale Toresd pageconen atebutevaue ‘Sting value (Sing) pagecontntgernutbute( at"); ‘oreads “at atte value fom page Scope note atlbute loge valle name String valuing) _pageConter getAtibutel at” pageContent SESSION, SCOPE), ‘hat value wit scope. tlsnot no Way ‘breads “atta” atte vale fom seston sop relate ln tag atts. ‘Totind pogecontextatibute value note: if we uy to place simple valu in ay atubte ten al be converted nto an wrapper automaticaly aut boxin) note: ifwe ty toed and ald the retrieved tribute value fom any scope into smote datatype varible.then the wrapper ‘object (atbte value) willbe converted int single aie wing “Saearchos given atabte nthe multiple scopes na flowing order where ever find le eam ‘Rveads the atibue value. Hsame atirbte iether nwo scopes. then lowe cape a ‘0% priony age Scope > request cope —> session ope —> aplication scope —> retums rll + + + eet vaue estas geevalve extsvae Whats the diference b/w gethtbute and findAtbute method? ‘Sgetatibutel) method searches for gven ateibue only the specified scope. int ovale ‘hen il ot searchin other scopes. ut vets nll ‘>finsaebutl) method serene forthe even attribute multe ope ‘hewn shove ifthe atibte spot avaiable in al the scopes then retusa. if savaiable Inspect cope then tcllects ed doe ot searchin athe scape. Wt thers lie spe ‘tha cles Wom spe ower scope To remove pagecontextatibute fer ppp TeecContertremoveattinaa( atl"; Removes “at attabute fom page seope pageConter remaventbuteat2"PageContet SESSION SCOPE}: “SRemover “att?” atibute frm senson scope ‘an work wth pagecontxt abt in seret programming? ‘Ans) not pose eco there no pageContext object In serve programming. ‘an read pageconten trates using dct pagerequestaesion,pplation bjs ‘ane| yer. bot not ecomand rote: even reverse pertion i alo posible Tem a nd te n> “eosaron pene ames pa center nt ph ‘Sperone same noes prune» te merino slasher Okomane Ase nS AAO ae a ceremeine iar Use case_on tags form page (html) > jsp, ———-DTO-——-——> Eve lass browser window Here Employee0TO is java bean having properties to hold both inputs and output.. 5 proeprties are ‘eno,ename,basisal grossSal.netsal note: sine multiple endusers may submit same form wit eit values from multiple browsers and thelr tabs So it recomanded to take DTO class obj scope as request scope notes: since th isnot state for Service class. itis better to create 1 object and use it for multiple times ‘So prefer keeping Service clas ob in aplieation scope JspAppi5-UseBean-UseCase [->EmployeedgmtSorvice java |—employeeMgmtServiceimpl java Ie [—>precessisp [->webxm! ‘Mini Project Discussions Problemt: ‘Writing jabe code (persistence logic) in every layer not recomanded... We should place only in DAO classes. So the RS (ResultSet obj) generested in DAO class cannot be sent to service to controller to jsp comps. directly. Problem2: We ean send only Serializable objects over the network.. We can not send JORC ResultSet obj ‘rom One Project to another project over the n/w becor JDBC RS Is nota Serlizable object. Sehations miebpreage De ee coh rote Al collections re sealable objects by deta) Solution2::_Use RowSets instead of ResultSets (note: RowSets are serializable objects by default ->Very few JOBC crvers support rowsets) Symenomnized Collection ‘> Allows multiple threads ata time Allows one thread a atime eg: Vector, HashTable ogi: ArrayList, Linkeetdst,Hashitap note: After puting data into Collection if ur planning note: Aer puting data int Cllecton i wr planing to perform both readrit operations simuiteenousiyt0 perform onl read operations on that collection ‘onthat collection then prefer using synchronized then prefer using non-ynchronze cllection for callection for Tread safety, the achieving prformencs While copying RS object records to List Collection (used to preserve the insertion order) we have Problem thatis_ each record of RS contains multiple values.s0 they can not be copied asthe each clement of Araylet becoz each element Arraylist can hold only one object. rs(Resultset) aol aed i araytist) 102 rash vieag— 35.66 —) 103 suresh delhi 65.66 |We can solve this problem using Java bean (80) support ..copy each Record values to one object of BO cass and add that object to the element of ArrayList. CHE __ "(Resse student60 obj a (rays) 101" raed 5.65 te oz * room vag 35.66 —} "RS bo : 400 25 > 103" woth dati ese JW = | Sample code to copy ResultSet object records to ArrayList collection a the object of BO class Statement st=concreateStaterent): ResultSet rvst.executeCuery{"SELECT * FROM STUDENT"); LUsteStudentBO>listenew ArrayList); whilst) /Teopy each record of Rs to each abject of 80 Studemt60 boznew student60); bo.setSno(es.getint(); bo.setsname(s.gettring(2)); bousetsadd(rs.getsting)}; bo.setavelrs.getfoat(4)}; 1/4 each of bO class to Ust collection list. ad(0; ) ‘Where did uw use Jave beans in ur Project? Where did w use Collections in roject? public lass studentB0 { private Int sno; rivate string sname; rivate String sadd; ere 5h re tb etna, ‘sce , (a ieeremamat cep ay cramer nears ah Be tr Jonni Scientia ‘Sects ae ator pcan on ane ie nat asta ee ftectrone soe ie ntl rt yo da “fcr Decrement Se a ee wp y ann tn i ee cnr fe neat op 3g wy | rior __» i uaa oat dt oN 6 1) Revealed rons ae. “sictenantatomn Sg

You might also like