SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet Advanced
 
Java Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 BasicsJava Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 Basics
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Jsp elements
Jsp elementsJsp elements
Jsp elements
 
Integration Of Springs Framework In Hibernates
Integration Of Springs Framework In HibernatesIntegration Of Springs Framework In Hibernates
Integration Of Springs Framework In Hibernates
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet Basic
 
Jsp
JspJsp
Jsp
 
Jsp lecture
Jsp lectureJsp lecture
Jsp lecture
 
Jsp
JspJsp
Jsp
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
 
Spring Web Views
Spring Web ViewsSpring Web Views
Spring Web Views
 
Jsp
JspJsp
Jsp
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTL
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Jsp
JspJsp
Jsp
 
Lecture 5 JSTL, custom tags, maven
Lecture 5   JSTL, custom tags, mavenLecture 5   JSTL, custom tags, maven
Lecture 5 JSTL, custom tags, maven
 
Jsp advance part i
Jsp advance part iJsp advance part i
Jsp advance part i
 
JSP Directives
JSP DirectivesJSP Directives
JSP Directives
 
JSP Technology I
JSP Technology IJSP Technology I
JSP Technology I
 
Servlet and jsp interview questions
Servlet and jsp interview questionsServlet and jsp interview questions
Servlet and jsp interview questions
 

Ähnlich wie Lap trinh web [Slide jsp]

Intro To Sap Netweaver Java
Intro To Sap Netweaver JavaIntro To Sap Netweaver Java
Intro To Sap Netweaver Java
Leland Bartlett
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 7 ...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 7 ...Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 7 ...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 7 ...
WebStackAcademy
 
3.jsp tutorial
3.jsp tutorial3.jsp tutorial
3.jsp tutorial
shiva404
 

Ähnlich wie Lap trinh web [Slide jsp] (20)

Introduction to JSP.pptx
Introduction to JSP.pptxIntroduction to JSP.pptx
Introduction to JSP.pptx
 
Jsp in Servlet by Rj
Jsp in Servlet by RjJsp in Servlet by Rj
Jsp in Servlet by Rj
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
Intro To Sap Netweaver Java
Intro To Sap Netweaver JavaIntro To Sap Netweaver Java
Intro To Sap Netweaver Java
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 7 ...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 7 ...Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 7 ...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 7 ...
 
3.jsp tutorial
3.jsp tutorial3.jsp tutorial
3.jsp tutorial
 
14 mvc
14 mvc14 mvc
14 mvc
 
J2EE jsp_03
J2EE jsp_03J2EE jsp_03
J2EE jsp_03
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Atul & shubha goswami jsp
Atul & shubha goswami jspAtul & shubha goswami jsp
Atul & shubha goswami jsp
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
 
JSP Components and Directives.pdf
JSP Components and Directives.pdfJSP Components and Directives.pdf
JSP Components and Directives.pdf
 
Jsp quick reference card
Jsp quick reference cardJsp quick reference card
Jsp quick reference card
 
Jsp1
Jsp1Jsp1
Jsp1
 
4. jsp
4. jsp4. jsp
4. jsp
 
ADP - Chapter 5 Exploring JavaServer Pages Technology
ADP - Chapter 5 Exploring JavaServer Pages TechnologyADP - Chapter 5 Exploring JavaServer Pages Technology
ADP - Chapter 5 Exploring JavaServer Pages Technology
 
Chap4 4 2
Chap4 4 2Chap4 4 2
Chap4 4 2
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
 
Introduction to jsp
Introduction to jspIntroduction to jsp
Introduction to jsp
 
Introduction to jsp
Introduction to jspIntroduction to jsp
Introduction to jsp
 

Kürzlich hochgeladen

Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Kürzlich hochgeladen (20)

FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
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
  • 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