Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 31 - JavaServer Pages (JSP): Bonus for Java™ Developers

Similar presentations


Presentation on theme: "Chapter 31 - JavaServer Pages (JSP): Bonus for Java™ Developers"— Presentation transcript:

1 Chapter 31 - JavaServer Pages (JSP): Bonus for Java™ Developers
Outline Introduction JavaServer Pages Overview A First JavaServer Page Example Implicit Objects Scripting Scripting Components Scripting Example Standard Actions <jsp:include> Action <jsp:forward> Action <jsp:plugin> Action <jsp:useBean> Action Directives page Directive include Directive

2 Chapter 31 - JavaServer Pages (JSP): Bonus for Java™ Developers
Outline Custom Tag Libraries Simple Custom Tag Custom Tag with Attributes Evaluating the Body of a Custom Tag World Wide Web Resources

3 JavaServer Pages (JSP)
31.1 Introduction JavaServer Pages (JSP) Extension of servlet technology Designed to simplify dynamic content delivery Additional packages Package javax.servlet.jsp Contains main JSP classes and methods Package javax.servlet.jsp.tagtest Contains custom tag classes and methods

4 31.2 JavaServer Pages Overview
Key Componenets Directives Define settings of JSP container Actions Encapsulate predefined tag actions Often performed based upon client request Also Create Java Objects for scriplets Scriptlets Enable Java code within a JSP Tag libraries Tag extension mechanism User defined custom tags

5 31.2 JavaServer Pages Overview
JSPs Vs. Servlets JSPs Look like XHTML documents Used when most content is fixed Servlets Used when most content is dynamic JSPs and servlets are interchangeable JSPs are compiled to servlets at first request Life-cycle is identical

6 31.3 A First JavaServer Page Example
Upcoming JavaServer Page Example

7 Clock.jsp Simple JSP expression
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig. 31.1: clock.jsp --> 6 7 <html xmlns = " 8 <head> <meta http-equiv = "refresh" content = "60" /> 11 <title>A Simple JSP Example</title> 13 <style type = "text/css"> big { font-family: helvetica, arial, sans-serif; font-weight: bold; font-size: 2em; } </style> </head> 20 <body> <p class = "big">Simple JSP Example</p> 23 <table style = "border: 6px outset;"> <tr> <td style = "background-color: black;"> <p class = "big" style = "color: cyan;"> 28 <!-- JSP expression to insert date/time --> <%= new java.util.Date() %> 31 </p> </td> </tr> Clock.jsp Simple JSP expression JSP expressions deliniated by <%= and %>. This will insert a string representation of the date.

8 Clock.jsp Program Output
</table> </body> 37 38 </html> Clock.jsp Program Output

9 30.4 Implicit Objects Implicit Objects
Provide access to servlet capabilities within JSPs Scopes Application Owned by JSP container Manipulatable by any Servlet or Application Page Exist in page that defined them Individual instance for each page Request Exist for duration of request Session Exist for entire client session

10 31.4 Implicit Objects

11 31.4 Implicit Objects

12 31.5 Scripting Scripting Allows JSPs to place Java code within page

13 31.5.1 Scripting Components Scripting components Scriptlets Comments
Delimited by <% and %> Blocks of Java code Comments Scriptlet Comments delimiated by / and / JSP comments delimited by <%-- and --%> XHTML comments delimited by <!-- and --> Expressions Delimited by <%= and %> Result converted to a String object

14 30.5.1 Scripting Components Scripting Components Declarations
Delimited by <%! and %> Define variables and methods Require terminating semicolon Escape sequences Upcoming table

15 Scripting Components

16 Scripting Example Upcoming example Demonstrates basic scripting

17 Welcome.jsp Demonstrate scriptlet and expressions
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig. 31.4: welcome.jsp --> 6 <!-- JSP that processes a "get" request containing data. --> 7 8 <html xmlns = " 9 <!-- head section of document --> <head> <title>Processing "get" requests with data</title> </head> 14 <!-- body section of document --> <body> <% // begin scriptlet 18 String name = request.getParameter( "firstName" ); 20 if ( name != null ) { 22 %> <%-- end scriptlet to insert fixed template data --%> 24 <h1> Hello <%= name %>, <br /> Welcome to JavaServer Pages! </h1> 29 <% // continue scriptlet 31 } // end if else { 34 Welcome.jsp Demonstrate scriptlet and expressions Obtain request parameter via scriptlet. Expression will display the string value of name

18 35 %> <%-- end scriptlet to insert fixed template data --%>
36 <form action = "welcome.jsp" method = "get"> <p>Type your first name and press Submit</p> 39 <p><input type = "text" name = "firstName" /> <input type = "submit" value = "Submit" /> </p> </form> 44 <% // continue scriptlet 46 } // end else 48 %> <%-- end scriptlet --%> </body> 51 52 </html> <!-- end XHTML document --> Welcome.jsp

19 Welcome.jsp Program Output

20 30.6 Standard Actions Standard actions
Provide access to common JSP tasks Including resource content Forwarding Requests Interacting with JavaBeans Processed by container at request time Delimited by <jsp:action> and </jsp:action> Actions defined in upcoming table

21 31.6 Standard Actions

22 31.6.1 <jsp:include> action
Enables dynamic content inclusion Creates copy of resource Often are XHTML or other JSP pages

23 31.6.1 <jsp:include> Action

24 31.6.1 <jsp:include> Action
Upcoming example Uses the <jsp:include> action to add HTML and JSP pages

25 Banner.html 1 <!-- Fig. 31.7: banner.html -->
2 <!-- banner to include in another document --> 3 <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> 10 <p> <a href = 13 /> 14 <br /> B Boston Post Road, Suite 200, Sudbury, MA 01776 </p> 19 </div> Banner.html

26 Toc.html 1 <!-- Fig. 31.8: toc.html -->
2 <!-- contents to include in another document --> 3 4 <p><a href = " Publications/BookStore 6 </a></p> 7 8 <p><a href = " What's New 10 </a></p> 11 12 <p><a href = " Downloads/Resources 14 </a></p> 15 16 <p><a href = " FAQ (Frequently Asked Questions) 18 </a></p> 19 20 <p><a href = " Who we are 22 </a></p> 23 24 <p><a href = " Home Page 26 </a></p> 27 28 <p>Send questions or comments about this site to <a href = 30 </a><br /> Copyright by Deitel & Associates, Inc. All Rights Reserved. 34 </p> Toc.html

27 Clock2.jsp 1 <!-- Fig. 31.9: clock2.jsp -->
2 <!-- date and time to include in another document --> 3 4 <table> <tr> <td style = "background-color: black;"> <p class = "big" style = "color: cyan; font-size: 3em; font-weight: bold;"> 9 <%= new java.util.Date() %> </p> </td> </tr> 14 </table> Clock2.jsp

28 Include.jsp 1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig : include.jsp --> 6 7 <html xmlns = " 8 <head> <title>Using jsp:include</title> 11 <style type = "text/css"> body { font-family: tahoma, helvetica, arial, sans-serif; } 16 table, tr, td { font-size: .9em; border: 3px groove; padding: 5px; background-color: #dddddd; } </style> </head> 25 <body> <table> <tr> <td style = "width: 160px; text-align: center"> <img src = "images/logotiny.png" width = "140" height = "93" alt = "Deitel & Associates, Inc. Logo" /> </td> 34 <td> Include.jsp

29 <jsp:include> action tag, accesses external resources.
36 <%-- include banner.html in this JSP --%> <jsp:include page = "banner.html" flush = "true" /> 40 </td> </tr> 43 <tr> <td style = "width: 160px"> 46 <%-- include toc.html in this JSP --%> <jsp:include page = "toc.html" flush = "true" /> 49 </td> 51 <td style = "vertical-align: top"> 53 <%-- include clock2.jsp in this JSP --%> <jsp:include page = "clock2.jsp" flush = "true" /> 57 </td> </tr> </table> </body> 62 </html> <jsp:include> action tag, accesses external resources. Include.jsp

30 Include.jsp Program Output

31 31.6.2 <jsp:forward> Action
Enables the JSP to redirect client Current JSP halts processing, immediately transfers client Page attribute determines forwarding location Upcoming example demonstrates forward action

32 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig : forward1.jsp --> 6 7 <html xmlns = " 8 9 <head> <title>Forward request to another JSP</title> 11 </head> 12 13 <body> <% // begin scriptlet 15 String name = request.getParameter( "firstName" ); 17 if ( name != null ) { 19 %> <%-- end scriptlet to insert fixed template data --%> 21 <jsp:forward page = "forward2.jsp"> <jsp:param name = "date" value = "<%= new java.util.Date() %>" /> </jsp:forward> 26 <% // continue scriptlet 28 } // end if else { 31 %> <%-- end scriptlet to insert fixed template data --%> 33 <form action = "forward1.jsp" method = "get"> <p>Type your first name and press Submit</p> Forward1.jsp If the firstname parameter is specified, forward the user to the second page with the current date.

33 Forward1.jsp Program Output
36 <p><input type = "text" name = "firstName" /> <input type = "submit" value = "Submit" /> </p> </form> 41 <% // continue scriptlet 43 } // end else 45 %> <%-- end scriptlet --%> 47 </body> 48 49 </html> <!-- end XHTML document --> Forward1.jsp Program Output

34 Forward2.jsp 1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- forward2.jsp --> 6 7 <html xmlns = " 8 9 <head> <title>Processing a forwarded request</title> 11 <style type = "text/css"> big { font-family: tahoma, helvetica, arial, sans-serif; font-weight: bold; font-size: 2em; } </style> 19 </head> 20 21 <body> <p class = "big"> Hello <%= request.getParameter( "firstName" ) %>, <br /> Your request was received <br /> and forwarded at </p> 26 <table style = "border: 6px outset;"> <tr> <td style = "background-color: black;"> <p class = "big" style = "color: cyan;"> <%= request.getParameter( "date" ) %> </p> </td> </tr> </table> Forward2.jsp

35 Forward2.jsp Program Output
36 </body> 37 38 </html> Forward2.jsp Program Output

36 31.6.3 <jsp:plugin> Action
Adds applet, JavaBean or XHTML element Enables the client to download Java plug-in Upcoming table shows plug-in attributes

37 31.6.3 <jsp:plugin> Action

38 31.6.3 <jsp:plugin> Action
Upcoming Example Applet draws a picture via Java2d JSP displays applet and embeds java plug-in Ensures all clients can view applet

39 ShapesApplet.java Define Applet ShapesApplet Initialize applet
1 // Fig : ShapesApplet.java 2 // Applet that demonstrates a Java2D GeneralPath. 3 package com.deitel.advjhtp1.jsp.applet; 4 5 // Java core packages 6 import java.applet.*; 7 import java.awt.event.*; 8 import java.awt.*; 9 import java.awt.geom.*; 10 11 // Java extension packages 12 import javax.swing.*; 13 14 public class ShapesApplet extends JApplet { 15 // initialize the applet public void init() { // obtain color parameters from XHTML file try { int red = Integer.parseInt( getParameter( "red" ) ); int green = Integer.parseInt( getParameter( "green" ) ); int blue = Integer.parseInt( getParameter( "blue" ) ); 24 Color backgroundColor = new Color( red, green, blue ); 26 setBackground( backgroundColor ); } 29 // if there is an exception while processing the color // parameters, catch it and ignore it catch ( Exception exception ) { // do nothing } } ShapesApplet.java Define Applet ShapesApplet Initialize applet

40 ShapesApplet.java Draw shapes
36 public void paint( Graphics g ) { // create arrays of x and y coordinates int xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 }; int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 }; 44 // obtain reference to a Graphics2D object Graphics2D g2d = ( Graphics2D ) g; 47 // create a star from a series of points GeneralPath star = new GeneralPath(); 50 // set the initial coordinate of the GeneralPath star.moveTo( xPoints[ 0 ], yPoints[ 0 ] ); 53 // create the star--this does not draw the star for ( int k = 1; k < xPoints.length; k++ ) star.lineTo( xPoints[ k ], yPoints[ k ] ); 57 // close the shape star.closePath(); 60 // translate the origin to (200, 200) g2d.translate( 200, 200 ); 63 // rotate around origin and draw stars in random colors for ( int j = 1; j <= 20; j++ ) { g2d.rotate( Math.PI / 10.0 ); 67 g2d.setColor( new Color( ( int ) ( Math.random() * 256 ), ( int ) ( Math.random() * 256 ), ShapesApplet.java Draw shapes

41 ShapesApplet.java 71 ( int ) ( Math.random() * 256 ) ) ); 72
g2d.fill( star ); // draw a filled star } } 76 } ShapesApplet.java

42 Plugin.jsp use plugin action
1 <!-- Fig : plugin.jsp --> 2 3 <html> 4 <head> <title>Using jsp:plugin to load an applet</title> </head> 8 <body> <jsp:plugin type = "applet" code = "com.deitel.advjhtp1.jsp.applet.ShapesApplet" codebase = "/advjhtp1/jsp" width = "400" height = "400"> 15 <jsp:params> <jsp:param name = "red" value = "255" /> <jsp:param name = "green" value = "255" /> <jsp:param name = "blue" value = "0" /> </jsp:params> 21 </jsp:plugin> </body> 24 </html> The JSP plugin parameter includes the applet in the page, and ensures the client has the Java plug-in. Plugin.jsp use plugin action

43 Plugin.jsp Program Output

44 31.6.4 <jsp:useBean> Action
Enables JSP to manipulate a Java Object Same scope as implicit objects Must specify attribute class or type Attribute type will locate an existing object Attribute class will create a new object Upcoming table includes other useBean attributes

45 31.6.4 <jsp:useBean> Action

46 31.6.4 <jsp:useBean> Action
Upcoming example Demonstrates useBean action Loads advertisement rotator

47 Rotator.java Define JavaBean Rotator
1 // Fig : Rotator.java 2 // A JavaBean that rotates advertisements. 3 package com.deitel.advjhtp1.jsp.beans; 4 5 public class Rotator { private String images[] = { "images/jhtp3.jpg", "images/xmlhtp1.jpg", "images/ebechtp1.jpg", "images/iw3htp1.jpg", "images/cpphtp3.jpg" }; 9 private String links[] = { " + "deitelassociatin", " + "deitelassociatin", " + "deitelassociatin", " + "deitelassociatin", " + "deitelassociatin" }; 21 private int selectedIndex = 0; 23 // returns image file name for current ad public String getImage() { return images[ selectedIndex ]; } 29 // returns the URL for ad's corresponding Web site public String getLink() { return links[ selectedIndex ]; } 35 Rotator.java Define JavaBean Rotator

48 Rotator.java 36 // update selectedIndex so next calls to getImage and
// getLink return a different advertisement public void nextAd() { selectedIndex = ( selectedIndex + 1 ) % images.length; } 42 } Rotator.java

49 Create a new instance of the rotator bean named rotator.
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig : adrotator.jsp --> 6 7 <jsp:useBean id = "rotator" scope = "application" class = "com.deitel.advjhtp1.jsp.beans.Rotator" /> 9 10 <html xmlns = " 11 <head> <title>AdRotator Example</title> 14 <style type = "text/css"> big { font-family: helvetica, arial, sans-serif; font-weight: bold; font-size: 2em } </style> 20 <%-- update advertisement --%> <% rotator.nextAd(); %> </head> 24 <body> <p class = "big">AdRotator Example</p> 27 <p> <a href = "<jsp:getProperty name = "rotator" property = "link" />"> 31 <img src = "<jsp:getProperty name = "rotator" property = "image" />" alt = "advertisement" /> </a> Adrotator.jsp Create a new instance of the rotator bean named rotator. getProperty action functions the same as calling rotator.getLink()

50 Adrotator.jsp Program Output
</body> 37 </html> Adrotator.jsp Program Output

51 31.6.4 <jsp:useBean> Action

52 31.6.4 <jsp:useBean> Action
Upcoming example GuestBook application Stores information in a database Database connectivity via JavaBean

53 GuestBean.java Define Bean GuestBean Storage Bean
1 // Fig : GuestBean.java 2 // JavaBean to store data for a guest in the guest book. 3 package com.deitel.advjhtp1.jsp.beans; 4 5 public class GuestBean { private String firstName, lastName, ; 7 // set the guest's first name public void setFirstName( String name ) { firstName = name; } 13 // get the guest's first name public String getFirstName() { return firstName; } 19 // set the guest's last name public void setLastName( String name ) { lastName = name; } 25 // get the guest's last name public String getLastName() { return lastName; } 31 // set the guest's address public void set ( String address ) { = address; GuestBean.java Define Bean GuestBean Storage Bean

54 GuestBean.java 36 } 37 38 // get the guest's email address
} 37 // get the guest's address public String get () { return ; } 43 } GuestBean.java

55 GuestDataBean.java Define Class GuestDataBean Set up database
1 // Fig : GuestDataBean.java 2 // Class GuestDataBean makes a database connection and supports 3 // inserting and retrieving data from the database. 4 package com.deitel.advjhtp1.jsp.beans; 5 6 // Java core packages 7 import java.io.*; 8 import java.sql.*; 9 import java.util.*; 10 11 public class GuestDataBean { private Connection connection; private PreparedStatement addRecord, getRecords; 14 // construct TitlesBean object public GuestDataBean() throws Exception { // load the Cloudscape driver Class.forName( "COM.cloudscape.core.RmiJdbcDriver" ); 20 // connect to the database connection = DriverManager.getConnection( "jdbc:rmi:jdbc:cloudscape:guestbook" ); 24 getRecords = connection.prepareStatement( "SELECT firstName, lastName, FROM guests" ); 29 addRecord = connection.prepareStatement( "INSERT INTO guests ( " + "firstName, lastName, ) " + "VALUES ( ?, ?, ? )" ); GuestDataBean.java Define Class GuestDataBean Set up database Defines the database driver, URL, and SQL statements.

56 GuestDataBean.java Database access methods
} 37 // return an ArrayList of GuestBeans public List getGuestList() throws SQLException { List guestList = new ArrayList(); 42 // obtain list of titles ResultSet results = getRecords.executeQuery(); 45 // get row data while ( results.next() ) { GuestBean guest = new GuestBean(); 49 guest.setFirstName( results.getString( 1 ) ); guest.setLastName( results.getString( 2 ) ); guest.set ( results.getString( 3 ) ); 53 guestList.add( guest ); } 56 return guestList; } 59 // insert a guest in guestbook database public void addGuest( GuestBean guest ) throws SQLException { addRecord.setString( 1, guest.getFirstName() ); addRecord.setString( 2, guest.getLastName() ); addRecord.setString( 3, guest.get () ); 66 addRecord.executeUpdate(); } 69 // close statements and terminate database connection Obtain the guest list from the database. Return each guest in a bean. GuestDataBean.java Database access methods

57 GuestDataBean.java Close database
protected void finalize() { // attempt to close database connection try { getRecords.close(); addRecord.close(); connection.close(); } 79 // process SQLException on close operation catch ( SQLException sqlException ) { sqlException.printStackTrace(); } } 85 } GuestDataBean.java Close database

58 GuestBookLogin.jsp useBean action
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig : guestBookLogin.jsp --> 6 7 <%-- page settings --%> 8 page errorPage = "guestBookErrorPage.jsp" %> 9 10 <%-- beans used in this JSP --%> 11 <jsp:useBean id = "guest" scope = "page" class = "com.deitel.advjhtp1.jsp.beans.GuestBean" /> 13 <jsp:useBean id = "guestData" scope = "request" class = "com.deitel.advjhtp1.jsp.beans.GuestDataBean" /> 15 16 <html xmlns = " 17 18 <head> <title>Guest Book Login</title> 20 <style type = "text/css"> body { font-family: tahoma, helvetica, arial, sans-serif; } 25 table, tr, td { font-size: .9em; border: 3px groove; padding: 5px; background-color: #dddddd; } </style> 33 </head> 34 35 <body> GuestBookLogin.jsp useBean action Obtain an instance of each bean. Assigns the bean name within the JSP.

59 GuestBookLogin.jsp Obtain information from user
<jsp:setProperty name = "guest" property = "*" /> 37 <% // start scriptlet 39 if ( guest.getFirstName() == null || guest.getLastName() == null || guest.get () == null ) { 43 %> <%-- end scriptlet to insert fixed template data --%> 45 <form method = "post" action = "guestBookLogin.jsp"> <p>Enter your first name, last name and address to register in our guest book.</p> 49 <table> <tr> <td>First name</td> 53 <td> <input type = "text" name = "firstName" /> </td> </tr> 58 <tr> <td>Last name</td> 61 <td> <input type = "text" name = "lastName" /> </td> </tr> 66 <tr> <td> </td> 69 <td> GuestBookLogin.jsp Obtain information from user

60 GuestBookLogin.jsp Add new guest to book
<input type = "text" name = " " /> </td> </tr> 74 <tr> <td colspan = "2"> <input type = "submit" value = "Submit" /> </td> </tr> </table> </form> 83 <% // continue scriptlet 85 } // end if else { guestData.addGuest( guest ); 89 %> <%-- end scriptlet to insert jsp:forward action --%> 91 <%-- forward to display guest book contents --%> <jsp:forward page = "guestBookView.jsp" /> 94 <% // continue scriptlet 96 } // end else 98 %> <%-- end scriptlet --%> 100 </body> 101 102 </html> GuestBookLogin.jsp Add new guest to book Calls the guestData Bean to write this new guest into the address book. The forward the client to the guestBookView JSP.

61 Obtain an instance of the GuestDataBean class with useBean action.
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig : guestBookView.jsp --> 6 7 <%-- page settings --%> 8 page errorPage = "guestBookErrorPage.jsp" %> 9 page import = "java.util.*" %> 10 page import = "com.deitel.advjhtp1.jsp.beans.*" %> 11 12 <%-- GuestDataBean to obtain guest list --%> 13 <jsp:useBean id = "guestData" scope = "request" class = "com.deitel.advjhtp1.jsp.beans.GuestDataBean" /> 15 16 <html xmlns = " 17 <head> <title>Guest List</title> 20 <style type = "text/css"> body { font-family: tahoma, helvetica, arial, sans-serif; } 25 table, tr, td, th { text-align: center; font-size: .9em; border: 3px groove; padding: 5px; background-color: #dddddd; } </style> </head> 35 Obtain an instance of the GuestDataBean class with useBean action. GuestBookView.jsp

62 Obtain, then Iterate through the guestList and display its contents.
<body> <p style = "font-size: 2em;">Guest List</p> 38 <table> <thead> <tr> <th style = "width: 100px;">Last name</th> <th style = "width: 100px;">First name</th> <th style = "width: 200px;"> </th> </tr> </thead> 47 <tbody> 49 <% // start scriptlet 51 List guestList = guestData.getGuestList(); Iterator guestListIterator = guestList.iterator(); GuestBean guest; 55 while ( guestListIterator.hasNext() ) { guest = ( GuestBean ) guestListIterator.next(); 58 %> <%-- end scriptlet; insert fixed template data --%> 60 <tr> <td><%= guest.getLastName() %></td> 63 <td><%= guest.getFirstName() %></td> 65 <td> <a href = "mailto:<%= guest.get () %>"> <%= guest.get () %></a> </td> </tr> GuestBookView.jsp Obtain, then Iterate through the guestList and display its contents.

63 GuestBookView.jsp 71 72 <% // continue scriptlet 73
} // end while 75 %> <%-- end scriptlet --%> 77 </tbody> </table> </body> 81 82 </html> GuestBookView.jsp

64 GuestBookErrorPage.jsp Error page
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig : guestBookErrorPage.jsp --> 6 7 <%-- page settings --%> 8 page isErrorPage = "true" %> 9 page import = "java.util.*" %> 10 page import = "java.sql.*" %> 11 12 <html xmlns = " 13 <head> <title>Error!</title> 16 <style type = "text/css"> bigRed { font-size: 2em; color: red; font-weight: bold; } </style> </head> 25 <body> <p class = "bigRed"> 28 <% // scriptlet to determine exception type // and output beginning of error message if ( exception instanceof SQLException ) %> 33 An SQLException 35 GuestBookErrorPage.jsp Error page

65 GuestBookErrorPage.jsp 36 <%
<% else if ( exception instanceof ClassNotFoundException ) %> 39 A ClassNotFoundException 41 <% else %> 45 An exception 47 <%-- end scriptlet to insert fixed template data --%> 49 <%-- continue error message output --%> occurred while interacting with the guestbook database. </p> 53 <p class = "bigRed"> The error message was:<br /> <%= exception.getMessage() %> </p> 58 <p class = "bigRed">Please try again later</p> </body> 61 62 </html> GuestBookErrorPage.jsp

66 31.6.4 <jsp:useBean> Action
Fig JSP guest book sample output windows.

67 31.6.4 <jsp:useBean> Action
Fig JSP guest book sample output windows.

68 31.6.4 <jsp:useBean> Action
Fig JSP guest book sample output windows.

69 31.6.4 <jsp:useBean> Action
Fig JSP guest book sample output windows.

70 31.7 Directives Directive Overview
Information sent to JSP container to specify properties Error pages Include external content Specify custom tag libraries Delimited by and %> Processed when JSP is translated

71 31.7 Directives

72 31.7.1 page Directive Page directive Specifies global JSP Settings
Specific attributes on upcomming table

73 page Directive

74 page Directive

75 31.7.2 include Directive Directive include
Includes content of another source in page Attribute file Only attribute Specifies URL of resource to include Differences from Action <jsp:include> Include action updates resource each refresh Changes in resource are reflected in page Include directive maintains the original resource Upcoming example Reimplements include.jsp with include directive

76 IncludeDirective.jsp 1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig : includeDirective.jsp --> 6 7 <html xmlns = " 8 <head> <title>Using the include directive</title> 11 <style type = "text/css"> body { font-family: tahoma, helvetica, arial, sans-serif; } 16 table, tr, td { font-size: .9em; border: 3px groove; padding: 5px; background-color: #dddddd; } </style> </head> 25 <body> <table> <tr> <td style = "width: 160px; text-align: center"> <img src = "images/logotiny.png" width = "140" height = "93" alt = "Deitel & Associates, Inc. Logo" /> </td> 34 <td> IncludeDirective.jsp

77 Include directive examples IncludeDirective.jsp
36 <%-- include banner.html in this JSP --%> 38 include file = "banner.html" %> 39 </td> </tr> 42 <tr> <td style = "width: 160px"> 45 <%-- include toc.html in this JSP --%> 47 include file = "toc.html" %> 48 </td> 50 <td style = "vertical-align: top"> 52 <%-- include clock2.jsp in this JSP --%> 54 include file = "clock2.jsp" %> 55 </td> </tr> </table> </body> 60 </html> Include directive examples IncludeDirective.jsp

78 IncludeDirective.jsp Program Output

79 31.8 Custom Tag Libraries Custom tag libraries
Encapsulate complex JSP functionality Defined in Tag of package javax.servlet.jsp.tagtext Normally extend TagSupport or BodyTagSupport Allow developers to expand JSPs without Java knowledge Can directly manipulate JSPs JSPs access via taglib directive Upcoming table show attributes

80 31.8 Custom Tag Libraries

81 CustomTagWelcome.jsp Custom tag example Program Output
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig : customTagWelcome.jsp > 6 <!-- JSP that uses a custom tag to output content. --> 7 8 <%-- taglib directive --%> 9 taglib uri = "advjhtp1-taglib.tld" prefix = "advjhtp1" %> 10 11 <html xmlns = " 12 <head> <title>Simple Custom Tag Example</title> </head> 16 <body> <p>The following text demonstrates a custom tag:</p> <h1> <advjhtp1:welcome /> </h1> </body> 23 24 </html> Specify the location of the tag library with the taglib directive. CustomTagWelcome.jsp Custom tag example Program Output Call custom tag.

82 Load tag and print welcome.
1 // Fig : WelcomeTagHandler.java 2 // Custom tag handler that handles a simple tag. 3 package com.deitel.advjhtp1.jsp.taglibrary; 4 5 // Java core packages 6 import java.io.*; 7 8 // Java extension packages 9 import javax.servlet.jsp.*; 10 import javax.servlet.jsp.tagext.*; 11 12 public class WelcomeTagHandler extends TagSupport { 13 // Method called to begin tag processing public int doStartTag() throws JspException { // attempt tag processing try { // obtain JspWriter to output content JspWriter out = pageContext.getOut(); 21 // output content out.print( "Welcome to JSP Tag Libraries!" ); } 25 // rethrow IOException to JSP container as JspException catch( IOException ioException ) { throw new JspException( ioException.getMessage() ); } 30 return SKIP_BODY; // ignore the tag's body } 33 } Load tag and print welcome. WelcomeTagHandler.java Define tag handler WelcomeTagHandler Implements custom tag functionality

83 advjhtp1-taglib.tld Define tag information
1 <?xml version = "1.0" encoding = "ISO " ?> 2 <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" " 5 6 <!-- a tag library descriptor --> 7 8 <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>advjhtp1</shortname> 12 <info> A simple tab library for the examples </info> 16 <!-- A simple tag that outputs content --> <tag> <name>welcome</name> 20 <tagclass> com.deitel.advjhtp1.jsp.taglibrary.WelcomeTagHandler </tagclass> 24 <bodycontent>empty</bodycontent> 26 <info> Inserts content welcoming user to tag libraries </info> </tag> 31 </taglib> Required taglibrary meta information advjhtp1-taglib.tld Define tag information Designate the tags name and location, and that this tag has no attributes. Fig Custom tag library descriptor file (advjhtp1-taglib.tld).

84 31.8.2 Custom Tag With Attributes
Allow customizable tags Upcoming example Demonstrates a Custom tag with attributes

85 Include the custom tag library. CustomTagAttribute.jsp
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- Fig : customTagAttribute.jsp > 6 <!-- JSP that uses a custom tag to output content. --> 7 8 <%-- taglib directive --%> 9 taglib uri = "advjhtp1-taglib.tld" prefix = "advjhtp1" %> 10 11 <html xmlns = " 12 <head> <title>Specifying Custom Tag Attributes</title> </head> 16 <body> <p>Demonstrating an attribute with a string value</p> <h1> <advjhtp1:welcome2 firstName = "Paul" /> </h1> 22 <p>Demonstrating an attribute with an expression value</p> <h1> <%-- scriptlet to obtain "name" request parameter --%> <% String name = request.getParameter( "name" ); %> 29 <advjhtp1:welcome2 firstName = "<%= name %>" /> </h1> </body> 33 34 </html> Include the custom tag library. CustomTagAttribute.jsp Specifying an attribute for a custom tag.

86 CustomTagAttribute.jsp Program Output

87 1 // Fig. 31.34: Welcome2TagHandler.java
2 // Custom tag handler that handles a simple tag. 3 package com.deitel.advjhtp1.jsp.taglibrary; 4 5 // Java core packages 6 import java.io.*; 7 8 // Java extension packages 9 import javax.servlet.jsp.*; 10 import javax.servlet.jsp.tagext.*; 11 12 public class Welcome2TagHandler extends TagSupport { private String firstName = ""; 14 // Method called to begin tag processing public int doStartTag() throws JspException { // attempt tag processing try { // obtain JspWriter to output content JspWriter out = pageContext.getOut(); 22 // output content out.print( "Hello " + firstName + ", <br />Welcome to JSP Tag Libraries!" ); } 27 // rethrow IOException to JSP container as JspException catch( IOException ioException ) { throw new JspException( ioException.getMessage() ); } 32 return SKIP_BODY; // ignore the tag's body } 35 Welcome2TagHandler.java Define Class Welcome2TagHandler.java Displays attribute value

88 36 // set firstName attribute to the users first name
public void setFirstName( String username ) { firstName = username; } 41 } Welcome2TagHandler.java

89 Define attribute parameters advjhtp1-taglib.tld
1 <!-- A tag with an attribute --> 2 <tag> <name>welcome2</name> 4 <tagclass> com.deitel.advjhtp1.jsp.taglibrary.Welcome2TagHandler </tagclass> 8 <bodycontent>empty</bodycontent> 10 <info> Inserts content welcoming user to tag libraries. Uses attribute "name" to insert the user's name. </info> 15 <attribute> <name>firstName</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> 21 </tag> Define attribute parameters advjhtp1-taglib.tld Fig Element tag for the welcome2 custom tag.

90 31.8.3 Evaluating the Body of a Custom Tag
Custom Tag Element body Defines variables that may be used in JSP May iterate over Element body Extends class BodyTagSupport Upcoming example Demonstrates tag body processing

91 CustomTagBody.jsp Define tag library
1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 5 <!-- customTagBody.jsp --> 6 7 <%-- taglib directive --%> 8 taglib uri = "advjhtp1-taglib.tld" prefix = "advjhtp1" %> 9 10 <html xmlns = " 11 <head> <title>Guest List</title> 14 <style type = "text/css"> body { font-family: tahoma, helvetica, arial, sans-serif } 19 table, tr, td, th { text-align: center; font-size: .9em; border: 3px groove; padding: 5px; background-color: #dddddd } </style> </head> 29 <body> <p style = "font-size: 2em">Guest List</p> 32 <table> <thead> CustomTagBody.jsp Define tag library

92 CustomTagBody.jsp Program Output
<th style = "width: 100px">Last name</th> <th style = "width: 100px">First name</th> <th style = "width: 200px"> </th> </thead> 39 <%-- guestlist custom tag --%> <advjhtp1:guestlist> <tr> <td><%= lastName %></td> 44 <td><%= firstName %></td> 46 <td> <a href = "mailto:<%= %>"> <%= %></a> </td> </tr> </advjhtp1:guestlist> </table> </body> 55 56 </html> Call the custom tag guestlist to iterate over the guest information and display a table. CustomTagBody.jsp Program Output

93 Obtain the guestlist for the guest data bean.
1 // Fig : GuestBookTag.java 2 // Custom tag handler that reads information from the guestbook 3 // database and makes that data available in a JSP. 4 package com.deitel.advjhtp1.jsp.taglibrary; 5 6 // Java core packages 7 import java.io.*; 8 import java.util.*; 9 10 // Java extension packages 11 import javax.servlet.jsp.*; 12 import javax.servlet.jsp.tagext.*; 13 14 // Deitel packages 15 import com.deitel.advjhtp1.jsp.beans.*; 16 17 public class GuestBookTag extends BodyTagSupport { private String firstName; private String lastName; private String ; 21 private GuestDataBean guestData; private GuestBean guest; private Iterator iterator; 25 // Method called to begin tag processing public int doStartTag() throws JspException { // attempt tag processing try { guestData = new GuestDataBean(); 32 List list = guestData.getGuestList(); iterator = list.iterator(); 35 GuestBookTag.java Obtain the guestlist for the guest data bean.

94 If there are more guests, loop and continue processing.
if ( iterator.hasNext() ) { processNextGuest(); 38 return EVAL_BODY_TAG; // continue body processing } else return SKIP_BODY; // terminate body processing } 44 // if any exceptions occur, do not continue processing // tag's body catch( Exception exception ) { exception.printStackTrace(); return SKIP_BODY; // ignore the tag's body } } 52 // process body and determine if body processing // should continue public int doAfterBody() { // attempt to output body data try { bodyContent.writeOut( getPreviousOut() ); } 61 // if exception occurs, terminate body processing catch ( IOException ioException ) { ioException.printStackTrace(); return SKIP_BODY; // terminate body processing } 67 bodyContent.clearBody(); 69 If there are more guests, loop and continue processing. GuestBookTag.java

95 GuestBookTag.java 70 if ( iterator.hasNext() ) {
processNextGuest(); 72 return EVAL_BODY_TAG; // continue body processing } else return SKIP_BODY; // terminate body processing } 78 // obtains the next GuestBean and extracts its data private void processNextGuest() { // get next guest guest = ( GuestBean ) iterator.next(); 84 pageContext.setAttribute( "firstName", guest.getFirstName() ); 87 pageContext.setAttribute( "lastName", guest.getLastName() ); 90 pageContext.setAttribute( " ", guest.get () ); } 94 } GuestBookTag.java

96 GuestBookTagExtraInfo.java Contains custom tag variable information
1 // Fig : GuestBookTagExtraInfo.java 2 // Class that defines the variable names and types created by 3 // custom tag handler GuestBookTag. 4 package com.deitel.advjhtp1.jsp.taglibrary; 5 6 // Java core packages 7 import javax.servlet.jsp.tagext.*; 8 9 public class GuestBookTagExtraInfo extends TagExtraInfo { 10 // method that returns information about the variables // GuestBookTag creates for use in a JSP public VariableInfo [] getVariableInfo( TagData tagData ) { VariableInfo firstName = new VariableInfo( "firstName", "String", true, VariableInfo.NESTED ); 17 VariableInfo lastName = new VariableInfo( "lastName", "String", true, VariableInfo.NESTED ); 20 VariableInfo = new VariableInfo( " ", "String", true, VariableInfo.NESTED ); 23 VariableInfo varableInfo [] = { firstName, lastName, }; 26 return varableInfo; } 29 } Define each variable and its type GuestBookTagExtraInfo.java Contains custom tag variable information

97 Specifies that this custom tag contains JSP information in its body
1 <!-- A tag that iterates over an ArrayList of GuestBean --> 2 <!-- objects, so they can be output in a JSP > 3 <tag> <name>guestlist</name> 5 <tagclass> com.deitel.advjhtp1.jsp.taglibrary.GuestBookTag </tagclass> 9 <teiclass> com.deitel.advjhtp1.jsp.taglibrary.GuestBookTagExtraInfo </teiclass> 13 <bodycontent>JSP</bodycontent> 15 <info> Iterates over a list of GuestBean objects </info> 19 </tag> Specifies that this custom tag contains JSP information in its body advjhtp1-taglib.tld Fig Element tag for the guestlist custom tag.


Download ppt "Chapter 31 - JavaServer Pages (JSP): Bonus for Java™ Developers"

Similar presentations


Ads by Google