Download presentation
Presentation is loading. Please wait.
1
JavaServer Pages (JSP)
27 JavaServer Pages (JSP)
2
A fair request should be followed by the deed in silence.
If it’s a good script, I’ll do it and if it’s a bad script and they pay me enough, I’ll do it. George Burns A fair request should be followed by the deed in silence. Dante Alighieri Talent is a question of quantity. Talent does not write one page: it writes three hundred. Jules Renard Every action must be due to one or other of seven causes: chance, nature, compulsion, habit, reasoning, anger, or appetite. Aristotle
3
OBJECTIVES In this chapter you will learn:
The differences between servlets and JSPs. To create and deploy JavaServer Pages. To use JSP’s implicit objects and scriptlets to create dynamic Web pages. To specify global JSP information with directives. To use actions to manipulate JavaBeans in a JSP, to include resources dynamically and to forward requests to other JSPs.
4
27.1 Introduction 27.2 JavaServer Pages Overview 27.3 First JSP Example 27.4 Implicit Objects 27.5 Scripting 27.5.1 Scripting Components 27.5.2 Scripting Example 27.6 Standard Actions 27.6.1 <jsp:include> Action 27.6.2 <jsp:forward> Action 27.6.3 <jsp:useBean> Action 27.7 Directives 27.7.1 page Directive 27.7.2 include Directive 27.8 Case Study: Guest Book 27.9 Wrap-Up 27.10 Internet and Web Resources
5
27.1 Introduction JavaServer Pages
Extension of Servlet technology Separate the presentation from the business logic Simplify the delivery of dynamic Web content Reuse existing Java components JavaBean Custom-tag libraries Encapsulate complex functionality Classes and interfaces specific to JSP Package javax.servlet.jsp Package javax.servlet.jsp.tagext
6
27.2 JavaServer Pages Overview
Key components Directives Actions Scripting elements Tag libraries
7
27.2 JavaServer Pages Overview (Cont.)
Directive Message to JSP container i.e., program that compiles/executes JSPs Enable programmers to specify Page settings Content to include from other resources Custom tag libraries used in the JSP
8
27.2 JavaServer Pages Overview (Cont.)
Action Predefined JSP tags that encapsulate functionality Often performed based on information from client request Can be used to create Java objects for use in scriptlets
9
27.2 JavaServer Pages Overview (Cont.)
Scripting elements Enable programmers to insert Java code in JSPs Performs request processing Interacts with page elements and other components to implement dynamic pages Scriptlets One kind of scripting element Contain code fragments Describe the action to be performed in response to user request
10
27.2 JavaServer Pages Overview (Cont.)
Custom Tag Library JSP’s tag extension mechanism Enables programmers to define new tags Tags encapsulate complex functionality Tags can manipulate JSP content
11
27.2 JavaServer Pages Overview (Cont.)
JSPs Look like standard XHTML or XML Normally include XHTML or XML markup Known as fixed-template data Used when content is mostly fixed-template data Small amounts of content generated dynamically Servlets Used when small amount of content is fixed-template data Most content generated dynamically
12
Software Engineering Observation 27.1
Literal text in a JSP becomes string literals in the servlet that represents the translated JSP.
13
27.2 JavaServer Pages Overview (Cont.)
When server receive the first JSP request JSP container translates a JSP into a servlet Handle the current and future requests Code that represents the JSP Placed in servlet’s _jspService method JSP errors Translation-time errors Occur when JSPs are translated into servlets Request-time errors Occur during request processing Methods jspInit and jspDestroy Container invokes them when initializing and terminating a JSP Defined in JSP declarations
14
Performance Tip 27.1 Some JSP containers translate JSPs to servlets at installation time. This eliminates the translation overhead for the first client that requests each JSP.
15
27.3 First JSP Example Simple JSP example (Fig. 27.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
16
meta element refreshes the Web page every 60 seconds
Outline clock.jsp (1 of 2) Line 9 Line 24 meta element refreshes the Web page every 60 seconds Creates Date object that is converted to a String implicitly and displayed in paragraph (p) element
17
Outline clock.jsp (2 of 2) Program output
18
Software Engineering Observation 27.2
JavaServer Pages are easier to implement than servlets when the response to a client request consists primarily of markup that remains constant between requests.
19
Software Engineering Observation 27.3
The JSP container converts the result of every JSP expression into a string that is output as part of the response to the client.
20
27.4 Implicit Objects Implicit Objects
Provide access to many servlet capabilities within a JSP 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
21
27.4 Implicit Objects (Cont.)
Request scope Objects exist for duration of client request Objects go out of scope when 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
22
Fig. 27.2 | JSP implicit objects. (1 of 2)
23
Fig. 27.2 | JSP implicit objects. (2 of 2)
24
27.5 Scripting Scripting Dynamically generated content
Insert Java code and logic in JSP using scripting
25
27.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
26
Common Programming Error 27.1
Placing a JSP comment or XHTML comment inside a scriptlet is a translation-time syntax error that prevents the JSP from being translated properly.
27
Software Engineering Observation 27.4
JSPs should not store client state information in instance variables. Rather, they should use the JSP implicit session object. For more information on how to use the session object, visit Sun’s J2EE tutorial at java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html.
28
Fig. 27.3 | JSP escape sequences.
29
27.5.2 Scripting Example Demonstrate basic scripting capabilities
Responding to get requests
30
Software Engineering Observation 27.5
Scriptlets, expressions and fixed-template data can be intermixed in a JSP to create different responses based on the information in a request.
31
Outline (1 of 3) Lines 17-23 Line 19 Line 26
welcome.jsp (1 of 3) Lines 17-23 Line 19 Line 26 Scriptlet used to insert Java code Use request implicit object to get parameter JSP expression
32
Scriptlets used to insert Java code
Outline welcome.jsp (2 of 3) Lines and lines 45-49
33
Outline welcome.jsp (3 of 3) Program output
34
Error-Prevention Tip 27.1 It is sometimes difficult to debug errors in a JSP, because the line numbers reported by a JSP container normally refer to the servlet that represents the translated JSP, not the original JSP line numbers. Program development environments enable JSPs to be compiled in the environment, so you can see syntax error messages. These messages include the statement in the servlet that represents the translated JSP, which can be helpful in determining the error.
35
Error-Prevention Tip 27.2 Many JSP containers store the source code for the servlets that represent the translated JSPs. For example, the Tomcat installation directory contains a subdirectory called work in which you can find the source code for the servlets translated by Tomcat. Recall from Chapter 26 that the log files located in the logs subdirectory of the Tomcat installation directory are also helpful for determining the errors.
36
Error-Prevention Tip 27.3 Always put the closing brace for the if statement and the else in the same scriptlet.
37
27.6 Standard Actions JSP standard actions
Provide access to common tasks performed in a JSP Including content from other resources Forwarding requests to other resources Interacting with JavaBeans JSP containers process actions at request time Delimited by <jsp:action> and </jsp:action>
38
Fig. 27.5 | JSP standard actions. (1 of 2)
39
Fig. 27.5 | JSP standard actions. (2 of 2)
40
27.6.1 <jsp:include> Action
Enables dynamic content to be included in a JSP More flexible than include directive Requires more overhead when page contents change frequently
41
Software Engineering Observation 27.6
According to the JavaServer Pages 2.0 specification, a JSP container is allowed to determine whether a resource included with the include directive has changed. If so, the container can recompile the JSP that included the resource. However, the specification does not provide a mechanism to indicate a change in an included resource to the container.
42
Performance Tip 27.2 The <jsp:include> action is more flexible than the include directive, but requires more overhead when page contents change frequently. Use the <jsp:include> action only when dynamic content is necessary.
43
Common Programming Error 27.2
Specifying in a <jsp:include> action a page that is not part of the same Web application is a request-time error—the <jsp:include> action will not include any content.
44
Fig. 27.6 | Action <jsp:include> attributes.
45
Outline include.jsp (1 of 3)
46
Outline (2 of 3) Lines 38-39 Line 45
include.jsp (2 of 3) Lines 38-39 Line 45 Lines 49-50 Use JSP include action to include banner.html Use JSP include action to include toc.html Use JSP include action to include clock2.jsp
47
Outline include.jsp (3 of 3) Program output
48
Outline banner.html
49
Outline toc.html
50
Outline clock2.jsp Line 14 Lines 17-20 Line 25 Use request object’s getLocale method to obtain the client’s Locale Invoke DateFormat static method getDateTimeInstance to obtain a DataFormat object for the specified Locale Format Date with specified DataFormat
51
27.6.2 <jsp:forward> Action
Enables JSP to forward request to different resources Forward requests to resources in same context <jsp:param> action Specifies name-value pairs of information Name-value pairs are passed to other actions
52
Software Engineering Observation 27.7
When using the <jsp:forward> action, the resource to which the request will be forwarded must be in the same context (Web application) as the JSP that originally received the request.
53
Outline (1 of 2) Line 14 Lines 20-23
forward1.jsp (1 of 2) Line 14 Lines 20-23 Use request implicit object to get parameter Forward request to forward2.jsp
54
Outline forward1.jsp (2 of 2) Program output
55
Get date parameter from request
Outline forward2.jsp (1 of 2) Line 21 Line 28 Receive request from forward1.jsp, then get firstName parameter from request Get date parameter from request
56
Outline forward2.jsp (2 of 2) Program output
57
27.6.3 <jsp:useBean> Action
Enables JSP to manipulate Java object Creates Java object or locates an existing object for use in JSP
58
Common Programming Error 27.3
One or both of the <jsp:useBean> attributes class and type must be specified—otherwise, a translation-time error occurs.
59
Fig. 27.13 | Attributes of the <jsp:useBean> action.
60
Return image file name for book cover image
Outline Rotator.java (1 of 2) Lines 26-29 Return image file name for book cover image
61
Return hyperlink to book at Amazon.com
Outline Rotator.java (2 of 2) Lines 32-35 Lines 39-42 Update Rotator so subsequent calls to getImage and getLink return information for different advertisements
62
Outline Use jsp:useBean action to obtain reference to Rotator object
adrotator.jsp (1 of 2) Lines 7-8 Line 19 Lines 24-29 Invoke Rotator’s nextAd method Define hyperlink to Amazon.com site
63
Outline adrotator.jsp (2 of 2) Program output
64
27.6.3 <jsp:useBean> Action (Cont.)
Action <jsp:getProperty> Attribute name Specify the bean object to manipulate Attribute property Specify the property to get Replace <jsp:getProperty> action with JSP expressions <%= rotator.getLink() %> <%= rotator.getImage() %>
65
Software Engineering Observation 27.8
Action <jsp:setProperty> can use request-parameter values to set JavaBean properties of the following types: Strings, primitive types (boolean, byte, char, short, int, long, float and double) and type-wrapper classes (Boolean, Byte, Character, Short, Integer, Long, Float and Double). See Fig. 27.22 for an example.
66
Fig. 27.16 | Attributes of the <jsp:setProperty> action.
67
Common Programming Error 27.4
Conversion errors occur if you use action <jsp:setProperty>’s value attribute to set JavaBean property types that cannot be set with request parameters.
68
27.7 Directives JSP directives Messages to JSP container
Enable programmer to: Specify page settings Include content from other resources Specify custom-tag libraries Delimited by and %>
69
Fig | JSP directives.
70
27.7.1 page Directive JSP page directive
Specifies JSP’s global settings in JSP container
71
Common Programming Error 27.5
Providing multiple page directives with one or more repeated attributes in common is a JSP translation-time error, unless the values for all repeated attributes are identical. Also, providing a page directive with an attribute or value that is not recognized is a JSP translation-time error.
72
Software Engineering Observation 27.9
According to the JSP specification, section , the extends attribute “should not be used without careful consideration as it restricts the ability of the JSP container to provide specialized superclasses that may improve on the quality of rendered service.” Remember that a Java class can extend exactly one other class. If your JSP specifies an explicit superclass, the JSP container cannot translate your JSP into a subclass of one of the container application’s own enhanced servlet classes.
73
Fig. 27.18 | Attributes of the page directive. (1 or 3)
74
Fig. 27.18 | Attributes of the page directive. (2 or 3)
75
Fig. 27.18 | Attributes of the page directive. (3 or 3)
76
Common Programming Error 27.6
Using JSP implicit object session in a JSP that does not have its page directive attribute session set to true is a translation-time error.
77
27.7.2 include Directive JSP include directive
Includes content of another resource at JSP translation time Not as flexible as <jsp:include> action
78
Outline includeDirective.j sp (1 of 3)
79
Outline (2 of 3) Line 34 Use include directive to include banner.html
includeDirective.j sp (2 of 3) Line 34 Line 40 Line 44 Use include directive to include banner.html Use include directive to include toc.html Use include directive to include clock2.jsp
80
Outline includeDirective.j sp (3 of 3) Program output
81
27.8 Case Study: Guest Book Demonstrate Action <jsp:setProperty>
JSP page directive JSP error pages Use of JDBC
82
Outline GuestBean.java (1 of 2) Lines 7-9 GuestBean declares three guest properties: firstName, lastName and
83
Outline GuestBean.java (2 of 2)
84
Outline (1 of 3) Line 19 Line 22 Line 23 Line 24 Line 25
GuestDataBean.java (1 of 3) Line 19 Line 22 Line 23 Line 24 Line 25 Load MySQL driver Create a CachedRowSet object using Sun’s reference implementation CachedRowSetImpl Set the CachedRowSet’s database URL property Set the CachedRowSet’s database username property Set the CachedRowSet’s database password property
85
Outline Set the CachedRowSet’s database command property
Execute the query specified by the command property GuestDataBean.java (2 of 3) Lines 28-29 Line 30 Line 38 Lines 41-50 Move the CachedRowSet’s cursor before the first row Create the GuestBean objects for each row in the CachedRowSet
86
Outline Invoke the CachedRowSet’s moveToInsertRow method to remember the current row and move the cursor to the insert row GuestDataBean.java (3 of 3) Line 58 Lines 61-63 Line 64 Line 65 Line 66 Invoke the CachedRowSet’s updateString method to update the column values Invoke the CachedRowSet’s insertRow method to insert the row into the rowset Invoke the CachedRowSet’s moveToCurrentRow method to move the cursor back to the current row Invoke the CachedRowSet’s acceptChanges method to propagates the changes in the rowset to the underlying database
87
page directive defines information that is globally available in JSP
Outline page directive defines information that is globally available in JSP guestBookLogin.jsp (1 of 3) Line 8 Lines 11-14 Use jsp:useBean actions to obtain references to GuestBean and GuestDataBean objects
88
Set properties of GuestBean with request parameter values, because the input elements have the same names as the GuestBean properties Outline Verify that the user fills in all the entries, including first name, last name and guestBookLogin.jsp (2 of 3) Line 34 Lines 36-89
89
Outline guestBookLogin.jsp (3 of 3) Line 74 Line 77 Add GuestBean guest to GuestDataBean guestData Forward request to guestBookView.jsp
90
27.8 Case Study: Guest Book (Cont.)
Line 34 Specify “*” for attribute property Match request parameters to properties Can set the properties individually <jsp:setProperty name = “guest” property = “firstName” param = “firstName” /> <jsp:setProperty name = “guest” property = “lastName” param = “lastName” /> <jsp:setProperty name = “guest” property = “ ” param = “ ” /> <% guest.setFirstName( request.getParameter( “firstName” ) ); %>
91
Use jsp:useBean action to obtain reference to GuestDataBean
Outline Use page directive import to specify Java classes and packages that are used in JSP context guestBookView.jsp (1 of 2) Lines 9 and 10 Lines 13-14 Use jsp:useBean action to obtain reference to GuestDataBean
92
Outline guestBookView.jsp (2 of 2) Lines 45-64 Use scriptlet and expressions to display last name, first name and address for all guests
93
Outline Use page directive isErrorPage to specify that guestBookError-Page is an error page guestBookErrorPage .jsp (1 of 3) Line 8
94
Use implicit object exception to determine error to be displayed
Outline Use implicit object exception to determine error to be displayed guestBookErrorPage .jsp (2 of 3) Lines 28 and 36
95
Display the actual error message from the exception
Outline guestBookErrorPage .jsp (3 of 3) Line 60 Display the actual error message from the exception
96
Fig. 27.25 | JSP guest book sample output windows. (1 of 3)
97
Fig. 27.25 | JSP guest book sample output windows. (2 of 3)
98
Fig. 27.25 | JSP guest book sample output windows. (2 of 3)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.