Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
242
Chapter 10 JSP Scripting Elements
When converted to a servlet by the JSP engine, this fragment will result in
something similar to the following.
if (Math.random() < 0.5) {
out.println("Have a nice day!");
} else {
out.println("Have a lousy day!");
}
Special Scriptlet Syntax
There are two special constructs you should take note of. First, if you want to
use the characters
%>
inside a scriptlet, enter
%\>
instead. Second, the XML
equivalent of
<% Code %>
is
Code
The two forms are treated identically by JSP engines.
10.4 JSP Declarations
A JSP declaration lets you define methods or fields that get inserted into the
main body of the servlet class (outside of the
_jspService
method that is
called by
service
to process the request). A declaration has the following form:
<%! Java Code %>
Since declarations do not generate any output, they are normally used in
conjunction with JSP expressions or scriptlets. For example, here is a JSP
fragment that prints the number of times the current page has been
requested since the server was booted (or the servlet class was changed and
reloaded). Recall that multiple client requests to the same servlet result only
in multiple threads calling the
service
method of a single servlet instance.
They do not result in the creation of multiple servlet instances except possibly
when the servlet implements
SingleThreadModel
. For a discussion of
Sin
gleThreadModel
, see Section 2.6 (The Servlet Life Cycle) and Section 11.3
(The isThreadSafe Attribute). Thus, instance variables (fields) of a servlet are
shared by multiple requests and
accessCount
does not have to be declared
static
below.
<%! private int accessCount = 0; %>
Accesses to page since server reboot:
<%= ++accessCount %>
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved