Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

AhmadLang / Java, How To Program, 2004

.pdf
Скачиваний:
626
Добавлен:
31.05.2015
Размер:
51.82 Mб
Скачать

[Page 1286 (continued)]

27.5. Scripting

JavaServer Pages often present dynamically generated content as part of an XHTML document that is sent to the client in response to a request. In some cases, the content is static but is output only if certain conditions are met during a request (e.g., providing values in a form that submits a request). JSP programmers can insert Java code and logic in a JSP using scripting.

[Page 1287]

27.5.1. Scripting Components

The JSP scripting components include scriptlets, comments, expressions, declarations and escape sequences. This section describes each of these scripting components. Many of these are demonstrated in Fig. 27.4 at the end of Section 27.5.2.

Scriptlets are blocks of code delimited by <% places in method _jspService at translation

and %>. They contain Java statements that the container time.

JSPs support three comment styles: JSP comments, XHTML comments and scripting-language comments. JSP comments are delimited by <%-- and --%>. These can be placed throughout a JSP, but not inside scriptlets. XHTML comments are delimited with <!-- and -->. These, too, can be placed throughout a JSP, but not inside scriptlets. Scripting language comments are currently Java comments, because Java currently is the only JSP scripting language. Scriptlets can use Java's end-of-line // comments and traditional comments (delimited by /* and */). JSP comments and scripting-language comments are ignored and do not appear in the response to a client. When clients view the source code of a JSP response, they will see only the XHTML comments in the source code. The different comment styles are useful for separating comments that the user should be able to see from those that document logic processed on the server.

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.

As we discussed in Section 27.3, JSP expressions are delimited by <%= and %> and contain a Java expression that is evaluated when a client requests the JSP containing the expression. The container converts the result of a JSP expression to a String object, then outputs the String as part of the response to the client.

Declarations, delimited by <%! and %>, enable a JSP programmer to define variables and methods for use in a JSP. Variables become instance variables of the servlet class that represents the translated JSP. Similarly, methods become members of the class that represents the translated JSP. Declarations of variables and methods in a JSP use Java syntax. Thus, a variable declaration must end with a semicolon, as in

<%! int counter = 0; %>

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.

Special characters or character sequences that the JSP container normally uses to delimit JSP code can be included in a JSP as literal characters in scripting elements, fixed template data and attribute values using escape sequences. Figure 27.3 shows the literal character or characters and the corresponding escape sequences and discusses where to use the escape sequences.

Figure 27.3. JSP escape sequences.

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

 

Escape

 

Literal

sequence

Description

 

 

 

<%

<\%

The character sequence <% normally indicates the beginning of a

 

 

scriptlet. The <\% escape sequence places the literal characters

 

 

<% in the response to the client.

%>

%\>

The character sequence %> normally indicates the end of a

 

 

scriptlet. The %\> escape sequence places the literal characters

 

 

%> in the response to the client.

'

\"

As with string literals in a Java program, the escape sequences

"

\"

for characters '," and \ allow these characters to appear in

\

\\

attribute values. Remember that the literal text in a JSP

 

 

becomes string literals in the servlet that represents the

 

 

translated JSP.

 

 

 

[Page 1288]

27.5.2. Scripting Example

Figure 27.4 demonstrates responding to get requests with basic scripting capabilities. The JSP enables the user to input a first name, then outputs that name in the response. Using scripting, the JSP determines whether a firstName parameter was passed as part of the request. If not, the JSP returns an XHTML document containing a form through which the user can input a first name. Otherwise, the JSP obtains the firstName value and uses it as part of an XHTML document that welcomes the user to JavaServer Pages.

Figure 27.4. Scripting a JavaServer Pagewelcome.jsp.

(This item is displayed on pages 1289 - 1290 in the print version)

1

<?xml version = "1.0" ?>

2

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4

 

 

 

5

<!-- Fig. 27.4: welcome.jsp -->

6

<!--

JSP that

processes a "get" request containing data. -->

7

 

 

 

8

<html

xmlns =

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

9

 

 

 

10<!-- head section of document -->

11<head>

12<title>Processing "get" requests with data</title>

13</head>

14

15<!-- body section of document -->

16<body>

17<% // begin scriptlet

18

19 String name = request.getParameter( "firstName" );

20

21if ( name != null )

22{

23%> <%-- end scriptlet to insert fixed template data --%>

25

<h1>

26

Hello <%= name %>, <br />

27

Welcome to JavaServer Pages!

28

</h1>

29

 

30

<% // continue scriptlet

31

 

32} // end if

33else {

34

 

 

 

 

 

35

%>

<%--

end scriptlet to insert

fixed template data --%>

36

 

 

 

 

 

37

 

 

<form action = "welcome.jsp" method = "get">

38

 

 

 

<p>Type your first name

and press Submit</p>

39

 

 

 

 

 

40

 

 

 

<p><input type = "text" name = "firstName" />

41

 

 

 

<input type = "submit" value = "Submit" />

42

 

 

 

</p>

 

43

 

 

</form>

 

44

 

 

 

 

 

45

<%

//

continue scriptlet

 

46

 

 

 

 

 

47

 

}

//

end else

 

48

 

 

 

 

 

49%> <%-- end scriptlet --%>

50</body>

51

52 </html> <!-- end XHTML document -->

[View full size image]

Note that most of the code in Fig. 27.4 is XHTML markup (i.e., fixed-template data). Throughout the body element (lines 1650) are several scriptlets (lines 1723, 3035 and 4549) and a JSP expression (line 26). Note that three JSP comment styles appear in this JSP (at line 5, line 17 and line 23).

The scriptlets define an if...else statement that determines whether the JSP received a value for the first name as part of the request. Line 19 uses method getParameter of JSP implicit object request (an HttpServletRequest object) to obtain the value for parameter firstName and assigns the result to variable name. Line 21 determines whether or not name is null. If it is not null, a value for the first name was passed to the JSP as part of the request. If this condition is true, the scriptlet terminates temporarily so that the fixedtemplate data at lines 2528 can be output. The JSP expression in line 26 outputs the value of variable name (i.e., the first name passed to the JSP as a request parameter). The scriptlet continues at lines 3035 with the closing brace of the if statement's body and the beginning of the else part of the if...else statement. If the condition at line 21 is false, lines 2528 are not output. Instead, lines 3743 output a form element. The user can type a first name in the form and press the Submit button to request the JSP again and execute the if statement's body (lines 2528).

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.

[Page 1290]

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.

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.

Error-Prevention Tip 27.3

Always put the closing brace for the if statement and the else statement in the same scriptlet.

To test Fig. 27.4 in Tomcat, copy welcome.jsp into the jsp directory created in Section 27.3. Then, open your Web browser and enter the following URL:

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

[Page 1291]

When you first execute the JSP, it displays the form in which you can enter your first name, because the preceding URL does not pass a firstName parameter to the JSP. After you submit your first name, your browser should appear as shown in the second screen capture of Fig. 27.4. [Note: As with servlets, it is possible to pass get request arguments as part of the URL. The following URL supplies the firstName parameter to welcome.jsp.]

http://localhost:8080/jhtp6/jsp/welcome.jsp?firstName=Paul

[Page 1291 (continued)]

27.6. Standard Actions

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

<jsp:action> and </jsp:action>, where action is the standard action name. In cases where nothing appears between the starting and ending tags, the XML empty element syntax <jsp: 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

 

 

<jsp:include>

Dynamically includes another resource in a JSP. As the JSP

 

executes, the referenced resource is included and processed.

<jsp:forward>

Forwards request processing to another JSP, servlet or static

 

page. This action terminates the current JSP's execution.

<jsp:plugin>

Allows a plug-in component to be added to a page in the form

 

of a browser-specific object or embed HTML element. In the

 

case of a Java applet, this action enables the browser to

 

download and install the Java Plug-in, if it is not already installed

 

on the client computer.

<jsp:param>

Used with the include, forward and plugin actions to specify

 

additional name-value pairs of information for use by these

 

actions.

JavaBean Manipulation

 

<jsp:useBean>

Specifies that the JSP uses a JavaBean instance (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.

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

 

 

[Page 1292]

27.6.1. <jsp:include> Action

JavaServer Pages support two include mechanismsthe <jsp:include> action and the include directive. Action <jsp:include> 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 <jsp:include> 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 <jsp:include>.

 

Figure 27.6. Action <jsp:include> 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 <jsp:include> action is more flexible than the include directive, but requires more over-head when page contents change frequently. Use the <jsp:include> action only when dynamic content is necessary.

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 errorthe <jsp:include> action will not include any content.

The next example demonstrates action <jsp:include> 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 <jsp:include> 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 <jsp:include>.

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

1

<?xml version = "1.0"?>

2

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4

 

 

5

<!--

Fig. 27.7: include.jsp -->

6

 

 

7

<html

xmlns = "http://www.w3.org/1999/xhtml">

8

 

 

9<head>

10<title>Using jsp:include</title>

12<style type = "text/css">

13body

14{

15

font-family: tahoma, helvetica, arial, sans-serif;

16

}

17

 

18table, tr, td

19{

20

font-size: .

9em;

21

border: 3px

groove;

22

padding: 5px;

23

background-color: #dddddd;

24}

25</style>

26</head>

27

28<body>

29<table>

30<tr>

31

<td style =

"width: 160px; text-align: center">

32

<img src

= "images/logotiny.png"

33

width

= "140" height = "93"

34

alt =

"Deitel & Associates, Inc. Logo" />

35

</td>

 

36

<td>

 

37

<%-- include banner.html in this JSP --%>

38

<jsp:include page = "banner.html"

39

flush

= "true" />

40

</td>

 

41</tr>

42<tr>

43

<td style = "width: 160px" >

44

<%-- include

toc.html in this JSP --%>

45

<jsp:include

page = "toc.html" flush = "true" />

46

</td>

 

47

<td style = "vertical-align: top">

48

<%-- include

clock2.jsp in this JSP --%>

49

<jsp:include

page = "clock2.jsp"

50

flush = "true" />

51

</td>

 

52</tr>

53</table>

54</body>

55</html>

[View full size image]

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

<!--

Fig. 27

.8:

banner

.html

-->

2

<!--

banner

to

include

in another

document -->

3<div style = "width: 580px">

4<p>

5Java(TM), C, C++, Visual Basic(R),

6Object Technology, and <br /> Internet and

7World Wide Web Programming Training <br />

8On-Site Seminars Delivered Worldwide

9</p>

10<p>

11<a href = "mailto:deitel@deitel.com">deitel@deitel.com</a>

12<br />978.461.5880<br />12 Clock Tower Place, Suite 200,

13Maynard, MA 01754

14</p>

15</div>

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

<!--

Fig. 27.

9:

toc.html

 

-->

2

<!--

contents

to

include

in

another document -->

3

 

 

 

 

 

 

4<p><a href = "http://www.deitel.com/books/index.html">

5Publications/BookStore

6</a></p>

7

8<p><a href = "http://www.deitel.com/whatsnew.html">

9What's New

10</a></p>

11

12<p><a href = "http://www.deitel.com/books/downloads.html">

13Downloads/Resources

14</a></p>

15

16<p><a href = "http://www.deitel.com/faq/index.html">

17FAQ (Frequently Asked Questions)

18</a></p>

19

20<p><a href = "http://www.deitel.com/intro.html">

21Who we are

22</a></p>

23

24<p><a href = "http://www.deitel.com/index.html">

25Home Page

26</a></p>

27

28<p>Send questions or comments about this site to

29<a href = "mailto:deitel@deitel.com">

30deitel@deitel.com

31</a><br />

32Copyright 1995-2005 by Deitel & Associates, Inc.

33All Rights Reserved.

34</p>

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

<!--

Fig.

27.10: clock2.jsp

-->

2

<!--

date

and time to include in another document

-->

3

 

 

 

 

4<table>

5<tr>

6<td style = "background-color: black;">

7

<p

class = "big" style = "color: cyan; font-size: 3em;

8

 

font-weight: bold;">

 

9

 

 

 

10

 

<%-- script to determine client local and --%>

11

 

<%-- format date accordingly

--%>

12

 

<%

 

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

</p>

 

27

</td>

 

 

28

</tr>