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

Java Chapter - 6

Uploaded by

sriramman100
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
23 views

Java Chapter - 6

Uploaded by

sriramman100
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 53
CLE tiey JDBC AND SERVLETS qaPTeR OUTLINE 66 DDL 67h Ey och wn TURE 2 | ancHitec = e 5.1 JBC AND UNDERSTAND DBE Bry, wt we wereld Aeohcale we JDBC stands 1) pepe » independent connectivity bene ‘the Java gf OBC Og gaan MENT, je Ones Comey : Promeriing ngage an 008 T0 ang (APY) thet ME a fogarty ete JOBC AM Po sate ee andt manipulates th » Oe aaa eran eR send SQL and PL/SQL stat ae ‘ rst any. w mated tha oo - savers of JDBC is 4 3 that come rane aa lava SE q, ‘The JDBC library includes 5 rr ontyassoclated win database Us y Making a connection to a database j ae ok d its data from relational database. + To access tables and its 42 fo send queries and Uf « to and from a JOBC application y obtain and modify the results to and able. + Find the metadata of the t rations on a database, ike creating table, querying data, \ + Performing different ope updating data, inserting data fror + Creating SQL or MySQL statements + Executing SQL or MySQL queries in the database + Viewing & Modifying the resulting records. ma Java application. Fundamentally, JDBC isa specification that provides a complete set of Interfaces that allows for portable access to an underlying database. Java can be used to write different types of executables, such as + Java Applications. + Java Applets. + Java Servlets, + Java Server Pages (JSPs). + Enterprise JavaBeans (EJBs). All of these different executables are able to use a JDBC driver to access a database, and take advantage of the stored data. JDBC provides the same capabilities as ODBC. allowing Java programs to contain database-independent code. Why JDBC is needed? It is important to understand why we need Java Database connectivity. Java applications are required to connect with database. Java: : are written in Java programming language, but the database Structured Query Language (SQL). In order to establish a cor ‘WARNING: XEROX | PHOTOCOPYING OF Thig Nov 01, 2022, 06:08 segs nnn serves pion at database, JOBC 1 Used, JDBC contains ase of irk appear Mo connect J0va application to the database 5 of JOBC : With JDBC, we can connec ayer nNect to any database even if iti paver pase mi aiferent database management systems. The folowing are the advantage. sored o” implied Enterprise Development: JDBC code becomes very less by Aptis simple to install and maintain. Iti very easy to write a JDBC program, ero Configuration for Network Computers ; The JDBC API requires no configuration on client side, We require a suitable driver to connect to the avabase. It may be even a bridge driver or a driver writen in pure java language Full Access to Metadata : JDBC API includes special classes and interfaces with vahich we can obtain metadata, The metadata includes the database table's fields, umber of primary Keys etc. We can insert data dynamically also into a database No Installation : A pure java driver does not need special installation procedure itis freely downloadable. Database Connection Identified by URL : JDBC technology exploits the ‘advantages of internet - standard URLs, to identify database connections. The JDBC 2.0 API adds an ever better way to identify and connect to a database using Datasource, object, DataSource objects can provide connection pooling and transaction management. (v) Included in the J2EE Platform : As JDBC API is needed in enterprise applications to connect to database, itis included in the Java2,0 Enterprise Edition JDBC Architecture : The JDBC API supports both two-tier and three-ter processing models to access the database they are 1. Two-tier model. 2. Three-tier model. ae |————Gient machine—— FIG 6.1 : Two-tier Architecture of JDBC ith the database: ticular database nthe two-tier model, a Java application directly communicates Wi f quires a JDBC driver to establish the communication with the Pa ‘WaRMiNG : Ox /PHOTOCOPHING OFTHIS BOOK SWLEGAL 48 suns fr those GUETICS BFE Ser bag i 4 g gatabase, FOr machine oF it May Be locateg “i a tr sar pe of at chiteCtUe is clegy a ? om |e war nese aia | ; hen, the dat a han tt om : ree, be an om raver 307 sats reeture inereases te perfor be) s cue : proces aren THs type of a ; ror veut TS : tion deploy™ nt. é i ° the applica ee : “| re eA J wr { syeenin JL , memes Se acne ¢ Machine : cee iitect ire of JDBC sage: Theor Arche j | turat Diagram : Basic JDBC Architect | eal [ave arptcation | peer le [ wwacar | sepa [, Daver | Manas ml Bek [ee sat So |e [ove oie | ‘As JDBC supports both two-tier model and three-tier model for d However, JDBC architecture has two layers as listed below. JDBC API : This provides the application-to-JDBC Manager the ie various methods and interface for easy communication b and database. It uses driver managers and also database sper transparent connectivity to different databases. ‘WARNING :xEROX | HOTOCOPYING DF ee £ FF: £4 Components: The JDBC API provies the owing inlacs and ye {Common JOB 28 DeierManager: Daverttanager i cl aot eemnecon ruts he va appcaion wth pe nab I sa prot fonder JDBC fh database Connection. W Yous te se driers in an aptenion oexbin conection wi at Driver: Driver ithe interlace wh the appication ane the databo read, you use DriverManager objects when rth working wih Driver objects Jn manages the communicators happeing Beiweon es cet of Ly Wipe: rag arash deta stole object repre trvounh connect Connection : Connection Geubase. The connection commu jon object ont aL quate, an object 10 submit tha fa oj erated ror tis aia 0 eee poametess Statement: Statements an inter sto the datad ome derived itertc odio ‘SQL statement Somed to executing totes 4 tna a ceive rm tb daca data ceseved 107 the rest ject nl set contains it quer ResultSet: Res tne execution of S database after you execute {0 allow you to move through tion cass 5 Ue guy vag Siemens jen N= z z yeess SQL reques ire 001 joec Diver #4 — ables jave aPP! ret jication 10 Int the database jsut ann eres TI= « Nov 01, 2022, 06:09 A = prver es 25 # dg Dee 18 DD are a ‘m (ODBC). This driver Converts JOBC casing, ae + S ins adc =" na tT tse NOESY 7 =| : hea 4 cost of Applic: 3 Increase* ec cals into database Se + Eaxy 10 us = nnectvty to all databases supported by the ODBC Driver. Disadvantages : + Slow execution time @ = 2 . + Dependent on ODBC Driver a + Uses Java Native IntrfaceUND to make ODBC call + Performance degraded because JDBC method cal s converted into the ODBC function cal + The ODBC driver needs to be installed on the client machine 2. Native API Driver: Thstype of daver make use of Java Native Inerace(IND Welcome to First Serviet Example"); ppw.printin(*); pw.close()/elosing the stream Step-3 : Compile the serviet For compiling the Servlet, serviet-api.jar file is required to be loaded. Different Servers provide different jar files [sar fie servlet Apache Tomcat Weblogic Glassfish | javacejar SBoss Two ways to load the jar file + set classpath classpath=c: \apcheTomeat7.O\\ib\servlet-api.jar + paste the jar file in JREflib/ext folder Put the java file in any folder. After compiling the java file, paste the .class file of serviet in WEB-INF/classes directory. Step-4 : Create the deployment descriptor (web.xm! file) The deployment descriptor is an xml file, from which Web Container gets the information about the serviet to be invoked The web container uses the Parser to get the information from the web.xm! file There are many xml parsers such as SAX, DOM and Pull There are many elements in the web.xml file, Here is given some necessary elements to run the simple servlet program, web.xmi file ‘waning: xeROX PHOTOCOPYING OFTHIS BOOK IS WLEGAL Nov 01, 2022, 06:14 a reciserviet-name cexervietnamerF irarsorvietxA™P cegerut-cinsa>FIrEtServet™ jeorviet-ol888" etserviet® cegerviet-mapping” ce vet ror prraserdtexarpiserl am steciurt-patter™ ceun-pattern>/te : a Understanding web.xml in 120 servlets i web.xml wser's request to 2 specified fl ner (Ex. Tomeat) to handover ; Used by the Servlet Contalt ( a class. . . a cerviet namesieervcefalla | ceorviet-clase>serviet_classserviet_clas S a “egervietname>serviet_name | ccut-pattem>url_of_actions \ 2 : Starting of the web.xml should be done with this tag cserviet>: Details regarding serviels, the name, serviet class. cserviet-name>: Name of the servlet, used within the servlet again. : Servlet class file is specified here. Servlet container 1 was written in a package, then it must be like package class. | : Mapping servlet class and the url of the users 1es user's request and then forwards it to the class file dete n>: The pattern (the url) to which the user's 1 Click on advanced tab then environment variables Click on the new tab of user variable -> Write JAVA_HOME in variable name and paste the path of jdk folder in variable value -> ok -> ok -> ok. ram Files\Java\jakt.7.0_79 Program Files\Wavaljre7 2. How to change port number of apache tomcat : Changing the port number is required if there is another server running on the same system with same port number Suppose you have installed oracle, you need to change the port number of apache tomcat because both have the default port number 8080 conf directory Open server-xmi file in notepad, It is located inside the apache-tomea 8080 and replace 8080 by any four digit number Change the Connector port instead of 8080. Let us replace it by 9999 and save this file, Step-6 : Access the servlet using browser ‘Alter the serviet is started, We can access the Servlet by typing the following ur in browser. hitp:/localhost:6080/ FirstServietExample/ts {nox | PHOTOCOPYING OFTHIS BOOK S LEGAL cao emma Te cieee Welcome to First Serviet ExamP [APL : The javax.sorviet packages represent interfaces Salanen or ree tains many interfaces and rylet package cont snd eleses for serviet API. The jovax-servit P cl ; tre used by the serviet or web containet These are not specific to any uhutp package contains interfaces and classes that are ‘and javax.serviet HP classes that protocol. The javax-servi + hitp requests Only. fe interfaces of javax.serviet package y interfaces in javax.serviet responsible fo Let's see what are the Interfaces in javax.serviet package = There 2 many package. They are as follows Ta fiers an objet ht pets cering tasks on ie he Fede 0 sreure (a servlet state cotet), oon the response fom = FEATS SS provided by the servlet container tothe developet in ofa filtered request fora resource |AFilterChain san object tiving a view nt the invocation < FiteConfig ‘iter configuration object wed by a servet container to pas information after during initialization, RequestDispatcher Defines an object that receives requests from the client and sends them an) _ resource (uch asa seve HTML il of SP file) on th ee | Servtet ‘Defines methods that all servlets must implement, ServetConfig, |A servlet configuration object used by a servlet container to pass information toa servet during initialization. ServletContext ‘Defines a set of methods that a servlet uses to communicate with its senvet | conlainer, for example, 0 get the MIME type ofa il, dispatch request write to alg file Senetcontestatbulisensr Implantation of his interac receive notations of anges tt tribute list on the servlet context of a web application Nov 01, 2022, 06:14 singleThreadMosel Deprected, Ax of Jva Servlet APL2.4, with odie replacement Classes in javax.servlet package : There are many classes in javax servlet packag) They are as follows : = Deri SenieContewAwributeEvent This s the event las fr noications senile somtext ofa web application SenleContextEvent Thins the event class for notations about changes tthe servlet conten SeretlnptStean Provides an inp sri for reading binary dt rom clon request incu anfficient readL.ine method for reading data one ine at tine ServletRequstAtibutevent This sth event clas fr notifications of chan request in an application, SerletRoquestevent vents ofthis kind indicate lecyee events fora ServieR | SerewReques Wrapper Provide a convenient implementation ofthe ServltRequs inter te subclassed by developers withing adapt the request oa Servlet Provides a convenient implementation ofthe SerletResponsenterfic tha ServeiResponseWrapper ing to aap the espose from a Servi «an be subclass by developers wi eral exception a serve an throw when it encounters ifclty ServetException Defines agen | UnavaiabeException ‘Defines an exception tat serve ote rows to ince that itis pean or temporarily unavailable. wan x0 Tocore OTH BOOKS GAL Nov 01, 2022, serviet http package HrpSessionListencr Classes in javax.serviet.http package : Th package. They are as follows a HiapServietRequestWrapper HupServletResponse Wrapper HupSessionBindingF vent HmpSessionE vent WARNING : XEROX / PHOTOCOPYING OF 1 Nov 01, 2022, 06:14 sage # There are many IMeCaes iy A Le : 1s follows: | eA a save wo provide HTTP-specific funetionaiy, | t container events notifying may listen t and that session willbe activated, | aise aa Onjects that are bound 1 4 800 them that seasione wit! bo passivated This tener interocecan be pfemnentel iN Ore BS his web application. = when it is bound to or unbound from a session, oe to the attribute lists of ed when it ‘Causes an object to be notifi ee As of ava(u) Servlet API for sGcirty tosses nea Deprecated. As of Java I — replacement fottue ae implement ae nlf of change othe Tit ofacve | sessions in a web application. _ 4 .ere are many classes in javax.servlet.hitp Implementations of this inter Description. Creates a cookie, a small amount of information sent by a servlettoa Web | browse, saved by the browser, and later sent back to the server. | Provides an bat clas te sub cased to oteate an HTT seule suite fora Web site Provides a convenient implementation of the HutpServletResponse interface that can be sub classed by developers wishing to adapt the response from a Sele. | Event of tis type are cther sent 1 an objest that implements HetpSessionBindingL istener when it is bound or unbound from a session, OF 103) ‘HitpSession Attribut r that has been configured in the deployment deserptor when any atibue is bound, unbound or replaced in a sesio Liste This isthe class representing event notifications for changes 1 1 web application, Deprecated. As of Jva(im) Servlet API2, {JOBC AND SERVLETS. 5.10 HANDLING HTTP REQUEST AND RESPONSES WITH E GRAMS Tho HtpSerlet class provides specialized methods that handle the varios « methods are doDelete( ), doGet( ), doHeadi ), doOptions( ), doPost( ), doP @ XAMPLE PRO Handling HTTP GET Requests : Here we will develop a servlet that handies an HTTP GET request. The serviet is invoked when a form on a web page is submitted The example contains two files. A web page is defined in ColorGet.htmi, and a serviet is defined in ColorGetServiet java. The HTML source code for ColorGet. htm! is shown in the following listing. It defines a form that contains a select element and a submit button. Notice that the action parameter of the form tag specifies a URL. The URL identifies a servlet to process the HTTP GET request. 1 File : File Name: ColorGet.html
Color: WARMING = XEROX / PHOTOCOPYING OF THIS ve java own in the rltowing listing. The doGeyy ai ey requosts that are sent to this serveg jotreequest to obtain the selection tha, 'd to be sent to the user 2” File : File Name Color Gets Ser jet. javi y HTTP GE ‘of HuipServ! then formulate’ 1 code for ColorGetServi The soure Sats method is overridden 10 rower ituses the getParameter() method was made by the user. A resp: Import java.io." import javax. servi." fet ht." Import javax serv ie public class ColorGetServiet extends HilpServl : tiie vold doGet(HtipServietRequest request, HttpServietResponse response) public vold doGet throws ServietException, IOException o sting calor = oqunstgtParametercoler response setContentType("texthim"); Printwriter pw = response.getWriter(); pw printin(*The selected color is: ") pw printin(color); pw.close() , Compile the above servlet. Next, copy it to the appropriate directory, and update the web.xml file, as previously described. Then, perform these steps to test this example : * Start Tomeat, if itis not already running, + Display the web page in a browser. * Select a color. * Submit the web page. After completing these steps, the browser will dis, is dynamicé , Play the response that is ally generated by the servlet be One other point : Parameters for an HTTP GET request are included as part of the URL that is sent to the web server, A , » ene aie ssume that the user ‘option submits the form. The the browser to ihe sane fe ead rm. The URL sent from hittp:/ocalhost:8080/examples/servi [ESSIEN 00 tno serves HTTP POST request. The servitis invoked when a form on a web pages array tains two fi age is submit is defined in ColorPostServiet java and a servet The HTML source code for ColorPost.html is shown in the following hi specifies that the POST method should be used, and the action parameter foe tre form tag specifies a different servlet Ieee 4st File : File Name : ColorPost.ntm! ehimnl>
"Red'>Red -Green "Gr Blue">Blue 2°4 File : File Name : ColorPostServietjava The source code for ColorPostServiet java is shown in the following Using. The doPost) method is overridden to process any HTTP POST requess that =f sent to this servit, It uses the getParameter( ) method of HrtpServietRequest 10 obtain the selection that was made by the user. A respon: se is then formulated. import java.io." vie import javax. import javax.serviet http." wxtends HitpServiet public class ColorPostServiet ©? Nov 01, 2022, 06:14 Nov 01, 2022, 0615 JOBE ano stnvieTs In this example, the doGet () method of HttpServiet class is overridden to handle thi HTTP GET request. The two parameters passed to the doGet () method are re ji a res, the Objects of HttpServietRequest and HttpServietResponse interface rasp The req object allows to read data provided in the client request and the res object used to develop Response for the client request. oa The corresponding HTML code for this servlet is as follows Get.htm!
Login ID Password

assword" NAME="password” ‘

This HTML code create as web page containing a form Web Page Displaying the Form Get.htmi it on the Enter the required data and press the subm Oa ne a will display the response generated dynamica 7 [e ennccan_onnentm testo iL ‘Your opin 1D is: Suresh ‘Your pass ord 8° Su of HttpServietRequest interface 5 used to .e server, For example, consider the URL rearing to the right of the question mark for the HTTP GET request. Note that, the getParameter () method retrieve data attached to the URL sent to th in the address bar of Figure. The string apps known as the query string contains the parameters Serviet for handling HTTP POST request Example : Like doGet () method, the do Post () method is invoked by server through service () method to handle HTTP POST request. The doPost () method is used when large amount of data is required to be passed to the server which is not possible with the help of doGet () method. In doGet () method, parameters are appended to the URL whereas. in do Post () method parameters are sent in separate line in the HTTP request body. The do Get () method is mostly used when some information is to be retrieved from the server and the doPost () method is used when data is to be updated on server or data is to be submitted to the server. To understand the working of do Post () method, let us consider a sample program to define a serviet for handling the HTTP POST request. A program to define a serviet for handling HTTP POST request. ServietPostExample.java Import java.io." import java.uti.*; Import javax.serviet."; public class ServletPostExampi . public void doPost(HttpServietRequ ‘ServietException, IOException { extends HttpServiet 3t req, HitpServietResponse res) throws PrintWriter out = res.getWriter() String login= req.getParameter(“loginig"), BOTA 20 avo senveers String password req getParameter(‘password"); ‘out printin(“Your fogin 10 is: *); out printin login) out printin("Your password is: *); cout printin(password): out.close() ) The corresponding HTML code for this servlet is as follows Post.htm!
Login !D dciB>

{c="Form!"METHOD="post" ACTION="hitp:Mlocalnost:8080/ServietPostExample">

Passwor

This HTML code create as web page containing a form Enter the required data and press the submit button on the web Pag ‘The browser will display the response generated dynamically by the corresponding serviet. Post.html ip: /lcalh.2080/servhtn. — oy ele oe = € SF hocathort! [Ep moc. sonovernome = € & tocstmest ‘Your login 1D is: Suresh Your password is: Suresh Get vs. Post : There are many differences betwe see these differences : I Se | Incase of Get request, only limited amount of | a ‘can be sent because d sent in header Get request is not secured because data is | ssposed in URL ba Get request can be bookmarked. | Get request is idempotent, It means second po | request will be ignored until response of first I roquestis delivered, | Get request is more efficient and used more liiae @- ost fen the Get and Post request. Lets In case of post request, large amount of data can bel sent because data is sent in body. Post request is secured because data is not exposed in URL bar, Post request cannot be bookmarked. Post request is non-idempotent. Post request is less efficient and used less than get. than Post. 1) o () Ny nv (o iy Co) is i ys REVIEW QUESTIONS = 1 to create Statement object. fedStatement? alableStatement? methoo? is service() method? What is destroy() method? What is JSDK? 7. What is web.xml file? doGet() and doPost() methods. Part-B (3 Marks Questions) Why JDBC is needed? DBC. eof JDBC with a diagram. 2. Wite any three advantages of J ectur 3. White about Two-tier Arch JBC with a diagram. 4. Write about Three-tier Architecture of JO Draw the JDBC architectural diagram 6. List any three common JOBC components waning : XEROX PHOTOCOPYING OF ws 0K S MLEGAL 9, White the stops to conn 10. " 1 3 “ 18 16. 17. 18 19, 20. a 2 23. 24. |. Write a java program using JOBC to connect to Oracle database, ‘Write short notes on JOBG drivers sntages of Notwor 1 er Z 9 Waite the advantages and disadvar «any ve application with te database using JOBC rent types of Statements in JOBC. 4 Write the steps involved in ereating a simple Serviet a List the methods used to execute an SQL statement A 13. List liter Write about PreparedStatement? : compare Scrollable ResultSet and Non-Serollable ResultSet \ Fh List some methods of Scrollable ResultSet Draw the if cycle of serviets. Draw the architecture of servet. a White the advantages of servets Write the diference between CGI and serviets Discuss Java Serviet Development Ki List any three classes and interfaces in javax. sevlet package. List any thre classes and interfaces injavax.serviet tp package. How to set JAVA_HOME in the environment variable? Write any three differences between Get and Post methods, Part-C (5 Marks Questions) Explain JDBC Architecture witha diagram. Write the advantages of DBC. Explain the following drivers (0) JDBC-ODBC bridge Driver ' (0) Native API Driver Explain the following drivers (a) Network Protocol Driver (b) Thin Driver Explain the steps to establish a connection to database using JDBC, Nov 01,2 Wan X88 [SUES 00 ano servers Explain about 3 kinds of statements Statement Prepared S Statement and Callable 5 4, Explain PreparedStatement with an example program «@._ Explain CallableStatement with an example program, » about Serollable ResultSet in JDBC with an example program 0. Expl Write a JOBC program to create student database. ite a JDBC program to insert records into employee database 4. Write a JDBC Program to delete a row in a table. 14 Write a JDBC Program to update 2 row ina table forviet and explain its life cycle. Define s fg. Explain about creating a simple serviet. itferent classes and interfaces available in javax.serviet package. 7. W vite citferent classes and inter explain the process ofhandiing HTTP process ofhandling HTTP P_ ST requests wih an example program faces avaitable in javax. servlet http package. T requests with an example program Explain the .sbetween ET andP ST requets Write any five difference: ox; porocoryn oF THSBOOK'S UUEGAL

You might also like