IT2255 Web Essentials - Unit V Servlets and Database Connectivity

1,043 views 31 slides May 17, 2023
Slide 1
Slide 1 of 31
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31

About This Presentation

Servlets: Java Servlet Architecture – Servlet Life cycle – Form GET and POST actions – Sessions – Cookies – Database connectivity – JDBC


Slide Content

IT2253 Web Essentials
Unit V –Servlets and Database Connectivity
Kaviya.P
Kamaraj College of Engineering & Technology

Unit IV –Servlets and Database Connectivity
Servlets:JavaServletArchitecture–ServletLifecycle
–FormGETandPOSTactions–Sessions–Cookies–
Databaseconnectivity–JDBC–Creationofsimple
interactiveapplications–Simpledatabaseapplications

Servlets –Introduction
•Servlettechnologyisusedtocreateawebapplication(residesatserversideand
generatesadynamicwebpage).
•ServletsaretheJavaprogramsthatrunontheJava-enabledwebserveror
applicationserver.
•Theyareusedtohandletherequestobtainedfromthewebserver,processthe
request,producetheresponse,thensendaresponsebacktothewebserver.
•Properties:
•Servletsworkontheserver-side.
•Servletsarecapableofhandlingcomplexrequestsobtainedfromthe
webserver.

Java Servlet Architecture
ExecutionofServletsbasicallyinvolvessixbasicsteps:
1.Theclientssendtherequesttothewebserver.
2.Thewebserverreceivestherequest.
3.Thewebserverpassestherequesttothecorrespondingservlet.
4.Theservletprocessestherequestandgeneratestheresponseintheformof
output.
5.Theservletsendstheresponsebacktothewebserver.
6.Thewebserversendstheresponsebacktotheclientandtheclientbrowser
displaysitonthescreen.

Java Servlet Architecture

Java Servlet Architecture
•Client:ItsendsHTTPrequestsovertothewebserverandagainprocessing
theresponseitgetsbackfromtheserver.
•WebServer:Primaryjobofawebserveristoprocesstherequestsand
responsesthatausersendsovertimeandmaintainhowawebuserwould
beabletoaccessthefilesthathasbeenhostedovertheserver.Theserveris
asoftwarewhichmanagesaccesstoacentralizedresourceorserviceina
network..Therearepreciselytwotypesofwebservers:
–Staticwebserver
–Dynamicwebserver

Java Servlet Architecture
•WebContainer:Acomponentinservletarchitecturewhichisresponsible
forcommunicatingwiththeservlets.Twoprimetasksofawebcontainer
are:
–Managingtheservletlifecycle
–URLmapping
Webcontainersitsattheserver-sidemanagingandhandlingalltherequests
thatarecomingineitherfromtheservletsorfromsomeJSPpagesor
potentiallyanyotherfilesystem.

Java Servlet Architecture
Types of Servlets:
•Generic Servlets
•HTTP Servlets
To create a Servlet:
1.Implementing Servlet Interface
2.Extending Generic Servlet
3.Extending HTTP Servlet

Java Servlet Architecture
CGI(CommonGatewayInterface)
•CGItechnologyenablesthewebservertocallanexternalprogramandpassHTTPrequest
informationtotheexternalprogramtoprocesstherequest.
•Foreachrequest,itstartsanewprocess.
Disadvantages
•Ifthenumberofclientsincreases,ittakesmoretimeforsendingtheresponse.
•Foreachrequest,itstartsaprocess,andthewebserverislimitedtostartprocesses.
•Itusesplatformdependentlanguagee.g.C,C++,perl.

Java Servlet Architecture
AdvantagesofServlet
•ThewebcontainercreatesthreadsforhandlingthemultiplerequeststotheServlet.
•ThreadshavemanybenefitsovertheProcessessuchastheyshareacommon
memoryarea,lightweight,costofcommunicationbetweenthethreadsarelow.
•Advantages:Betterperformance,Portability,Robust,Secure.

Java Servlet Architecture
Website:staticvs
dynamic
Acollectionofrelatedwebpagesthatmaycontaintext,images,
audioandvideo.
HTTPThedatacommunicationprotocolusedtoestablish
communicationbetweenclientandserver.
HTTPRequestsTherequestsendbythecomputertoawebserverthatcontains
allsortsofpotentiallyinterestinginformation.
GetvsPostItgivesthedifferencebetweenGETandPOSTrequest.
ContainerUsedinjavafordynamicallygeneratingthewebpagesonthe
serverside.
Server:Webvs
Application
Usedtomanagethenetworkresourcesandforrunningthe
programorsoftwarethatprovidesservices.
ContentTypeHTTPheaderthatprovidesthedescriptionaboutwhatareyou
sendingtothebrowser.

Servlet Life Cycle
•TheentirelifecycleofaServletismanagedbytheServletcontainerwhichuses
thejavax.servlet.
•StagesoftheServletLifeCycle:
•LoadingaServlet:LoadingandinitializingtheServletbytheServletcontainer
•InitializingtheServlet:AftertheServletisinstantiatedsuccessfully,the
ServletcontainerinitializestheinstantiatedServletobject.Thecontainer
initializestheServletobjectbyinvokingtheServlet.init(ServletConfig)method
•Requesthandling:ItcreatestheServletRequestandServletResponseobjects.
•DestroyingtheServlet:WhenaServletcontainerdecidestodestroytheServlet

Servlet Life Cycle

Servlet Life Cycle
ServletLifeCycleMethods
•init():TheServlet.init()methodiscalledbytheServletcontainerto
indicatethatthisServletinstanceisinstantiatedsuccessfullyandisaboutto
putintoservice.
•service():ItisinvokedtoinformtheServletabouttheclientrequests.
•destroy():ItrunsonlyonceduringthelifetimeofaServletandsignalsthe
endoftheServletinstance.

Servlet Life Cycle
ServletLifeCycleMethods

Form GET and POST Actions
GETMethod
•TheGETmethodsendstheencodeduserinformationappendedtothepagerequest.
•Thepageandtheencodedinformationareseparatedbythe?(questionmark)
symbol.
•TheGETmethodisthedefaultmethodtopassinformationfrombrowsertoweb
server.
•TheGETmethodhassizelimitation:only1024characterscanbeusedinarequest
string.
•ServlethandlesthistypeofrequestsusingdoGet()method.
•Example
http://www.test.com/hello?key1 = value1&key2 = value2

Form GET and POST Actions
POSTMethod
•MorereliablemethodofpassinginformationtoabackendprogramisthePOST
method.
•ThispackagestheinformationinexactlythesamewayasGETmethod,butinstead
ofsendingitasatextstringaftera?(questionmark)intheURLitsendsitasa
separatemessage.
•ServlethandlesthistypeofrequestsusingdoPost()method.

Form GET and POST Actions
ReadingFormDataUsingServlet
•getParameter()−Callrequest.getParameter()methodtogetthevalueofaform
parameter.
•getParameterValues()−Callthismethodiftheparameterappearsmorethanonce
andreturnsmultiplevalues,forexamplecheckbox.
•getParameterNames()−Callthismethodifyouwantacompletelistofall
parametersinthecurrentrequest.

Sessions
•SessionTrackingisawaytomaintainstate(data)ofanuser.Itisalso
knownassessionmanagementinservlet.
•Httpprotocolisastatelesssoitisneededtomaintainstateusingsession
trackingtechniques.
•Eachtimeuserrequeststotheserver,servertreatstherequestasthenew
request.
•Soweneedtomaintainthestateofanusertorecognizetoparticularuser.
•HTTPisstatelessthatmeanseachrequestisconsideredasthenewrequest.

Sessions

Sessions
SessionTrackingTechniques:TherearefourtechniquesusedinSession
tracking:
1.Cookies
2.HiddenFormField
3.URLRewriting
4.HttpSession

Cookies
•Acookieisasmallpieceofinformationthatispersistedbetweenthe
multipleclientrequests.
•Acookiehasaname,asinglevalue,andoptionalattributessuchasa
comment,pathanddomainqualifiers,amaximumage,andaversion
number.
TypesofCookie
•Non-persistentcookie:Itisvalidforsinglesessiononly.Itisremoved
eachtimewhenuserclosesthebrowser.
•Persistentcookie:Itisvalidformultiplesession.Itisnotremovedeach
timewhenuserclosesthebrowser.Itisremovedonlyifuserlogoutor
signout.

Cookies
AdvantageofCookies
1.Simplesttechniqueofmaintainingthestate.
2.Cookiesaremaintainedatclientside.
DisadvantageofCookies
1.Itwillnotworkifcookieisdisabledfromthebrowser.
2.OnlytextualinformationcanbesetinCookieobject.

Cookies
Cookieclass
•javax.servlet.http.Cookieclassprovidesthefunctionalityofusing
cookies.Itprovidesalotofusefulmethodsforcookies.
ConstructorofCookieclass
ConstructorDescription
Cookie()constructsacookie.
Cookie(Stringname,Stringvalue)constructsacookiewitha
specifiednameandvalue.

Cookies
MethodsofCookieclass
MethodDescription
publicvoidsetMaxAge(int
expiry)
Setsthemaximumageofthecookiein
seconds.
publicStringgetName()Returnsthenameofthecookie.The
namecannotbechangedaftercreation.
publicStringgetValue()Returnsthevalueofthecookie.
publicvoidsetName(Stringname)changesthenameofthecookie.
publicvoidsetValue(Stringvalue)changesthevalueofthecookie.

Database Connectivity -JDBC
•JDBCstandsforJavaDatabaseConnectivity.
•JDBCisaJavaAPItoconnectandexecutethequerywiththedatabase.

Database Connectivity -JDBC
•Thejava.sqlpackagecontainsclassesandinterfacesforJDBCAPI.
•AlistofpopularinterfacesofJDBCAPIaregivenbelow:
•Driverinterface
•Connectioninterface
•Statementinterface
•PreparedStatementinterface
•CallableStatementinterface
•ResultSetinterface
•ResultSetMetaDatainterface
•DatabaseMetaDatainterface
•RowSetinterface

Database Connectivity -JDBC
•AlistofpopularclassesofJDBCAPIaregivenbelow:
•DriverManagerclass
•Blobclass
•Clobclass
•Typesclass
•OnecanuseJDBCAPItohandledatabaseusingJavaprogramandcan
performthefollowingactivities:
1.Connecttothedatabase
2.Executequeriesandupdatestatementstothedatabase
3.Retrievetheresultreceivedfromthedatabase.

Database Connectivity -JDBC

Database Connectivity -JDBC
StepsinJDBC
•RegistertheDriverclass
Class.forName("oracle.jdbc.driver.OracleDriver");
•Createconnection
Connectioncon=DriverManager.getConnection("jdbc:oracle:thin:@localhost:
1521:xe","system","password");
•Createstatement
Statementstmt=con.createStatement();

Database Connectivity -JDBC
StepsinJDBC
•Executequeries
ResultSetrs=stmt.executeQuery("select*fromemp");
while(rs.next()){
System.out.println(rs.getInt(1)+""+rs.getString(2));
}
•Closeconnection
con.close();
Tags