Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Lap trinh web [Slide jsp]
1. 21/07/2009
1
Java Server Pages
http://www.vovanhai.wordpress.com
1
JSPBasics
2
JSP
JavaServerPage(JSP)isaserversidescriptlanguage
Savedwith.jspextension
Asimple,yetpowerfulJavatechnologyforcreatingandmaintainingdynamic-contentwebspages
JSPpageareconvertedbythewebcontainerintoaServletinstance
Itfocusonthepresentationlogicofthewebapplication
3
Architecture of JSP
4
JSPExpression
Includes expression in a scripting language page
5
Scriptlet
Refers to code blocks executed for every request.
6
2. 21/07/2009
2
Declarations
Defines the variables and methods for a JSPpage
7
Comments
Explains the functioning of the code
Comments are ignored by the servletduring compilation
Syntax
...
<!–-HTML comments -->
...
...
<%--JSPcomments --%>
... ... <% /*Scripting languages comments*/ %> ...
8
Directives
ControlsthestructureoftheservletbysendingmessagesfromtheJSPpagetotheJSPcontainer.
Specifythescriptinglanguagetoused.
DenotetheuseofcustomtaglibraryinaJSPpage.
BeusedtoincludethecontentofanotherJSPpage.
…
Syntax
...
<%directivenameattribute = “value”%>
... Specifies the JSPdirective
Refers to the directive attribute
9
Directives –Contd…
The types of JSPdirectives are:
page-Associates the attributes that affect the entire JSPpage
include-Sends message to the JSPcontainer to include the contents of one file into another
taglib-Enables the use of custom tags in the JSPpage
10
pageDirective
11
includeDirective12
3. 21/07/2009
3
taglibDirective
13
Standard Actions
Tags affecting the behavior of JSPat runtime and the response sent back to web browser
Syntax:
...
<jsp: standard action>
...
Standard Action
Description
<jsp: useBean>
Accesses the functions of custom tags
<jsp: param>
Provides name and value to the parameters used by the JSP page
<jsp: include>
Includes the output from one file into the other files
<jsp: forward>
Transfers control from a JSPpage to another
<jsp: plugin>
Uses a pluginto execute an applet or bean
14
JSPImplicit Object
15
Implicit Objects
Are loaded by the Web Container automatically and maintains them in a JSPpage
The names of the implicit objects are reserved words of JSP
Access dynamic content using JavaBeans
Types of implicit objects
16
Implicit Objects (cont)
Object
Class / Interface
page
javax.servlet.jsp.HttpJspPage
config
javax.servlet.ServletConfig
request
javax.servlet.http.HttpServletRequest
response
javax.servlet.http.HttpServletResponse
out
javax.servlet.jsp.JspWriter
session
javax.servlet.http.HttpSession
application
javax.servlet.ServletContext
pageContext
javax.servlet.jsp.PageContext
exception
java.lang.Throwable
17
The requestObject
18
RepresentstherequestfromtheclientforaWebpage
Controlsinformationassociatedwitharequestfromclient
Includesthesource,URL,headers,cookiesandparameters
4. 21/07/2009
4
The responseObject
19
Manages the response generated by JSPcontainer and sends response to the client
Is passed as a parameter to JSP_jspService() method
The outObject
20
Represents the output stream, then it will be sent to the client as a response for the request
Is has page scope
The sessionObject
21Provides all the objects available in the JSPpages within the session
The applicationObject
22
Is used to share the data between all application pages
Can be accessed by any JSPpresent in the application
The pageContextObbject(1)
23
Provides methods to access all attributes defined by implicit objects in the page.
Provides methods to transfer control from one web page to another
osetAttribute()
ogetAttribute()
ogetAttributeNamesInScope()
oremoveAttribute()
The pageContextObbject(2)
24
Find the scope or specify the scope
5. 21/07/2009
5
ServletObject (1)
25
The pageobject: is an instance of the servletprocessing the current request in a JSPpage.
ServletObject (2)
26The “config” Object:
oStores the information of the servlet
oRepresents the configuration of the servletdata where a JSPpage is compiled
oIt has page scope
The exceptionObject
27
Is used to handle errors in a JSPpage
Is used to trace the exception thrown during the execution
It has page scope
Error handling
<%@page errorpage=“error.jsp”%>
< --some of code,…-->
index.jsp
error.jsp
<%@page isErrorPage=“true”%> <% if(exception!=null){ out.println(exception.getMessage()); } %>
28
Standard Actions
29
Standard Actions
30
AreXMLliketagswhichtaketheformofanXMLtagwithanameprefixedjsp
Areusedfor
Forwardingrequestsandperformingincludesinpage
EmbeddingtheappropriateHTMLonpages
InteractingbetweenpagesandJavaBeans
Providingadditionalfunctionalitytotaglibraries
Syntax:
<jsp:actionNameattribute=“value”>...</jsp:actionName>
Someproperties
Using<jsp>prefix
Theattributesarecasesensitive
Valueintheattributesmustbeenclosedindoublequotes
Standardactionscanbeeitheranemptyoracontainertag
30
6. 21/07/2009
6
<jsp:include>
31
Include either static or dynamic file in jspfile at the time of page request.
Static case: The content is included in the calling jspfile.
Dynamic case: it acts on the request and send back a result that is include in the JSPpage.
Syntax:
<jsp:include: page=“webURL”|<%=exp%> flush=“true”/>
<jsp:forward>
32
It’s used to forward the request and response to another jsppage or servlet
Syntax:
<jsp:forwardpage=“{webURL|<%=exp%>}”>
<jsp:paramname=“{paramName|<%=exp%>”}/>
<jsp:forward>
Allow to pass one or more name/value pairs as parameters to an included or forwarded resource like a jsppage.
Syntax:
<jsp:paramname=“thename” value=“{thevalue|<%=exp%>}”
<jsp:param>
<jsp:plugin>
33
Used in the execution of an applet or bean.
Syntax:
<jsp:plugintype=“bean|applet” code=“ClassFileName” codebase=“classFileDirectoryName” <jsp:params> <jsp:paramname=“thename” value=“thevalue”> </jsp:params> [<jsp:fallback> display message to user</jsp:fallback>
</jsp:plugin>
<jsp:fallback>
34
Display a text message to user if the plug- in could not start.
Syntax:
<jsp:fallback> html message</jsp:fallback>
JavaBeans
35
Concept
36
JavaBeans are reusable components that can be deployed in java.
Define the interactivity of Java object
Allow creation of graphical components that can be reused in GUI application.
Can be embedded in multiple applications, servletand jsp.
Requirements:
oBe a public class
oHave a public constructor with no arguments
oHave get/set methods to read/write bean properties
Components of JavaBeans:
◦Properties
Getters and setters
◦Methods
◦Events
7. 21/07/2009
7
<jsp:useBean>
Is used to create a reference and include an existing bean component in JSP
The <jsp:useBean> follows to locate or instantiate the Bean
Attempsto locate a Bean within the scope
Defines an object reference variable with the name
Stores a reference to it in the variable, if it retrieves the Bean
Instantiates it from the specified class, it is cannot retrieve the Bean
Syntax: <jsp:useBeanid=“name” class=“class” scope=“page/session/request/application” />
37
<jsp:getProperty>
38
Using for retrieve properties value of the Bean.
RetrievesabeanpropertyvalueusingthegettermethodsanddisplaystheoutputinaJSPpage
The<jsp:getProperty>andexpressionconvertthevalueintoastringandinsertitintoanimplicitoutobject
Somedrawbacks
Failstoretrievethevaluesofindexesproperty
Failstodirectlyaccessenterprisebeancomponents
Syntax:
<jsp:getPropertyname=“Bean_Alias” property=“PropertyName”/>
<jsp:setProperty>
39
Retrieves a bean property value using the getter methods and displays the output in a JSPpage
The <jsp:getProperty> and expression convert the value into a string and insert it into an implicit out object
Some drawbacks:
◦Fails to retrieve the values of indexes property
◦Fails to directly access enterprise bean components
Syntax:
<jsp:setPropertyname=“Bean_Alias” property=“Property_Name” value=“TheValue” param=“Parameter”/>
JavaBeans & Scriptlets
40
JavaBeanscanbeaccessedfromscriptingelementindifferentways.DoitlikesinJ2SE.
TheJSPcontainerconvertsthestringvaluesintononstringvaluesbytheattributevaluesthatevaluatethecorrectdatatypetosetthepropertyvalue
Expression Language
41
Expression Language (EL)
42
New feature of JSP2.0
Allows JSPdevelopers to access java objects via a compact, easy-to-use shorthand style (similar to JavaScript)
It can handle both expressions and literals
Developed by two groups
JSPStandard Tag Library expert group
JSP2.0 expert group
Syntax: ${EL Expression}
8. 21/07/2009
8
EL Implicit Objects
43Implicit Objects
pageContext
cookie
initParamparamValues
param
header
headerValuesapplicationservletContext
request
session
response
Request Headers and Parameters
44
param: return a value that maps a request parameter name to a single string valueex: "${param.Name}“
paramValues: return an array of values is mapped to the request parameters from clientex: “${paramValues.Name[0]}”
header: return a request header name and maps the value to single string value. ex: ${header[“host”]}
headerValues: return an array of values is mapped to the request headerex: ${headerValues.Name}
cookie: returns the cookies name mapped to the single cookie objectex: ${cookie.name.value}
initParam: returns a context initialization parameter name, which is mapped to a single value.
Scope variables (1)
45
Variables are used to store and access values in JSPprogram
Variable refers as a attributes that are stored in standard scope such as page, request, session and application
Dot operator . or square brackets [ ] can be used to access value of variable
Example
${pageScope.color}
${pageScope[“color”]}
Scope Variables (2)
46
EL Operators
47
*
/ or div
+
-
% or mod
< or lt
> or gt
< = or le
> = or ge
= = or eq
!= or ne
&& or and
|| or or
! or not
empty
Operators
Empty
LogicalRelational
Arithmetic
Example
48
9. 21/07/2009
9
JSPStandard Tag Library (JSTL)
49
Concept
JSTLprovides a set of reusable standard tag that work for create jsppages.
JSTLallows programming using tags rather than scriptletcode.
JSTLhas tags, such as:
◦Iteratorsand conditional tags
◦Internationalization tags
◦SQL tags
50
Types Of Tags Libraries
51
JSP Standard Tag Library (JSTL)
Core Tag Library
I18N & Formatting Tag Library
SQL Tag Library
XML Tag Library
Core Tag Library
52
General Purpose Tags
Decision Making Tags
Iteration Tags
set
removeout
forEachforTokens
if
choose
Core Tag Library
General Purpose Tags
53
<c:set>: assigns a value to a variable in scope
<c:remove>: remove a scope variable
<c:out>: evaluate an expression and store a result in the current JspWriterobject.
<c:catch>: provides an exception handling functionality, such as try-catch inside jsppages without using scriptlet
Syntax:
<c:setvar=“varName” value=“value” scope=“page|request|session|application” />
<c:removevar=“varName” scope=“page|request|session|application” />
<c:outvalue=“value|expression” escapeXml=“true|false” default=“defaultValue” />
<c:catch/>
Example
54
10. 21/07/2009
10
Decision-Making Tags
55
<c:if>: used for conditional execution of the code
<c:choose>: similar switch statement in java
Iteration Tags
56
<c:forEach>: used to repatethe body content over a collection of objects.
<c:forTokens>: used to iterate over a collection of tokens separated by user-specified delimiters.
SQL Tag Library
57
SQL Tag Library
setDataSourcequery
update
param
transaction
The sql:setDataSourceTag
58
The sql:queryTag
The sql:updateTag
59
The sql:paramTag
60