Professional Documents
Culture Documents
Rabbits
By Vikram Vaswani and Harish Kamath
Table of Contents
Counting Down....................................................................................................................................................1
For−gone Conclusion..........................................................................................................................................5
A Positive Response..........................................................................................................................................17
i
Counting Down
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.
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!
}
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:
Here's an example:
<html>
<head>
</head>
<body>
<%!
int countdown=30;
Counting Down 1
The JSP Files (part 3): Black Light And White Rabbits
%>
<%
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.
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!
Counting Down 2
Doing More With Loops
There's one caveat with the "while" loop. If the conditional expression evaluates as false the first time, the
code within the curly braces will never be executed. If this is not what you want, take a look at the "do−while"
loop, which comes in handy in situations where you need to execute a set of statements *at least* once.
do
{
do this!
} while (condition)
For example, the following lines of code would generate no output whatsoever, since the conditional
expression in the "while" loop would always evaluate as false.
However, the construction of the "do−while" loop is such that the statements within the loop are executed
first, and the condition to be tested is checked after. Using a "do−while" loop implies that the code within the
curly braces will be executed at least once − regardless of whether or not the conditional expression evaluates
as true.
do
{
out.println ("Bingo!");
break;
} while (bingo == 699);
%>
Looks like gibberish? Well, hang in there a minute...the "counter" here is a JSP variable that is initialized to a
numeric value, and keeps track of the number of times the loop is executed. Before each execution of the loop,
the "condition" is tested − if it evaluates to true, the loop will execute once more and the counter will be
appropriately incremented; if it evaluates to false, the loop will be broken and the lines following it will be
executed instead.
And here's a simple example that demonstrates how this loop can be used:
<html>
<head>
<basefont face="Arial">
</head>
<body>
<center>Turning The Tables, JSP−Style!</center>
<br>
<%!
// define the number
int number = 7;
int x;
%>
<%
// use a for loop to calculate tables for that number
For−gone Conclusion 5
The JSP Files (part 3): Black Light And White Rabbits
for (x=1; x<=15; x++)
{
out.println(number + " X " + x + " = " + (number*x) + "<br>");
}
%>
</body>
</html>
7 X 1 = 7
7 X 2 = 14
7 X 3 = 21
7 X 4 = 28
7 X 5 = 35
7 X 6 = 42
7 X 7 = 49
7 X 8 = 56
7 X 9 = 63
7 X 10 = 70
7 X 11 = 77
7 X 12 = 84
7 X 13 = 91
7 X 14 = 98
7 X 15 = 105
Right up front, a variable is defined, containing the number to be used for the multiplication table; we've used
7 here − you might prefer to use another number.
Next, a "for" loop has been constructed, with "x" as the counter variable. If you take a look at the first line of
the loop, you'll see that "x" has been initialized to 1, and is set to run no more than 15 times.
For−gone Conclusion 6
The JSP Files (part 3): Black Light And White Rabbits
Finally, the println() function is used to take the specified number, multiply it by the current value of the
counter, and display the result on the page.
For−gone Conclusion 7
The Sound Of Breaking Loops
When dealing with loops, there are two important keywords you should be aware of: "break" and "continue".
The "break" keyword is used to exit a loop when it encounters an unexpected situation. A good example of
this is the dreaded "division by zero" error − when dividing one number by another one (which keeps
decreasing), it is advisable to check the divisor and use the "break" statement to exit the loop as soon as it
becomes equal to zero.
As you've already seen, the "continue" keyword is used to skip a particular iteration of the loop and move to
the next iteration immediately − it's demonstrated in the following example:
int x;
for (x=1; x<=10; x++)
{
if (x == 7)
{
continue;
}
else
{
out.println(x + " ");
}
}
%>
In this case, JSP will print a string of numbers from 1 to 10 − however, when it hits 7, the "continue"
statement will cause it to skip that particular iteration and go back to the top of the loop. So your string of
numbers will not include 7 − try it and see for yourself.
First, there's the indexOf() method, which is used to locate the first occurrence of a character or substring in a
larger string. If you ran the following code snippet,
<%
// define variable
String storyName = "The Pied Piper Of Hamlin";
// find index
int i = storyName.indexOf("i");
// print index
out.println("The letter i first occurs at " + i + " in the
string " +
storyName);
%>
Yes, the first character is treated as index 0, the second as index 1, and so on. These programmers...
The opposite of this is the lastIndexOf() function, used to identify the last occurrence of a character or
substring in a larger string. Take a look:
<%
// define variable
String storyName = "The Pied Piper Of Hamlin";
// find index
int i = storyName.lastIndexOf("Pi");
// print index
out.println("The string Pi last occurs at " + i + " in the
string " +
storyName);
%>
In case the character or substring is not located, the function will return an error code of −1.
// define variable
String whatIWant = " gimme my space ";
// trim!
// returns "gimme my space"
whatIWant.trim();
%>
The toUpperCase() and toLowerCase() methods come in handy to alter the case of a string.
// define variable
String someString = "don't SCREam, help is oN the WAy!";
The startsWith() and endsWith() functions are used to verify whether a string starts or ends with a specified
character or sequence of characters. The following example should illustrate this clearly.
if (alpha.startsWith(prefix))
{
out.println("The string " + alpha + " starts with " + prefix +
"
");
}
if (beta.startsWith(prefix))
{
out.println("The string " + beta + " starts with " + prefix +
"
");
}
if (alpha.endsWith(suffix))
{
out.println("The string " + alpha + " ends with " + suffix + "
");
}
if (beta.endsWith(suffix))
{
out.println("The string " + beta + " ends with " + suffix + "
");
}
%>
// define variables
String someString = "97";
int aRandomNumber = 3;
");
%>
If you'd prefer to do things the other way around, the next example bears careful consideration.
// define variables
int someNumber = 97;
int aRandomNumber = 3;
");
%>
Since the Response object is an "implicit" object (so called because you do not need to explicitly create an
instance of the object when you want to use it), you can begin using it immediately in a JSP document. The
following example demonstrates using it to turn off caching via the "Cache−Control" header.
response.setHeader("Cache−Control","no−cache");
%>
response.setHeader("Location", "error.html");
%>
You can use the sendRedirect() method to accomplish something similar − remember to use an absolute URL
here.
response.sendRedirect("http://my.server.com/error.html");
%>
You can set the MIME type of a document with the setContentType() method.
A Positive Response 17
The JSP Files (part 3): Black Light And White Rabbits
response.setContentType("image/jpeg");
%>
and even set a cookie with the addCookie() method − more on this as we progress through this series.
That's about all we have time for. Next time, we'll be exploring the JSP Response object, used to process data
from HTML forms...so you don't want to miss that one!
Note: All examples in this article have been tested on Linux/i586 with Tomcat 3.2 and JServ 1.1. Examples
are illustrative only, and are not meant for a production environment. YMMV!
A Positive Response 18