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.

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 <% and %>. They contain Java statements that the container places in method _jspService at translation 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 . 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)

Literal

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

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)

"http://www.w3.org/1999/xhtml"> 9 10 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
 8 
Processing "get" requests with data 13 14 15 16 17 <% // begin scriptlet 18 19 String name = request.getParameter( "firstName" ); 20 21 if ( name != null ) 22 { 23 %> <%-- end scriptlet to insert fixed template data --%> 24 25

Hello <%= name %>,
27 Welcome to JavaServer Pages! 28

29 30 <% // continue scriptlet 31 32 } // end if 33 else { 34 35 %> <%-- end scriptlet to insert fixed template data --%> 36 37 "welcome.jsp" method = "get"> 38

Type your first name and press Submit

39 40

"text" name = "firstName" /> 41 "submit" value = "Submit" /> 42

43 44 45 <% // continue scriptlet 46 47 } // end else 48 49 %> <%-- end scriptlet --%> 50 51 52

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.

 

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

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


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