WT (UNIT-4)

You might also like

Download as pdf
Download as pdf
You are on page 1of 32
4 Scanned with CamScanner | + the Anatomy Of a DP Pag Page | A JSP page is simply 4 vs coeb page | with TSP elements fom gFneraling the pots | os she poge dhat dither fo each request | ar shown in figure below * kext rat <7@ page longuage =" =" java” content ire “a TSP dement 2) bgcolon = * wohite * 5 | — template tert < \sp suseBean 7 | id = * userTnfe class = Com.ona-jsp-beans userinfo. UsevInfoBeon"> 7 | esp: sekProperty narne <"userTnfo’ prc petty = te /> < | isp: wseBean ¥ =P element The fpllccsing ingosimation usar sated : | berplake ke
  • ] demerte
      Greil Address + TH template AU tat ouk painkln (“”): owk- print (" Demo elbte >"); JsP element is converted into comespondi Eves Java cade: This phase is clted translation phase. fie cukpuk of branslation phase is « Sewlee Scanned with CamScanner Fon exarnple + oun aya JSP acts converted into Fay Soule + Jawa 3) This sewulet is compiled to generate the serulet clars file: This phase Is atted eq creat. Prrocerming phase. 4) The TSP conkainen thas execsker the seowlee clad file: 5) A oreeyrerted page is then actioined to lhe client as a >respornse Scanned with CamScanner “Peclanations eee on “The ISP page dhat we ewoite is beamed into class dekinition. So eshen we declare a Vleotiedole Te Sunken Sy Declanation ag <7. | Dedosialion code /. > » We can declane stakle member, instance Ucatiable and methods Iinsicle “Declaration Trg . ® ox method in ISP inside Dectentalion Fag: Example + Zkikle > TSP Declaration Demo edt Sbing mg = “Aletlo": p> a body > Mesteae le: <7. ou: paiinkln Cg); 7. > < [body > <[heral> Oulpul : ISP Dedwation Dew Message iss Hello Scanned with CamScanner ‘Te aboue ISP cocte contains che declaration within < Zt f> bog * We can declane a funekion oh a method in IsP just similar fo variable Following Ts? example illuslakes the use of funetion declaration and clefinilvon. Method Dero -j sp "content ype = "bexk /htmt" 7. > p> <7 public Sbiing MyFuncion ( sbing mag) i sretuarn rnag); 3 fo Use of Method < bedy> J 71. cuk-prinelo(" Before funckion call 4 ms > Akeor fandion cals <7 = MyFunekion C Technical Publications”) #> < Jbody |heral> Scanned with CamScanner Output + Oo) Use of Malhod | : [-[s fx Before function call + Hello After function call: Technical Publications Scanned with CamScanner # | @ Jsp — Dinectives “Distectives in Ise provide dinections and insbiuc tions Lo the container, tae it how b& handle certain aspects of the ISP processitg. * A TSP dineckive affects the cumall sbructire of; Ae sowlek class» TE uscally has the fpllow'ng fore — pe dinective athoibute = “value” | x Dinectives can have a ruember of atboiibule |eshich you can list down ar key-value pains and seperated by Cormmas- | The blanks beteseen the @ symbol and lathe ditective narne , and bekuean Ake Leak | ebisibuke and dhe desing J>, ore optional - —— = = —— | SNo | Directive & Description 1 |<7z@ page= 1-> | Tekin page-dependent atlaibutes, such an |soiipting Language, amon page and buffeting preg rinemenes- a. | Tetudes a fle desing the Ganslation phase 3. | | | Attributes : Atbsibute & paspose._ bubker Specifies 0 bafpering model for the output stream, (2 | autoFlush | leanbols -the bojfor. 3. | ContentType Defines the chenacken encoding scheme behavior of -the servlet oukput: 4. | extends Specifies « Supenrclars that the. generated Serulee musk extend & | Koguege [Pefines the programming language used, in athe Tsp poge: 6. | Session Specifies cohether oa nok the TsP page Pattiipates W NTTP Sessions Scanned with CamScanner ‘The ‘include Disiective : © lem, "s , | 'he include’ dinective is eed fo include a | pile dusting cthe tiamslation phase. This dinediv tells the container to merge the other extomnal files sith 4 | | Content of | eoing ‘Ihe translation phase . | | cuovient Ist You mas Code. the ‘include’ clinectives angecheore Ww gown ase, rae x The general tusage form of chis dinectiue is as follows - | [27.@ include file = “selative wrt"> © The filename in the include dinective is | achuatly a relative ORL: Th qe just speciby ja fylename te with no associated pet , dhe [asp compiler assumes hak dhe file is in ~the | same dinectony as your Isp % You can woitke the xIML equivalent of dhe above synker as fellows — Zjep: dinective-include file =" aetative unl" “The kaglib Directive + The TavaSewien Pages API allows you te define cuciom Ist tags that look Uke IML om XML cs and a tag Upraay Is a sek of cen anes tags cthak implement ceestam behavior: * The lib cineckive cleclanes “that geo Jee poge uses a set of cxustom bags , Identifies Ane location of Ahe botany and provides Scanned with CamScanner Means bpm ‘identifaing Ahe custom tags ‘wi goun Tse Page * the baglib dinective {allows the syntax jgnen below — | |

      < [body > |< Ihtal> Scanned with CamScanner Output + emo fon Templake Teak =x T= Twinkle Tusinkle litle stan © Hello Teh is equal to HIML and TAUA Scanned with CamScanner @) Jsp — Timplicit Objects : ‘The Tmplicit Objects ae the Jaua objects thot: Ihe TSP conkainen maker available bs the developers in each page and the developer can call ners ctineckly evithout being explicitly cleclaned * Following table Usts out dhe nine Implécit Objects at” ISP Suppomts — © request | This is the MltpSewlet Request object associated with the areqyro © d1esporvse This is the AWpSewletRepone abject! associated eith Ane sespormie to The client © ouk This is the Potinctalaiken object cased fe send output t the client © Session This is the HipSession object arrotia Led eaith the srequest eagplication | This is the SewletContert obj ete asnotiaked with Ihe application context ° Contig This Ie the SewletConfi obj ec: ameciaked will dhe page: spege Contert | This encapsulaker ase of Sewer specifi featrores like higher petfsrrance Topwirikens meas ‘Bis Ws simply a synonym for this, & is used to ell the methods clefined by he Granalated senvlet class Scanned with CamScanner © Exception The Exception abject aller dhe exception data to be accessed by desiernated Isp. Scanned with CamScanner Pages : oO Using Beans an Tsp A TaaBean is a Specially conskucked Tava claw comitten in dhe Term and ceded actortirg fo dhe TauaBeans APT specifications. * Following are the nique characteristics dhat distinguish a TJauaBean from othen Tava classes — e Tk provides a default, no-angament censtructon ® Tk should be Setatigable and that ochich can inmplement ‘the Serializable ineerkace ® Fk may have a sumber of properties which can be mead om conitten. e xk have a Aumben 3h . gehen" and " Setten’ methods fpa the Ppropertics. JariaBeans Properties + A JavaBean property is a named athailate dhat can be accessed by the wsen of the object: The attribute can be of any Java daka bype + ‘inclucting the clasnes that ge lefare| * A TFauaBean property wiag be read, wortke, mead only on conite only. TauaBean Properties ane accemed Ahnough tee methods in dhe JavaBeans implernentakion class — Scanned with CamScanner s-Ne get Pacpentyname ¢ > Fon example if property name 1s fpersktlame, jour method name weuld be gekFiatNamec) & riead cthak paroperty This method is Called accedson. set PaopertyName ©) g Qs Fon example, ih properly name is fosthlare, jour methed name oould be set FioukName O) fo wotite thak property - This method 1s called nuctaton. * A read-only atlotibute will have only a get Pnopenbynlame©) method, and a ewnite— only attotibute evill have only a set Pacpery Name ( g methed- I! Example public clas Skident Bean implements Senialigable String Roo; Sbirg Nlame : Public void setRno ( Stig ano) t his Rno = mos Scanned with CamScanner public vold get no ( fetag ) @ { ack Rno; 4 public void sethlarne CString name) q his Name = name 5 5 Public void getName ) g aekiad Warne ; j + Thene ane Vania Scopes casing, eshich “the bean can be used in Isp Page ) page Scope + Te bean object gels disappeared a> A000 dine cucrenk page gees discanded. Me default Scope fpr o bean WO jsp Prge Isa page scope 2) Recyuest Stope! Me bean object semainr in existence ar Long as the meanest object is present 8) Session Scope: A session can be defined os a specie poriod oh Aime , input type = “button” narne =" submit” value = “Submit? > <| boty > abc jsp chtmt> < body > < jsp: set Properly name = "login" prerety- “usen"/ You entered parrwond asi < jsp. get Property name =" login” Parcpoily = "pax" /> You ane a < 7 login. vakicl ake Cinaveen", “cte’ Pp userebas Scanned with CamScanner Validate Bean - java class talidate Bean implements Serratisable § Shing Nase ; Shing Pours: public void setName (Sbirng same) dhis Name = name ; 4 public void gettlame > mneboin Name; 4 public void setfars (Sbing pass) his. Pass = pars; 4 Pubic void grtucd i retran Pars; 4 Public Sting Alalidatke (Sting si, Sting 2) i if (st- equals (name ib $2: equals Cpars)) sreksuin valid 5 else, mekunn invalid 5 Scanned with CamScanner Using Cookies 8 Cookies ane the smal Lert filer that ane stoned in the clients computer. * Mese ane basicathy used fy keep back Of dhe csons who browse -the web. The information Stoned ‘in Ihe Cookie is grnvualty name , age sid, cily and So on. ~ The senuen soiipk sends a set of cookies fe the beowser. The bsowse stones Ahis infomation on The local machine and makes cue of “Ihis ‘Iingoamation next time tohen the bowser is barocosing dhe web - « Cookies wre usually Set IN HTTP headen. Marios methods used in handling the Cookies ane - i) Crreake Cookie 2) Read Cookie 3) Delke Cookie D Create Cookie: step 1+ Im JsP dhe cookie is created wing dhe consbrckorn named Cookie: TE Dreqyeninres boo panameko — name and valise. Example Scanned with CamScanner Step 2: Then we can set dhe valiclity Pertiod bem Ahe cookie natty che method ‘sekMaxfge | Fos example fe sek “the cookie ative foo au hs we coill aatite dhe cede as cookie + sek Mas fge (60% 60% au) : | in Skee 3 + Now our Cookie is rreacky Ao send over tale Can add the cookie iN HTTP sespone header as follows aresponne « add cookie (cookie); Di Read Cookie : SEP 1! Fiast “lhe cookie is nebieved cing gekCenkienty method: es { Ee step a: Then sing getName > and getWoluet) Ape cookies ane read. methods DVeteke cookie : ee oS. SkeP 1: Read the already created cookie and stone ik in Cookie ohjece Cookie cookie= new Cookie ("nome") **); | Scanned with CamScanner . ©) step 2: Then set 1G period of existence as o seta Age methed: This means that cookie is. acually deteted - Cookie + sekMaxfye(0); cookie + setNalue C"); back to mespone header Step 3+ Add his cookie nesporve - add Cookie (cookie Scanned with CamScanner rr FO aE Cookie example < body2 gt Shing shuts aceyrest - gee Farrameton ("item"); Shing sora = aieq west ace Poscameten (" vy "»D, Sori atia = sreqyuerl sgte Parameter C"add’); meqyucat: gk Raswameten C" st”); String stay = ih (s3 [= nut $ Cookie eve new Cookie Catit. shiz); arexponse add Cookie (61); areaporse « send Redinect Chindex hem") alse iy (sty b= null’) g cookie chien Cookiesl I= request gtk Gok) for Cink iz0; icckientCookies-length 5 tas) i cut: paint ("<@>"s client Cookies C13 etntame ()+"1"4 dienk Cookieal}} qebilotue Oa" z[@>
      " oe 3 i> | < [body > | | | | Scanned with CamScanner TsP © Session Handling is we use a request scope and by to access the data over multiple pages, then same data can be chanel by multiple pages: But sometimes we need le use game data a, maltiple Aequests FoA example in Alospitat management austem , the dient infostma tion is, enbened initicully only That patient may eenlerg 0 dhaough vortices bests 8 operations . TE is then Shot necessary fox him cto enter he some formation ouet again and in. Te same set of information is used by uSsiows operations Yn the hospital mnanagernent system: In such session scope Is used a case the * HTTP is a request -mesponse p2ctocol Rak means ehen user eaants to access some toeb page, the web berowser makes nequeat to sewer ‘and server arekcuins thet page oo sresponse - x Buk at she same dime HTTP is also called as a stateless protocol That means ashen browser sends a rrecyttest te the server, Beer processes it afd sends the metponie fy the browse and does not srememben anyini about the mecyuest: So eshen borwuse} sels “tee game sieayuest do the Seroen, talces IE as o New prea een proce: So, ie is areqpuirred dhak seiuen Should Eeep brads oh the usen on mequek made by the his prwoblern Anene ane thetee sower user To Solve methods used - Scanned with CamScanner betroeen browsen and seweT, Uso an Thus | Use of Cookies a Embedding hicklen fields tn an stmt Aisin, 3 Sending ORL string in mesporse body * Fon sendi in fommetion +o and fre ap is used: Mis TD is basi a Session-1b, session- TD is Passed bekween the browse and sower hile — pocesst the, inypamnation - This method of keaping Grace of; au cthe information lbebween senven and browser wing Session- 2D Is called session trode na Scanned with CamScanner Comectir se bo database win JSP Ly) ( “There axe 5 steps fa connect any java | . . gd application esith dhe database in java using Wee» Mey are as follows * & Registen the dotiver class b Creabing connection 9 Creating statement d) Executing qyuotiet 2 chosing connection a) Reglsten the dativen class : The fosNamet) method of class is used fo jeken the doiven class. This method is used bo chyncart cally load the dave class Is : nto: public static void foaXame(Sbing classlame) Ahrows ClascNot Found Exception Example : Class. fosiname Cc com: mays + Jd bc. Deaiven”); 8) Coreate the connection objec: : ‘The arbconnection() method ob DaivenM class is used ke establish connection esith dhe database . i Scanned with CamScanner Syntace : public static Connection get Connection (Shing wal, Shing nome , Shing passuoad ) Example + Connection con = Dai Manage: get Connection Cust, user, password ); 6) Careate a Statiment Object: Tre Cieake Statement ¢) method of Connection inkothace Is used bo create skakement» The object of skaternent is respontible te execute quuenies with the chtabase » 4g nkat! public Statement create Statement ©) Ahsrowt SQLException Example: Statement stink = con, creake Statement) ; 4) Crete he quest? the execute Query C) method of Skakernent interhace is used fo execute queries to the dokobase. This method rsebuant the object of ResulkSet thak can be used to ae all the mecords» of the table - Scanned with CamScanner S Syntax: ( public ReswhSet exetube Queny (Sbing sl) thors SQLException Exon ple : ReselkSet ris = skmnk. executeQueny (" select -« J from esp") e) close the, Connection object: By chosing connection , object skakernenk and Resulk set sill be closed autorsati cally. The cloce 6) method ob Connection interface is used to close the Connection | Syntace : public void closed) fhorows — SQLException | Example: con: close OC); Scanned with CamScanner

  • You might also like