SlideShare a Scribd company logo
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
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
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
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
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
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
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}
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
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
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
21/07/2009 
11 
The sql:transactionTag 
61 
62 
Internationalization(I18N) 
63 
I18NBasics(1) 
64 
Internationalization 
Themethodofdesigninganapplicationthatcanbeadaptedtoaregionoralanguagewithoutmuchchangeinthetechnology 
HelpsincreatinginternationalizedWebapplicationthatstandardizeformattednumericanddate-timeoutput(supportingmultiplelanguages) 
Localization 
Isaprocessofmakingofproductorservicelanguage,culturalandlocal“lookandfeel”specific 
ALocaleisasimpleobjectidentifyingaspecificlanguageandgeographicregion(java.lang.Locale) 
Isdenotedbyxx_YY(languagecode_lettercountry) 
UnicodeinJava,isa16bitcharacterencoding 
ResourceBundlescontainlocale-specificobjects 
Internationalizing (1) 
65 
ResourceBundles 
IsasetofrelatedclassesthatinheritfromResourceBundle 
Theseveralmethods 
publicstaticfinalResourceBundlegetBundle(StringbaseName, Localelocale) 
publicabstractEnumerationgetKeys() 
publicLocalegetLocale() 
publicfinalObjectgetObject(Stringkey) 
publicfinalStringgetString(Stringkey) 
FormattingDatesinServlets 
UsingpredefinedFormats:SHORT,MEDIUM,LONG,FULL 
CreateaformatterwiththegetDateInstance()methodofDateFormatclass 
Invokingtheformat()method 
CustomisingFormats:UsingtheSimpleDateFormatclass 
Internationalizing (2) 
66 
FormattingCurrencies 
Currency:thisclassrepresentscurrencybyISO4217currencycodes 
publicStringgetCurrencyNode() 
publicStringgetSymbol() 
publicstaticCurrencygetInstance(Localelocale) 
NumberFormat:thisisanabstractbaseclassforallnumberformats 
publicfinalStringformat(doublenumber) 
publicCurrencygetCurrency() 
publicstaticfinalNumberFormatgetInstance() 
publicNumberparse(Stringstr)throwsParseException 
publicvoidsetCurrency(Currencycurrency) 
FormattingPercentages 
publicstaticfinalNumberFormatgetPercentInstance() 
publicstaticNumberFormatgetPercentInstance(LocaleinLocale)
21/07/2009 
12 
Internationalizing (3) 
67 
FormattingMessages 
UsingtheMessageFormatObjects 
ThearrayofobjectsusingtheformatspecifiersembeddedinthepatternformatetedbytheMessageFormat.format() 
Theclassesforformattingmessages 
MessageFormat 
MessageFormat.Field

More Related Content

PDF
J2EE jsp_01
PDF
Java Web Programming [5/9] : EL, JSTL and Custom Tags
PDF
Java Web Programming [8/9] : JSF and AJAX
PDF
Java Web Programming [6/9] : MVC
PPTX
Implicit objects advance Java
PDF
Java Web Programming [4/9] : JSP Basic
PPTX
Implicit object.pptx
PPTX
Introduction to JSP
J2EE jsp_01
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [6/9] : MVC
Implicit objects advance Java
Java Web Programming [4/9] : JSP Basic
Implicit object.pptx
Introduction to JSP

What's hot (20)

PDF
Java Web Programming [3/9] : Servlet Advanced
PDF
Java Web Programming [7/9] : Struts2 Basics
PPTX
Jsp presentation
PPTX
Jsp elements
DOC
Integration Of Springs Framework In Hibernates
PDF
Java Web Programming [2/9] : Servlet Basic
DOCX
PPTX
PPTX
JSP - Java Server Page
PPTX
Spring Web Views
PPT
JSP Standart Tag Lİbrary - JSTL
PPT
Jsp ppt
PDF
PDF
Lecture 5 JSTL, custom tags, maven
DOC
Jsp advance part i
PPTX
JSP Directives
PDF
JSP Technology I
PPTX
Servlet and jsp interview questions
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [7/9] : Struts2 Basics
Jsp presentation
Jsp elements
Integration Of Springs Framework In Hibernates
Java Web Programming [2/9] : Servlet Basic
JSP - Java Server Page
Spring Web Views
JSP Standart Tag Lİbrary - JSTL
Jsp ppt
Lecture 5 JSTL, custom tags, maven
Jsp advance part i
JSP Directives
JSP Technology I
Servlet and jsp interview questions
Ad

Similar to Lap trinh web [Slide jsp] (20)

PPT
Server side development on java server pages
PPTX
Java server pages
PPT
PPTX
Introduction to JSP.pptx
PPTX
JSP AND XML USING JAVA WITH GET AND POST METHODS
PPTX
JSP.pptx programming guide for beginners and experts
PPTX
SCWCD : Java server pages CHAP : 9
PPTX
The java server pages
PPT
Atul & shubha goswami jsp
PDF
JSP Components and Directives.pdf
PPT
Session 5 : intro to jsp - Giáo trình Bách Khoa Aptech
PPTX
Learning jsp
PPTX
WT Unit-Vuufvmjn dissimilating Dunkirk k
PPTX
JSP- JAVA SERVER PAGES
PPTX
Jsp Introduction Tutorial
PDF
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 7 ...
PPTX
JAVA SERVER PAGES
PPSX
Java server pages
Server side development on java server pages
Java server pages
Introduction to JSP.pptx
JSP AND XML USING JAVA WITH GET AND POST METHODS
JSP.pptx programming guide for beginners and experts
SCWCD : Java server pages CHAP : 9
The java server pages
Atul & shubha goswami jsp
JSP Components and Directives.pdf
Session 5 : intro to jsp - Giáo trình Bách Khoa Aptech
Learning jsp
WT Unit-Vuufvmjn dissimilating Dunkirk k
JSP- JAVA SERVER PAGES
Jsp Introduction Tutorial
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 7 ...
JAVA SERVER PAGES
Java server pages
Ad

Recently uploaded (20)

PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
additive manufacturing of ss316l using mig welding
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
DOCX
573137875-Attendance-Management-System-original
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
Sustainable Sites - Green Building Construction
PPTX
Geodesy 1.pptx...............................................
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
bas. eng. economics group 4 presentation 1.pptx
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
CH1 Production IntroductoryConcepts.pptx
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
additive manufacturing of ss316l using mig welding
Operating System & Kernel Study Guide-1 - converted.pdf
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
573137875-Attendance-Management-System-original
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Model Code of Practice - Construction Work - 21102022 .pdf
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Arduino robotics embedded978-1-4302-3184-4.pdf
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Sustainable Sites - Green Building Construction
Geodesy 1.pptx...............................................
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx

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
  • 11. 21/07/2009 11 The sql:transactionTag 61 62 Internationalization(I18N) 63 I18NBasics(1) 64 Internationalization Themethodofdesigninganapplicationthatcanbeadaptedtoaregionoralanguagewithoutmuchchangeinthetechnology HelpsincreatinginternationalizedWebapplicationthatstandardizeformattednumericanddate-timeoutput(supportingmultiplelanguages) Localization Isaprocessofmakingofproductorservicelanguage,culturalandlocal“lookandfeel”specific ALocaleisasimpleobjectidentifyingaspecificlanguageandgeographicregion(java.lang.Locale) Isdenotedbyxx_YY(languagecode_lettercountry) UnicodeinJava,isa16bitcharacterencoding ResourceBundlescontainlocale-specificobjects Internationalizing (1) 65 ResourceBundles IsasetofrelatedclassesthatinheritfromResourceBundle Theseveralmethods publicstaticfinalResourceBundlegetBundle(StringbaseName, Localelocale) publicabstractEnumerationgetKeys() publicLocalegetLocale() publicfinalObjectgetObject(Stringkey) publicfinalStringgetString(Stringkey) FormattingDatesinServlets UsingpredefinedFormats:SHORT,MEDIUM,LONG,FULL CreateaformatterwiththegetDateInstance()methodofDateFormatclass Invokingtheformat()method CustomisingFormats:UsingtheSimpleDateFormatclass Internationalizing (2) 66 FormattingCurrencies Currency:thisclassrepresentscurrencybyISO4217currencycodes publicStringgetCurrencyNode() publicStringgetSymbol() publicstaticCurrencygetInstance(Localelocale) NumberFormat:thisisanabstractbaseclassforallnumberformats publicfinalStringformat(doublenumber) publicCurrencygetCurrency() publicstaticfinalNumberFormatgetInstance() publicNumberparse(Stringstr)throwsParseException publicvoidsetCurrency(Currencycurrency) FormattingPercentages publicstaticfinalNumberFormatgetPercentInstance() publicstaticNumberFormatgetPercentInstance(LocaleinLocale)
  • 12. 21/07/2009 12 Internationalizing (3) 67 FormattingMessages UsingtheMessageFormatObjects ThearrayofobjectsusingtheformatspecifiersembeddedinthepatternformatetedbytheMessageFormat.format() Theclassesforformattingmessages MessageFormat MessageFormat.Field