Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

WT Unit 3

Download as pdf
Download as pdf
You are on page 1of 41
Scanned with CamScanner | oO | Seowlet technology is used fo create eweb application (mesides a sewer side and generates “dynamic seb page ). | | * Servlet technol is rtobast and sealable | because of java dau wage * Befonre sewlet, C42 (Common Gatewoy Tnkeiface }) sexipling | Language sar popule as a sewer-side | pos mammming layguage: But there axe mary disadvantages for This Lechnolegy ~*~ Thene are many inkerbaces and classes in Ahe seswlet APT such as Sewlet, GenerieSerulet , AUPSawlee, SeowleReq werk, SenulekRespome etc Wh is _a Sele 7 Soult 1s desoibed in many ways , depending On cthe conkext * Sewlet is a technology ie, used fo create web applicalion. 4 Servlet is an APL that provides many Interfaces and classes including documents x Sewlee is an interface that must be implemented — fp venting any sewlet * Sowlee is a claw chat extend the capabili- ties of the Sewers and steeponel b the iacoméy meayuest ‘LE con otespond be ony types of eeqyuncat| Scanned with CamScanner Connmnan Gateway Tnterrfoce (47) i CGI technolo yy enables ‘the web sewer to call an external pacgram and pase HITP request infomation “to the extemal program fe process the seqyest For each reall iE skasits a news process. “Disadvantage of cgi: Tere ane many parblems in cq technology: : ) a Namber of clients incieases, it takes mone time ben sending mesporse 2) Fon each rreqyueat , it stants a proce, and web senven is limited b stant prrecesee D TE user platform dependent language - eqn C,Ctt, pet Advantege of Sewlek + Tene arte many advantages of sewlet over Cqi: The web conkoinen cleates dhneads ad handling the mretiple requests the seruleb- Tineads have o bet of benefits oven the processes Such as they share & Common memory aren, Gght useight’, cask eh commusication ae: “hel twrensn fone lous. “The baste benefits ofr Soule ane an follows = a) Betten powoamance : because ik wreakes a thread fe each req rere nok procean Scanned with CamScanner ) Foottahility : 8 because it ger java language 0 2) Robust + Sewlets are manoged by TUM So we don't need & coossly about memos lentes gerkege Collection ete A) Secuse + because ik caer java language xs Like ~ Cycle of a Senvlet : “Thee methods ane cenbal to the dite yde of | a senvlet + Tease ane init), senice 2 and | desboy cr ‘They axe implemented by evo senulel | gn og i “0. Land ane invoked ak spectpic bimnes @ senven | Lek us Considen a typical user scenviio to undeukand when These methods ane called. ~~ Fistsk, assume that a user enter a Unifor Resounce Locator (urL) to a Web brouser + The browse thea generates an HTTP meqarest foo dhis RL. This request fs cthen Sent te the appropmiake Sewer x Lecond, this AITP request is received by dhe web Sewer Te seaver maps “this sreqyuest ig a ponlicutoar sewlee The Serle is dynamica. ty autrieved and bored into the address space of the seowen- % Third - the serve ‘wwtokes the InikO? method of che seowlet + This method Vs inoked: only when cine Senulet \s fut loaded into memory, ines posite to pans inikiatigntion pooometer fo the sewlet so W rags configune itcets | Scanned with CamScanner %* Fowrlh , the server ‘invokes dhe sevice ¢) method of the Seulee- This method ts called Ly porocess the HTTP srequuest You eill see that it is possible fer dhe sewlet be read deta “thal has been poroviced ‘in the ATTP equresk Tk roe also poumulake an ITE response [por the chene # The sesiwlet stemains in the Sewers Jaddavens space and i available te process any ether ATITP mequests received from Clients. Te Seowicet) methed 1S called fpr cach arn? requck *% Finally, the sewer may decide to unload the sewilee fron We memory + Pe al goritnns ky cohich As dekermination ts made ane specific ke each Seven The senven calls dhe destroyed method fo stelinguish any merowoicer Audi as fle handles chat oe allocated fom the sewlet Tinpsatank deka moy be saved to 0 persistant stone. The memory alloted fpr che sewlel and We objects can then be grabege collected Scanned with CamScanner Steps fe quake Sewlet Progaam: i) create a dinectory sbructwie D orate a seavlet 3) compile the servlet D create a cleplogmn ent. descipton 5) skort The server and deploy dhe pardjeck 2 Access cthe sewlek D wieate a directory douckune » Demo WEB -INE HTML | — classes (folder> CSS | esebe vent (filed L— Ub (folder> Favaseiiptt index: Now | java soudune of Sewlet D) owate a sewlet: senulet can be created in a difperent ways 9) by ienglementing Seulet kerpace By dheriting The GenoiieSeulee clans ¢ by ‘nhesiting Ahe itp Seorulete chasa Scanned with CamScanner D Compile the seule + | Sele can be compiled by cash Jor files Jor files cre sequined +o be leaded. Servlee - opt eu | v WE tan set the elarrpath on it can be copied manually, into dhe Seawes. 4) vreake deployment desviipton : Deployment desciipfom is an sine fle crth a name web-amb “+ Fao his amt fle web conkaine gets the “intarnakion about the sewlek to be ‘Vnstokect web. amt Zuweb-app> filename 4 /sewlet - name s ZSeowlek class > Aeusnome < /sowlek —clasas < [servlet > é selee — wopping > ésemvlek-Rame> filesame ¢ (seswlet names repli < (ut -patterns + [seule snapping > 4/web-app > Scanned with CamScanner ® 5) Skat dhe sewlek and seploy the pacjece Mere are choo eonyp, te seplay the paoject 4) hod deployment 8) Soft cleplaymente | ® sobe cleployraent: Copy the demo folder into seaver rmonualy In Wedoes Cire, seven) Copy & Paste the complete olden of the poroject - Tn appache web-apps is the seven Col xampp | Tomenk | web —apps n Copy corepleke folder bb) Soft deployment: For soft cleployment first create a wan file | By compaesting au files (i-e » Piepivg D a war pe is grnewtedt. * A ccan fle Is Cteaked esti Jor commands local host {toto / manage [hlral. D: (>demo/ Jan wh Demo want 2) Access the Serle: hitp: IL locathost | Verso — ik file name is Rok Specityed then ik directly access iMdex html. ‘Scanned with CamScanner ‘The Sewlet API : Two packages conlain the cleasser and interhace cthak are required fo build Servleee ‘They C ate a) Javan. seule B) Jawan -serulee hep a) Javan + Senet Package : |___Thenpace_ ___Deseription | Seorulet, Meclones Lifecycle methods for a seaulee Servlet C enbig Allows servlets -to get ititinligation pootamebers Searulee Context Enables servlets +o \g even and access information about their emvinonment SeuletReqrest | Used to stead data fron cient mreqy west: SowlekResponse | Used -to asmiike data to a client seaponae. , Siig\e Tarene Model Tndicates that the senulee i¢ dhneod Safe Scanned with CamScanner class Description Genertic Serle ‘Um@emenls he Senutel nel Serwlet Crahig, inkerfaces Sewulet Lagat bream — | provides aan ‘inpuk sbreain fos readiag meyer fromm a chrent Serwlet Output Shream [provides an output stream {pa fondling seapentes doo chia Serulek Excepton indicates @ senuleé exon occured - Onavailable Exception indicates a servlee 1s unavaul-| able. |The Servlet Interface | an senutebs musk “implement the Sewlee Interace | Tk declosres dhe inie C2, Sewicedd and desbioy [methods hak are called by the sewer dioing the Ute eypte of o seowlel - The mekhods clefined by Soule ane shown M table belous | [Method “Desoniption Nid hestor fo called ashen the sewlee is unloaded « Sew 1 i Seurlee Conlig atGons @ SeawletCenbig object, get Seoulet Conti hak conkains any initaligabon porrarnekers Shing gresewletdabr meen sbing deacribing Ain senulek 1 Scanned with CamScanner Ucid init-CSewulekCenfig s)| called cchen ne celeb ie | thease Senule Exception | Witaliged: Thiliatigation | Pornamekens fox the sewlel tan, be obtained fron sc. fe Unauailable Exception should be Hracwan ih a seule cannot be ‘initialised Ucid service (Sewwlek Request called to process fo neqjueak from ov client The myeqyuat grorm Ahe client can be mead from eq). The aiesporie to Hhe client can be conitlen to ares fin exception is pes Ay ao Sewlee os LO pooblern ecu ney, SowldkReapomac 24) Atos SerulekExaption, ToException Me SewuleConhlg Tnkerbece The Sebel Contig interbace 's implemented by the server. Tk allows the Senile to obtain Cont aaration daka ushen ik 1s loaded. The metheds deckoned by this \nkerbace ote summesiiged here Method DVesoiiption Seavlek Contert sreksorns he context fer this qrtseulebContext seoulee: Shing get nit Raoorncker |actunns the value of ‘nittiakigaiog { Sbiing paasn’) [parameter named” Pararn Enumeration : sebamts an enumeration of all gekTnit faxametoitlarnest Jfiniticdigabion panamekor names. Sbivng gurSeouleeName ©) ] rekon the name 4 “the ‘nwtoting sewlel Scanned with CamScanner The SeowletContert Toterkoce Me Senile Contert ‘wkehace is ‘implemented by he Sewer TE enalles the Sewleks +o cbtain Tnkeamakion abouk their Enviowament . Sevenal oh ib methods ane Summaiiged in Aelole beloco - Method Description Object gee Allsibute rekurnt the vatue of the Cstring alin) [sewer aboibuke named atta Sbing getMine Type | tenons the MIME ype of; Csbing file) — | ble Shing qk Rest Path dielinns the reat peth that Cormesponds to Ane Wiartucl path upath. Sting geeSowerTrfo ty |retuans injsoralion about the sewer. C Storing vpath) cid egy (Sting £) wootikes sto dhe semlek ba told leg CString S: luomite S$ and dhe slack tace AWmowahle ¢) fom @ to dhe Senutee tq lucid seksi bube geks the obisibuke specified’ (Stig ation, Object val] by atiny to the vatue passed An val The SewletRequest Therjeace The SewlekReqeeede “Interface 1s ‘implemented by Ane Sewer. De enables a serlee do chtatn ‘inhorreakion about vthe cliente meqreak- Several 4) WE methods ane summestiged In) bable below: Scanned with CamScanner D Method SDeseriptien Object gebiitibute |Aekeoins the value of the CSbring alls) albtitute named alta Shing gclcheorackerEntol rebwirs the Character envodhing oO of dhe neq treat ink get content Lerginc > rekuns the sige of the request The value -1 18 ackworned if the sige is unavailable String got ContentType C)| rAetwins the bype of the meqpuedk 3d d LA nut value ta ebusced he type cannol be clekennined |SeruletTaput Stream nekwwins the Serwlek TnpuleStrea | gebinpat treat > Hhak can be used do read bireou) dporows TOEcception |dake from the scéqyuest «An legal take Exception is trecovon iy qekReaclenc) har abready bean Tucked fpa this seqpunt Sbiing get Peoameten retesins the volver of dhe (sting prame) |porameber named prome Enumeration nekwnn an enumerabion of qt Paxamekernarnes dhe panameker names for C) Lnis meant String Ll] geefarcaweborllatiey retire an o> tonbaining Cotring name) values assodicked aith -lhe a pooramekert gpecitied by nears | [Shing gttPrtocslo areas a desniption of The pactoce\ Scanned with CamScanner | BufferedReader pete a biftened sender tral eb Readend) Ar be used to mead bert [roe the rreqquese An ie istalsexcphen| is Hhooun If gekrnpubSbreamnc 5 | her already bein invoked {0% | pis, srecyeneate theows TOExce tien lag gekRemoteAddre | returns the sting eaysivalent of the client sPaddoiew, | | String ck RermckelloskO] melavins the sbring equivalent | oh the CUenk host narve | | Soing AeeScherne CD [orekuor the Grantentscin sche | Ap the ORL wed bua The neque | {Sbiveg att SewerName C) arclaow Ane nase of “the Sewer Hine getSewerfonk ¢ d dekroms the port munloen. Sewlek Response Toterda ce The SewlekResporre inkerjace 1S implemented by dhe sewen. TE enables a senulee to foamulake a aesforne fpr a client Seterat of ib methods ane Sumnmaciiped ‘ny dalle below Method _ Description Soi atekuows the Cchosackes encoding gtichanecker Eneaddivgs fpr the repose SerwlbOukpuk Stream —Jaretiowr a SewleeOulpuestyeam qetoukpuk streame) pihak can be tsed to wnite bi Aiows TOExeaption AXES to the Responie. An <1 StateExcepton is thaoun ik geeweiiterd) hos aby besa invoked fom this mtqnueal Scanned with CamScanner 4 Painttnloiiken get waikent siete a PoinkWariker that con be used to woriike character doko 4o “the mesporee AN SMleqal ShakeExcaption is tborown iy gtoutpatstoearnt) has abneady been intoked for ARs aequal Aprows Toexception \cid set Contentlerath | sets dhe content lenath fon the Cink ig mesporre to sine uicld sek ContentType sets the content: (ype fpr the € sting type ) sresponse clo type SizgleThneadModel Loterface This Vileesipitie is ured do Indicate that only a gingle Horead will execute the seswiiac> methed of A Seaulek ab a given me. at defines no contanty and dectanes no methods. Tf a servlet implements Ais. ‘inkeyre » dhe sewer has too option. Feat, ik can creske somtenol instances of the Seowlek - when a cient seqmres& aoviiver, tk is sent +o an available Wakance of the sewlet- Second, ik con gyreloanige access Ae dhe senwlele. The GenesticSeowle Class ‘The GeneriicSerwlet: class provides ienplementakions of the basic Lle cycle methods fora seaulet and \s Kapicoly Subclassed by seaulet developeu - Generic Sewlet implemen the Senulee and | SowlekConkig inkeifaas, Th addition, © method ts Jappend a Shing cto the Sewen log file is availble. The Siqnakwores ol this method ane chocon here : ®) Scanned with CamScanner veld log C Shing 3) wid log (sting <, Throwable < ) More, § is dhe sbing te be appended to the log, and @ ts an exception dhak ecavted: ne Soules hes “the Serwlet Ampat Shean class extends ‘Input Stream Hk is ‘implemented by serve and paovides an np sbyeam Ahak a sewlel developer can woe to nead the daka from lhe chien request Tk defines “the defaulk consbutom. Tn addition, « encthod is Provided “Lo aread bytes ftom The stren ibs signature js shown here + Ink sreacttine( byte OI bughe, ink apsck, Ink sige) dios TOEcception x Alene, arma bufher is the asvay into which sige byes ane placed sorting at offsel-- ‘The method rectors the acksol Rumben of bytes on ~1 if cthe end -of the stream condition Is encountered. {The ServlekOutput Stream clay, The SeowlekOutpul Strearn class extends Oukpwe Saeaen. TE is implemented by the sewer and Provides an oukpuk stream rat a serulek cleoeleper can be used to snvite data to a client rtespowe. A clefaualt consbyuckon \s. clefined | ak abo defines painkO and Painklac) methods, tchich cukpuk data to the sbeam | Scanned with CamScanner Ke Handling Http Reqrest & Responses ‘The Altp Souulet. class Provides specialized method: that handle the various pea of ‘ie Ley weal A Sewleé developer typically ouetrides one of | Anes methods + These methods axe doDeletec), dogetc), dotlead¢), doOptionst), doR osk 9, doPut ©) and ddfuacel). A Complete deaciiption of othe different types af HTTP requesti is beyond “Ihe scape of his book. Jloweven , “the QeT and Post req ests ane commnetilay used eohen, none fon input Therefene , this section presen examples of of these Cares. *” Handling HTTP GET Requests Alene we will develop a Sowlel that handles an HTTP |Get request - The senile is Invoked ashen a fpam on a Web e is Submitted. The example | Contains two files: A Web page is “eyes in | ColomGek- htm and o sowlet is defined 10 [Colon GekSeowlet sjosra Te HIML Sounce Cade fom | ColomGet “him. is shown 9 fpllowirg Usting. rk |aegines a fpan dhok conkairs a select element land a submit button: Notice drat the action |pasameker of tne fem tg specifi a vet ‘The ORL identifies a serlet cto Powocess “the HATP GET sreqpreae Scanned with CamScanner Colon < Select name = “Celon" slag =" ">
| The sounce code for Colon Get Sewlee: java is shown in the following Usting, The dogeber method ts ovtenstidden to process ame Amie get sieqents Anat: ane sent do dhic seawlek- Tk ceses dhe getParamekenl) method of; AP Seale Req reac fy obtain this selection that war made b the wer A mesporue is chen Jormuloted. Scanned with CamScanner 3) Import jovie-to x; ( Import javax senulel x5 Import Jauiax: seurlel HHP. Xs Pablic clams ColongetSerulet extends AM pSenvlet public uoid dlocyet (AllpSerlet Request arequerl, AU PSeowletRepore sresponse) Ahwows Servlet Exception, TOException | Sbring colar = areayverk- get Faaramek eC” colon”); siesponae - sek ContentType C" ext / htmi "): Poiinktabiiken pus = response - get Worker O); pe printhle ("ces The selected colon is: "): pao patinLtn (colon); pw close C7; 4 [Compile the seaulee and pertoaim these steps (te best this example: Is Skank Tomeat , if iE is not already sunning a Display the Uleb page nM a baowsen. Selec a colon | | | \2 Subriit the Web poge ¥ Afton completing Ahese Sheps, the brouser cwill display he mespomae hat is clynamicably qenernked by Ihe Semtee . One othey poink : Panarmekent {or an HME GET mrequucsk anc inchaded a» pan of dhe ORL That is cent ty Mhe Web sewen. Assume hat -the wasen se flecks Ahe red option and sabsmit -the {pom - The ore Senk fromm the bouneee fo the senvey hs | hep: [I locathost + 2020 / examples [ serwlet / ColonGekSeulet] Scanned with CamScanner Colon = Red. The chanactens te the ai he of the Yuestion mask are known ar the 9 qyucuy Shing. landing HTTP POST Requests - goa % lene we ceil lewelop a senulet thak handles an HTTP POST riequcse- The Senulek is invoked when oo form on a Web pege \s Submilled|, The example conkorm boo filer A twoeb page Ts defined in ColomPosk him and a seulet te ane is shown in che follovsing Usting . TE is identical be Colordick-htrn except that the method pancmetenr fom the foamn bag explicitly Specifies that -the Post methed should be used, and dhe action panameten fon the form tog specifies a alifherent sewlet- | dbedy> | gcenken> Chore nase = Foam’ method = action = “hip: I localhost :¢o8e /e xamples | settee ( ColonPotk Sowtet. " > * post” £5 Coloni< 167 ceded wesnex “cohen” sige e “1 > “Red” > Red < loption > # aean"> Cyneon < lopk on > Zoftion value = Zophion value = <[seleck > Cbn> The selected colon fe: | pe: patinkln Coston) 5 pus: chose CD 5 3 Compile -the Servlet and Paiform the Same skeps a desorbed 19 the previous section to test ik Scanned with CamScanner Note: Porarnebens fp an HTP POST mequesl ane rok Included as peat of the ORL ~fhat is sent ihe web server in this example, the ORL Sent form the browser to the sewen is + cho hitp + // locathost : 8080 /examples/ sewlet / Color Get Serwlet The pastameten names and Valies are seat 10 she body of he dTTP areqytrest « Scanned with CamScanner Using Cookies (3) Now, lets develop a sewlet that illudrates how to use Cookies. The sewlet ts invoked eshen a fon on a Web pege is submitted: The example Contains three files as auremnoniged hene + File Description Add Cookie htm Allows a usen to spedity value fea the Ceokie named My Cookie * AddCookieSewlek jaa Porocesses the Submission eh fdiCookie -hemn * GekCookiesSenulel- java Displays cookie vallrer * The HTML source code fon AddCookie him is shown in the following listing * This Page Contains a bert field in ushich |@ Valse can” be entened-Thare is also a Submit button on the page when this bubbon is preased, tye value in the text field is sent to fldCoobie Senile ula an HTP Post request fheml> < bedy> ~cenken> ¢fomm Aame =" Fox” method =" post” action = "hltp: // local host :8080 /examples / seaulet / Add CookieSenulet ">| 2B> Enten -the value i= MyCookie | Scanned with CamScanner The sowice tode fon AddCookieSowlet java is shown in she following Listing. Te gets the Malue of “Ihe penermeter named “data” rt then wreater a Cookie object that has ‘the name * My Cookie "and Conkains the value of the “data* ponameten: The Cookie is then added b the headen of the HTTP mrespome via che addCoakiel) method: A feedback menage is hen cosiitlen to “We brtouosen- import joula -to-x impont Javtax: seuilet Import javax- seouilet “Hee x; Public class Add Cookie Sewlek extends Hlkp Servlet Public Utd dofost ( MpSewlReayuek rrequal, HiipSewlebRespovre >tesporae |) thiows SerwleLExcephion , Lo Exception t Mf gee poxameken from ire seapteak Shing data = meqnresk get Panameken C'daka" ), UY oreote cookie | Cookie cookie =new Covkie(" My Cookie”, data); g A add tookce to #ITP mrexporme preaponise - add Cookie (cookie); Wo votike output to broustey prexpovuie- setContentType Ckert (htenl")- Bimkitlsiker puss response. gekWaikony; peorpaintla (cas MyCockie has ben set -to''), Scanned with CamScanner pes patinthn (data) ; ® Pus. close); * ‘The source cece frm Geb CookiesSenulet pw is shown in the follow Using. Te invokes dhe ek Cookies) method +o mead Cookies “that ane included in the a Get Drequuest The ames and Valuer of these Cookies ane “then ensittten Gs the HTTP aesponse Observe that the qeenamecd and qateenti methods axe Called to oblain this inpormation Impoak — Jasta io %s import jauat servlet -% Import jaan: senulee “help. x; Public dass GekCookiesServlee extends Hitp Servlet 7 public uoid do get ( He pSenulet Request sreqnuok| Hub Sewlee Response siesporue ) Arrows SevlebExcaption, Lo Exception Gee cookies from header of HTTP request | Cookiel] cookies= request gekCookieh 35 | Wf Display ‘these cookies pieaponse - sek ContentType C' text] hemi") 5 Paintaiter pure response. gekiulaiterC>; peo paintta C'<8 >" Ds fon Cink \20;1< cookies Leng ty vite) : Sing name = cookies [3 -gebtlamet) ; Sting Value = cookies Ci} ger Malue); Poo: patina C'name = "4 mame" value = "+ Value); Scanned with CamScanner poo: close C5 3 Compile the Serulek and Peitbparm hese steps: I. Sot Tomeats if IE is nok abteady sunning. 2: Display Add Cookie “htm in a baceaser. 3. Enter the value fon My cookie 4s Suubmitt the seb Page Alken completing dhese steps gee will obsewe. dhak a feedback Message is displayed by the browser. Next, mequeskt the fellowivg ORL via dhe bawsen | hip: //Localthost ! Bo8o/ examples /serulek / GekCookieSentd Fobsewe ‘that the name and value of the cookie ane displayed in the browser. x In this example, an expimabon date is nok explicitly assigned to che cookie via the SekMax Age ©) method ol Cookie. Therebone , che Cookie expines eshen Ahe brouser seamion ends. You can experionent by uaing sekMaxAge (> and Observe thak the tootie is then saved to the dick oo he client machine Scanned with CamScanner SION ‘Tracking @ HTTP is a skakeless pretoeal. Each requ ese is \ndependent of the previous one. Hlouscoen, iM some applications, ik is Necessary +o save Stake infpamation so thek infeamakion can be collected for seooral inkeickions bebwern a browser and a Seaver: Sessions provide such a mechanism: * A session can be ereaked ula the Gee Session method of MepSenvlet Request » fn HePSession object ts mekurned. Tis object can Stone a sek of Rennes dhak orsodiate names crit) objets: The sek Albsibuke (>, gekAtbiibuke (9, Att AbsibuteNames? 3 and memovedthibuke () methods of Uikp Session manage Anese Bindings - TE 1S important to Aote thak session state is sKaaedl among eli the sewleks 4pate ane arscaker wid a peortinlan client ~*~ ‘The follow sewlek ilusGiakes how fo use ression shake “The gtk Session L2 method get the aourenk session. A new session is Created if one coe nck aljeady exist. The get Altai bute) method is called to cbbain the cbyect tho is beund te the name “date”. That objec is a Dake chjeck that encapsutakes the ctoke and Line shen Anis page tees Last accessed. A ‘Dake cbyeck entapsulating the Gement dake and iene ig then Cieaked he set Abksibeked ) method We Called do bind 4the name "date ” te his chyece Scanned with CamScanner | impomk java io. *; Import joa abil es import jevore - senlek a5 Import jovtat: sennitel + hike 5 Pubic dass Date Sowlel extends MpSoule t Public void doget Cilip Servlet Request rrequert | HlpSewleeResporse ateaponse ) Ahaows SewlekException, TOExce ption Gee the lppSession object Hip Session ats = neq weak get Session (bre), MW Get Waiken aresponse » sek Content ype ("kext [heml") 5 ParinkiAloites: Pus = sresponre + grewlrrter O; Por patat (""); MU virpley cake / bine of lank access Dake dake = (Date) hs. get Abritbuke C'dede'} , i (dake t= ned) pus: paint C* Last access: tdake +” )} 4 UVisplay ewwrent dake [time date =new Dake Cd; hs. gee Allvibake (" dake”, dake); perrpriatly (" Curent date 1 "4 dake); | ! Scanned with CamScanner & When yor fiwk mreqyeteat This sexvlet , dhe - browser displogs one Cine coidth dhe ceoutenk date and time infomation. On subseqyuent Jnvocations, boo Lnes core displayed The file tine shows dhe date and lime when the Sewilet was lak accesred. The second line shows dhe jooent dake and -Kene- Scanned with CamScanner % Dbroduction te IDB t- > Tn leday's Scenario, Many enlerprise level applicalans need fo iMlvauk With databases far sfeving information. 5 For This purpace,, We used om APT Coplicaton prigram eming Tulerfaca) te ODBC L open Dalabase Connedivilg ) . datebate APL fe conned- ad > The OPBe APT was The ApL uses OPBH eneala query With Me data bate + Buk, opBe daver which ig ubillem wm c language Cie plalfdm dependent and uncecuvad)+ > Tat iu hy java has defined ‘Aprc (tava Dolobate connodavilg.). Kak uses Ippe divers He own APL, called cw -Hen fm gava language). | x pith Java. Appine >the dpe dvivers ave move compadrble te provide dalabate Cowmmund CAA + ; ad euewle query with comnet an acs te connect with => apee ib a Jevo APT to te dalzbote. apee Apt Uses Abe dive dokabote + > Ipwe Supporto Wide. level of podatbilil, ant Ise and 2asy te ule- . | a praqvamnmey needs a Speitce dave} | is simple > In pee APL, te specie dallabate » te conned | RDBMS Di ver iene: qvacle . dbe» chivey « OvacleDviver ~ | Mygabews | cemumgelidbe Diver SyBose com + Sybase. jdbe . SbDivey Carsenver | coms micro Soft. jdbe + SqlServer | Der com. tbrm«dbr+ jdbe- nen DRLDAvev | | | © List cb Some populay Driverl Scanned with CamScanner % IDB Avchi led The main -fandion oth The ange is to prvide a slaidard abstraction chy “ave applications to communi cadion MiTh databate + etn f -_ | gava Applicaton “apee APT | th | fg “nt a | sipee Devers) | [ape Divers | | uote sau | Sorel a 24:- the Iowe Archilectione The seve. opplicadton Wak wont to be programmed using ps chaon io Kpere, with a dalabote hat to communi cola pre APL - tm SOL sraguasle Tho ‘TpRe Pavey is raguived to process aud generele the neosulls. she TpRe dviver has awkiteebaa. The Dave” Manage with Speu-te fs be plays om trnpowand sche.‘ nw uses Some spuhe dababoses+ Hak emables ave Te DBC eye chively come” is a Sofware component” the dalabate. dvvers te > Tpse Davey aprtcaoa te ‘hiack With Scanned with CamScanner Theve ave 4 types ob apne dvivers, tose ave > Type -! Diver CIpae- pee bridge. Avner) > Type - 2 Driver (pavtial spec driver) java dyer for middleware) | wR divek dalabate connedton) | > Type~ 3 Diver Cpuve > Wre- 4 Driver (pure java dvvey oi % Type-| Diver Cappe - ODBC badge. ddver) t+ The Spe -! driver ack as o ridge bekween TRC | and other dolabase comnedivilg mechanisms such os ODBE+ The pge-opwe bridge dvivey Use% ope. chiver Fe comm: diver converti soRC te the database » he IpBe- ODBC bridge inte The ODBC method call - method calls ova Applicahon I pee Apr av DBC Davey cea! dpge- opRe bridge Dever OPBe Diver (ae © Dal& base Serve Be Bridge DOVE gig: Appe- OP! Scanned with CamScanner Advanlas x Easy fe use- & Com be eatily Connedad te any dalabate « Disadvanliges : * pey-f&amance dagraded because lavge number of vans ~lalons (ie apne calls fe opee calls). client % The opge driver weeds fe Machine. be ivstalled on the % Type-2 Driver Cpovlial Ipge dyer) :- cies ob The type-2 drivey use The database . So Tes dvivey Ts alto This drivey ch te dobabase Am. I called as pavtiol ToBE dyer: pee apr converti Spac wmelhod colle is rt whatten enliely in java, 5 the client - Side iby called as Nokive - APL diver ints Maltve callt go it is qpRe Diver Menage Nodive APL diver Ege Nakive APL dyivey Scanned with CamScanner Advawlagee: x pev-fAmance x guilae fo use With Sevyey - Side Ditadvawlag: 2st | Xk Way ineyeata Weeds fe yun hence ib is @ pare ave gp divers x wus Nodive chivey ne x The Vendor cHenk Ubvary veads to be the cost of the OPP Trak converts Spee calls —spehe dalabose protecel ods to inslatled on dient plobfor The Type -3 davey & covnpletely ee dey + % Type-2 DriveY Cpuve Tova driver -for mriddlawere ) t= implemented middle wore Capplicakion cupgaded Wan ange-opke beidge chiver. applications. cach clonk Malina vd machi ae, on tw indatled on che Gealon Ue apeicalion) mi + in qova, | | | server) The type -3 Gaver viet 7a aly inks te ven dot divedly o inde go ik ts gov. Applicaton _[ apee APT Sowe Davey collad a Nelwork protocet yb Scanned with CamScanner w No clienk side Ubvavy is naquivad on cliewk sido. | and auls downloadable. | | x pave Java drivers Dis advawkiges + ae Nehwork Support Is Yagut te costly compared ts vad on client Machine. K This dvivey they dvivers. X Type <4 Driver Choe _jove chiver, with dived database, comedy et eee —_— | diver, Which convert databose profecel | is a pue Jove The type -4 diver givedly ints The vendor Spec Spee calls thin dyer: hak Ue why if ib Knaus my as avo Application pee APT L TBC Diver —_y Thy Diver Fig Tein Divey- Ad voulages : ye Tus caver & germ java dvvev aud ante daswloadable. % Beller performance thaw all ofhey dwvers re No Solflwave is veguivad at client sida ov pisadvawlage ss x Divas depends on the Dolabate- Server side - Scanned with CamScanner % Dolabase Progvawming using apBe 2 Spec APT, ave used by a Java application te communi -cala utite a delabate- Ga ofhey words , We use gore connediiy Code ‘m Java application te communicate wilh a dalabase + Theve ave 5 sleps te conned any Java application With | Ter datsbase mM Java using IDBE. They ave ot elles * | Step: Regisley tke diver clocs step 2: Creating connetion Sepa: creating slatement slep 4! Execling s@L slalemen | step 5.1 closing connedtdn. i x Shep 1:- CRegislér Hie doiver cla class) Te dvivev class With driver Manage Jn this slep, we ~os\sler by using for Nowe wofhod of class class + Syrfox: closs | | | | | | | The close tht connedin { Exaragla % Scanned with CamScanner Ceomnectvily With ovacle database) We Example :- tH the ovecle dalabate, | rot connecting java application wi | | we need 1 Know fellasiug infermaon 13 per-tern dolobote | comectivily with ovacte+ | Tq Was ehample. be ave using oracle (09 a tke database, | $0 te Mood te Know dellaotng iveformedion deer class by orache dalabate is * vache vjabe -chivey. Oracle Davey" dev he ovacle 106 Aalabate | cor tee ovecle dallsbad® x Davey class 1 The ® Commection URL? the connertion URL is *ydbe tovacle tthin t@locabhost:1s212xe"- Where jabe is the Apr, oracle is the dababate, thin is the diver, Locabhost ‘& fhe Sevvey name. on tthich ovocle is vunning , 161 is tke park Muwnbey and xe is The ovade Sewice Name+ % Usemamet The defaulle username for Me oracle database is slam patiword is givem by the User ak tame ef installing tke ovale dolabate + “ a password | 3 Te Comned: ava applicalton with tra evade dokobase oydbett ier “ble is required to be loaded. = Treva ave tue woys to load the otbety chellass ary one dy toro umyse 1. posle The oydbete- jor ajo fife we nerd © “Ble. in “jove tyre] Wb Jet elder 2+ Sb clase path then go ts “javor/ tre) b] ent” giestly, Seaveh Whe ajdbeiy-jav le dedav and pasle the jor fle heve- wor) Sek class path 5 Te sak classpath, gots environ etaceyath al on vw lab, In Vosable neme- mle aydber ie by appending eK vovioble then click Vawoble value paste the path ts ojdbelu-ser y+) os % pt \oraclexe Lapp ovacle\praduct \ ped -0\ gener Ab \oyd betycieys 5, Scanned with CamScanner % Exaynple 3 fs insert fuo of mia records Lelle orsk Creal o table and se in avacle calabate » qpenerl? conned | ov i hav 2-l4o) , x per (lo), Name Vere sqt> create fable emp(id num ge tuber (20)! 1 x . sgt> insert ints emp values (S0L,' Madhu 30)! carr insert — ats emp Valet ( Sor, ‘Havi', 3295 sat> Mserk into emp values ( $03, 'Sotti'!, 33) java application With Ovacle database for Seledhng sebiving dala + import tovassql.% + inagork ova ORL x 3 clase Selectpate {ute slate void main (Sing gst) t Ry t, Slept tload Tha dvver class ; Class fpYnlame (oracle sit be dvvey Ovacle Diver") 5 Wi Step 11 evrekE the Comnedion objec fonnedivn con = Divermanagey- gekCownestion ( “ydbe ovocle thin: @ locathatk1S2) xe", “system "adi" S + Mskep 32 cxeaté The Stalomeuk objed Stalament slit = con. cvsate Statement C9» | W Shep 42 eneadz guery Relea stmt Ofetale Query (Shek * dom emp"); tabile. Crs. mexbO) “cyl. cubs prindln Crs. getnk ty 4" ate. gekgting I+ oe ge get ting@2)) 5 3 step S con. closet) 5 otc CExcaphion e) { syste eouk-photly lex} t + close Ite connedon otjede Scanned with CamScanner | oabpek: DIV> Jovac seleckdala java DAV> java gelet-pata Sor Madhu 30 Sor Hawi $03 gol 33 a pene inapork java Sal ok innport java. SRLS class nsevt Dake public Static void main (Shing agit) { hey Class -ortlaone. Covocle jdbe- diver 2 Comnedion con = Davermanogey Stademant stat = con- cash “gens enewstecpdale C" insert wes om System out prnkle (Da sevtid --- con. closes 3 calzh CEntaption &) { ; system. oub panty C25 a t outpuk! DAD fovac Tutertdata -jave Dive Jeva Sutertdala. Anse vted «+ 3 comned’ Java axpplicaltnn with ovacle. ovalepyvey aye etcpvnetin (rydbe + ovacle Chia s@bcabhost : S21 2x2", Staldwant O; p velues (S04, * ganesh’, 283); * gyslea® 5 Nadwin' 4, Scanned with CamScanner % plograms Java application Ulith oracle databate tor update dala. Updelecals, | imnpork Java tale Vmper JovaUkL #7 closs Updatedata t public stake void main (sting avgst3) t bey { Class eefortgone. Covatle idkt- divers O ovacle Diver"); Connedtion con = Driver Mawagey » age conmerkion C* jdbc ovate + kin: @ locolhosts isi zxe.", “system, “ " odeain") 5 Slafomant stu = Con Cyaate Slatement 05 ete eneuste Update C Cc cupdale emp bok age= 38 there Systena ous pinta C updalad-« + ="); coms clote (9 id= $03"); 3 caleh CEnaption ©) { System: oud: panth (" encegtion is’ +25 ce Dt/> jovac Updatedats . yavo. pi}> evo updated Updated .++ + anne class s+ e DiveyManoger class adi as an ileveface bekwoon Ule™ and davers. Te koops Frack de the dvvers Hol ave aualiable ond handler establishing a comertion bebwooy a dolabata and the capper”) calé davey. Scanned with CamScanner

You might also like