JSP Tag Libraries

Скачать в pdf «JSP Tag Libraries»

Listing 2.4 Improved JSP file that uses scriptlets and expression printing




double num = Math.random(); boolean bigger = num > 0.5; int cap = (int)(num * 10);



Is <%= num %> bigger then 0.5? <br>

<% if(bigger) { %>


<% } else { %>


<% } %>



Now, let’s loop randomly … <br>

<% for(int i = 0 ; i < cap ; i++)    { %>

This is iteration number <%= i %>. <br> <% } %>




As you can see, using the expression printing syntax made the code cleaner and more readable.

NOTE Many see scriptlets as a necessary evil since using too many scriptlets in code breaks the separation of presentation and business logic. Scriptlets are a powerful weapon; after all, they are written in Java—a full-blown programming language. Yet, like most powerful weapons, consider carefully before using them. For example, implementing business logic or some reusable code by using a scriptlet in your page is dangerous and could harm your content developers. As we will see in this book, custom JSP tags are an excellent tool to avoid the scriptlet overflow.

Having seen a simple scriptlet example, let’s look at how scriptlets interact with the rich JSP environment on which they depend for web functionality. We saw an example of this in
listing 2.2 where we used an object called request to fetch the

Скачать в pdf «JSP Tag Libraries»