[ Team LiB ] Previous Section Next Section

Using the <% %> Tags in a JavaServer Page

As you saw in the HelloWorld.jsp example, the <% and %> tags in a JSP file are used to indicate the presence of Java code within the HTML. The JSP specification allows for languages other than Java to be used for scripting; at the present time, however, few servers support languages other than Java. Eventually there will be more support for other scripting languages, but until that time, and certainly for the rest of this book, the focus is on Java as the JSP scripting language.

Let's take a look at another example of a JavaServer Page in Listing 1.4.

Listing 1.4 Source Code for Greeting.jsp
<html>
<body>
Good
<%
    java.util.Calendar currTime = new java.util.GregorianCalendar();

    if (currTime.get(currTime.HOUR_OF_DAY) < 12)
    {
%>
        Morning!
<%
    }
    else if (currTime.get(currTime.HOUR_OF_DAY) < 18)
    {
%>
        Afternoon!
<%
    }
    else
    {
%>
        Evening!
<%
    }
%>
</body>
</html>

If you are unfamiliar with either Active Server Pages or JavaServer Pages, the code in Listing 1.4 probably looks absolutely bizarre to you. First, remember that the code outside of the <% %> tag pair is sent verbatim. Of course, that might lead you to conclude that the three strings, Morning!, Afternoon!, and Evening!, should all be sent in the response. What really happens is that items outside of the <% %> tag pair are converted into Java statements that print out the HTML verbatim. Because the Morning!, Afternoon!, and Evening! strings occur within an if statement, they are printed only when their section of the if block is true.

Listing 1.5 shows you a portion of the Java code generated by the JSP in Listing 1.4. (Don't worry, you won't have to look at the Java code for every JSP in this book or even in this hour.)

Listing 1.5 Java Code Generated by Listing 1.4
      out.write("<html>\r\n");
      out.write("<body>\r\nGood\r\n");

    java.util.Calendar currTime = new java.util.GregorianCalendar();
    if (currTime.get(currTime.HOUR_OF_DAY) < 12)
    {
      out.write("\r\n        Morning!\r\n");
    }
    else if (currTime.get(currTime.HOUR_OF_DAY) < 18)
    {
      out.write("\r\n        Afternoon!\r\n");
    }
    else
    {
      out.write("\r\n        Evening!\r\n");
    }

      out.write("\r\n");
      out.write("</body>\r\n");
      out.write("</html>\r\n");

Comparing Listing 1.5 to Listing 1.4, you should begin to get the idea of how the code within <% and %> relates to the rest of the file.

Reading through JSPs

graphics/didyouknow_icon.gif

It's easier to read through a JSP if you remember that any text outside the <% and %> tags is really just shorthand for an out.write statement containing that text.


Listing 1.4 illustrates how scriptlets and HTML can be intermixed. However, it is not a good example of how to make a clear, readable JSP file.

    [ Team LiB ] Previous Section Next Section