Wednesday, April 27, 2011

JSP:Expressions

Expressions provide an easy method of sending out dynamic strings to a client.
An expression must have a start, <%=, end, %>, and an expression between. An
expression element differs in syntax from a scriptlet by an equal sign that must
appear immediately after the start. Expressions always send a string of text to a
client, but the object produced as a result of an expression does not have to
always end up as an instance of a String object.Any object left as the result of an
expression automatically has its toString() method called to determine the
value of the expression. If the result of the expression is a primitive, the prim-
itive’s value represented as a string is used.

Combined with scriptlets, expressions are useful for many different purposes.
A good example is using a scriptlet that is combined with an expression to
provide a method of iterating over a collection of values. The scriptlet provides a
loop, while expressions and static content are used to send information in a
response. Iteration.jsp (Listing 4) provides an example of this along with a
demonstration of passing a non-String object as the result of an expression.
Listing 4 Iteration.jsp
<html>
<head>
<title>Iteration Example</title>
</head>
<body>
<%
String[] strings = new String[4];
strings[0] = "Alpha";
strings[1] = "in";
strings[2] = "between";
strings[3] = "Omega";
for (int i=0; i<strings.length;i++) { %>
String[<%= i %>] = <%= strings[i] %><br>
<% } %>
</body>
</html>
Save  Iteration.jsp in the base directory of the jspbook Web Application
and browse to http://127.0.0.1/jspbook/Iteration.jsp. The page displays a
list of an iteration through all of the values of the array. Figure 4 shows a
browser rendering of the output sent by Iteration.jsp.

No comments:

Post a Comment