The JSP Files (part 3): Black Light And White Rabbits (
Page 1 of 7 )
This week, learn all about the different types of loops supported
by JSP, and also expand your knowledge of the various String object
methods. Finally, take a quick tour of the JSP Response object in
preparation for learning how JSP handles form data.Last time out, you learned a little bit about the various conditional statements
and operators available in JSP. This week, we'll expand on those basics by
teaching you a little bit about the different types of loops available in JSP,
discuss a few more String object methods, and take a quick tour of the new
Response object.
First up, loops.
As you may already know, a
"loop" is a programming construct that allows you to execute a set of statements
over and over again, until a pre-defined condition is met.
The most basic
loop available in JSP is the "while" loop, and it looks like this:
while (condition)
{
do this!
}
Or, to make the concept clearer,
while (temperature is below freezing)
{
wear a sweater
}
The "condition" here is a standard conditional expression,
which evaluates to either true or false. So, were we to write the above example
in JSP, it would look like this:
while (temp <= 0)
{
sweater = true;
}
Here's an example:
<html>
<head>
</head>
<body>
<%!
int countdown=30;
%>
<%
while (countdown > 0)
{
out.println(countdown + " ");
countdown--;
}
out.println("<b>Kaboom!</b>");
%>
</body>
</html>
Here, the variable "countdown" is initialized to 30, and a
"while" loop is used to decrement the value of the variable until it reaches 0.
Once the value of the variable is 0, the conditional expression evaluates as
false, and the lines following the loop are executed.
Here's the output:
30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4
3 2 1 Kaboom!