Web Development with JavaServer Pages

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


NOTE Java statements corresponding to a JSP page’s static content, expressions, and scriptlets are used to create the _jspService() method of the corresponding servlet. This method is responsible for generating the output of the JSP page. Directives and declarations are also translated into servlet code, but do not contribute to the _jspService() method and so are not affected by scoping due to scriptlets. On the other hand, the JSP Bean tags, discussed in chapter 7, are translated into Java statements for the _jspService() method and therefore are subject to scoping restrictions introduced via scriptlets.

5.5 Flow of control


This ability of scriptlets to introduce statement blocks without closing them can be put to good use in JSP pages to affect the flow of control through the various elements, static or dynamic, that govern page output. In particular, such scriptlets can be used to implement conditional or iterative content, or to add error handling to a sequence of operations.

5.5.1 Conditionalization


Java’s if statement, with optional else if and else clauses, is used to control the execution of code based on logical true/false tests. Scriptlets can use the if statement (or the appropriate analog if the scripting language is not Java) to implement conditional content within a JSP page. The following page fragment, for example, uses the fact() method introduced earlier in this chapter to compute the factorial of a page variable named x, as long as it is within the appropriate range:


<% if (x < 0) { %>


<p>Sorry, can’t compute the factorial of a negative number.</p>

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