Wednesday, April 27, 2011

JSP: Declarations

Declarations are the third and final scripting element available for use in JSP. A
declaration is used like a scriptlet to embed code in a JSP, but code embedded by
a declaration appears outside of the _jspService()method. For this reason code
embedded in a declaration can be used to declare new methods and global class
variables, but caution should be taken because code in a declaration is not
thread-safe, unless made so by the writer of that code.

Listing 5 is a JSP designed to keep a page counter of how many times it has
been visited. The JSP accomplishes this by declaring a class-wide variable in a
declaration, using a scriptlet to increment the variable on page visits, and an
expression to show the variable’s value.
Listing 5 PageCounter.jsp
<%! int pageCount = 0;
void addCount() {
pageCount++;
}
%>
<html>
<head>
<title>PageCounter.jsp</title>
</head>
<body>
<% addCount(); %>
This page has been visited <%= pageCount %> times.
</body>
</html>
Save PageCounter.jsp in the base directory of the jspbook Web Application
and browse to http://127.0.0.1/jspbook/PageCounter.jsp. Refresh the
browser a few times to watch the JSP count how many times it has been visited.
Figure 5 shows a browser rendering of the output after visiting the JSP 6 times.



No comments:

Post a Comment