0% found this document useful (0 votes)
105 views92 pages

4 JSP

The document discusses JavaServer Pages (JSP) which is an extension of servlet technology used for web content delivery and reuse of existing Java components without programming Java. It describes JSPs and servlets, the JSP lifecycle, implicit objects available in JSPs, and provides an example JSP that displays the current date and time by creating a Date object.

Uploaded by

Oussama ELMIR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
105 views92 pages

4 JSP

The document discusses JavaServer Pages (JSP) which is an extension of servlet technology used for web content delivery and reuse of existing Java components without programming Java. It describes JSPs and servlets, the JSP lifecycle, implicit objects available in JSPs, and provides an example JSP that displays the current date and time by creating a Date object.

Uploaded by

Oussama ELMIR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

JavaServer Pages

1 Introduction
2 JavaServer Pages Overview
3 First JavaServer Page Example
4 Implicit Objects
5 Scripting
5.1 Scripting Components
5.2 Scripting Example
6 Standard Actions
6.1 <jsp:include> Action
6.2 <jsp:forward> Action
6.3 <jsp:useBean> Action
7 Directives
7.1 include Directive
7.2 page Directive
7.3 EL and Custom Tag Libraries
8 Servlet and JSP Resources
1 Introduction

•  JavaServer Pages
–  Extension of Servlet technology
•  Web content delivery
•  Reuse existing Java components
–  Without programming Java
•  Create custom tags
–  Encapsulate complex functionality
•  Classes and interfaces specific to JSP
–  Package javax.servlet.jsp
–  Package javax.servlet.jsp.tagext
2 JavaServer Pages Overview (cont.)

•  JSPs
–  Look like standard HTML or XHTML
•  Normally include HTML or XHTML markup
–  Known as fixed-template data
–  Used when content is mostly fixed-template data
•  Small amounts of content generated dynamically (java
code)
•  Servlets
–  Used when small amount of content is fixed-
template data
•  Most content generated dynamically
2 JavaServer Pages Overview (cont.)

•  Some servlets do not produce content


–  Invoke other servlets and JSPs
•  JSPs execute as part of a Web server
–  JSP container
•  JSP first request
–  JSP container translates a JSP into a servlet
•  Handle the current and future requests
•  Same life cycle as a servlet
–  _jspService method à service method in servlet
–  _jspInit method à init method in servlet
–  _jspDestroy method à destroy method in servlet
Cycle de vie durant la phase d'exécution
3 A First JavaServer Page Example

•  Simple JSP example (Fig. 1)


–  Demonstrates
•  Fixed-template data (XHTML markup)
•  Creating a Java object (java.util.Date)
•  Automatic conversion of JSP expression to a String
•  meta element to refresh Web page at specified interval
–  First invocation of clock.jsp
•  Notice the delay while:
–  JSP container translates the JSP into a servlet
–  JSP container compiles the servlet
–  JSP container executes the servlet
•  Subsequent invocations should not experience the same delay
1 <?xml version = "1.0"?> Outline
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
6
<!-- Fig. 1: clock.jsp -->
Cock.jsp
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8
9
10
<head>
<meta http-equiv = "refresh" content = "60" />
Line 10
11 Meta
12 <title>A Simple JSP Example</title>
13 element
meta element refreshes the
14 <style type = "text/css">
15 .big { font-family: helvetica, arial, sans-serif; refershes
Web page every 60 seconds

the Web
16 font-weight: bold;
17 font-size: 2em; }

page
18 </style>
19 </head>

every 60
20
21 <body>

seconds.
22 <p class = "big">Simple JSP Example</p>
23
24 <table style = "border: 6px outset;"> Outline
25 <tr>
26 <td style = "background-color: black;">
27 <p class = "big" style = "color: cyan;">
28
Creates Date object that is
29 <!-- JSP expression to insert date/time -->
30 <%= new java.util.Date() %>
converted to a String
31
implicitly and displayed in
32 </p> paragraph (p) element
33 </td>
34 </tr> Clock.jsp
35 </table>
36 </body>

Line 30
37
38 </html>

Creates
Date
object
Outline

Clock.jsp
DEMO
Utilité des JSP

•  Création de pages "design"


•  Analyse de formulaires
•  Possibilité d’interfaçage avec de "vrais" servlets
•  Accès à toute classe Java mise à disposition
(notamment des "beans")
4 Implicit Objects
•  Implicit Objects
–  Provide access to many servlet capabilities within a JSP
–  Accessibles depuis la page JSP sans avoir besoin de les déclarer
préalablement
–  Déclarés et crées par le conteneur
–  Four scopes
•  Application scope
–  Objects owned by the container application
–  Any servlet or JSP can manipulate these objects
•  Page scope
–  Objects that exist only in page in which they are defined
–  Each page has its own instance of these objects
•  Request scope
–  Objects exist for duration of client request
–  Objects go out of scope after response sent to client
•  Session scope
–  Objects exist for duration of client’s browsing session
–  Objects go out of scope when client terminates session or when session timeout
occurs
Les objets implicites JSP

objet signification
HttpServletRequest l'objet à partir duquel on a accès à la requête du
request client Web (getParameter, getParameterNames,
getParameterValues)

HttpServletResponse l'objet avec lequel on peut construire la réponse


response du serveur Web à son client. Permet de fixer les
entêtes http à envoyer au client Web

JspWriter out le flux de sortie qui nous permet d'envoyer du


code HTML au client (print, println)
Implicit object   Description
Application Scope
application This javax.servlet.ServletContext object represents the container in which the JSP
executes.
Page Scope
config This javax.servlet.ServletConfig object represents the JSP configuration options.
As with servlets, configuration options can be specified in a Web application descriptor.
exception This java.lang.Throwable object represents the exception that is passed to the JSP error
page. This object is available only in a JSP error page.
out This javax.servlet.jsp.JspWriter object writes text as part of the response to a
request. This object is used implicitly with JSP expressions and actions that insert string content
in a response.
page This java.lang.Object object represents the this reference for the current JSP instance.

pageContext This javax.servlet.jsp.PageContext object hides the implementation details of the


underlying servlet and JSP container and provides JSP programmers with access to the implicit
objects discussed in this table.
response This object represents the response to the client and is normally an instance of a class that
implements HttpServletResponse (package javax.servlet.http). If a protocol
other than HTTP is used, this object is an instance of a class that implements
javax.servlet.ServletResponse.
Request Scope
request This object represents the client request. The object normally is an instance of a class that
implements HttpServletRequest (package javax.servlet.http). If a protocol other
than HTTP is used, this object is an instance of a subclass of javax.servlet.Servlet-
Request.
Session Scope
session This javax.servlet.http.HttpSession object represents the client session
information if such a session has been created. This object is available only in pages that
participate in a session.
Fig. 25.2 JSP implicit objects.
1 <?xml version = "1.0"?> Outline
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 4: welcome.jsp -->
6 <!-- JSP that processes a "get" request containing data. -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9
10 <!-- head section of document -->
11 <head>
12 <title>Processing "get" requests with data</title>
13 </head>
14
15 <!-- body section of document -->
16 <body>
17 <% // begin scriptlet
18
19 String name = request.getParameter( "firstName" );
20 Use request implicit
21 if ( name != null ) { object to get parameter
22
23 %> <%-- end scriptlet to insert fixed template data --%>
24
2 JavaServer Pages Overview

•  Key components
–  Scriptlets
–  Directives
–  Actions
–  Tag libraries
2 JavaServer Pages Overview (cont.)

•  Scriptlet
–  Also called “Scripting Elements”
–  Enable programmers to insert Java code in JSPs
–  Performs request processing
•  Interacts with page elements and other components to
implement dynamic pages
5.1 Scripting Components

•  JSP scripting components


–  Scriptlets (delimited by <% and %>)
–  Comments
•  JSP comments (delimited by <%-- and --%>)
•  XHTML comments (delimited by <!-- and -->)
•  Java’s comments (delimited by // and /* and */)
–  Expressions (delimited by <%= and %>)
–  Declarations (delimited by <%! And %>)
–  Escape sequences
Expressions
•  Les expressions JSP sont, des expressions Java qui vont être
évaluées à l'intérieur d'un appel de méthode print
•  Une expression commence par les caractères <%= et se termine
par les caractères %>
•  Comme l'expression est placée dans un appel de méthode, il est
interdit de terminer l'expression via un point-virgule

•  Syntaxe: <%=expression%>
•  Equivalent à: out.println(expression) ;

•  Exemple : <%=new Date()%>


•  Equivalent à: out.println(new Date()) ;
Déclarations
•  Dans certains cas, il est nécessaire d'ajouter des méthodes et des attributs à la
servlet qui va être générée (en dehors de la méthode de service).
•  Une construction JSP particulière permet de répondre à ces besoins. Elle
commence par les caractères <%! et se termine, par les caractères %>. Voici un
petit exemple d'utilisation.
•  Exemple:

<%@ page language="java" %>


<HTML>
<HEAD>
<TITLE>Exemple d'utilisation de déclarations JSP</TITLE>
<%! private int userCounter = 0; %>
</HEAD>
<BODY>
<H1 align="center">Exemple d'utilisation de déclarations JSP</H1><P>
Vous êtes le <%= ++userCounter %><SUP>ième</SUP> client du site</P>
</BODY>
<HTML>
5.2 Scripting Example

•  Demonstrate basic scripting capabilities


–  Responding to get requests
1 <?xml version = "1.0"?> Outline
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 4: welcome.jsp -->
6 <!-- JSP that processes a "get" request containing data. -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9
10
11
<!-- head section of document -->
<head>
welcome.
12 <title>Processing "get" requests with data</title> jsp
13 </head>
14

Lines 17-23
15 <!-- body section of document -->
16 <body>
17 <% // begin scriptlet
Scriptlets used to
18 insert Java code

Line 19
19 String name = request.getParameter( "firstName" );
20 Use request implicit
21 if ( name != null ) { object to get parameter
22
23 %> <%-- end scriptlet to insert fixed template data --%>
24
25 <h1> Outline
26 Hello <%= name %>, <br /> JSP expression
27 Welcome to JavaServer Pages!
28 </h1>
29
Scriptlets used to
30 <% // continue scriptlet
31
insert Java code
32 } // end if
33 else {
34
35 %> <%-- end scriptlet to insert fixed template data --%>
welcome.
36 jsp
37 <form action = "welcome.jsp" method = "get">
38 <p>Type your first name and press Submit</p>

Line 26
39
40 <p><input type = "text" name = "firstName" />
41 <input type = "submit" value = "Submit" />
42 </p>

Lines 30-35
43 </form>
44

and 45-49
45 <% // continue scriptlet
46
47 } // end else
48
49 %> <%-- end scriptlet --%>
50 </body>
51
52 </html> <!-- end XHTML document -->
Outline

welcome.
jsp
DEMO
2 JavaServer Pages Overview (cont.)

•  Delimited by <jsp:action> and </jsp:action>


•  JSP standard Actions
–  Predefined JSP tags that encapsulate functionality
–  Provide access to common tasks performed in a JSP
•  Including content from other resources
•  Forwarding requests to other resources <jsp:forward>
•  Interacting with JavaBeans
–  Often performed based on information from client request
–  Can be used to create Java objects for use in scriptlets
6 Standard Actions

Action   Description
<jsp:include> Dynamically includes another resource in a JSP. As the JSP executes, the
referenced resource is included and processed.
<jsp:forward> Forwards request processing to another JSP, servlet or static page. This
action terminates the current JSP’s execution.
<jsp:plugin> Allows a plug-in component to be added to a page in the form of a
browser-specific object or embed HTML element. In the case of a
Java applet, this action enables the downloading and installation of the
Java Plug-in, if it is not already installed on the client computer.
<jsp:param> Used with the include, forward and plugin actions to specify
additional name/value pairs of information for use by these actions.
JavaBean Manipulation
<jsp:useBean> Specifies that the JSP uses a JavaBean instance. This action specifies the
scope of the bean and assigns it an ID that scripting components can use
to manipulate the bean.
<jsp:setProperty> Sets a property in the specified JavaBean instance. A special feature of
this action is automatic matching of request parameters to bean properties
of the same name.
<jsp:getProperty> Gets a property in the specified JavaBean instance and converts the result
to a string for output in the response.
Fig. 25.5 JSP standard actions.
6.1 <jsp:include> Action

•  <jsp:include> action
–  E n a b l e s c o n t e n t t o b e
included in a JSP dynamically

Attribute Description
page Specifies the relative URI path of the resource
to include. The resource must be part of the
same Web application.
flush Specifies whether the buffer should be flushed
after the include is performed. In JSP 1.1,
this attribute is required to be true.
Fig. 25.6 Action <jsp:include> attributes.
1 <!-- Fig. 7: banner.html --> Outline
2 <!-- banner to include in another document -->
3 <div style = "width: 580px">
4 <p>
5 Java(TM), C, C++, Visual Basic(R),
6 Object Technology, and <br /> Internet and
7 World Wide Web Programming Training&nbsp;<br />
8 On-Site Seminars Delivered Worldwide
9 </p>
10
11 <p>
12 <a href = "mailto:deitel@deitel.com">deitel@deitel.com</a>
13 <br />978.461.5880<br />12 Clock Tower Place, Suite 200,
14 Maynard, MA 01754
15 </p>
16 </div> banner.html
1 <!-- Fig. 8: toc.html --> Outline
2 <!-- contents to include in another document -->
3
4 <p><a href = "http://www.deitel.com/books/index.html">
5 Publications/BookStore
6 </a></p>
7
8 <p><a href = "http://www.deitel.com/whatsnew.html">
9 What's New
10 </a></p>
11
12 <p><a href = "http://www.deitel.com/books/downloads.html">
13 Downloads/Resources
14 </a></p>
15
16 <p><a href = "http://www.deitel.com/faq/index.html">
17
18
FAQ (Frequently Asked Questions)
</a></p>
toc.html
19
20 <p><a href = "http://www.deitel.com/intro.html">
21 Who we are
22 </a></p>
23
24 <p><a href = "http://www.deitel.com/index.html"> Outline
25 Home Page
26 </a></p>
27
28 <p>Send questions or comments about this site to
29 <a href = "mailto:deitel@deitel.com">
30 deitel@deitel.com
31 </a><br />
32 Copyright 1995-2003 by Deitel &amp; Associates, Inc.
33 All Rights Reserved.
34 </p>

toc.html
1 <!-- Fig. 9: clock2.jsp --> Outline
2 <!-- date and time to include in another document -->
3
4 <table>
5 <tr>
6 <td style = "background-color: black;">
7 <p class = "big" style = "color: cyan; font-size: 3em;
8 font-weight: bold;">
9
10 <%-- script to determine client local and --%>
11 <%-- format date accordingly --%>
12 <% Use Locale to
13 // get client locale
format Date
14
15
java.util.Locale locale = request.getLocale(); clock2.j
with specified
16
17
// get DateFormat for client's Locale
java.text.DateFormat dateFormat =
sp
DateFormat

18 java.text.DateFormat.getDateTimeInstance(
19 java.text.DateFormat.LONG,
20
21
java.text.DateFormat.LONG, locale );
Lines 14-20
22 %> <%-- end script --%>
23
24 <%-- output date --%>
25 <%= dateFormat.format( new java.util.Date() ) %>
26 </p>
27 </td>
28 </tr>
29 </table>
1 <?xml version = "1.0"?> Outline
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10: include.jsp -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8
9 <head>
10 <title>Using jsp:include</title>
11
12 <style type = "text/css">
13 body {
14 font-family: tahoma, helvetica, arial, sans-serif;
15 } include.
16
17 table, tr, td { jsp
18 font-size: .9em;
19 border: 3px groove;
20 padding: 5px;
21 background-color: #dddddd;
22 }
23 </style>
24 </head>
25
26 <body> Outline
27 <table>
28 <tr>
29 <td style = "width: 160px; text-align: center">
30 <img src = "images/logotiny.png"
31 width = "140" height = "93"
32 alt = "Deitel & Associates, Inc. Logo" />
33 </td>
34
35 <td>
36
37 <%-- include banner.html in this JSP --%>
38 <jsp:include page = "banner.html" Use JSP action to
39 flush = "true" /> include banner.html
40
41 </td>
42 </tr>
43
44 <tr> Use JSP action to
45 <td style = "width: 160px"> include toc.html
46
47 <%-- include toc.html in this JSP --%>
48 <jsp:include page = "toc.html" flush = "true" />
49
50 </td>
51
52 <td style = "vertical-align: top"> Outline
53
54 <%-- include clock2.jsp in this JSP --%>
Use JSP action to
55 <jsp:include page = "clock2.jsp"
include clock2.jsp
56 flush = "true" />
57
58 </td>
59 </tr>
60 </table>
61 </body>
62 </html>
Exercice

•  Nous souhaitons reprendre le site de l’EMI avec la


technologie JSP en utilisant l’action Include.
–  Réaliser une Template incluant :
1.  Un Entête de page incluant
1.  Un document html pour le logo de l’école
2.  Un menu horizontal inclus dans toutes les pages
(Accueil, Ecole, Formation, …)
2.  Un Pied de page incluant
1.  Un document html pour Copyright
2.  Un menu horizontal inclus dans toutes les pages
(Accueil, Actualité, Accès-Contacts, Plan du site)
3.  Une zone Incluant le document principal
6.2 <jsp:forward> Action

•  <jsp:forward> action
–  Enables JSP to forward request to different resources
•  Can forwarded requests only resources in same context
•  <jsp:param> action
–  Specifies name/value pairs of information
•  Name/Value pairs are passed to other actions
1 <?xml version = "1.0"?> Outline
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 11: forward1.jsp -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8
9 <head>
10 <title>Forward request to another JSP</title>
11 </head>
12
13 <body>
14 <% // begin scriptlet
15
16 String name = request.getParameter( "firstName" );
17
18 if ( name != null ) {
19
20 %> <%-- end scriptlet to insert fixed template data --%>
21
Forward request to
22 <jsp:forward page = "forward2.jsp">
forward2.jsp
23 <jsp:param name = "date"
24 value = "<%= new java.util.Date() %>" />
25 </jsp:forward>
26
27 <% // continue scriptlet Outline
28
29 } // end if
30 else {
31
32 %> <%-- end scriptlet to insert fixed template data --%>
33
34 <form action = "forward1.jsp" method = "get">
35 <p>Type your first name and press Submit</p>
36
37 <p><input type = "text" name = "firstName" />
38 <input type = "submit" value = "Submit" />
39 </p>
40 </form>
41 forward1
42 <% // continue scriptlet
43 .jsp
44 } // end else
45
46 %> <%-- end scriptlet --%>
47 </body>
48
49 </html> <!-- end XHTML document -->
1 <?xml version = "1.0"?> Outline
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- forward2.jsp -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml"v
8
9 <head>
10 <title>Processing a forwarded request</title>
11
12 <style type = "text/css">
13 .big {
14 font-family: tahoma, helvetica, arial, sans-serif;
15 font-weight: bold;
16 font-size: 2em;
17 }
18 </style>
Receive request from
19 </head> forward1.jsp, then
20 get firstName
21 <body> parameter from request
22 <p class = "big">
23 Hello <%= request.getParameter( "firstName" ) %>, <br />
24 Your request was received <br /> and forwarded at
25 </p>
26
27 <table style = "border: 6px outset;"> Outline
28 <tr>
29 <td style = "background-color: black;">
30 <p class = "big" style = "color: cyan;">
Get date parameter
31 <%= request.getParameter( "date" ) %>
from request
32 </p>
33 </td>
34 </tr>
35 </table>
36 </body>
37
38 </html>
DEMO
6.3 <jsp:useBean> Action

•  <jsp:useBean> action
–  Enables JSP to manipulate Java object
•  Creates Java object or locates an existing object for use in JSP

Attribute   Description
id The name used to manipulate the Java object with actions
<jsp:setProperty> and <jsp:getProperty>. A variable of
this name is also declared for use in JSP scripting elements. The name
specified here is case sensitive.
scope The scope in which the Java object is accessible—page, request,
session or application. The default scope is page.
class The fully qualified class name of the Java object.
beanName The name of a bean that can be used with method instantiate of
class java.beans.Beans to load a JavaBean into memory.
type The type of the JavaBean. This can be the same type as the class
attribute, a superclass of that type or an interface implemented by that
type. The default value is the same as for attribute class. A
ClassCastException occurs if the Java object is not of the type
specified with attribute type.
Fig. 25.13 Attributes of the <jsp:useBean> action.
6.3 <jsp:useBean> Action (cont.)
Attribute Description
name The ID of the JavaBean for which a property (or properties) will be
set.
property The name of the property to set. Specifying "*" for this attribute
causes the JSP to match the request parameters to the properties of the
bean. For each request parameter that matches (i.e., the name of the
request parameter is identical to the bean’s property name), the
corresponding property in the bean is set to the value of the parameter.
If the value of the request parameter is "", the property value in the
bean remains unchanged.
param If request parameter names do not match bean property names, this
attribute can be used to specify which request parameter should be
used to obtain the value for a specific bean property. This attribute is
optional. If this attribute is omitted, the request parameter names must
match bean property names.
value The value to assign to a bean property. The value typically is the result
of a JSP expression. This attribute is particularly useful for setting
bean properties that cannot be set using request parameters. This
attribute is optional. If this attribute is omitted, the JavaBean property
must be of a type that can be set using request parameters.
Fig. 25.16 Attributes of the <jsp:setProperty> action.
1 // Fig. 14: Rotator.java Outline
2 // A JavaBean that rotates advertisements.
3 package com.deitel.jhtp5.jsp;
4
5 public class Rotator {
6 private String images[] = { "images/advjHTP1.jpg",
7 "images/cppHTP4.jpg", "images/iw3HTP2.jpg",
8 "images/jwsFEP1.jpg", "images/vbnetHTP2.jpg" };
9
10 private String links[] = {
11 "http://www.amazon.com/exec/obidos/ASIN/0130895601/" +
12 "deitelassociatin",
13 "http://www.amazon.com/exec/obidos/ASIN/0130384747/" +
14 "deitelassociatin", Rotator.
15 "http://www.amazon.com/exec/obidos/ASIN/0130308978/" +
16 "deitelassociatin", java
17 "http://www.amazon.com/exec/obidos/ASIN/0130461342/" +
18 "deitelassociatin",
19 "http://www.amazon.com/exec/obidos/ASIN/0130293636/" +
20 "deitelassociatin" };
21
22 private int selectedIndex = 0;
23
24 // returns image file name for current ad Outline
Return image file name
25 public String getImage()
26 { for book cover image
27 return images[ selectedIndex ];
28 }
29
30 // returns the URL for ad's corresponding Web site
Return hyperlink to
31 public String getLink()
32 {
book at Amazon.com
33 return links[ selectedIndex ];
34 }
35
36 // update selectedIndex so next calls to getImage and
Update Rotator so
37 // getLink return a different advertisement
subsequent calls to
38 public void nextAd()
39 {
getImage and getLink
40 selectedIndex = ( selectedIndex + 1 ) % images.length; return information for
41 } different advertisements
42 }
1 <?xml version = "1.0"?> Outline
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 15: adrotator.jsp -->
6
7 <jsp:useBean id = "rotator" scope = "application" Use jsp:useBean
8 class = "com.deitel.jhtp5.jsp.Rotator" /> action to obtain reference
9 to Rotator object
10 <html xmlns = "http://www.w3.org/1999/xhtml">
11
12 <head>
13 <title>AdRotator Example</title>
14
15 <style type = "text/css">
16 .big { font-family: helvetica, arial, sans-serif;
17 font-weight: bold;
18 font-size: 2em }
19 </style>
20
21 <%-- update advertisement --%>
Invoke
22 <% rotator.nextAd(); %>
Rotator’s
23 </head>
24
nextAd method
25 <body> Outline
26 <p class = "big">AdRotator Example</p>
27
Define hyperlink to
28 <p>
Amazon.com site
29 <a href = "<jsp:getProperty name = "rotator"
30 property = "link" />">
31
32 <img src = "<jsp:getProperty name = "rotator"
33 property = "image" />" alt = "advertisement" />
34 </a>
35 </p>
36 </body>
37 </html>
DEMO
Exercice

•  Créer une classe Personne


•  Créer une classe Groupe composée de plusieurs
personnes
–  Constructeur remplit une ArrayList de personnes
–  Utiliser un index pour se déplacer dans la ArrayList
–  Utiliser un String courant contenant le nom et prénom de
la personne pointée par index
•  Créer une page JSP permettant d’afficher la
personne à chaque mise à jour de la page
7 Directives

•  Directive
–  Message to JSP container
•  i.e., program that compiles/executes JSPs
–  Enable programmers to specify
1.  Content to include from other resources
2.  Page settings
3.  EL and Custom tag libraries used in the JSP

•  Delimited by <%@ and %>


7 Directives (cont.)

Directive Description
page Defines page settings for the JSP container to
process (global settings).
include Causes the JSP container to perform a translation-
time insertion of another resource’s content. As the
JSP is translated into a servlet and compiled, the
referenced file replaces the include directive and
is translated as if it were originally part of the JSP.
taglib Allows programmers to define new tags in the form
of tag libraries, which can be used to encapsulate
functionality and simplify the coding of a JSP.
Fig. 25.17 JSP directives.
7.1 include Directive

•  JSP include directive


–  Includes content of another resource at JSP translation time
•  Not as flexible as <jsp:include> action
1 <?xml version = "1.0"?> Outline
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 19: includeDirective.jsp -->
6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8
9 <head>
10 <title>Using the include directive</title>
11
12 <style type = "text/css">
13 body {
14 font-family: tahoma, helvetica, arial, sans-serif;
15 }
16
17 table, tr, td {
18 font-size: .9em;
19 border: 3px groove;
20 padding: 5px;
21 background-color: #dddddd;
22 }
23 </style>
24 </head>
25
26 <body> Outline
27 <table>
28 <tr>
29 <td style = "width: 160px; text-align: center">
30 <img src = "images/logotiny.png"
31 width = "140" height = "93"
32 alt = "Deitel & Associates, Inc. Logo" />
33 </td>
34
35 <td>
36
37 <%-- include banner.html in this JSP --%>
Use include directive to
38 <%@ include file = "banner.html" %>
include banner.html
39
40 </td>
41 </tr>
42
43 <tr>
44 <td style = "width: 160px">
45
46 <%-- include toc.html in this JSP --%>
Use include directive
47 <%@ include file = "toc.html" %>
to include toc.html
48
49 </td>
50
51 <td style = "vertical-align: top"> Outline
52
53 <%-- include clock2.jsp in this JSP --%>
Use include directive
54 <%@ include file = "clock2.jsp" %>
to include clock2.jsp
55
56 </td>
57 </tr>
58 </table>
59 </body>
60 </html>
7.1 Exercice

•  Reprendre l’exemple précédent concernant


l’action include avec la directive include

•  Quelles sont les conséquences de ce changement


au niveau :
–  Codage
–  Exécution
7.2 page Directive (cont.)

Attribute   Description
language The scripting language used in the JSP. Currently, the only valid value
for this attribute is java.
extends Specifies the class from which the translated JSP will be inherited. This
attribute must be a fully qualified class name.
import Specifies a comma-separated list of fully qualified type names and/or
packages that will be used in the current JSP. When the scripting
language is java, the default import list is java.lang.*,
javax.servlet.*, javax.servlet.jsp.* and
javax.servlet.http.*. If multiple import properties are
specified, the package names are placed in a list by the container.
session Specifies whether the page participates in a session. The values for this
attribute are true (participates in a session—the default) or false
(does not participate in a session). When the page is part of a session,
implicit object session is available for use in the page. Otherwise,
session is not available, and using session in the scripting code
results in a translation-time error.
Fig. 25.18 Attributes of the page directive.
7.2 page Directive (cont.)

Attribute  
Description
errorPage Any exceptions in the current page that are not caught
are sent to the error page for processing. The error page
implicit object exception references the original
exception.
isErrorPage Specifies if the current page is an error page that will be
invoked in response to an error on another page. If the
attribute value is true, the implicit object exception
is created and references the original exception that
occurred. If false (the default), any use of the
exception object in the page results in a translation-
time error.
contentType Specifies the MIME type of the data in the response to
the client. The default type is text/html.
Fig. 25.18 Attributes of the page directive.

See GuestBook
example for error page
management
7. 2 Case Study: Guest Book

•  Demonstrate
–  Action <jsp:setProperty>
–  JSP page directive
–  JSP error pages
–  Use of JDBC
7. 2 Case Study: Guest Book (Cont.)
7. 2 Case Study: Guest Book (Cont.)
1 // Fig. 20: GuestBean.java Outline
2 // JavaBean to store data for a guest in the guest book.
3 package com.deitel.jhtp5.jsp.beans;
4
5 public class GuestBean {
6 private String firstName, lastName, email;
7
8 // set the guest's first name
9 public void setFirstName( String name )
10 {
11 firstName = name;
12 } GuestBean defines three
13 guest properties: firstName,
14 // get the guest's first name lastName and email
15 public String getFirstName()
16 {
17 return firstName;
18 }
19
20 // set the guest's last name
21 public void setLastName( String name )
22 {
23 lastName = name;
24 }
25
26 // get the guest's last name Outline
27 public String getLastName()
28 {
29 return lastName;
30 }
31
32 // set the guest's email address
33 public void setEmail( String address )
34 {
35 email = address;
36 }
37
38 // get the guest's email address
39 public String getEmail()
40 {
41 return email; GuestBean.java
42 }
43 }
1 // Fig. 21: GuestDataBean.java Outline
2 // Class GuestDataBean makes a database connection and supports
3 // inserting and retrieving data from the database.
4 package com.deitel.jhtp5.jsp.beans;
5
6 // Java core packages
7 import java.io.*;
8 import java.sql.*;
9 import java.util.*;
10
11 public class GuestDataBean {
12 private Connection connection;
13 private PreparedStatement addRecord, getRecords;
14
Specify database location
15 // construct TitlesBean object
16 public GuestDataBean() throws Exception
17 {
18
Load Cloudscape
System.setProperty( "db2j.system.home", "C:/Cloudscape_5.0" );
driver
19
20 // load the Cloudscape driver
21 Class.forName( "com.ibm.db2j.jdbc.DB2jDriver" );
22
23 // connect to the database
GuestDataBean connects
24 connection = DriverManager.getConnection(
25 "jdbc:db2j:guestbook" );
to guestbook database
26
27 statement = connection.createStatement(); Outline
28 }
29
30 // return an ArrayList of GuestBeans
31 public ArrayList getGuestList() throws SQLException
32 {
33 ArrayList guestList = new ArrayList();
34
35 // obtain list of titles
36 ResultSet results = statement.executeQuery( GuestDataBean provides
37 "SELECT firstName, lastName, email FROM guests" );
method getGuestList to
38
manipulate database
39 // get row data
40 while ( results.next() ) {
41 GuestBean guest = new GuestBean();
42
43 guest.setFirstName( results.getString( 1 ) );
44 guest.setLastName( results.getString( 2 ) );
45 guest.setEmail( results.getString( 3 ) );
46
47 guestList.add( guest );
48 }
49
50 return guestList;
51 }
52
53 // insert a guest in guestbook database Outline
54 public void addGuest( GuestBean guest ) throws SQLException
55 {
56 statement.executeUpdate( "INSERT INTO guests ( firstName, " +
57 "lastName, email ) VALUES ( '" + guest.getFirstName() + "', '" +
58 guest.getLastName() + "', '" + guest.getEmail() + "' )" );
59 }
GuestDataBean provides
60
61 // close statements and terminate database connection
methods addGuest to
62 protected void finalize() manipulate database
63 {
64 // attempt to close database connection
65 try {
66 statement.close();
67 connection.close();
68 }
69
70 // process SQLException on close operation
71 catch ( SQLException sqlException ) {
72 sqlException.printStackTrace();
73 }
74 }
75 }
1 <?xml version = "1.0"?> Outline
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
page directive defines
5 <!-- Fig. 22: guestBookLogin.jsp -->
information that is
6
7 <%-- page settings --%>
globally available in JSP
8 <%@ page errorPage = "guestBookErrorPage.jsp" %>
9 Use jsp:useBean
10 <%-- beans used in this JSP --%>
actions to obtain references
11 <jsp:useBean id = "guest" scope = "page"
to GuestBean and
12 class = "com.deitel.jhtp5.jsp.beans.GuestBean" />
13 <jsp:useBean id = "guestData" scope = "request"
GuestDataBean objects
14 class = "com.deitel.jhtp5.jsp.beans.GuestDataBean" />
15
16 <html xmlns = "http://www.w3.org/1999/xhtml">
17
18 <head>
19 <title>Guest Book Login</title>
20
21 <style type = "text/css">
22 body {
23 font-family: tahoma, helvetica, arial, sans-serif;
24 }
25
26 table, tr, td { Outline
27 font-size: .9em;
28 border: 3px groove;
29 padding: 5px;
30 background-color: #dddddd;
31 }
32 </style>
33 </head>
34
35 <body>
36 <jsp:setProperty name = "guest" property = "*" />
37
Set properties of
38 <% // start scriptlet
GuestBean with request
39
40 if ( guest.getFirstName() == null ||
parameter values
41 guest.getLastName() == null ||
42 guest.getEmail() == null ) {
43
44 %> <%-- end scriptlet to insert fixed template data --%>
45
46 <form method = "post" action = "guestBookLogin.jsp">
47 <p>Enter your first name, last name and email
48 address to register in our guest book.</p>
49
50 <table> Outline
51 <tr>
52 <td>First name</td>
53
54 <td>
55 <input type = "text" name = "firstName" />
56 </td>
57 </tr>
58
59 <tr>
60 <td>Last name</td>
61
62 <td>
63 <input type = "text" name = "lastName" />
64 </td>
65 </tr>
66
67 <tr>
68 <td>Email</td>
69
70 <td>
71 <input type = "text" name = "email" />
72 </td>
73 </tr>
74
75 <tr> Outline
76 <td colspan = "2">
77 <input type = "submit"
78 value = "Submit" />
79 </td>
80 </tr>
81 </table>
82 </form>
83
84 <% // continue scriptlet
85
86 } // end if
87 else {
88 guestData.addGuest( guest );
89
90 %> <%-- end scriptlet to insert jsp:forward action --%>
91
92 <%-- forward to display guest book contents --%>
93 <jsp:forward page = "guestBookView.jsp" />
94
Forward request to
95 <% // continue scriptlet
guestBookView.jsp
96
97 } // end else
98
99 %> <%-- end scriptlet --%>
100 </body>
101
102</html>
1 <?xml version = "1.0"?> Outline
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 23: guestBookView.jsp --> Use page directive
6 import to specify Java
7 <%-- page settings --%> classes and packages that
8 <%@ page errorPage = "guestBookErrorPage.jsp" %>
are used in JSP context
9 <%@ page import = "java.util.*" %>
10 <%@ page import = "com.deitel.jhtp5.jsp.beans.*" %>
11
12 <%-- GuestDataBean to obtain guest list --%> Use jsp:useBean
13 <jsp:useBean id = "guestData" scope = "request" action to obtain reference
14 class = "com.deitel.jhtp5.jsp.beans.GuestDataBean" /> to GuestDataBean
15
16 <html xmlns = "http://www.w3.org/1999/xhtml">
17
18 <head>
19 <title>Guest List</title>
20
21 <style type = "text/css">
22 body {
23 font-family: tahoma, helvetica, arial, sans-serif;
24 }
25
26 table, tr, td, th { Outline
27 text-align: center;
28 font-size: .9em;
29 border: 3px groove;
30 padding: 5px;
31 background-color: #dddddd;
32 }
33 </style>
34 </head>
35
36 <body>
37 <p style = "font-size: 2em;">Guest List</p>
38
39 <table>
40 <thead>
41 <tr>
42 <th style = "width: 100px;">Last name</th>
43 <th style = "width: 100px;">First name</th>
44 <th style = "width: 200px;">Email</th>
45 </tr>
46 </thead>
47
48 <tbody>
49
50 <% // start scriptlet Outline
51 Scriptlet displays last
52 List guestList = guestData.getGuestList(); name, first name and email
53 Iterator guestListIterator = guestList.iterator(); address for all guests
54 GuestBean guest;
55
56 while ( guestListIterator.hasNext() ) {
57 guest = ( GuestBean ) guestListIterator.next();
58
59 %> <%-- end scriptlet; insert fixed template data --%>
60
61 <tr>
62 <td><%= guest.getLastName() %></td>
63
64 <td><%= guest.getFirstName() %></td>
65
66 <td>
67 <a href = "mailto:<%= guest.getEmail() %>">
68 <%= guest.getEmail() %></a>
69 </td>
70 </tr>
71
72 <% // continue scriptlet Outline
73
74 } // end while
75
76 %> <%-- end scriptlet --%>
77
78 </tbody>
79 </table>
80 </body>
81
82 </html>
1 <?xml version = "1.0"?> Outline
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 24: guestBookErrorPage.jsp --> Use page directive
6 isErrorPage to specify
7 <%-- page settings --%> that guestBookError-
8 <%@ page isErrorPage = "true" %>
Page is an error page
9 <%@ page import = "java.util.*" %>
10 <%@ page import = "java.sql.*" %>
11
12 <html xmlns = "http://www.w3.org/1999/xhtml">
13
14 <head>
15 <title>Error!</title>
16
17 <style type = "text/css">
18 .bigRed {
19 font-size: 2em;
20 color: red;
21 font-weight: bold;
22 }
23 </style>
24 </head>
25
26 <body> Outline
27 <p class = "bigRed">
28
29 <% // scriptlet to determine exception type
30 // and output beginning of error message Use implicit object
31 if ( exception instanceof SQLException ) exception to determine
32 %> error to be displayed
33
34 An SQLException
35
36 <%
37 else if ( exception instanceof ClassNotFoundException )
38 %>
39
40 A ClassNotFoundException
41
42 <%
43 else
44 %>
45
46 An exception
47
48 <%-- end scriptlet to insert fixed template data --%>
49
50 <%-- continue error message output --%> Outline
51 occurred while interacting with the guestbook database.
52 </p>
53
54 <p class = "bigRed">
55 The error message was:<br />
56 <%= exception.getMessage() %>
57 </p>
58
59 <p class = "bigRed">Please try again later</p>
60 </body>
61
62 </html>
DEMO
7. 2 Exercice

•  Reprenez l’exemple précédent utilisant la classe Personne


7. 3 Expression language

•  Permet d'accéder plus facilement aux données de


l'application ainsi qu'aux composants JavaBeans
<c:if test="${sessionScope.cart.numberOfItems > 0}">
… </c:if>
•  Ces expressions sont évaluées par le "JSP expression
evaluator"
•  Pour activer/désactiver cette fonctionnalité
<%@page isELIgnored="true|false"% >
•  Destiné à remplacer l'utilisation des scriptlets
7. 3 Comparatif EL / Scriptlet
exemple qui utilise
c:if, c:foreach, request, scope

<center>
<jsp:useBean id= "person" class="Person" />
<%=person.getName()%>
</center>
<center>
${person.name}
</center>
7. 3 Custom Tag Library

•  Custom Tag Library


–  JSP’s tag extension mechanism
–  Enables programmers to define new tags
•  Tags encapsulate complex functionality
•  New tags should be defined in an archive library file
–  Tags can manipulate JSP content
7.3 Custom Tag librairies - Principes

•  Le programmeur définit la syntaxe pour chaque balise et


implémente le comportement associé à chaque balise dans
la classe de gestion des balises (tag handler class)
•  Il décrit ensuite la librairie de balises qu'il vient de créer via
un Tag library descriptor (*.tld)
•  Les auteurs de pages peuvent ensuite importer et utiliser les
balises définies dans les bibliothèques de balises comme
s'ils utilisaient des balises standards
–  Déclaration d'utilisation via <%@taglib…%>
–  Utilisation via <%prefix:name….%>
7.3 Custom Tag librairies -Principes

•  Spécifier dans la page JSP qu'on souhaite utiliser


une librairie de balises via la directive

<%@ taglibprefix=”tagPrefix”( uri=”tagLibraryURI”| tagdir=”tagDir”) %>

/WEB-INF/tags/dir

•  On associe à cette déclaration d'utilisation


l'emplacement du fichier de description de la
librairie de balises, fichier *.tld et un préfixe
identifiant la librairie de balises
7.3 Custom Tag librairies - Syntaxe
d'invocation des balises dans les pages JSP

<prefix:tag attr1="value" ... attrN="value" />

<prefix:tag attr1="value" ... attrN="value" >


body
</prefix:tag>
Avec
•  prefix : qui identifie la librairie concernée
•  tag : qui identifie une balise particulière à
l'intérieur de la librairie
•  attr1 ... attrN : qui permet de modifier le
comportement de la balise
7.3 Custom Tag librairies –
Exemple de code JSP

<!DOCTYPE HTML PUBLIC "-//w3c//dtd html 4.0 transitional//en">


<html>
<head>
<%@ taglib uri="/WEB-INF/msajsp-taglib.tld" prefix="msajsp"%>
<title> <msajsp:example1 /> </title>
</head>
<body bgcolor="#FFFFFF">
<h1> <msajsp:example2 /> </h1>
<msajsp:example3/>
</body>
</html>
DEMO
Résumé (scriplet, action, directive)

•  Les données statiques sont transformées en code


d'écriture sur le flot de sortie associé à la réponse
•  Les éléments JSP sont traités différemment
–  Les éléments de scripts sont insérés dans le code de la servlet
issu de la page JSP
–  Les éléments d'action sont convertis en appels de méthodes
sur des composants JavaBean, ou en invocation de l'API
Servlet
–  Les directives sont utilisées pour contrôler la façon dont le
conteneur Web traduit et exécute la page
JSP et Servlet

•  Vous pouvez utiliser le modèle MVC (Modèle Vue Contrôleur).


Chaque URL invoque une servlet
•  Les servlets ont pour but de construire les objets JavaBeans chargés
de prendre en charge la logique métier
•  Ensuite, le contrôleur (la servlet) donne la main à la vue (la JSP) qui
devra se charger de construire la réponse HTML
•  Pour ce faire, la JSP utilisera les JavaBeans, par l'intermédiaire des
actions JSP

•  C'est la servlet qui connaît sa JSP associée


•  Une page JSP est une servlet
Exercice

•  Reprenez l’exemple précédent utilisant la classe


Personne
•  Créez une Servlet capable de se connecter à la
base de donnée afin de récupérer les données des
personnes et créer un groupe de personne (Ref. un
des exercices sur les servlets)
•  Faite les modifications nécessaires pour faire
fonctionner l’ensemble de façon que
–  La servlet réponde à la requête utilisateur
–  La servlet crée une liste de personnes
–  La page JSP affiche la liste.
8 Servlet and JSP Resources

•  JSP at Sun Microsystems


–  java.sun.com/products/jsp
•  Servlets at Sun Microsystems
–  java.sun.com/products/servlet
•  J2EE at Sun Microsystems
–  java.sun.com/j2ee

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy