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 =" ">

You might also like