The JSP Files (part 1): Purple Pigs In A Fruitbasket - Enter John Doe (
Page 4 of 7 )
Variables are the bread and butter of every programming language...and JSP has
them too. A variable can be thought of as a programming construct used to store
both numeric and non-numeric data; this data can then be used in different
places in your JSP scriptlets.
JSP supports a number of different
variable types: integers, floating point numbers, strings and arrays. Unlike
PHP, which can automagically determine variable type based on the data it holds,
JSP requires you to explicitly define the type of each variable before using
it.
Every variable has a name - in JSP, a variable name is preceded by a
keyword indicating the variable type, and must begin with a letter, optionally
followed by more letters and numbers. Variable names are case-sensitive, and
reserved keywords cannot be used as variable names.
For example,
"popeye", "one_two_three" and "bigPirateShip" are all valid variable names,
while "byte" and "123" are invalid variable names.
The following example
demonstrates how variables can be used in a JSP document.
<html>
<head>
</head>
<body>
<%!
// define variables here
String name = "John Doe";
%>
<%
// code comes here
out.println("My name is " + name );
%>
</body>
</html>
As you can see, we've first defined a variable named
"name", set things up so that it will hold string, or character, data, and
assigned a value ("John Doe") to it. This value is then used by the println()
function to display a message in the HTML page.
My name is John Doe
If you're sharp-eyed, you'll have noticed a slight
difference between the two JSP blocks in the example above - the first looks
like this
<%!
...
%>
while the second looks like this
<%
...
%>
The first block, within which the variables are defined,
is referred to as the "declaration block"; variables declared within this block
are available globally, to each and every scriptlet within that JSP
document.
You can also define a variable without assigning a value to it,
or assign a value to it at a later stage - for example, the following code
snippets are equivalent.
<%
String name;
name = "John Doe";
%>
<%
String name = "John Doe";
%>