0% found this document useful (0 votes)
3 views

java-2-j2ee

The document provides an overview of JDBC (Java Database Connectivity) concepts, focusing on ResultSet and its methods for accessing query results. It details the types of ResultSets (TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, TYPE_SCROLL_SENSITIVE) and their functionalities, as well as the RowSet interface and its associated Reader/Writer facilities. Key terms related to JDBC and a series of questions for assessment are also included.

Uploaded by

ravindra paliwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
3 views

java-2-j2ee

The document provides an overview of JDBC (Java Database Connectivity) concepts, focusing on ResultSet and its methods for accessing query results. It details the types of ResultSets (TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, TYPE_SCROLL_SENSITIVE) and their functionalities, as well as the RowSet interface and its associated Reader/Writer facilities. Key terms related to JDBC and a series of questions for assessment are also included.

Uploaded by

ravindra paliwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 30
JRE Database Concepts 2016- 2018 Batch — Determines the maximum number of rows a ResultSet may contain — Unless explicitly set, the number of rows is unlimited (return value of 0) + getQueryTimeout/setQueryTimeout — Specifies the amount of a time a driver will wait for a statement to complete before throwing a SQLException. 2.13 RESULTSET ResultSet and Cursors ‘The rows that satis! y a particular query are called the result set. The number of rows returned in a result set can be zero or more. A user can a ss the data in a result set using a cursor one row at a time from top to bottom. A cursor can be thought of as a pointer to the rows of the result set that has the ability to keep track of which row is currently being accessed. The IDBC API supports a cursor to move both forward and backward and also allowing it to move to a specified row or to a row whose position is relative to another row. Types of Result Sets ‘The ResultSet interface provides methods for retrieving and manipulating the results of executed queries, and ResultSet objects can have different functionality and characteristics. These characteristics are result set type, result set concurrency, and cursor hold ability. ‘The type of a ResultSet object determines the level of its functionality in two areas: the ways in which the cursor can be manipulated, and how concurrent changes made to the underlying data source are reflected by the ResultSet object. ‘The sensitivity of the ResultSet object is determined by one of three different ResultSet types: TYPE_FORWARD_ONLY — the result set is not scrollable ie. the cursor moves only forward, from before the first row to after the last row. Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHI Page 19/24 JRE Database Concepts 2016- 2018 Batch TYPE_SCROLL_INSENSITIVE — the result set is scrollable; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position. cursor can move both forward VE — the result set is scrollable; its TYPE_SCROLL_SENST1 and backward relative to the current position, and it can move to an absolute position. Before you can take advantage of these features, however, you need to create a scrollable ResultSet object. The following line of code illustrates one way to create a scrollable ResultSet object: Statement stmt = con,createStatement(ResultSet. TYPE_SCROLL ResultSet.CONCUR_READ_ONLY); SENSITIVE, ResultSet sts = stmt.executeQuery(" The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, and TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR__UPDATABLE. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY. Result Set Methods ‘When a ResultSet object is first created, the cursor is positioned before the first row. To move the cursor, you can use the following methods: + next() - moves the cursor forward one row. Returns true ifthe cursor is now positioned ona row and false if the cursor is positioned after the last row. * previous() - moves the cursor backwards one row. Returns true if the cursor is now positioned on a row and false if the cursor is positioned before the first row. Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHI Page 20/24 JRE Database Concepts 2016- 2018 Batch + first() - moves the cursor to the first row in the ResultSet object. Returns true if the cursor is now positioned on the first row and false if the ResultSet object does not contain any rows. + last() - moves the cursor to the last row in the ResultSet object. Returns true if the cursor is now positioned on the last row and false if the ResultSet object does not contain any rows. beforeFirst() - positions the cursor at the start of the ResultSet object, before the first row. If the ResultSet object does not contain any rows, this method has no effect % aflerLast() - positions the cursor at the end of the ResultSet object, after the last row. If the ResultSet object does not contain any rows, this method has no effect. 4 relative(int rows) - moves the cursor relative to its current position. + absolute(int n) - positions the cursor on the n-th row of the ResultSet object 2.14 METADATA RowSetMetaData: This interface, derived from the ResultSetMetaData interface, provides information about the columns in a RowSet object. An application can use RowSetMetaData methods to find out how many columns the rowset contains and what kind of data each column can contain, The RowSetMetaData interface provides methods for setting the information about columns, but an application would not normally use these methods. When an application calls the RowSet method execute, the RowSet object will contain a new set of rows, and its RowSetMetaData object will have been internally updated to contain information about the new columns. The Reader/Writer Facility ‘A RowSet object that implements the RowSetInternal interface can call on the RowSetReader object associated with it to populate itself with data, It can also call on the RowSetWriter object associated with it to write any changes to its rows back to the data source from which it originally got the rows, A rowsel that remains connected to its data source does not need to use a reader and writer because it can simply operate on the data source directly. Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHI Page 21/24 JRE Database Concepts 2016- 2018 Batch RowSetInternal: By implementing the RowSetInternal interface, a RowSet object gets access to its internal state and is able to call on its reader and writer. A rowset keeps track of the values in its current rows and of the values that immediately preceded the current ones, referred to as the original values. A rowset also keeps track of (1) the parameters that have been set for its command and (2) the connection that was passed to it, if any. A rowset uses the RowSetInternal methods behind the scenes to get access to this information. An application does not normally invoke these methods directly. RowSetReader: A disconnected RowSet object that has implemented the RowSetInternal interface can call on its reader (the RowSetReader object associated with it) to populate it with data, When an application calls the RowSet.execute method, that method calls on the rowset’s reader to do much of the work. Implementations can vary widely, but generally a reader makes a connection to the data source, reads data from the data source and populates the rowset with it, and closes the connection. A reader may also update the RowSetMetaData object for its rowset The rowset's internal state is also updated, either by the reader or directly by the method RowSet execute. RowSetWriter: A disconnected RowSet object that has implemented the RowSetInternal interface can call on its writer (the RowSetWriter object associated with it) to write changes back to the underlying data source. Implementations may vary widely, but generally, a writer will do the following: * Make a connection to the data source * Check to see whether there is a conflict, that is, whether a value that has been changed in the rowset has also been changed in the data source ‘* Write the new values to the data source if there is no conflict * Close the connection ‘The RowSet interface may be implemented in any number of ways, and anyone may write an implementation. Developers are encouraged to use their imaginations in coming up with new ‘ways to use rowsets SUMMARY Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHI Page 22/24 JRE Database Concepts 2016- 2018 Batch ‘The JDBC API is a natural Java interface to the basic SQL abstractions and concepts. It builds on ODBC rather than starting from seratch, so programmers familiar with ODBC will find it very easy to leam JDBC. An API for database-independent connectivity between the J2EE platform and a wide range of data sources. The JDBC API supports both models for database access: two- tier (direct database access) and three-tier (communication with the database over a "middle-tier” on the database server or a separate machine). The purpose of the JDBC package is to provide vendor-neutral access to relational databases. KEY TERMS © JDBC API: support application to IDBC manager communications © DBC driver manager: support JDBC manager to driver implementation ‘© IDBC-ODBC bridge: provides JDBC access using ODBC as the communications pipe. ‘© Native API, partly Java Driver: converts JDBC calls directly into calls on the client to the native database API. his requires binary code on the client machine. ‘© JDBC Net Driver: translates JDBC into DBMS independent protocol. This independent protocol is translated by a server into native DBMS calls. Generally deployed using a middleware server. ‘© Native Protocol - Pure Java: converts JDBC into DBMS native network calls, QUESTIONS 1 Mark Questions (Multiple choice based) LA is a collection of dat afield b. record c. database d. DBMS 2A is a document that defines all components of a database, aSQL b. database scheme c.table file 3. The JDBC process is divided into routines a2 b3 4 as 4. The method is used to load the JDBC driver. a.Class.forName() b, Results.next() Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHI Page 23/24 JRE Database Concepts 2016- 2018 Batch System. out printin() d, DB.createStatement() S.A, i a server side program. aserviet_b. JSP EB d. Java 6. The uniquely identifies the attribute from other attributes of the same entity. a.attributename — b. attribute size c.attribute format d.attribute type 1 data stores numbers only. a Character b. Alpha —_c. Alphanumeric d. Numeric 8. There are methods of the ResultSet object that are used to position the virtual cursor. a3 b4 cS a6 9. The method returns the URL of the database. a. getDatabaseProductName() _ b.getUserName() c.getURLO 4. getschemas() 10. The is the maximum number of characters required to represent values of the data. adata name b. data type c. data size . attribute 2 Mark Questions 1. Define Data, Database and Database Schema. Give a brief notes on different levels of Database Schema. What is JDBC API? Write short notes on Statement objects. ween List two different packages used in JDBC API 6. List various Resultsets methods. 8 Mark Questions 1. Explain the six steps to create a database schema with suitable examples. Write a brief note on Normalizing Data with suitable example. Explain the architecture of JDBC Describe in Detail four different Types of JDBC Driver. Explain about Resultsets in Detail. awa wN Write a database connectivity program in j2EE for maintaining students detail. Prepared by Dr. Manju Priya, Department of CS, CA & IT, KAH Page 24/24 aqqy ainqume. puosar aqqra atdm — |ewep sureyuoo req aseqeyep v Jo jusuodwios v s1 | wep | swaa prose exep prey. “aun nuove we 04 s1aj0u saa ager vave swaa Ts &q poBeueu st oseqeiep V aseqeep | swaa aseqniep proses ‘etep Jo won2oI}00 & 1 ——— soasuy| —_pado endo! zido} Lado suonsand TLIND SO?S'W It ssv1D, T0edSO91 AOD Loaranas Tl + Walsads agave: Loaraas ONAIOS WALAdWOO dO LNAWLUVaA (spremuo 9102 toy pomnupe sorepypues a4) 404) 120 149 ~ ar0requtt0.) (9561 9¥ DDN Je € HoNs9S 1apUN PoystgEIsA AUsi9ANIN powseq) NOILVONGg WaAHOTH IO AWAAVOV WVOVaaV ada onyea uonnyop somos ainqune | ainqune ainggme aounos angie | yeuuz0y aingune -anyea angus ayy Jo wiSIs0 ayy sayynuap! au. ad&t | anya uonnyop ‘uoysKs Sunstxo amp wn siwodde reunroy aynqume | anqune: ainggme azisamqune | reurog anqume fanqume we yom uw Aem om Jo sisisuos oq, anyea uorunyap adét | anyea uonryop ‘ainqume aq) ainqume | amqune angume azsamquye | auenanqune {or paudisse BIE FEA adéi eyep | _amqune ays cep ada eyep aweu erep _ |parersosse erep Jo sonstiaroereys ayy saquasap | sumer ep | aingeme azys tiep adéa ewep aaen evep fom Jo siuauoduros Buys paretaaiqge aq ues | “ep ay Arnuapy aueu ere | amnqune as evep ad&a ewep aweu eyep for ajqyssod se sioroeseys say se axey pinoys —— | aureu erep | ainqune aais wep adh cep ureu eyep au or nny © aptaoud erep ayy Jo amnyeu oy “erep amp Jo sanyea yuasaudas oy wep | _aimqume aais ep 2d rep aureu rep — {paxmbor sioroeseyo Jo soqunu wununtxeus oy) st > “eep yy Yat add erep | _amqume ois ee oda eiep aumeu erep _ {porersosse ame reap sonzea Jo pury amp saquosap | oureu rep | ange ozis rep adi evep oureu Prep aq oy} wong oumu anbym oq luonreunzoyt sainqune stwaust409 sanguine sonyea ‘siuauoye erep 0 paanpas aq jsnat sonqea sonyea sanqume| siuounuos | ainqume stwounos | _songea pasinbas arqeidesae fae aquosop or past st req) wxoy wHOy aaxg S| | s s ¢ £ z ssutzoy jeurrou ae ary ‘Avon ep omsse oy pur mep wepunpas ozrumnm oF sdnoss paras wonezyeaoN | woneary, undnory wonezteaLION. uonsesuesy fort siomoy> eiep SuzquesI0 Jo ssaoord ayy st 99140 seep Arewig suraumnueydyy atey | ouaumueydyy rudy aajserey _framo pue ‘soem ‘spray ixay ae, sazoys ep — | eofoy | _yeai807 sursumueydyy rudy aa 9eI4 ‘o1L10 SoK ~ somyea omy Jo aui0 SaroWs PIED outyoreg | susumy, awit /area rudy Pe) ‘sonyea oun pue ayep sau01s eIep ououmy | ououmy | _oysumueydry rudy aaj9RIeYD ‘Aquo szoquma sax01s Prep ‘saoquanr pie auounueydyy | osumy | _suoumueydty rudy oereyD _|'suoneniound ‘siaroesey> [eonaqeydye soxois rep —_____| eydiy | owewny | suaunueydiy eudiy aayoerey srarpeieyp jeonaqeyde dquo sai01s erep ‘suonemaumdl seperyg | oyaumy | syeunueydyy ead zaysereyD _|pue _szaiserey wonoqeydye _sorois_ewep | AyuBormt | onoge amp Aouapuadop Aouapuadop pojyea st sdnox8} jarajar_| Jo auON wes Teaonouny _[etep so skoy uByai0y pu er YL fox ‘uata]9 prep Jo sdnos oan uoansag dayst Koy uttoroy | uBtar0y Koy Aron Koy Areusrid |e weap 01 past dnost soqouy Jo Kay Arce ¥I K Aouapuadap | ouapuadap Aowapuadep ep KaquoN wey | aarusuen [ewo! Aowrepunpar v Aouopuadap awapuodap st eyep Aayuou war Teaonouny Kouepunpar {se yons ep somo wo spuodap eyep uoyAr sins90 vi Koy siuatuaya evep| Koy Kawunad | uBia10y oy renniy oy Aouad opt Ayonbsun yeap yuow|9 wep est | ‘wu jeuzou! ANE ANY ANE 1 ou ANZ IN IN € ANI ou ANI INb INE INL oquore aq 0} woreuZosH ay} Sasmnbas v anoge aq iqunasse 1815] sdnos | yoouon sioafqo sdnost ep azttesI0 oy Kea wourtH0D ¥ Owowawe hsoweoxs-qcr uownSie ue se Azan (daandainaaxo Odsondainsaxa_ | Qawensoysse.y | Orxewsninsey four passed st yorum ‘pomtour ayy sureywos yoafgo ywouareIs aK. £ s t £ z sued Jo ssistoa Tan au y9olgo Burns v oF SUMS OSungie8 Qowenzoysse( [aq Jo mor yuaxna ayy uF uuMIos paryfoads e Jo anyer am Odung323 Qasoraa. Onxaursyinsoy [kdoa o} pasn st yoafgo iaguinsey ayy Jo powpaur au (nee ‘woreagorea saauuere-wauroqes Oasorrrqa_ | soeauu03 (ssorsracr Orowsynsoy | Qawenuoy'ssei5 fom ayourumar oy _poyies st pompous ayy, Omauiar | warrsara | Quonoauuosn vigawaiepauues | syauueg | ai aseuepuasig Qawenoy sso 90{go quowoyms # aywox9 0} pasn st poxjaus au Quonsamos) | Orouae | Quonsomo>: sfusteurpioaug | gowarrga [aS uodeuepyosuC, awenoysse) -aseqeiep axp aouarayor 0} ssaooud axp ynoynomp poss} s{ vey) aoepIa}uT onDaUUOD w sua poyou ————— ay Oweware 0 seraioga. |upuud-nownskg (awenoy'sse (aureysoy'sse1 Orxow'synsoy SOALEP ETAT 248 PeOT 91 pasn st poyyous ————— ay. s s b € z sounnos out papap st ssao0ud ar aU. t s t € z SIOALIP J¢qAr Jo soda aw ary MOMOTEISOTETTED ‘Suyssoooud soypiny 109 lojqnuea 40 yoalqo wonda|joo wart v OnE TOgIASIY oH WO IEP ragunsey_| aguas wauiarersparedaid wauiayers _|édoo oF pasn are req) spomaur supestios 199[q0 41 wowiosmisparedasd wwouarelsarqeyyes 1090 ragyinsey awotmorersporedard awomoyers fog Suysn_pamnaaxa pue parduroard oq avs Aronb TOS V ppoyidasoa Azan) quawarersarqeyre> lay Suieq Isp nog Azanb e aynsaxe Ajareypaumusy oF spaau wawarers | iagunsoy, awowarersporedaid quawayeys _fuauodwios gaz e seaauay pasn st ysafgo ~~ au ange ay Aad 2MN Aq passaooidampaaord parors ay} 01 passed NI_|_soouon LAONI no NI_[>q 01 spoou wey evep Aue surequos rayouresed —— oq ainpasoad paoys & Buyyeo ay sayauuesed| € s b € z [yo sodé’ ———— posn oafgo _qwowarmsaqrite 241 wotoreasoyqette> soalgo ace e yea pogHnsay quouioyeispamedand quauiaeis _|aoxy ampasosd paroys & y1e9 01 pasn st yalqo — 41, Onweware asporedsid Oioworergarea9 oafqo wuowormgparedaig ax wos Ostandeino9x9_| _QaureNzoy'sser9 Jor partes st y99fgo wonsouuoD ayp Jo pomour 94. (momomgorea19 Owoworergarea9 yoafqo yuomores e umas Qainaaxe | _Qérondainoaxe_| _Qauensoy'ssery Jor parrea sf yafgo wonseuuos ayy Jo poyraur ————— au. ppoumyaa sypnsax jd aq Aur a20qp Garnoaxe | Qansoxe | QArondeinooxa | Qowensoysse.a | _Orxaursynsoy fog past st yoafqo womoreis ay Jo poyrour —— 4 ( )mowarayop Omoyararan OBumngarepdn Qmorrepdn | Onmneeepdn fe woy mor e arowas or pasn st poyjour i )moyarajop agUINsay axp Jo tumnpo9} Q8amngarepdn OSungawepdn Qmoyorpdn | _Onmneerpdn fom so onyea om aBaeyo or pase st poaur ————— ou t ymowarsrap “porpaus ——— au Bussn Aq anqen TIAN] Oueneerepda OSumngarepda Qmoyarepdn | _Oumneerepdn fe qua paseida aq ues ragunsey ayn Jo wUINJos & Ul anyea y) “rojommesed ou Wt poureauoa smor Jo roquunts Oeanejar_| Oarmjosqe Qaanejer Ovxou Orsay |payraods axp zosino yea ap saaous poyrous ay agynsay axp ut mor asayy 2g) Oomjosqe (oan Oveou 1 paypioods sosina jemts yp soxour poyjour ~~ 4 tosino jenytta a4 worIsod 01 pasn| 9 9 s ’ [exe rep a90{q0 rosunsoy om 50 spomaus — aa oxoy, rep] Oran | Oasop @ (Qamaaxo Onan OStngio# _|sureyaoo mor ayp Jr ann ueajoog P stuMIas pou aH, {stamndusos| anoge amt jo uonessuo® — amyny ayy, “sompasoad _parors| 1no_|_josu0N LOONI no Ni_faq Aq powumyar anyea e supeyios aajauresed ————— ayy ‘ampasoid poiors & woly HoneULIOsUt anoge ayn 9X pur ampaoord pasoys ax oF uoneULO;UE ssed_ Od] Lnont_ | yoouon AONE 100 NT_ [ov pasm st yeyp soyounered aj8uis & st soyouresed ———— ay | ( (jaune, ( Jumo>uumpogy8 | wumjoy8 soy creumagas JaSUNsoY a¢p Wt pourEyu0d| Osage 13 | _Qsampaooigie’ suuunjos Jo sequunu ay sumer pow —— aq. re) ( mum )skoysswumagio’ Ose1qeL8 Osaqezi8 | _Qsampaoorgie® -asequiep aqy Ur ayqen Jo souret star porpjour 4 ‘Onun03 ¢ munjopr )sKoycaeunnsg1o8 Osammpaooigio® Osaqesie8 | _Qsampaooigio® -soureu ainpasoid paiors suaniax porous 24 O1un09, ¢ OsKoydreungrs | mumjosrd )sKoy crews io8 Osaqeid | _Qsampaooigio® ‘skoy Areunad summyax poyrous 94, 0 (Qowexron seuroyosiod porgoseqereqas aseqerep oy) ut (seuroosio8 Oran? | Qowensoses8 oigetiear soureu euioyps ayy qe sumox poyou — ay 0 (Qawexion sewoysstod pogoseqereqas Tames Oranw# | Ooumprospi8 -aseqeiep x1 JO TAA amp suamiax porpou 41, 0 Qouenyon seuroyosto8 porgoseqereqas Qowenyiosqi08 Oras | Oawensosqes ‘auureazasn aq) stamias powaus ———— ayy, (Qowene 0 (Qowexron porgoseqrinqyas_| seuaypsiai porgaseqereqias Oran | auenuosp yes -aseqetep ayy Jo sweu jonposd axp sumiar porous ou | 2011 | Java Servlets | 7/5 Batch UNIT-IL Java Servlets: Benefits Anatomy — Reading Data from Client Reading HTTP Request Headers — Sending Data to client — Working with Cookies, TEXT BOOKS 1, Jim Keogh. (2010). The Complete Reference J2EE, Tata McGraw Hill: New Delhi, Ist Edition. REFERENCES 1. David R. Heffelfinger (2011), Java EE 6 Development with NetBeans 7,Packt Publishers," Edition, 2. Joel Murach, Michael Urban, (2014), Murach's Java Servlets and JSP, (Murach: Training & Reference). 3rd Edition 3. Joseph, J. Bambara et al. (2007). J2EE Unleashed , New Delhi:Tech Media, 1" Edition. 4. Paul, J. Perrone., Venkata, S. R. Chaganti., Venkata S. R. Krishna., & Tom Schwenk, (2003), J2EE Developer's Handbook Sams Publications, New Delhi, 1* Edition. 5. Rod Johnson. (2004), J2EE Development without EJB , New Delhi: Wiley Dream Tech, 1* Edition 6. Budi Kurniawan (2012), Servlet & JSP: A Tutorial, Brainy Software Publisher, 1“ Edition. 7. Mahesh P. Matha (2013), JSP and SERVLETS: A Comprehensive Study PHI Learning, 1" Edition, WEB SITES 1. www.java.sun.com/javaee! www java sun.com/j2ee/1.4/docs/tutorial/doc! www,j2eebrain.com/ www javaworld.com/ wep www.corej2eepatterns.com! Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 1/41 | 2016- Java Servlets | 7/5 Batch JAVA SERVLETS OVERVIEW OF SERVLET Servlets are Java programming language objects that dynamically process requests and construct responses. The Java Servlet API allows a software developer to add dynamic content to a Web server using the Java platform. The generated content is commonly HTML, but may be other data such as XML. Servlets are the Java counterpart to non-Java dynamic Web content technologies such as PHP, CGI and ASP.NET, and as such some find it easier to think of them as ‘Java scripts’. Servlets can maintain state across many server transactions by using HTTP cookies, session variables or URL rewriting The servlet API, contained in the Java package hierarchy javax.servlet, defines the expected interactions of a Web container and a servlet. A Web container is essentially the component of a Web server that interacts with the servlets. The Web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights. A Servlet is an object that receives @ request and generates a response based on that request. The basic servlet package defines Java objects to represent servlet requests and responses, as well as objects to reflect the servlet's configuration parameters and execution environment. The package javax.servlet http defines HTTP-specific subclasses of the generic servlet elements, including session management objects that track multiple requests and responses between the Web server and a client, Servlets may be packaged in a WAR file as a Web application. Servlets are server side components. These components can be run on any platform or any server due to the core java technology which is used to implement them, Servlets augment the functionality of a web application. They are dynamically loaded by the server's Java runtime environment when needed. On receiving an incoming request from the client, the web server/container initiates the required servlet. The servlet processes the Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 2/41 Java Servlets client request and sends the response back to the server/container, which is routed to the client. Wet Sever Server Response Dbiect = hosting the Browser Servlet Client Request Object — Figure 3.1 HTTP request response model. Web based Client/server interaction uses the HTTP (hypertext transfer protocol). HTTP is a stateless protocol based on a request and response model with a small, finite number of request methods like GET, POST, HEAD, OPTIONS, PUT, TRACE, DELETE, CONNECT . etc. The response contains the status of the response and meta information describing the response. Most of the servlet-based web applications are built around the framework of the HTTP request/response model (Figure 3.1), Servlet Request And Response There are three different players in figure 3.2. They are browser, web server, and servlet container. In many cases, a web server and a servlet container are running in a same machine even in a single virtual machine. So they are not really distinguished in many cases. The role of the web server is to receive HTTP request and then passes it to the web container or servlet container which then creates Java objects that represent “HTTP request” and a “session” and then dispatches the request to the servlet by invoking service() method defined in the servlet Prepared by Dr.S.Manju Priya, Assoc.Prof, Dept of CS,CA & IT Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 3/41 Java Servlets | 331° Batch REE (16CSP301) Figure 3.2 Three different players And once the servlet handles the request, it creates a HTTP response, which is then sent to the client through the web server. © nrtPservteiRequest object Information about an HTTP request © headers . Query String © session Cookies . HTTPServietResponse object Used for formatting an HTTP response . Headers Status codes © Cookies 3.1 BENEFITS OF JAVA SERVLETS When developing server-side software applications, its size becomes larger and automatically complexity intrudes in. It is always helpful if such a large application gets, broken into discreet modules that are each responsible for a specific task. This divide and conquer principle helps to maintain and understand easily. Java Servlets provide a way to modularize user application. Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 4/41 | 2011 Java Servlets | 7/5 Batch Advantages of Servlets 1, No CGI limitations Abundant third-party tools and Web servers supporting Servlet Access to entire family of Java APIs Reliable, better performance and scalability Platform and server independent Secure Most servers allow automatic reloading of Servlet's by administrative action. 3.2 JAVA SERVLET ANATOMY The life cycle ofa servlet is controlled by servlet-container in which the servlet has been deployed. When a HTTP request is mapped to a servlet, the container performs the following steps. If.an instance of the servlet does not exist, the Web container 0 Loads the servlet class © Creates an instance of the servlet class © Initializes the servlet instance by calling the init() method Invokes the service method, passing IIttpServletRequest and IlttpServletResponse objects as parameters. serviee() into, acer, aor osee, Figure 3.3 Methods used in Java Servlets The init() method gets called once when a servlet instance is created for the first time. And then service() method gets called every time there comes a new request. Now service() method in turn calls doGet() or doPost() methods for incoming HTTP requests, And finally when the servlet instance gets removed, the destroy() method gets called. So init() and destroy() methods get called only once . Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 5/41 Java Servlets | 331° Batch Figure 3.3 Httprequest and Hitpresponse Example for init): public class CatalogServlet extends HttpServiet { private BookDB bookDB; 11 Perform any one-time operation for the servlet, like getting database connection object. // Note: In this example, database connection object is assumed {to be created via other means (via life cycle event mechanism) 1 and saved in ServletContext object. This is to share a same 1 database connection object among multiple servlets. public void init() throws ServletException { bookDB = (BookDB)getServletComtext() getAttribute("bookDB"); if (bookDB — null) throw new UnavailableException("Couldn't get database."); } Example: destroy, public class CatalogServlet extends HitpServlet { private BookDB bookDB; public void init() throws ServletException { bookDB = (BookDB)getServletContext(). Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 6/41 | 2011 | Java Servlets | 7/5 Batch getAttribute("bookDB"); if (bookDB = null) throw new UnavailableException("Couldn't get database."); 3 public void destroy() { bookDB = null; } This is destroy example code again from CatalogServlet code. Here destroy() method nulling the local variable that contains the reference to database connection, service() methods take generic requests and responses: — service(ServletRequest request, ServletResponse response) = doGet() or doPost() take HTTP requests and responses: © doGet(HupServietRequest request, HttpServletResponse response) © doPost(HttpServietRequest request, HttpServletResponse response) The Figure 3.4 shows how service () method of a subclass of GenericServlet class is invoked. Figure 3.4 using service() method to invoke GenericServlet class Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 7/41 Java Servlets doGet() and doPost() Methods Using doGet() and doPost() itis possible to do the following functions: —Can able to extract client sent information such as user-entered parameter values that were sent as query string. To set and get attributes to and from scope objects. Perform some business logic or access the database, Optionally include or forward your requests to other web components, Populate HTTP response message and then send it to client. Example: Simple doGetQ) import javax.servlet.*; import javax.servlet.http.*; import java.io.*; Public class HelloServlet extends HttpServlet { public void doGet(HttpServietRequest request, HutpServletResponse response) throws ServletException, IOException { #/ Just send back a simple HTTP response response.setContentType("text/html"); PrintWriter out = response. getWriter(); out printhn("First Servlet"); out.printin("Hello J2EE Programmers! "); } } ‘This is a very simple example code of doGet() method. In this example, a simple HTTP response message is created and then sent back to client( shown in fig.3.5).. Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 8/41 Java Servlets | 331° Batch Server _HitpSerlet subclass dF Figure 3.5 HitpServiet subclass 3.3 READING DATA FROM A CLIENT A Client uses either the GET or POST Method to pass information to a java servlet, The doGet() or doPost() netgid us called in the Java Servlet depending on the ‘method used by the client. Data sent by a client is read into java servlet by calling the getParameters() method of the HttpservietRequest object that instantiated in the argument list of the doGet() and dopost() methods. The getParameters() method requires one argument, which is the name of the parameter that contains the data sent by the client, The getParameters() method returns a String object. The String object contains the value of the parameter, if the client assigns a value to the parameter. An empty string object is returned if the client didn’t assign a value to the parameter. Also, a null is returned if the parameter isn’t received from the client. AHITML form can contain a set of check boxes or other form objects that have the same data name but different values. ‘This means that data received from a client might have multiple occurrences of the same parameter name, The user can read a set of parameters that have the same name by calling the getParameterValues() method, The getParameterValues() method has one argument which is the name of the parameter, and returns an array of string objects. Bach element of the array contains a value of the set of parameters. The getParameterValues( ) method returns a null if data received from the client doesn’t contain the parameter named in the argument. Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 9/41 | 2016- Java Servlets | 7/5 Batch User can retrieve all the parameters by calling the getParameterNames() method. ‘The getParameterNames() method does not require an argument and returns an Enumeration. Parameter names appear in any order and can be cast to String object and used with the getParameter() and getParameterValues() methods, Figure conatins an HTML form that prompts a user to enter their name , when the user selects the Submit button, the browser calls the URL /servlet/HelloServlet Java Servlet and sends the usemame as data. Figure illustrates the HelloServlet.class Java Servlet that reads data sent by this form, In this example the getParameter() method returns a string that is assigned to the email String object called email. The value of the email String object is then returned to the browser in the form of an HTML page. Greetings Form
What is your name? ‘This form submits a form variable named username to the URL /servlet/HelloServlet. The HelloServlet itself does little more than create an output stream, read the username form variable, and print a nice greeting for the user. Here’s the code: import javax.servlet.*; import javax.servlet.hitp.*; import java.io.*; public class HelloServlet extends HttpServlet { Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 10/41 | 2011 | Java Servlets | 7/5 Batch public void doGet({IttpServletRequest req, IttpServletResponse resp) throws ServletException, IOException { String name; name= req.getParameter("username"); resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.printin(""); out.printin("Finally, interaction!"); out.printin("Hello, " + name+"!"); out printin(""); Hello, Joe! ie [bocurent Dane 3.4 READING HTTP REQUEST HEADERS When an HTTP client (e.g. a browser) sends a request, it is required to supply a request line (usually GET or POST). If it wants to, it can also send a number of headers, all of which are optional except for Content-Length, which is required only for POST requests, Here are the most common headers: + Accept The MIME types the browser prefers. + Accept-Charset The character set the browser expects. + Accept-Encoding The types of data encodings (such as gzip) the browser knows how to decode. Servlets can explicitly check for gzip support and return gzipped HTML pages to browsers that support them, setting the Content-Eneoding response header to indicate that they are gzipped. In many cases, this can reduce page download times by a factor of five or ten. Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 11/41 Java Servlets + Accept-Language The language the browser is expecting, in case the server has versions in more than one language. + Authorization Authorization info, usually in response to a WWW- Authenticate header from the server + Connection Use persistent connection? If a servlet gets a Keep-Alive value here, or gets a request line indicating HTTP 1.1 (where persistent connections are the default), it may be able to take advantage of persistent connections, saving significant time for Web pages that include several small pieces (images or applet classes). To do this, it needs to send a Content-Length header in the response, which is most easily accomplished by writing into a ByteArrayOutputStream, then looking up the size just before writing it out. + Content-Length (for POST messages, how much data is attached) + Cookie (one of the most important headers; see separate section in this tutorial on handling cookies) + From (email address of requester '; only used by Web spiders and other custom clients, not by browsers) «Host (host and port as listed in the original URL) + I£Modified-Since (only retum documents newer than this, otherwise send a 304 Not Modified” response) + Pragma (the no-cache value indicates that the server should retum a fresh document, even if it is a proxy with a local copy) + Referer (the URL of the page containing the link the user followed to get to current page) + User-Agent (type of browser, usefil if servlet is returning browser-specific content) 3.5 SENDING DATA TO A CLIENT. A java Servlet responds to a client request by reading client data and the HTTP request headers, then processing information based on the nature of the request. For example, a client request for information about merchandise in an online product catalog requires the Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 12/41 | 2016- Java Servlets | 7/5 Batch Java Servlet to search the product database to retrieve product information and then format the product information into a web page which is returned to the client There are two ways in which a java Servlet replied to a client request. These are by sending information to the response stream and by sending information in the HTTP response header. ‘The HTTP response header is similar to the HTTP request header except the contents of the HTTP response header are generated by the web server that responds to the client’s request. Information is sent to the response stream by creating an instance of the PrintWriter object and then using the println() method to transmit the information to the client. An Hitp response header contains a status line, response headers, and a blank line, followed by the document. There are three components to the status line these are the HTTP version number, a status code and a brief message associated with the status code. example : HTTP/1.1 200 OK Content-type : text/plain My response In the above example The HTTP Version number is 1.1 and the status code is 200, indicating that everything is fine with the request that was received from the client. OK is the message that is associated with the status code. This example contains HTTP response Header, which is Content-Type that identifies the document Mime type as plain text. The document contains the expression My response. Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 13/41 | 2016- Java Servlets | 7/5 Batch 3.6 WORKING WITH COOKIES A cookie (called an Internet or Web cookie) is the term given to describe a type of message that is given to a Web browser by a Web server. The mainpurpose of a cookie is to identify users and possibly prepare customized Web pages or to save site login information for you. Cookies in Servlet A cookie is a small piece of information that is persisted between the multiple client requests. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. How Cookie works By default, each request is considered as a new request. In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user. 3) Request + Cookie ——'*“n 1) Request 2) Response + Cookie Browser Server ‘Types of Cookie There are 2 types of cookies in servlets. 1, Nompersistent cookie 2. Persistent cookie Prepared by Dr.S.Manju Priya, Department of CS, CA & IT, KAHE Page 14/41

You might also like