Wednesday, April 27, 2011

JSP: scriptlets

Scriptlets
Scriptlets provide a method for directly inserting bits of Java code between
chunks of template text. A scriptlet is defined with a start ,<%, an end, %>, with
code between. Using Java, the script is identical to normal Java code but without
needing a class declaration or any methods. Scriptlets are great for providing low-
level functionality such as iteration, loops, and conditional statements, but they
also provide a method for embedding complex chunks of code within a JSP.
For many reasons complex scriptlets should be avoided. This is mainly due to
the fact that the more scriptlets are used the harder it is to understand and
maintain a JSP. In this chapter most of the scriptlet examples are purposely kept
simple. This aids in directly demonstrating the core functionality of JSP, but it is
also done so that examples do not appear to encourage heavy use of scriptlets. As
an introduction, Listing 2 provides a simple JSP that loops to produce multiple
lines of text. Looping is accomplished the same as in Java but by placing the
equivalent Java code inside scriptlet elements. Loop.jsp
Listing 2 
<html>
<head>
<title>Loop Example</title>
</head>
<body>
<% for (int i=0; i<5;i++) { %>
Repeated 5 Times.<br>
<% } %>
</body>
</html>
Save  Loop.jsp in the base directory of the jspbook Web Application and
browse to http://127.0.0.1/jspbook/Loop.jsp. The page shows up with the
statement, “Repeated 5 Times.”, repeated five times.

output
Repeated 5 Times
Repeated 5 Times
Repeated 5 Times
Repeated 5 Times
Repeated 5 Times


It is important to note that the contents of the scriptlet did not get sent to a
client. Only the results of the scriptlet did. This is important because it shows that
scriptlets are interpreted by a container and that code inside a scriptlet is not by
default shared with visitors of the JSP.
A JSP may contain as many scriptlets as are needed, but caution should be
taken not to overuse scriptlets. Scriptlets make a JSP very hard to maintain and
are not easily documented; for example, tools like javadoc do not work with JSP

No comments:

Post a Comment