Title: Programmation des Applications Internet Internet Application Programming JavaServer Pages These slid
1Programmation des Applications Internet Internet
Application Programming JavaServer PagesThese
slides and case studies can be downloaded from
www.PauWare.com/MTI
2What is JSP?
- A JSP page is a server-side Web page. Such a page
is translated by a Web server into Web browser
interpretable code (HTML) - A JSP page is in fact translated into a servlet
at deployment time - A JSP page contains both common static data
(HTML) and JSP-specific elements to create
dynamic content - Based on the Unified Expression Language (UEL),
JSP is a more natural and efficient way for
writing pages, compared to having Java code in
pages, i.e., lt / Java statements here / gt - Contrary to servlets, JSP avoids the mixing
between control code and display code
3Common issues
- Common files extensions
- .jsp -gt standard JSP page
- .jspf -gt JSP page fragment
- .jspx -gt JSP XML-compliant page
- JSP promotes extensibility through tag libraries
especially (.tld files), connectivity with Java
code (beans) - JSP shares most of the mechanisms associated with
servelts configurations, filters, listeners - Example of configuration
- ltservletgt
- ltservlet-namegtliste_detenuslt/servlet-namegt
- ltjsp-filegt/liste_detenus.jsplt/jsp-filegt
- lt/servletgt
-
- ltservlet-mappinggt
- ltservlet-namegtliste_detenuslt/servlet-namegt
- lturl-patterngt/Liste_detenuslt/url-patterngt
- lt/servlet-mappinggt
4JSP page contents
- JSP page header
- lt_at_page contentType"text/html"
pageEncoding"UTF-8"gt - Comment
- lt-- this is a comment --gt
- UEL expressions
- lth1gtCréation détenu, session id.
pageContext.session.idlt/h1gt - lt-- get_id getter is required --gt
- JSP elements
- ltjspsetProperty name"une_personne"
property"initiales" value"FB"/gt /gt - lt-- getInitiales getter is required --gt
5Dealing with simple objects (beans)
- ltjspuseBean id"date_incarceration"
class"com.FranckBarbier.Java._Prison_de_Nantes._U
tilities.Time_Date scope"session"/gt - ltjspgetProperty name"date_incarceration"
property"_value"/gt - Java source code
- package com.FranckBarbier.Java._Prison_de_Nantes._
Utilities - public class Time_Date
- private java.sql.Timestamp _timestamp
- public Time_Date()
- _timestamp new java.sql.Timestamp(java.util.Cale
ndar.getInstance().getTimeInMillis()) -
- public String get_value()
- return java.text.DateFormat.getDateInstance(java.t
ext.DateFormat.FULL).format(_timestamp) -
- public String toString()
- return get_value()
-
6Bean capabilities
- Possible scopes are application, session,
request and page (default) - Beans automatically benefit from being
thread-safe - Bean suppression
- session.removeAttribute("date_incarceration")
- Beans are accessible and usable in UEL expressions
7Unified Expression Language (UEL)
- The need for putting aside, as much as possible,
Java code in pages has led to create and use UEL - To be avoided
- lt any Java code here gt
- Examples of a UEL expression (one displays a list
of items if and only if this list is not empty) - ltcif test"not empty applicationScope.Prison_de
_Nantes_Database._detenu_allInstances"gt -
- lt/cifgt
8UEL, foundations
- Immediate evaluation -gt expression (see also
JavaServer Faces) - Deferred evaluation -gt expression
- Reserved keywords and or not eq ne lt gt le ge
true false null instanceof empty div mod - UEL inhibition (for compatibility)
- ltel_ignoredgt (web.xml)
- lt_at_page isELIgnored"true"gt
- Request parameters
- empty param -gt true if no parameters
- empty param.X -gt true if the X parameter does
not exist - param"X" -gt X parameter itself
9Predefined objects in JSP pages
- Scoped objects
- applicationScope
- sessionScope
- requestScope
- pageScope
- pageContext
- pageContext.serveltContext
- pageContext.sessionContext
- pageContext.request
- pageContext.response
10Accessing to request attributes
- Emitting servelt
- request.setAttribute("entete_detenu_cree", "Le
détenu identifié par " detenu.get_n_ecrou() "
existe déjà") - Receiving JSP page
- lth3gtltcout value"requestScope.entete_detenu_cre
e"/gtlt/h3gt
11initParam implicit variable
- Usage
- lth6gtParamètre ltigtAuteurlt/igt défini dans
ltigtweb.xmllt/igt avec la balise ltigtltcontext-param
gtlt/igt ltcout value"initParam.Auteur"/gt - lt/h6gt
- Configuration (web.xml file)
- ltcontext-paramgt
- ltparam-namegtAuteurlt/param-namegt
- ltparam-valuegtFranck Barbierlt/param-valuegt
- lt/context-paramgt
12Getting data in pages
- Defining the destination of a forthcoming page
- ltform name"creation_incarceration"
action"pageContext.request.contextPath/Incarce
ration"gt - Getting the value of the detenu_allInstances
locally defined variable - ltcset var"detenu_allInstances"
value"applicationScope.Prison_de_Nantes_Databas
e._affaire_allInstances"/gt -
- ltcwhen test"not empty detenu_allInstances and
not empty affaire_allInstances"gt - Getting the value of a locally defined bean
- ltjspuseBean id"date_incarceration"
class"com.FranckBarbier.Java._Prison_de_Nantes._U
tilities.Time_Date" scope"session"/gt -
- sessionScope.date_incarceration
13Using functions in EL expressions
- Functions are static methods
- Functions are statically identified and located
as follows _at_taglib prefix"f" uri"/functions" - Example
- _at_taglib prefix"Prison_de_Nantes"
uri"/WEB-INF/Prison_de_Nantes_functions" - Tag lib file
- lttaglib version"2.0" xmlns"http//java.sun.com/x
ml/ns/j2ee" xmlnsxsi"http//www.w3.org/2001/XMLS
chema-instance" xsischemaLocation"http//java.su
n.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd"gt - lttlib-versiongt1.0lt/tlib-versiongt
- ltshort-namegtPrison_de_Nanteslt/short-namegt
- lturigt/WEB-INF/Prison_de_Nantes_functionslt/urigt
- ltfunctiongt
- ltnamegtNombre_de_detenus_crees_dans_sessionlt/namegt
- ltfunction-classgtcom.FranckBarbier.Java._Prison_de_
Nantes.Prison_de_Nanteslt/function-classgt - ltfunction-signaturegtString Nombre_de_detenus_crees
_dans_session()lt/function-signaturegt - lt/functiongt
-
14Connectivity ot other pages
- Including pages
- ltjspinclude page"/Prison_de_Nantes_banniere"/gt
- Forwarding pages
- ltjspforward
- Dispatching statements may support UEL expressions
15JavaServer Pages Standard Tag Library (JSTL)
- JSTL is a predefined (optional) library of useful
tags that is often used in JSP pages - JSTL is implemented and embodied by Java
third-party libraries (standard.jar and jstl.jar)
-gt to be included in WEB-INF/lib - Note GlassFish automatically makes JSTL
available for every Web applications through the
appserv-jstl.jar (proprietary) file
16JSTL elements
- Core
- lt_at_taglib uri"http//java.sun.com/jsp/jstl/core"
prefix"c"gt - Internationalization
- lt_at_taglib uri"http//java.sun.com/jsp/jstl/fmt"
prefix"fmt"gt - Database
- lt_at_taglib uri"http//java.sun.com/jsp/jstl/sql"
prefix"sql"gt - XML
- lt_at_taglib uri"http//java.sun.com/jsp/jstl/xml"
prefix"x"gt - Functions
- lt_at_taglib uri"http//java.sun.com/jsp/jstl/functi
ons" prefixfn"gt
17JSTL core
- cif, cchoose, cwhen, cothewise, cforEach,
cforTokens - cset, cremove, cout, ccatch
- cimport, curl, credirect, cparam
- Example
- ltccatch var"e"gt
- ltcset var"detenu_allInstances"
value"applicationScope.Prison_de_Nantes_Databas
e._detenu_allInstances"/gt - ltcset var"affaire_allInstances"
value"applicationScope.Prison_de_Nantes_Databas
e._affaire_allInstances"/gt - lt/ccatchgt
- ltcif test"e ne null"gt
- lth2gtException e.messagelt/h2gt
- lt/cifgt
18Displaying a list of objects
- ltcif test"not empty applicationScope.Prison_de
_Nantes_Database._detenu_allInstances"gt - lttable border"2"gt
- lttheadgt
- lttrgt
- ltthgtDétenult/thgt
- lt/trgt
- lt/theadgt
- lttbodygt
- ltcforEach var"detenu" items"applicationScope.
Prison_de_Nantes_Database._detenu_allInstances"gt - lttrgt
- lttdgtltcout value"detenu"/gtlt/tdgt
- lt/trgt
- lt/cforEachgt
- lt/tbodygt
- lt/tablegt
- lt/cifgt
19JSTL control statements, samples
- ltcchoosegt
- ltcwhen test"not empty detenu_allInstances and
not empty affaire_allInstances"gt - ltselect name"choix_detenu" size"1"gt
- ltcforEach var"detenu" items"detenu_allInstanc
es"gt - ltoption value"detenu"gtdetenult/optiongt
- lt/cforEachgt
- lt/selectgt
- ltselect name"choix_affaire" size"1"gt
- ltcforEach var"affaire" items"affaire_allInsta
nces"gt - ltoption value"affaire"gtaffairelt/optiongt
- lt/cforEachgt
- lt/selectgt
- ltjspgetProperty name"date_incarceration"
property"_value"/gt - lt/cwhengt
- ltcotherwisegt
- lth2gtIl n'y a de données disponibles concernant
les détenus et/ou les affaires pour procéder à
une incarcérationlt/h2gt - lt/cotherwisegt
- lt/cchoosegt
20JSTL internationalization
- Locale management fmtmessage, fmtsetLocale
- Formatting (relating to locales)
fmtformatNumber, fmtformatDate - Example
- ltjspuseBean id"date_incarceration"
class"java.util.Date" scope"session"/gt - ltfmtformatDate value"date_incarceration"
type"date" dateStyle"full" var"date_incarcerati
on_formatee"/gt -
- ltcout value"date_incarceration_formatee"/gt
21Connecting to databases in pages
- Although the direct access to databases is
possible in pages, such an approach may be
considered as obsolete. Page setting up - _at_taglib prefix"sql" uri"http//java.sun.com/jsp
/jstl/sql" - Database request example
- ltsqlquery var"detenus" dataSource"jdbc/Prison_d
e_Nantes"gt - select from DETENU
- lt/sqlquerygt
22Concurrent access
- lt_at_page isThreadSafe"false"gt lt-- default value
is "true"--gt - Compensations
- public class Counter
- private int _counter 0
- public synchronized int get_counter()
- return _counter
-
- public synchronized int set_counter(int counter)
- _counter counter
- return _counter
-
- public synchronized int increment()
- return _counter
-
23Custom tags
- A custom tag is a user-defined JSP new element
- Custom tags both accept incoming data from pages
and may pass data back to pages - Tags may have attributes or not attributes have
the possible following types - Simple
- Fragment
- Dynamic
24Tag file
- File location /WEB-INF/tags
- File name Prison_de_Nantes.tag (the file name is
the name of the tag!) - Content
- lt_at_tag description"Prison_de_Nantes.tag"
pageEncoding"UTF-8"gt - lt_at_tag body-content"empty"gt
- lt_at_attribute name"couleur" required"false"gt
- lt_at_attribute name"police" required"false"gt
- lt_at_attribute name"theme" required"false"gt
- lth1 style"colorcouleur font-stylepolice"
gtCreacuteation themelt/h1gt - Usage (tag declaration)
- lt_at_ taglib prefix"PN" tagdir"/WEB-INF/tags" gt
- ltPNPrison_de_Nantes couleur"red"
police"italic" theme"deacutetenu"/gt
25More complex tag file (1/2)
- Usage
- lt_at_taglib prefix"PN" tagdir"/WEB-INF/tags" gt
-
- ltPNN_ecrou n_ecrou_max"2008" n_ecrou_aleatoire"
x"/gt -
- Saisir nécrou ltinput type"text"
name"n_ecrou" value"x"/gt - N_ecrou.tag file (v. 1)
- lt_at_tag body-content"empty" description"N_ecrou.t
ag" example"ltPNN_ecrou n_ecrou_max\"2008\"
n_ecrou_aleatoire\"x\"/gt"gt - lt_at_attribute name"n_ecrou_max"
type"java.lang.Integer"gt - lt_at_attribute name"n_ecrou_aleatoire"
required"true" rtexprvalue"false"gt - lt_at_variable name-given"x" scope"AT_BEGIN"gt
- lt
- Integer max 0
- max (Integer) jspContext.getAttribute("n_ecrou_m
ax") - jspContext.setAttribute("x", com.FranckBarbier.Jav
a._Prison_de_Nantes.Prison_de_Nantes.n_ecrou(max).
toString()) - gt
26Called method in custom tag
- public class Prison_de_Nantes
-
- public static Integer n_ecrou(Integer max)
- if (max null)
- return new java.util.Random().nextInt(java.util.Ca
lendar.getInstance().get(java.util.Calendar.YEAR))
-
- return new java.util.Random().nextInt(max)
-
27More complex tag file (2/2)
- Same usage
- lt_at_taglib prefix"PN" tagdir"/WEB-INF/tags" gt
-
- ltPNN_ecrou n_ecrou_max"2008" n_ecrou_aleatoire"
x"/gt -
- Saisir nécrou ltinput type"text"
name"n_ecrou" value"x"/gt - N_ecrou.tag file (v. 2)
- lt_at_tag body-content"empty" description"N_ecrou.t
ag" example"ltPNN_ecrou n_ecrou_max\"2008\"
n_ecrou_aleatoire\"x\"/gt"gt - lt_at_attribute name"n_ecrou_max"
type"java.lang.Integer"gt - lt_at_attribute name"n_ecrou_aleatoire"
required"true" rtexprvalue"false"gt - lt_at_variable name-from-attribute"n_ecrou_aleatoire
" alias"y" scope"AT_BEGIN"gt - lt
- Integer max 0
- max (Integer) jspContext.getAttribute("n_ecrou_m
ax") - jspContext.setAttribute("y", com.FranckBarbier.Jav
a._Prison_de_Nantes.Prison_de_Nantes.n_ecrou(max).
toString()) - gt
Synchronized according to scope values NESTED
(default), AT_BEGIN and AT_END
28Tag files as library elements
- Prison_de_Nantes.tld file
- lttag-filegt
- ltnamegtN_ecroult/namegt
- ltpathgt/WEB-INF/tags/N_ecrou.taglt/pathgt
- lt/tag-filegt
29JavaServer Faces
- JavaServer Faces (JSF) is in fact an extended
(normalized) use of custom tags within JSP - JSF is based on an enhanced MVC framework like
Struts for example - JSF automates most of the recurrent tasks of Web
appplications design (navigation, validations) - Tag libraries
- lt_at_taglib uri"http//java.sun.com/jsf/core"
prefix"f"gt - lt_at_taglib uri"http//java.sun.com/jsf/html"
prefix"h"gt - Configuration faces-config.xml file
30JSF demo.
- See Prison_de_Nantes NetBeans Web application
project