Web Development with JavaServer Pages

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


{ Recognizer r1 = new Recognizer(new Coordinates(grid, 0, 0));


Recognizer r2 = new Recognizer(new Coordinates(grid, 100, 100)); r1.findProgram(«Flynn»); r2.findProgram(«Flynn»); %>


<h2>Status</h2>


<ul>


<li>First Recognizer: <%= r1.statusReport() %>


<li>Second Recognizer: <%= r2.statusReport() %>


</ul>


<% } %>


Alert Level:    <%= grid.alertLevel() %>


</body>


</html>


In this case, the first scriptlet introduces a new program block before creating the two Recognizer instances. The second scriptlet, toward the end of the page, closes this block. Within that block, the r1 and r2 instances are said to be in scope, and may be referenced freely. After that block is closed, these objects are out of scope, and any references to them will cause a compile-time error when the page is compiled into a servlet by the JSP container. Note that because the grid variable is introduced before the block is opened, it is in the page’s top-level scope, and can continue to be referenced after the second scriptlet closes the block opened by the first, as in the call to its alertLevel() method near the end of the page.


The reason this works has to do with the translation of the contents of a JSP page into source code for a servlet. Static content, such as HTML code, is translated into Java statements which print that text as output from the servlet. Similarly, expressions are translated into Java statements which evaluate the expression, convert the result to a string, and print that string value as output from the servlet. Scriptlets, however, undergo no translation at all, and are simply inserted into the source code of the servlet as is. If a scriptlet opens a new block without also closing it, then the Java statements corresponding to any subsequent static content or JSP elements simply become part of this new block. The block must ultimately be closed by another scriptlet, or else compilation will fail due to a Java syntax error.

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