CLE tiey
JDBC AND SERVLETS
qaPTeR OUTLINE
66 DDL
67hEy 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:08segs 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 SWLEGAL48
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 DFee
£
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:09A = 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:14a 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 LEGALcao 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:14singleThreadMosel 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
WARMING = XEROX / PHOTOCOPYING OF THISve 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>