Java Reference
In-Depth Information
JSP Declarations, Expressions, Scriptlets, and Directives
A JSP Web page is created the same way you make an HTML file, except JSP code
is added along with the HTML code. Additionally, instead of naming the file with
an extension of
.HTM or .HTML
, the extension is
.JSP
. The file should be placed in
the root folder of your Web server so it can be accessed by and processed through the
Web server.
The JSP elements we will briefly discuss are
declarations
,
expressions
,
scriptlets
,
and
directives
. All of these elements are identified by their own tags. The
declarations
tag allows us to define variables and methods. The variables and methods are accessible
from any scriptlets and expressions on the same page. Variable declarations are
compiled as instance variables for a class that corresponds to the JSP page. Declarations
are defined with the syntax
JSP elements
declaration
<%!
Declarations
%>
For example, the following defines an instance variable named
count
and a method
named
incrementCount
that increments the
count
variable:
<%!
private int
count = 0;
private void
incrementCount()
{
count++;
}
%>
We can access variables defined in declarations with
expression
. The syntax to embed
an expression is as follows:
expression
<%=
Expression
%>
Expressions are embedded directly into the HTML. The Web browser will display the
value of the expression in place of the tag. For example, we can output the value of the
count
variable in bold type with the following piece of HTML:
The value of count is <b> <%= count %> </b>
Blocks of Java code can be embedded in a
scriptlet
. The syntax for a scriptlet is
as follows:
scriptlet
<%
Java code
%>
If you wish to output HTML within a scriptlet, then this is done using
out.println()
,
which is used in the same manner as
System.out.println( )
. The variable
out
is
already defined for us and is of type
javax.servlet.jsp.JspWriter
. Also note that