Standard Actions

Table of contents:

We continue our JSP discussion with the JSP standard actions (Fig. 27.5). These actions provide JSP implementors with access to several of the most common tasks performed in a JSP, such as including content from other resources, forwarding requests to other resources and interacting with JavaBean software components. JSP containers process actions at request time. Actions are delimited by action> and action>, where action is the standard action name. In cases where nothing appears between the starting and ending tags, the XML empty element syntax action /> can be used. Figure 27.5 summarizes the JSP standard actions, which we use in the next several subsections.

Figure 27.5. JSP standard actions.

Action

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 browser to download and install 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.

JavaBean Manipulation

 

Specifies that the JSP uses a JavaBean instance (i.e., an object of the class that declares the JavaBean). This action specifies the scope of the object and assigns it an ID (i.e., a variable name) that scripting components can use to manipulate the bean.

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.

Gets a property in the specified JavaBean instance and converts the result to a string for output in the response.

27.6.1. Action

JavaServer Pages support two include mechanismsthe action and the include directive. Action enables dynamic content to be included in a JavaServer Page at request time. If the included resource changes between requests, the next request to the JSP containing the action includes the resource's new content. On the other hand, the include directive copies the content into the JSP once, at JSP translation time. If the included resource changes, the new content will not be reflected in the JSP that used the include directive, unless that JSP is recompiled, which normally would occur only if a new version of the JSP is installed. Figure 27.6 describes the attributes of action .

Figure 27.6. Action attributes.

Attribute

Description

page

Specifies the relative URI path of the resource to include. The resource must be part of the same Web application.

flush

Specifies whether the implicit object out should be flushed before the include is performed. If true, the JspWriter out is flushed prior to the inclusion, hence you could no longer forward to another page later on. The default value is false.

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.

Performance Tip 27.2

The action is more flexible than the include directive, but requires more over-head when page contents change frequently. Use the action only when dynamic content is necessary.

Common Programming Error 27.2

Specifying in a action a page that is not part of the same Web application is a request-time errorthe action will not include any content.

The next example demonstrates action using four XHTML and JSP resources that represent both static and dynamic content. JavaServer Page include.jsp (Fig. 27.7) includes three other resources: banner.html (Fig. 27.8), toc.html (Fig. 27.9) and clock2.jsp (Fig. 27.10). JavaServer Page include.jsp creates an XHTML document containing a table in which banner.html spans two columns across the top of the table, toc.html is the left column of the second row and clock2.jsp is the right column of the second row. Figure 27.7 uses three actions (lines 3839, 45 and 4950) as the content in td elements of the table. Using two XHTML documents and a JSP in Fig. 27.7 demonstrates that JSPs can include both static and dynamic content. The output window in Fig. 27.7 demonstrates the result of one request to include.jsp.

Figure 27.7. JSP include.jsp includes resources with .

(This item is displayed on pages 1293 - 1294 in the print version)

"http://www.w3.org/1999/xhtml"> 8 9 10


 1  "1.0"?>
 2  "-//W3C//DTD XHTML 1.0 Strict//EN"
 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4
 5 
 6
 7 
Using jsp:include 11 12 26 27 28 29 30 31 36 41 42 43 47 52 53
"width: 160px; text-align: center"> 32 "images/logotiny.png" 33 width = "140" height = "93" 34 alt = "Deitel & Associates, Inc. Logo" /> 35 37 <%-- include banner.html in this JSP --%> 38 "banner.html" 39 flush = "true" /> 40
"width: 160px" > 44 <%-- include toc.html in this JSP --%> 45 "toc.html" flush = "true" /> 46 "vertical-align: top"> 48 <%-- include clock2.jsp in this JSP --%> 49 "clock2.jsp" 50 flush = "true" /> 51
54 55

Figure 27.8. Banner (banner.html) to include across the top of the XHTML document created by Fig. 27.7.

(This item is displayed on page 1295 in the print version)


 1 
 2 
 3 
"width: 580px"> 4

5 Java(TM), C, C++, Visual Basic(R), 6 Object Technology, and
Internet and 7 World Wide Web Programming Training 
8 On-Site Seminars Delivered Worldwide 9

10

11 <a href="</span"> "mailto:deitel@deitel.com">deitel@deitel.com</a> 12
978.461.5880
12 Clock Tower Place, Suite 200, 13 Maynard, MA 01754 14

15

Figure 27.9. Table of contents (toc.html) to include down the left side of the XHTML document created by Fig. 27.7.

(This item is displayed on pages 1295 - 1296 in the print version)


 1 
 2 
 3
 4 

<a href="</span">"http://www.deitel.com/books/index.html"> 5 Publications/BookStore 6 </a>

7 8

<a href="</span">"http://www.deitel.com/whatsnew.html"> 9 What's New 10 </a>

11 12

<a href="</span">"http://www.deitel.com/books/downloads.html"> 13 Downloads/Resources 14 </a>

15 16

<a href="</span">"http://www.deitel.com/faq/index.html"> 17 FAQ (Frequently Asked Questions) 18 </a>

19 20

<a href="</span">"http://www.deitel.com/intro.html"> 21 Who we are 22 </a>

23 24

<a href="</span">"http://www.deitel.com/index.html"> 25 Home Page 26 </a>

27 28

Send questions or comments about this site to 29 <a href="</span"> "mailto:deitel@deitel.com"> 30 deitel@deitel.com 31 </a>
32 Copyright 1995-2005 by Deitel & Associates, Inc. 33 All Rights Reserved. 34

Figure 27.10. JSP clock2.jsp to include as the main content in the XHTML document created by Fig. 27.7.

(This item is displayed on page 1296 in the print version)


 1 
 2 
 3
 4 
 5 
 6 
28 
29 
"background-color: black;"> 7

"big" style = "color: cyan; font-size: 3em; 8 font-weight: bold;"> 9 10 <%-- script to determine client local and --%> 11 <%-- format date accordingly --%> 12 <% 13 // get client locale 14 java.util.Locale locale = request.getLocale(); 15 16 // get DateFormat for client's Locale 17 java.text.DateFormat dateFormat = 18 java.text.DateFormat.getDateTimeInstance( 19 java.text.DateFormat. LONG, 20 java.text.DateFormat. LONG, locale ); 21 22 %> <%-- end script --%> 23 24 <%-- output date --%> 25 <%= dateFormat.format( new java.util.Date() ) %> 26

27

Figure 27.10 (clock2.jsp) demonstrates how to determine the client's Locale (package java.util) and uses that Locale to format a Date with a DateFormat (package java.text) object. Line 14 invokes the request object's getLocale method, which returns the client's Locale. Lines 1720 invoke DateFormat static method geTDateTimeInstance to obtain a DateFormat object. The first two arguments indicate that the date and time formats should each be LONG format (other options are FULL, MEDIUM, SHORT and DEFAULT, see java.sun.com/j2se/5.0/docs/api/java/text/DateFormat.html for details of these formats). The third argument specifies the Locale for which the DateFormat object should format the date. Line 25 invokes the DateFormat object's format method to produce a String representation of the Date. The DateFormat object formats this String for the Locale specified in line 20. [Note: This example works for Western languages that use the ISO-8859-1 character set. For other languages, the JSP must specify the proper character set using the JSP page directive (Section 27.7.1). At the site java.sun.com/j2se/5.0/docs/guide/intl/encoding.doc.html, Sun provides a list of character encodings. The response's content type defines the character set to use in the response. The content type has the form "mimeType;charset=encoding" (e.g., ";text/html;charset=ISO-8859-1".]

To test Fig. 27.7 in Tomcat, copy banner.html, toc.html, clock2.jsp, include.jsp and the images directory into the jsp directory created in Section 27.3. Open your Web browser and enter the following URL:


 http://localhost:8080/jhtp6/jsp/include.jsp

 

27.6.2. Action

Action enables a JSP to forward request processing to a different resource, such as an error page. Request processing by the original JSP terminates as soon as the JSP forwards the request. Action has only a page attribute that specifies the relative URL of the resource (in the same Web application) to which the request should be forwarded.

Software Engineering Observation 27.7

When using the 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.

 

JavaServer Page forward1.jsp (Fig. 27.11) is a modified version of welcome.jsp (Fig. 27.4). The primary difference is in lines 2023, in which JavaServer Page forward1.jsp forwards the request to JavaServer Page forward2.jsp (Fig. 27.12). Note the action in lines 2122. This action adds a request parameter representing the date and time at which the initial request was received to the request object that is forwarded to forward2.jsp.

Figure 27.11. JSP forward1.jsp receives a firstName parameter, adds a date to the request parameters and forwards the request to forward2.jsp for further processing.

(This item is displayed on pages 1297 - 1298 in the print version)

"http://www.w3.org/1999/xhtml"> 8 9


 1  "1.0" ?>
 2  "-//W3C//DTD XHTML 1.0 Strict//EN"
 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4
 5 t
 6
 7 
Forward request to another JSP 10 11 12 <% // begin scriptlet 13 14 String name = request.getParameter( "firstName" ); 15 16 if ( name != null ) 17 { 18 %> <%-- end scriptlet to insert fixed template data --%> 19 20 "forward2.jsp"> 21 "date" 22 value = "<%= new java.util.Date() %>" /> 23 24 25 <% // continue scriptlet 26 27 } // end if 28 else 29 { 30 %> <%-- end scriptlet to insert fixed template data --%> 31 32 "forward1.jsp" method = "get" > 33

Type your first name and press Submit

34 35

"text" name = "firstName" /> 36 "submit" value = "Submit" /> 37

38 39 40 <% // continue scriptlet 41 42 } // end else 43 44 %> <%-- end scriptlet --%> 45 46

Figure 27.12. JSP forward2.jsp receives a request (from forward1.jsp in this example) and uses the request parameters as part of the response to the client.

(This item is displayed on pages 1298 - 1299 in the print version)

"http://www.w3.org/1999/xhtml"> 8 9


 1  "1.0"?>
 2  "-//W3C//DTD XHTML 1.0 Strict//EN"
 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4
 5 
 6
 7 
Processing a forwarded request 10 18 19 20

"big"> 21 Hello <%= request.getParameter( "firstName" ) %>,
22 Your request was received
and forwarded at 23

24 "border: 6px outset;"> 25 26 31 32
"background-color: black;"> 27

"big" style = "color: cyan;"> 28 <%= request.getParameter( "date" ) %> 29

30
33 34

The action specifies name-value pairs of information that are passed to the , and actions. Every action has two required attributesname and value. If a action specifies a parameter that already exists in the request, the new value for the parameter takes precedence over the original one. All the values for that parameter can be obtained by using the JSP implicit object request's getParameterValues method, which returns an array of Strings.

JSP forward2.jsp uses the name specified in the action ("date") to obtain the date and time. It also uses the firstName parameter originally passed to forward1.jsp to obtain the user's first name. The JSP expressions in Fig. 27.12 (lines 21 and 28) insert the request parameter values in the response to the client. The screen capture in Fig. 27.11 shows the initial interaction with the client. The screen capture in Fig. 27.12 shows the results returned to the client after the request was forwarded to forward2.jsp.

To test Fig. 27.11 and Fig. 27.12 in Tomcat, copy forward1.jsp and forward2.jsp into the jsp directory created in Section 27.3. Open your Web browser and enter the following URL to test forward1.jsp:


 http://localhost:8080/jhtp6/jsp/forward1.jsp

 

27.6.3. Action

Action enables a JSP to manipulate a Java object. This action creates a Java object or locates an existing object for use in the JSP. Figure 27.13 summarizes action 's attributes. If attributes class and beanName are not specified, the JSP container attempts to locate an existing object of the type specified in attribute type. Like JSP implicit objects, objects specified with action have a scopepage, request, session or applicationthat indicates where they can be used in a Web application. Objects with page scope are accessible only by the page in which they are defined. Multiple JSP pages can potentially access objects in other scopes. For example, all JSPs that process a single request can access an object in request scope.

Figure 27.13. Attributes of the action.

Attribute

Description

id

The name used to manipulate the Java object with actions and . A variable of this name is also declared for use in JSP scripting elements. The name specified here is case sensitive.

scope

The scope in which the Java object is accessiblepage, request, session or application. The default scope is page.

class

The fully qualified class name of the Java object.

beanName

The name of a JavaBean that can be used with method instantiate of class java.beans.Beans to load a JavaBean into memory.

type

The type of the JavaBean. This can be the same type as the class attribute, a superclass of that type or an interface implemented by that type. The default value is the same as for attribute class. A ClassCastException occurs if the Java object is not of the type specified with attribute type.

 

Common Programming Error 27.3

One or both of the attributes class and type must be specifiedotherwise, a translation-time error occurs.

 

Many Web sites place rotating advertisements on their Web pages. Each visit to one of these pages typically results in a different advertisement being displayed in the user's Web browser. Typically, clicking an advertisement takes you to the Web site of the company that placed the advertisement. Our first example of demonstrates a simple advertisement rotator bean that cycles through a list of five advertisements. In this example, the advertisements are covers for some of our books. Clicking a cover takes you to the Amazon.com Web site, where you can read about and possibly order the book.

The Rotator bean (Fig. 27.14) has three methods: getImage, getLink and nextAd. Method getImage returns the image file name for the book-cover image. Method getLink returns the hyperlink to the book at Amazon.com. Method nextAd updates the Rotator so that the next calls to getImage and getLink will return information for a different advertisement. Methods getImage and getLink each represent a read-only JavaBean propertyimage and link, respectively. These are read-only properties because no set methods are provided to change their values. Rotator keeps track of the current advertisement with its selectedIndex variable, which is updated by invoking method nextAd.

Figure 27.14. Rotator bean that maintains a set of advertisements.

(This item is displayed on page 1301 in the print version)


 1 // Fig. 27.14: Rotator.java
 2 // A JavaBean that rotates advertisements.
 3 package com.deitel.jhtp6.jsp.beans;
 4
 5 public class Rotator
 6 {
 7 private String images[] = { "images/advjHTP1.jpg",
 8 "images/cppHTP4.jpg", "images/iw3HTP2.jpg",
 9 "images/jwsFEP1.jpg", "images/vbnetHTP2.jpg" };
10
11 private String links[] = {
12 "http://www.amazon.com/exec/obidos/ASIN/0130895601/" +
13 "deitelassociatin",
14 "http://www.amazon.com/exec/obidos/ASIN/0130384747/" +
15 "deitelassociatin",
16 "http://www.amazon.com/exec/obidos/ASIN/0130308978/" +
17 "deitelassociatin",
18 "http://www.amazon.com/exec/obidos/ASIN/0130461342/" +
19 "deitelassociatin",
20 "http://www.amazon.com/exec/obidos/ASIN/0130293636/" +
21 "deitelassociatin" };
22
23 private int selectedIndex = 0;
24
25 // returns image file name for current ad
26 public String getImage()
27 {
28 return images[ selectedIndex ];
29 } // end method getImage
30
31 // returns the URL for ad's corresponding Web site
32 public String getLink()
33 {
34 return links[ selectedIndex ];
35 } // end method getLink
36
37 // update selectedIndex so next calls to getImage and
38 // getLink return a different advertisement
39 public void nextAd()
40 {
41 selectedIndex = ( selectedIndex + 1 ) % images.length;
42 } // end method nextAd
43 } // end class Rotator

JavaBeans were originally intended to be manipulated visually in visual development environments (often called builder tools or IDEs). Builder tools that support beans provide programmers with tremendous flexibility by allowing them to reuse and integrate existing disparate components that, in many cases, were never intended to be used together. These components can be linked together to create applets, applications or even new beans for reuse by others.

When used in an IDE, JavaBeans usually adhere to the following coding conventions:

  1. implement the Serializable interface
  2. provide a public no-argument constructor
  3. provide get and/or set methods for properties (which are normally implemented as fields).

When used on the server side, such as within a JSP or a servlet, JavaBeans are less restricted. For example, the Rotator bean does not implement the Serializable interface because there is no need to save and load the Rotator bean as a file. Recall that by default, if the programmer does not explicitly add constructors to a class, a public no-argument constructor is generated automatically. Also note that in the Rotator bean, properties image and link are read only because they provide only get methods.

Lines 78 of JavaServer Page adrotator.jsp (Fig. 27.15) obtain a reference to an instance of class Rotator. The id for the bean is rotator. The JSP uses this name to manipulate the bean. The scope of the object is session, so that every client will see the same sequence of ads during their browsing sessions. When adrotator.jsp receives a request from a new client, the JSP container creates the bean and stores it in that client's session (an HttpSession object). In each request to this JSP, line 19 uses the rotator reference created in line 7 to invoke the Rotator bean's nextAd method. Thus, each request will receive the next advertisement selected by the Rotator bean. Lines 2429 define a hyperlink to the Amazon.com site for a particular book. Lines 2425 introduce action to obtain the value of the Rotator bean's link property. Action has two attributesname and propertythat specify the bean object to manipulate and the property to get. If the JavaBean object uses standard JavaBean naming conventions, the method used to obtain the link property value from the bean should be getLink. Action invokes getLink on the bean referenced with rotator, converts the return value into a String and outputs the String as part of the response to the client. The link property becomes the value of the hyperlink's href attribute. The hyperlink is represented in the resulting Web page as the book cover image. Lines 2728 create an img element and use another action to obtain the Rotator bean's image property value.

Figure 27.15. JSP adrotator.jsp uses a Rotator bean to display a different advertisement on each request for the page.

(This item is displayed on pages 1302 - 1303 in the print version)

"http://www.w3.org/1999/xhtml"> 11 12


 1  "1.0"?>
 2  "-//W3C//DTD XHTML 1.0 Strict//EN"
 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4
 5 
 6
 7  "rotator" scope = "session" 
 8  class = "com.deitel.jhtp6.jsp.beans.Rotator" />
 9
10 
AdRotator Example 13 18 <%-- update advertisement --%> 19 <% rotator.nextAd(); %> 20 21 22

"big">AdRotator Example

23

24 <a href="</span"> " "rotator" 25 property = "link" />"> 26 27 " "rotator" 28 property = "image" />" alt = "advertisement" /> 29 </a> 30

31 32

The link and image properties can also be obtained with JSP expressions. For example, action in lines 2425 can be replaced with the expression


 <%= rotator.getLink() %>

 

Similarly, action in lines 2728 can be replaced with the expression


 <%= rotator.getImage() %>

 

The benefit of using actions is that someone who is unfamiliar with Java can be told the name of a property and the name of a bean, and it is the action's responsibility to invoke the appropriate methods. The Java programmer's job is to create a bean that supports the capabilities required by the page designer.

To test adrotator.jsp in Tomcat, copy adrotator.jsp into the jsp directory created in Section 27.3. You should have copied the images directory into the jsp directory when you tested Fig. 27.7. If not, you must copy the images directory there now. Copy Rotator.class into the jhtp6 Web application's WEBINFclassescomdeiteljhtp6jspeans directory in Tomcat. [Note: This example will work only if the proper package directory structure for Rotator is defined in the classes directory. Rotator is declared in package com.deitel.jhtp6.jsp.beans.] Open your Web browser and enter the following URL to test adrotator.jsp:

http://localhost:8080/jhtp6/jsp/adrotator.jsp

Try reloading this JSP several times in your browser to see the advertisement change with each request.

Action sets JavaBean property values and is particularly useful for mapping request parameter values to JavaBean properties. Request parameters can be used to set properties of primitive types boolean, byte, char, short, int, long, float and double and java.lang types String, Boolean, Byte, Character, Short, Integer, Long, Float and Double. Figure 27.16 summarizes the attributes.

Figure 27.16. Attributes of the action.

(This item is displayed on page 1305 in the print version)

Attribute

Description

name

The ID of the JavaBean for which a property (or properties) will be set.

property

The name of the property to set. Specifying "*" for this attribute specifies that the JSP should 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 the 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.

 

Software Engineering Observation 27.8

Action 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.

 

Common Programming Error 27.4

Conversion errors occur if you use action 's value attribute to set JavaBean property types that cannot be set with request parameters.


[Page 1305 (continued)]

27 7 Directives

Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover



Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net