Web Development with JavaServer Pages

Скачать в pdf «Web Development with JavaServer Pages»

Conversion to String






toString() method of object’s class

Notice that no semicolon was provided at the end of the Java code used in the example JSP expressions. This is because Java’s semicolon is a statement delimiter. A semicolon has the effect of transforming a Java language expression into a program statement. In Java, statements are evaluated purely for their side effects; they do not return values. Thus, leaving out the semicolon in JSP expressions is the right thing to do, because the JSP container is interested in the value of the enclosed code, not its side effects.

Given that this scripting element produces output only from expressions, not statements, you may be wondering if there is a convenient way to do conditional output in a JSP page. Java’s standard if/then construct, after all, is a statement, not an expression: its clauses are evaluated purely for side effects, not value. Fortunately, Java supports the oft-forgotten ternary conditional operator, which does return a value based on the result of a conditional test. The syntax of Java’s ternary operator is as follows:

test_expr ? true_expr : false_expr

Each operand of the ternary operator is itself an expression. The test_expr expression should evaluate to a boolean value. If the value of test_expr expression is true, then the true_expr expression will be evaluated and its result returned as the result of the ternary operator. Alternatively, if the value of test_expr expression is false, then the faise_expr expression is evaluated and its result will be returned. The ternary operator can thus be used in a JSP expression as in the following:

Скачать в pdf «Web Development with JavaServer Pages»