Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
JavaServer Pages 1 2 3 4 5 Introduction JavaServer Pages Overview First JavaServer Page Example Implicit Objects 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 fixedtemplate 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 1: clock.jsp --> Outline Cock.jsp <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <meta http-equiv = "refresh" content = "60" /> <title>A Simple JSP Example</title> <style type = "text/css"> .big { font-family: helvetica, arial, sans-serif; font-weight: bold; font-size: 2em; } </style> </head> <body> <p class = "big">Simple JSP Example</p> Line 10 Meta element meta element refreshes the Web page every 60 seconds refershes the Web page every 60 seconds. 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 <table style = "border: 6px outset;"> <tr> <td style = "background-color: black;"> <p class = "big" style = "color: cyan;"> <!-- JSP expression to insert date/time --> <%= new java.util.Date() %> </p> </td> </tr> </table> </body> </html> Outline Creates Date object that is converted to a String implicitly and displayed in paragraph (p) element Clock.jsp Line 30 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 request l'objet à partir duquel on a accès à la requête du client Web (getParameter, getParameterNames, getParameterValues) HttpServletResponse response l'objet avec lequel on peut construire la réponse 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 Application Scope Description 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. 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. 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. This java.lang.Object object represents the this reference for the current JSP instance. exception out page pageContext response Request Scope request Session Scope session Fig. 25.2 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. 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. 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.ServletRequest. 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. JSP implicit objects. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 4: welcome.jsp --> <!-- JSP that processes a "get" request containing data. --> <html xmlns = "http://www.w3.org/1999/xhtml"> <!-- head section of document --> <head> <title>Processing "get" requests with data</title> </head> <!-- body section of document --> <body> <% // begin scriptlet String name = request.getParameter( "firstName" ); if ( name != null ) { Use request implicit object to get parameter %> <%-- end scriptlet to insert fixed template data --%> Outline 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> Outline <!-- Fig. 4: welcome.jsp --> <!-- JSP that processes a "get" request containing data. --> <html xmlns = "http://www.w3.org/1999/xhtml"> <!-- head section of document --> <head> <title>Processing "get" requests with data</title> </head> <!-- body section of document --> <body> <% // begin scriptlet Scriptlets used to insert Java code String name = request.getParameter( "firstName" ); if ( name != null ) { Use request implicit object to get parameter %> <%-- end scriptlet to insert fixed template data --%> welcome. jsp Lines 17-23 Line 19 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 <h1> Hello <%= name %>, <br /> Welcome to JavaServer Pages! </h1> JSP expression <% // continue scriptlet } // end if else { %> <%-- end scriptlet to insert fixed template data --%> <form action = "welcome.jsp" method = "get"> <p>Type your first name and press Submit</p> <p><input type = "text" name = "firstName" /> <input type = "submit" value = "Submit" /> </p> </form> <% // continue scriptlet } // end else %> <%-- end scriptlet --%> </body> </html> <!-- end XHTML document --> Outline Scriptlets used to insert Java code welcome. jsp Line 26 Lines 30-35 and 45-49 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 <jsp:include> <jsp:forward> <jsp:plugin> <jsp:param> JavaBean Manipulation <jsp:useBean> Description Dynamically includes another resource in a JSP. As the JSP executes, the referenced resource is included and processed. Forwards request processing to another JSP, servlet or static page. This action terminates the current JSP’s execution. 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. Used with the include, forward and plugin actions to specify additional name/value pairs of information for use by these actions. 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 page flush Fig. 25.6 Description Specifies the relative URI path of the resource to include. The resource must be part of the same Web application. Specifies whether the buffer should be flushed after the include is performed. In JSP 1.1, this attribute is required to be true. Action <jsp:include> attributes. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <!-- Fig. 7: banner.html --> <!-- banner to include in another document --> <div style = "width: 580px"> <p> Java(TM), C, C++, Visual Basic(R), Object Technology, and <br /> Internet and World Wide Web Programming Training <br /> On-Site Seminars Delivered Worldwide </p> <p> <a href = "mailto:[email protected]">[email protected]</a> <br />978.461.5880<br />12 Clock Tower Place, Suite 200, Maynard, MA 01754 </p> </div> Outline banner.html 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <!-- Fig. 8: toc.html --> <!-- contents to include in another document --> Outline <p><a href = "http://www.deitel.com/books/index.html"> Publications/BookStore </a></p> <p><a href = "http://www.deitel.com/whatsnew.html"> What's New </a></p> <p><a href = "http://www.deitel.com/books/downloads.html"> Downloads/Resources </a></p> <p><a href = "http://www.deitel.com/faq/index.html"> FAQ (Frequently Asked Questions) </a></p> <p><a href = "http://www.deitel.com/intro.html"> Who we are </a></p> toc.html 24 25 26 27 28 29 30 31 32 33 34 <p><a href = "http://www.deitel.com/index.html"> Home Page </a></p> Outline <p>Send questions or comments about this site to <a href = "mailto:[email protected]"> [email protected] </a><br /> Copyright 1995-2003 by Deitel & Associates, Inc. All Rights Reserved. </p> toc.html 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <!-- Fig. 9: clock2.jsp --> <!-- date and time to include in another document --> Outline <table> <tr> <td style = "background-color: black;"> <p class = "big" style = "color: cyan; font-size: 3em; font-weight: bold;"> <%-- script to determine client local and --%> <%-- format date accordingly --%> <% // get client locale java.util.Locale locale = request.getLocale(); // get DateFormat for client's Locale java.text.DateFormat dateFormat = java.text.DateFormat.getDateTimeInstance( java.text.DateFormat.LONG, java.text.DateFormat.LONG, locale ); %> <%-- end script --%> <%-- output date --%> <%= dateFormat.format( new java.util.Date() ) %> </p> </td> </tr> </table> Use Locale to format Date with specified DateFormat clock2.j sp Lines 14-20 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> Outline <!-- Fig. 10: include.jsp --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Using jsp:include</title> <style type = "text/css"> body { font-family: tahoma, helvetica, arial, sans-serif; } table, tr, td { font-size: .9em; border: 3px groove; padding: 5px; background-color: #dddddd; } </style> </head> include. jsp 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 <body> <table> <tr> <td style = <img src width alt = </td> Outline "width: 160px; text-align: center"> = "images/logotiny.png" = "140" height = "93" "Deitel & Associates, Inc. Logo" /> <td> <%-- include banner.html in this JSP --%> <jsp:include page = "banner.html" flush = "true" /> Use JSP action to include banner.html </td> </tr> <tr> <td style = "width: 160px"> <%-- include toc.html in this JSP --%> <jsp:include page = "toc.html" flush = "true" /> </td> Use JSP action to include toc.html 52 53 54 55 56 57 58 59 60 61 62 <td style = "vertical-align: top"> <%-- include clock2.jsp in this JSP --%> <jsp:include page = "clock2.jsp" flush = "true" /> </td> </tr> </table> </body> </html> Outline Use JSP action to include clock2.jsp 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 Outline <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 11: forward1.jsp --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Forward request to another JSP</title> </head> <body> <% // begin scriptlet String name = request.getParameter( "firstName" ); if ( name != null ) { %> <%-- end scriptlet to insert fixed template data --%> <jsp:forward page = "forward2.jsp"> <jsp:param name = "date" value = "<%= new java.util.Date() %>" /> </jsp:forward> Forward request to forward2.jsp 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 <% // continue scriptlet Outline } // end if else { %> <%-- end scriptlet to insert fixed template data --%> <form action = "forward1.jsp" method = "get"> <p>Type your first name and press Submit</p> <p><input type = "text" name = "firstName" /> <input type = "submit" value = "Submit" /> </p> </form> <% // continue scriptlet } // end else %> <%-- end scriptlet --%> </body> </html> <!-- end XHTML document --> forward1 .jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 Outline <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- forward2.jsp --> <html xmlns = "http://www.w3.org/1999/xhtml"v <head> <title>Processing a forwarded request</title> <style type = "text/css"> .big { font-family: tahoma, helvetica, arial, sans-serif; font-weight: bold; font-size: 2em; } </style> </head> Receive request from forward1.jsp, then get firstName parameter from request <body> <p class = "big"> Hello <%= request.getParameter( "firstName" ) %>, <br /> Your request was received <br /> and forwarded at </p> 27 28 29 30 31 32 33 34 35 36 37 38 <table style = "border: 6px outset;"> <tr> <td style = "background-color: black;"> <p class = "big" style = "color: cyan;"> <%= request.getParameter( "date" ) %> </p> </td> </tr> </table> </body> </html> Outline Get date parameter from request 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 id scope class beanName type Fig. 25.13 Description 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. The scope in which the Java object is accessible—page, request, session or application. The default scope is page. The fully qualified class name of the Java object. The name of a bean that can be used with method instantiate of class java.beans.Beans to load a JavaBean into memory. 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. Attributes of the <jsp:useBean> action. 6.3 <jsp:useBean> Action (cont.) Attribute name Description 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Outline // Fig. 14: Rotator.java // A JavaBean that rotates advertisements. package com.deitel.jhtp5.jsp; public class Rotator { private String images[] = { "images/advjHTP1.jpg", "images/cppHTP4.jpg", "images/iw3HTP2.jpg", "images/jwsFEP1.jpg", "images/vbnetHTP2.jpg" }; private String links[] = { "http://www.amazon.com/exec/obidos/ASIN/0130895601/" "deitelassociatin", "http://www.amazon.com/exec/obidos/ASIN/0130384747/" "deitelassociatin", "http://www.amazon.com/exec/obidos/ASIN/0130308978/" "deitelassociatin", "http://www.amazon.com/exec/obidos/ASIN/0130461342/" "deitelassociatin", "http://www.amazon.com/exec/obidos/ASIN/0130293636/" "deitelassociatin" }; private int selectedIndex = 0; + + + + + Rotator. java 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 // returns image file name for current ad public String getImage() { return images[ selectedIndex ]; } // returns the URL for ad's corresponding Web site public String getLink() { return links[ selectedIndex ]; } // update selectedIndex so next calls to getImage and // getLink return a different advertisement public void nextAd() { selectedIndex = ( selectedIndex + 1 ) % images.length; } } Outline Return image file name for book cover image Return hyperlink to book at Amazon.com Update Rotator so subsequent calls to getImage and getLink return information for different advertisements 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> Outline <!-- Fig. 15: adrotator.jsp --> <jsp:useBean id = "rotator" scope = "application" class = "com.deitel.jhtp5.jsp.Rotator" /> Use jsp:useBean action to obtain reference to Rotator object <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>AdRotator Example</title> <style type = "text/css"> .big { font-family: helvetica, arial, sans-serif; font-weight: bold; font-size: 2em } </style> <%-- update advertisement --%> <% rotator.nextAd(); %> </head> Invoke Rotator’s nextAd method 25 26 27 28 29 30 31 32 33 34 35 36 37 <body> <p class = "big">AdRotator Example</p> <p> <a href = "<jsp:getProperty name = "rotator" property = "link" />"> <img src = "<jsp:getProperty name = "rotator" property = "image" />" alt = "advertisement" /> </a> </p> </body> </html> Outline Define hyperlink to Amazon.com site 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 page Description Defines page settings for the JSP container to process (global settings). include Causes the JSP container to perform a translationtime 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 19: includeDirective.jsp --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Using the include directive</title> <style type = "text/css"> body { font-family: tahoma, helvetica, arial, sans-serif; } table, tr, td { font-size: .9em; border: 3px groove; padding: 5px; background-color: #dddddd; } </style> </head> Outline 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 <body> <table> <tr> <td style = <img src width alt = </td> Outline "width: 160px; text-align: center"> = "images/logotiny.png" = "140" height = "93" "Deitel & Associates, Inc. Logo" /> <td> <%-- include banner.html in this JSP --%> <%@ include file = "banner.html" %> Use include directive to include banner.html </td> </tr> <tr> <td style = "width: 160px"> <%-- include toc.html in this JSP --%> <%@ include file = "toc.html" %> </td> Use include directive to include toc.html 51 52 53 54 55 56 57 58 59 60 <td style = "vertical-align: top"> <%-- include clock2.jsp in this JSP --%> <%@ include file = "clock2.jsp" %> </td> </tr> </table> </body> </html> Outline Use include directive to include clock2.jsp 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 language extends import session Fig. 25.18 Description The scripting language used in the JSP. Currently, the only valid value for this attribute is java. Specifies the class from which the translated JSP will be inherited. This attribute must be a fully qualified class name. 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. 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. Attributes of the page directive. 7.2 page Directive (cont.) Attribute errorPage Description 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 translationtime 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 20: GuestBean.java // JavaBean to store data for a guest in the guest book. package com.deitel.jhtp5.jsp.beans; Outline public class GuestBean { private String firstName, lastName, email; // set the guest's first name public void setFirstName( String name ) { firstName = name; } // get the guest's first name public String getFirstName() { return firstName; } // set the guest's last name public void setLastName( String name ) { lastName = name; } GuestBean defines three guest properties: firstName, lastName and email 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 // get the guest's last name public String getLastName() { return lastName; } Outline // set the guest's email address public void setEmail( String address ) { email = address; } // get the guest's email address public String getEmail() { return email; } } GuestBean.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 Outline // Fig. 21: GuestDataBean.java // Class GuestDataBean makes a database connection and supports // inserting and retrieving data from the database. package com.deitel.jhtp5.jsp.beans; // Java core packages import java.io.*; import java.sql.*; import java.util.*; public class GuestDataBean { private Connection connection; private PreparedStatement addRecord, getRecords; Specify database location // construct TitlesBean object public GuestDataBean() throws Exception { Load Cloudscape System.setProperty( "db2j.system.home", "C:/Cloudscape_5.0" ); driver // load the Cloudscape driver Class.forName( "com.ibm.db2j.jdbc.DB2jDriver" ); // connect to the database connection = DriverManager.getConnection( "jdbc:db2j:guestbook" ); GuestDataBean connects to guestbook database 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 statement = connection.createStatement(); Outline } // return an ArrayList of GuestBeans public ArrayList getGuestList() throws SQLException { ArrayList guestList = new ArrayList(); // obtain list of titles ResultSet results = statement.executeQuery( "SELECT firstName, lastName, email FROM guests" ); // get row data while ( results.next() ) { GuestBean guest = new GuestBean(); guest.setFirstName( results.getString( 1 ) ); guest.setLastName( results.getString( 2 ) ); guest.setEmail( results.getString( 3 ) ); guestList.add( guest ); } return guestList; } GuestDataBean provides method getGuestList to manipulate database 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 // insert a guest in guestbook database public void addGuest( GuestBean guest ) throws SQLException { statement.executeUpdate( "INSERT INTO guests ( firstName, " + "lastName, email ) VALUES ( '" + guest.getFirstName() + "', '" + guest.getLastName() + "', '" + guest.getEmail() + "' )" ); } // close statements and terminate database connection protected void finalize() { // attempt to close database connection try { statement.close(); connection.close(); } // process SQLException on close operation catch ( SQLException sqlException ) { sqlException.printStackTrace(); } } } Outline GuestDataBean provides methods addGuest to manipulate database 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 22: guestBookLogin.jsp --> <%-- page settings --%> <%@ page errorPage = "guestBookErrorPage.jsp" %> page directive defines information that is globally available in JSP Use jsp:useBean actions to obtain references to GuestBean and GuestDataBean objects <%-- beans used in this JSP --%> <jsp:useBean id = "guest" scope = "page" class = "com.deitel.jhtp5.jsp.beans.GuestBean" /> <jsp:useBean id = "guestData" scope = "request" class = "com.deitel.jhtp5.jsp.beans.GuestDataBean" /> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Guest Book Login</title> <style type = "text/css"> body { font-family: tahoma, helvetica, arial, sans-serif; } Outline 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 table, tr, td { font-size: .9em; border: 3px groove; padding: 5px; background-color: #dddddd; } </style> </head> Outline <body> <jsp:setProperty name = "guest" property = "*" /> <% // start scriptlet if ( guest.getFirstName() == null || guest.getLastName() == null || guest.getEmail() == null ) { %> <%-- end scriptlet to insert fixed template data --%> <form method = "post" action = "guestBookLogin.jsp"> <p>Enter your first name, last name and email address to register in our guest book.</p> Set properties of GuestBean with request parameter values 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 <table> <tr> <td>First name</td> <td> <input type = "text" name = "firstName" /> </td> </tr> <tr> <td>Last name</td> <td> <input type = "text" name = "lastName" /> </td> </tr> <tr> <td>Email</td> <td> <input type = "text" name = "email" /> </td> </tr> Outline 75 <tr> 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 95 <% // continue scriptlet 96 97 } // end else 98 99 %> <%-- end scriptlet --%> 100 </body> 101 102</html> Outline Forward request to guestBookView.jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Outline <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 23: guestBookView.jsp --> <%-- page settings --%> <%@ page errorPage = "guestBookErrorPage.jsp" %> <%@ page import = "java.util.*" %> <%@ page import = "com.deitel.jhtp5.jsp.beans.*" %> <%-- GuestDataBean to obtain guest list --%> <jsp:useBean id = "guestData" scope = "request" class = "com.deitel.jhtp5.jsp.beans.GuestDataBean" /> Use page directive import to specify Java classes and packages that are used in JSP context Use jsp:useBean action to obtain reference to GuestDataBean <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Guest List</title> <style type = "text/css"> body { font-family: tahoma, helvetica, arial, sans-serif; } 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 table, tr, td, th { text-align: center; font-size: .9em; border: 3px groove; padding: 5px; background-color: #dddddd; } </style> </head> <body> <p style = "font-size: 2em;">Guest List</p> <table> <thead> <tr> <th style = "width: 100px;">Last name</th> <th style = "width: 100px;">First name</th> <th style = "width: 200px;">Email</th> </tr> </thead> <tbody> Outline 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 <% // start scriptlet List guestList = guestData.getGuestList(); Iterator guestListIterator = guestList.iterator(); GuestBean guest; while ( guestListIterator.hasNext() ) { guest = ( GuestBean ) guestListIterator.next(); %> <%-- end scriptlet; insert fixed template data --%> <tr> <td><%= guest.getLastName() %></td> <td><%= guest.getFirstName() %></td> <td> <a href = "mailto:<%= guest.getEmail() %>"> <%= guest.getEmail() %></a> </td> </tr> Outline Scriptlet displays last name, first name and email address for all guests 72 73 74 75 76 77 78 79 80 81 82 <% // continue scriptlet } // end while %> <%-- end scriptlet --%> </tbody> </table> </body> </html> Outline 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Fig. 24: guestBookErrorPage.jsp --> <%-- page settings --%> <%@ page isErrorPage = "true" %> <%@ page import = "java.util.*" %> <%@ page import = "java.sql.*" %> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Error!</title> <style type = "text/css"> .bigRed { font-size: 2em; color: red; font-weight: bold; } </style> </head> Outline Use page directive isErrorPage to specify that guestBookErrorPage is an error page 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 Outline <body> <p class = "bigRed"> <% // scriptlet to determine exception type // and output beginning of error message if ( exception instanceof SQLException ) %> Use implicit object exception to determine error to be displayed An SQLException <% else if ( exception instanceof ClassNotFoundException ) %> A ClassNotFoundException <% else %> An exception <%-- end scriptlet to insert fixed template data --%> 50 51 52 53 54 55 56 57 58 59 60 61 62 <%-- continue error message output --%> occurred while interacting with the guestbook database. </p> <p class = "bigRed"> The error message was:<br /> <%= exception.getMessage() %> </p> <p class = "bigRed">Please try again later</p> </body> </html> Outline 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 – Utilisation via <%@taglib…%> <%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