Enterprise Java, Servlet, JDBC and JSP.pdf

PokemonSpyk 56 views 95 slides Sep 25, 2024
Slide 1
Slide 1 of 95
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
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95

About This Presentation

Fyhh


Slide Content

TO
ENTERPRISE JAVA
INTRODUCTION

JAVA
Programming
Language
Javaprogramminglanguageisahighlevellanguage,writtenina
human-readableform,makingitprogrammerfriendlyand
enablingittomorefocusontheproblemsolving.
Introduction to Enterprise Java

JAVA
Platform
Javaisaplatform,usedasanenvironmentinwhichJava
programmingapplicationsrun.
Introduction to Enterprise Java

JAVA
Programming
Language
Platform
Introduction to Enterprise Java
Hence,wecansaythatJavaisaprogramminglanguageaswellas
aplatform.

JVM and API
JVM and APIJVM and API
JVM and API
JAVA
PLATFORM
Standard
Edition
(Java SE)
Enterprise
Edition
(Java EE)
Java Programming Language Platforms
Micro
Edition
(Java ME)
JavaFX

JVM and API
JVM and APIJVM and API
JVM and API
JAVA
PLATFORM
Standard
Edition
(Java SE)
Enterprise
Edition
(Java EE)
Micro
Edition
(Java ME)
JavaFX
AlltheJavaplatformconsistsofJavaVirtualMachine(JVM)andan
ApplicationProgramInterface(API),enablingapplicationswrittenforthat
platformtorunonanycompatiblesystemwithallthebenefitsoftheJava
programminglanguage.

WhenwethinkoftheJavaprogramming,usuallywearethinkingaboutthe
JavaStandardEdition(JavaSE)API,whichisalsoknownasCoreJava.
Java Programming Language Platforms
Standard
Edition
(Java SE)
Java
Programming
Java SE API
(Core Java)

Java Programming Language Platforms
Standard
Edition
(Java SE)
JavaSEprovidesthefundamentalfeaturesofJavalanguageinthepurestform.
Itdescribesallthefeatureslikethebasictypes,objects,classesusedfor
developingapplicationsbasedondatabaseaccess,security,networkingand
developingGraphicalUserInterface(GUI).

Java EE platform has the fundamental base of the Java SE platform, used for
applications running on the servers.
Java Programming Language Platforms
Enterprise
Edition
(Java EE)
Java SE
Java EE

Java Programming Language Platforms
Enterprise
Edition
(Java EE)
ItservesanApplicationProgrammingInterface(API)andruntime
environmentforcreating,developingandexecutingextensive,scalable,reliable
andmulti-tieredbusinessapplications.

Virtual
Machine
Mobile
API
JavaMEplatformservesamobileAPIinconjunctionwithspace-efficient
virtualmachineforexecutingJavaapplicationsonsmalldevices,likemobile
phones.
Java Programming Language Platforms
Micro
Edition
(Java ME)
Java ME

Java Programming Language Platforms
Micro
Edition
(Java ME)
TheAPIisasubsetoftheJavaSEAPIhavingexceptionalclasslibraries
beneficialfordevelopingsmalldeviceapplications.

JavaFX Script
JavaFXisaplatformtobuildinternetbasedapplicationsusingalightweight
user-interfaceAPI,whichiswritteninJavaFXScript.
Java Programming Language Platforms
JavaFX
JavaFX

Java Programming Language Platforms
JavaFX
SunMicrosystemsdesignedJavaFXScriptasascriptinglanguage,thatis
compiledtoJavabytecodeforJVMtoexecute.
ApplicationsdevelopedusingJavaFXtechnologymaybeclientsofJavaEE
services.
JavaFX Script
Java
Virtual
Machine
(JVM)
Java
Byte code

What is Enterprise Application?
Enterprise
Edition
(Java EE)
ItservesanApplicationProgrammingInterface(API)andruntimeenvironment
forcreating,developingandexecutingextensive,scalable,reliableandmulti-
tieredbusinessapplications.
Inmulti-tieredbusinessapplications,theworkingoftheapplicationis
partitionedintodifferentfunctionalareas,knownastiers.

What is Enterprise Application?
Client Tier
Web Tier
Business Tier
Enterprise Information Systems (EIS) Tier
Client
Tier
Middle
Tier
Data
Tier

What is Enterprise Application?
Client Tier
Web Tier
Business Tier
EIS Tier
Java EE
Server
Client
Machine
Database
Server
User Interface Layer
(Presentation Logic)
Business Processing Layer
(Business Logic)
Data Storage and Access Layer
(Persistence Logic)

What is Enterprise Application?
Java EE Application 1 Java EE Application 2
Client Tier
Client Application Dynamic HTML Pages
Web Tier
Business Tier
EIS Tier
JSP Pages
Enterprise Beans Enterprise Beans
Database Database
Java EE
Server
Client
Machine
Database
Server

Java Servlet Technology
•ServletsaretheJavaprogramsthatrunsontheJava-enabledweb
serverorapplicationserver.
•Theyareusedtohandletherequestobtainedfromthewebserver,
processtherequest,producetheresponse,thensendresponsebackto
thewebserver.
•PropertiesofServlets:
-Servletsworkontheserver-side.
-Servletsarecapableofhandlingcomplexrequestsobtainedfrom
webserver.

Java Servlet Technology
•ExecutionofServletsinvolvessixbasicsteps:
1)Theclientssendtherequesttothewebserver.
2)Thewebserverreceivestherequest.
3)Thewebserverpassestherequesttothecorrespondingservlet.
4)Theservletprocessestherequestandgeneratestheresponsein
theformofoutput.
5)Theservletsendstheresponsebacktothewebserver.
6)Thewebserversendstheresponsebacktotheclientandthe
clientbrowserdisplaysitonthescreen.

Java Servlet Technology
•ServletArchitecture-

Java Servlet Technology
NeedForServer-SideExtensions(NeedforDynamicContent)
•Theserver-sideextensionsarenothingbutthetechnologiesthatare
usedtocreatedynamicWebpages.
•Actually,toprovidethefacilityofdynamicWebpages,Webpagesneed
acontainerorWebserver.
•Tomeetthisrequirement,independentWebserverprovidersoffer
someproprietarysolutionsintheformofAPIs(Application
ProgrammingInterface).

Java Servlet Technology
NeedForServer-SideExtensions(NeedforDynamicContent)
•TheseAPIsallowustobuildprogramsthatcanrunwithaWebserver.
•Inthiscase,JavaServletisalsooneofthecomponentAPIsofJava
PlatformEnterpriseEditionwhichsetsstandardsforcreatingdynamic
WebapplicationsinJava.

CGI vs Servlet
CGI (Common Gateway Interface)
•CGItechnologyenablesthewebservertocallanexternalprogramand
passHTTPrequestinformationtotheexternalprogramtoprocessthe
request.Foreachrequest,itstartsanewprocess.
•TherearemanyproblemsinCGItechnology:
-Ifthenumberofclientsincreases,ittakesmoretimeforsendingthe
response.
-Foreachrequest,itstartsaprocess,andthewebserverislimitedto
startprocesses.
-Itusesplatformdependentlanguagee.g.C,C++,perl.

CGI vsServlet

CGI vsServlet
Servlet
•TherearemanyadvantagesofServletoverCGI.Thewebcontainer
createsthreadsforhandlingthemultiplerequeststotheServlet.
•ThreadshavemanybenefitsovertheProcessessuchastheysharea
commonmemoryarea,lightweight,costofcommunicationbetweenthe
threadsarelow.

CGI vsServlet
Servlet
•TheadvantagesofServletareasfollows:
-Betterperformance:becauseitcreatesathreadforeachrequest,
notprocess.
-Portability:becauseitusesJavalanguage.
-Robust:JVMmanagesServlets,sowedon'tneedtoworryabout
thememoryleak,garbagecollection,etc.
-Secure:becauseitusesjavalanguage.

CGI vsServlet

Servlet Lifecycle
•Aservletlifecyclecanbedefinedastheentireprocessfromitscreation
tillthedestruction.
•Thefollowingarethepathsfollowedbyaservlet-
-Theservletisinitializedbycallingtheinit()method.
-Theservletcallsservice()methodtoprocessaclient'srequest.
-Theservletisterminatedbycallingthedestroy()method.
-Finally,servletisgarbagecollectedbythegarbagecollectorofthe
JVM.

Servlet Lifecycle
•Theinit()Method-Itiscalledonlyonce.Itiscalledonlywhenthe
servletiscreated,andnotcalledforanyuserrequestsafterwards.So,it
isusedforone-timeinitializations,justaswiththeinitmethodof
applets.
•Theservice()Method-Theservice()methodisthemainmethodto
performtheactualtask.Theservletcontainer(i.e.webserver)callsthe
service()methodtohandlerequestscomingfromtheclient(browsers)
andtowritetheformattedresponsebacktotheclient.

Servlet Lifecycle
•ThedoGet()Method-AGETrequestresultsfromanormalrequestfor
aURLorfromanHTMLformthathasnoMETHODspecifiedandit
shouldbehandledbydoGet()method.
•ThedoPost()Method-APOSTrequestresultsfromanHTMLform
thatspecificallylistsPOSTastheMETHODanditshouldbehandled
bydoPost()method.

Servlet Lifecycle
•Thedestroy()Method-Thedestroy()methodiscalledonlyonceatthe
endofthelifecycleofaservlet.Thismethodgivesyourservletachance
toclosedatabaseconnections,haltbackgroundthreads,writecookie
listsorhitcountstodisk,andperformothersuchcleanupactivities.

Servlet Lifecycle
•Thefollowingfiguredepictsatypicalservletlife-cyclescenario-
-FirsttheHTTPrequestscomingtotheserveraredelegatedtothe
servletcontainer.
-Theservletcontainerloadstheservletbeforeinvokingtheservice()
method.
-Thentheservletcontainerhandlesmultiplerequestsbyspawning
multiplethreads,eachthreadexecutingtheservice()methodofa
singleinstanceoftheservlet.

JDBC
•JDBCstandsforJavaDatabaseConnectivity.JDBCisaJavaAPIto
connectandexecutethequerywiththedatabase.
•ItisapartofJavaSE(JavaStandardEdition).
•JDBCAPIusesJDBCdriverstoconnectwiththedatabase.
•TherearefourtypesofJDBCdrivers:
-JDBC-ODBCBridgeDriver,
-NativeDriver,
-NetworkProtocolDriver,and
-ThinDriverservlet.

JDBC

JDBC
•BeforeJDBC,ODBCAPIwasthedatabaseAPItoconnectandexecute
thequerywiththedatabase.
•But,ODBCAPIusesODBC(OpenDatabaseConnectivity)driver
whichiswritteninClanguage(i.e.platformdependentandunsecured).
•ThatiswhyJavahasdefineditsownAPI(JDBCAPI)thatusesJDBC
drivers(writteninJavalanguage).
•WecanuseJDBCAPItohandledatabaseusingJavaprogramandcan
performthefollowingactivities:
-Connecttothedatabase.
-Executequeriesandupdatestatementstothedatabase.
-Retrievetheresultreceivedfromthedatabase.

JDBC
•JDBCincludesfourcomponents:
1)TheJDBCAPI
2)JDBCDriverManager
3)JDBCTestSuite
4)JDBC-ODBCBridge

JDBC
•JDBCincludesfourcomponents:
1)TheJDBCAPI–
-TheJDBCAPIprovidesprogrammaticaccesstorelationaldata
fromtheJavaprogramminglanguage.
-UsingtheJDBCAPI,applicationscanexecuteSQLstatements,
retrieveresults,andpropagatechangesbacktoanunderlyingdata
source.
-TheJDBCAPIcanalsointeractwithmultipledatasourcesina
distributed,heterogeneousenvironment.

JDBC
•JDBCincludesfourcomponents:
2)JDBCDriverManager-
-TheJDBCDriverManagerclassdefinesobjectswhichcanconnect
JavaapplicationstoaJDBCdriver.
-DriverManagerhastraditionallybeenthebackboneoftheJDBC
architecture.Itisquitesmallandsimple.
-TheStandardExtensionpackagesjavax.namingandjavax.sqllet
youuseaDataSourceobjectregisteredwithaJavaNamingand
DirectoryInterface(JNDI)namingservicetoestablishaconnection
withadatasource.

JDBC
•JDBCincludesfourcomponents:
3)JDBCTestSuite-
-TheJDBCdrivertestsuitehelpsyoutodeterminethatJDBC
driverswillrunyourprogram.
-Thesetestsarenotcomprehensiveorexhaustive,buttheydo
exercisemanyoftheimportantfeaturesintheJDBCAPI.

JDBC
•JDBCincludesfourcomponents:
4)JDBC-ODBCBridge-
-TheJavaSoftwarebridgeprovidesJDBCaccessviaODBCdrivers.
-YouneedtoloadODBCbinarycodeontoeachclientmachinethat
usesthisdriver.
-Asaresult,theODBCdriverismostappropriateonacorporate
networkwhereclientinstallationsarenotamajorproblem,orfor
applicationservercodewritteninJavainathree-tierarchitecture.

JDBC
•ThefollowingarethestepsforconnectivitybetweenJavaprogramand
database(AccessingDatabase):
1)LoadingtheDriver
2)Createtheconnections
3)Createastatement
4)Executethequery

JDBC
1)LoadingtheDriver-
-Tobeginwith,youfirstneedloadthedriverorregisteritbefore
usingitintheprogram.
-Registrationistobedoneonceinyourprogram.
-Youcanregisteradriverinoneoftwowaysmentionedbelow:
-Class.forName():Hereweloadthedriver’sclassfileintomemoryat
theruntime.
-Noneedofusingneworcreationofobject.Thefollowingexample
usesClass.forName()toloadtheOracledriver–
Class.forName(“oracle.jdbc.driver.OracleDriver”);

JDBC
1)LoadingtheDriver-
-DriverManager.registerDriver():DriverManagerisaJavainbuilt
classwithastaticmemberregister.
-Herewecalltheconstructorofthedriverclassatcompiletime.The
followingexampleusesDriverManager.registerDriver()toregister
theOracledriver–
DriverManager.registerDriver(neworacle.jdbc.driver.OracleDriver()).

JDBC
2)Createtheconnections–
-Afterloadingthedriver,establishconnectionsusing:
Connectioncon=DriverManager.getConnection(url,user,password)
-user–usernamefromwhichyoursqlcommandpromptcanbe
accessed.
-password–passwordfromwhichyoursqlcommandpromptcanbe
accessed.
-con:isareferencetoConnectioninterface.
-url:UniformResourceLocator.Itcanbecreatedasfollows:
Stringurl=“jdbc:oracle:thin:@localhost:1521:xe”.

JDBC
3)Createastatement–
-Onceaconnectionisestablishedyoucaninteractwiththedatabase.
-TheJDBCStatement,CallableStatement,andPreparedStatement
interfacesdefinethemethodsthatenableyoutosendSQL
commandsandreceivedatafromyourdatabase.
-UseofJDBCStatementisasfollows:
Statementst=con.createStatement();.

JDBC
4)Executethequery–
-Nowcomesthemostimportantparti.eexecutingthequery.Query
hereisanSQLQuery.Nowweknowwecanhavemultipletypesof
queries.Someofthemareasfollows:
-Queryforupdating/insertingtableinadatabase.
-Queryforretrievingdata.
-TheexecuteQuery()methodofStatementinterfaceisusedtoexecute
queriesofretrievingvaluesfromthedatabase.Thismethodreturns
theobjectofResultSetthatcanbeusedtogetalltherecordsofa
table.TheexecuteUpdate(sqlquery)methodofStatementinterfaceis
usedtoexecutequeriesofupdating/inserting.

JDBC Architecture
-TheJDBCAPIsupportsbothtwo-tierandthree-tierprocessingmodels
fordatabaseaccessbutingeneral,JDBCArchitectureconsistsoftwo
layers−
1)JDBCAPI:Thisprovidestheapplication-to-JDBCManager
connection.
2)JDBCDriverAPI:ThissupportstheJDBCManager-to-
DriverConnection.
-TheJDBCAPIusesadrivermanageranddatabase-specificdriversto
providetransparentconnectivitytoheterogeneousdatabases.

JDBC Architecture
-TheJDBCdrivermanagerensuresthatthecorrectdriverisusedto
accesseachdatasource.Thedrivermanageriscapableofsupporting
multipleconcurrentdriversconnectedtomultipleheterogeneous
databases.

JDBC Architecture
-JDBCsupportstwotypesofprocessingmodelsforaccessingdatabase
i.e.two-tierandthree-tier.
1.Two-tierArchitecture:
-Thisarchitecturehelpsjavaprogramorapplicationtodirectly
communicatewiththedatabase.
-ItneedsaJDBCdrivertocommunicatewithaspecificdatabase.
-Queryorrequestissentbytheusertothedatabaseandresultsare
receivedbackbytheuser.
-Thedatabasemaybepresentonthesamemachineoranyremote
machineconnectedviaanetwork.
-Thisapproachiscalledclient-serverarchitectureorconfiguration.

JDBC Architecture
2.Three-tierArchitecture:
-Inthis,thereisnodirectcommunication.Requestsaresenttothe
middletieri.e.HTMLbrowsersendsarequesttojavaapplication
whichisthenfurthersenttothedatabase.
-Databaseprocessestherequestandsendstheresultbacktothemiddle
tierwhichthencommunicateswiththeuser.
-Itincreasestheperformanceandsimplifiestheapplication
deployment.

JDBC Architecture
ComponentsofJDBCArchitecture
•DriverManager:Itisaclassthatcontainsalistofalldrivers.Whena
connectionrequestisreceived,itmatchestherequestwiththe
appropriatedatabasedriverusingaprotocolcalledcommunication
sub-protocol.Thedriverthatmatchesisusedtoestablishaconnection.
•Driver:Itisaninterfacewhichcontrolsthecommunicationwiththe
databaseserver.DriverManagerobjectsareusedtoperform
communication.
•Connection:Itisaninterfacewhichcontainsmethodstocontacta
database.

JDBC Architecture
ComponentsofJDBCArchitecture
•Statement:ThisinterfacecreatesanobjecttosubmitSQLqueriesor
statementstothedatabase.
•ResultSet:Thiscontainstheresultsretrievedaftertheexecutionofthe
SQLstatementsorqueries.
•SQLException:Anyerrorsthatoccurindatabaseapplicationare
handledbythisclass.

JDBC Architecture
Interfaces
Thejava.sqlpackageconsistsofmanyinterfaces.Somepopular
interfacesarementionedbelow:
•DriverInterface:Thisinterfaceallowsformultipledatabasedrivers.
DriverManagerobjectsarecreatedtocommunicatewiththedatabase.
TheseobjectsarecreatedbyDriverManager.registerDriver();
•ConnectionInterface:Connectioninterfaceestablishestheconnection
i.e.sessionbetweenjavaprogramandthedatabase.Ithasmany
methodslikerollback(),close()etc.

JDBC Architecture
Interfaces
•StatementInterface:Thisinterfaceprovidesmethodsfortheexecution
oftheSQLqueries.ItprovidesfactorymethodstogetaResultSet
object.SomemethodsofstatementinterfaceareexecuteQuery(),
executeUpdate()etc.
•PreparedStatementInterface:ThisinterfacehelpswhentheSQL
queriesneedtoimplementmanytimes.Itacceptsinputparameters
duringruntime.

JDBC Architecture
Interfaces
•CallableStatementInterface:Thisinterfaceisusedwhenstored
proceduresaretobeaccessed.Italsoacceptsparametersduringrun
time.
•ResultSetInterface:Thisinterfacehelpstostoretheresultreturned
aftertheexecutionoftheSQLqueries.

RequestDispatcherin Servlet
•TheRequestDispatcherinterfaceprovidesthefacilityofdispatching
therequesttoanotherresourceitmaybehtml,servletorjsp.
•Thisinterfacecanalsobeusedtoincludethecontentofanother
resourcealso.
•Itisoneofthewayofservletcollaboration.
•TherearetwomethodsdefinedintheRequestDispatcherinterface.

RequestDispatcherin Servlet
1) public void forward(ServletRequestrequest,ServletResponse
response)throws ServletException,java.io.IOException:Forwardsa
request from a servlet to another resource (servlet, JSP file, or HTML
file) on the server.

RequestDispatcherin Servlet
2) public void include(ServletRequestrequest,ServletResponse
response)throws ServletException,java.io.IOException:Includesthe
content of a resource (servlet, JSP page, or HTML file) in the response.

Cookies and Sessions
Cookies
•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.
•Working of Cookies is by default, each request is considered as a new
request.
•In cookies technique, we add cookie with response from the servlet.

Cookies and Sessions
Cookies
•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.

Cookies and Sessions
Types of Cookies
1) Non-persistent cookie -It isvalid for single sessiononly. It is removed
each time when user closes the browser.
2) Persistent cookie -It isvalid for multiple session. It is not removed
each time when user closes the browser. It is removed only if user logout
or signout.

Cookies and Sessions
Sessions
•Sessionsimply means a particular interval of time.
•Session Trackingis a way to maintain state (data) of an user.
•It is also known assession managementin servlet.
•Http protocol is a stateless so we need to maintain state using session
tracking techniques.
•Each time user requests to the server, server treats the request as the
new request.
•So we need to maintain the state of an user to recognize to particular
user.

Java Server Pages (JSP)
Introduction
•Java Server Pages (JSP) is a server-side programming technology that
enables the creation of dynamic, platform-independent method for
building Web-based applications.
•JSP have access to the entire family of Java APIs, including the JDBC
API to access enterprise databases.

Java Server Pages (JSP)
Why JSP?
•Performance is significantly better because JSP allows embedding
Dynamic Elements in HTML Pages itself instead of having separate
CGI files.
•JSP are always compiled before they are processed by the server
unlike CGI/Perl which requires the server to load an interpreter and
the target script each time the page is requested.

Java Server Pages (JSP)
Why JSP?
•JavaServerPages are built on top of the Java Servlets API, so like
Servlets, JSP also has access to all the powerful Enterprise Java APIs,
including JDBC, JNDI, EJB, JAXP, etc.
•JSP pages can be used in combination with servlets that handle the
business logic, the model supported by Java servlet template engines.

Java Server Pages (JSP)
Why JSP?
•Finally, JSP is an integral part of Java EE, a complete platform for
enterprise class applications.
•This means that JSP can play a part in the simplest applications to the
most complex and demanding.

Java Server Pages (JSP)
Applications of JSP
1) JSP vs. Active Server Pages (ASP)
•The advantages of JSP are twofold. First, the dynamic part is written
in Java, not Visual Basic or other MS specific language, so it is more
powerful and easier to use. Second, it is portable to other operating
systems and non-Microsoft Web servers.
2) JSP vs. Pure Servlets
•It is more convenient to write (and to modify!) regular HTML than to
have plenty of printlnstatements that generate the HTML.

Java Server Pages (JSP)
Applications of JSP
3) JSP vs. Server-Side Includes (SSI)
•SSI is really only intended for simple inclusions, not for "real"
programs that use form data, make database connections, and the
like.
4) JSP vs. JavaScript
•JavaScript can generate HTML dynamically on the client but can
hardly interact with the web server to perform complex tasks like
database access and image processing etc.
5) JSP vs. Static HTML
•Regular HTML, of course, cannot contain dynamic information.

Java Server Pages (JSP)
Servlet vs JSP
•Following is the distinguish between Servlet and JSP

Java Server Pages (JSP)
JSP Life Cycle
•The JSP pages follow these phases:
1)Translation of JSP Page
2)Compilation of JSP Page
3)Classloading(the classloaderloads class file)
4)Instantiation (Object of the Generated Servlet is created).
5)Initialization ( the container invokes jspInit() method).
6)Request processing ( the container invokes _jspService() method).
7)Destroy ( the container invokes jspDestroy() method).

Java Server Pages (JSP)
JSP Comments
•JSP comment marks to text or statements that the JSP container
should ignore.
•A JSP comment is useful when you want to hide or "comment out", a
part of your JSP page.
•Following is the syntax of the JSP comments −
<%--This is JSP comment --%>

Java Server Pages (JSP)
JSP Documents
•According to the JSP specification, a JSP page can be written in 2
formats:
1)JSP Page Format-A JSP page written in an HTML format with JSP
elements expressed as <% ... %> tags as described in the previous
section.
2)JSP Document Format-A JSP page written in an XML format with
JSP elements expressed as XML elements.

Java Server Pages (JSP)
JSP Elements -JSP Declaration
•A declaration tag is a piece ofJava code for declaring variables,
methods and classes.
•If we declare a variable or method inside declaration tag it means that
the declaration is made inside the servlet class but outside the service
method.
•We can declare a static member, an instance variable (can declare a
number or string) and methods inside the declaration tag.
•Syntax of declaration tag :
<%! Dec var%>
•Here Dec varis the method or a variable inside the declaration tag.

Java Server Pages (JSP)
JSP Elements -JSP Scriptlet
•Scriptlettag allows to write Java code into JSP file.
•JSP container moves statements in _jspservice() method while
generating servlet from jsp.
•For each request of the client, service method of the JSP gets invoked
hence the code inside the Scriptletexecutes for every request.
•A Scriptletcontains java code that is executed every time JSP is
invoked.
•Syntax of Scriptlettag:
<% java code %>
•Here <%%> tags are scripletstag and within it, we can place java
code.

Java Server Pages (JSP)
JSP Elements -JSP Expression
•Expression tag evaluates the expression placed in it.
•It accesses the data stored in stored application.
•It allows create expressions like arithmetic and logical.
•It produces scriptlessJSP page.
•Syntax:
<%= expression %>
•Here the expression is the arithmetic or logical expression.

Java Server Pages (JSP)
JSP Elements -JSP Expression
•Expression tag evaluates the expression placed in it.
•It accesses the data stored in stored application.
•It allows create expressions like arithmetic and logical.
•It produces scriptlessJSP page.
•Syntax:
<%= expression %>
•Here the expression is the arithmetic or logical expression.

Any Questions… ???
Tags