Java Reference
In-Depth Information
Using Local Variables in a JSP Script
To declare an instance method or instance variable in a JSP script, you
must use a JSP declaration tag which begins with the tag, <%!, as shown in
Table 12-6 on page 839. Recall that instance variables are shared among all
threads of a servlet, including servlets generated from a JSP. Local variables
declared within a script, however, are thread-safe and require no special tags
in addition to being within a scriptlet. If you define a variable of a class from
another package, you will need to import the package as discussed earlier.
Recall that when the WebStocks servlet retrieved a quote from the Yahoo!
stock quote server, it stored the resulting String object as the session attribute,
quote. This string contains comma-delimited data, with each record separated by
a newline character (\n). Displaying the string as a whole would not be informa-
tive to a user, as it contains delimiters. A delimiter is a character, such as a
comma or a newline, used to separate data fields, particularly in a stream of tex-
tual data. The data fields must be separated out, with the delimiters discarded.
Separating out delimited data is called parsing . Each data field then can be
formatted as desired and displayed in a meaningful way to the user.
Because the data is returned as a String object, a StringTokenizer object can
be used to parse the string. A StringTokenizer object allows an application to
break a string into tokens. A token is a set of characters separated from other
tokens by one or more delimiters; that is, the data fields.
Figure 12-73 on the next page displays lines 152 through 196 of the code for
mainForm.jsp. Lines 160 and 161 create a new StringTokenizer object, using the
String from the quote session attribute and a set of delimiters. The set of delim-
iters is a string that contains the delimiter characters — in this case, a double
quote (“), a comma (,), and a newline (\n). Because the double quote is itself
enclosed within double quotes, it must be preceded by a backslash, similar to the
newline character. The hasMoreTokens() method in line 167 tests if more
tokens are available from the StringTokenizer's string. Each stock quote has nine
requested fields, as outlined in the requirements document in Figure 12-2 on
page 781. The nextToken() method in line 170 returns the next token from the
StringTokenizer. The data for each of the nine fields is placed into a StringBuffer
array for later manipulation. Once the array is loaded, each field is printed to the
HTML textarea which begins on line 154. A textarea provides a scrollable text
box that displays multiple rows of data on a Web page. Recall that with a servlet,
you had to get a PrintWriter object to print data to the Web page. The JSP
already has a default PrintWriter object named, out, used in lines 163 through
190 to print data to the Web page.
Search WWH ::




Custom Search