Scriptlets

A scriptlet is a block of code enclosed between a scriptlet-start identifier, <%, and an end identifier, %>:

<%@ page language="java" contentType="text/html" %>
<html>
<body bgcolor="white">
<jsp:useBean id="clock" class="java.util.Date" />

               <% if (clock.getHours() < 12) { %>
  Good morning!
<% } else if (clock.getHours() < 17) { %>
  Good day!
<% } else { %>
  Good evening!
<% } %>

</body>
</html>

Here, a clock bean is first created by the <jsp:useBean> action and assigned to a variable with the same name. It is then used in four scriptlets, together forming a complete Java if statement with template text in the if and else blocks:

<% if (clock.getHours() < 12) { %>

An if statement, testing if it’s before noon, with a block start brace

<% } else if (clock.getHours() < 17) { %>

The if block end brace and an else-if statement, testing if it’s before 5 P.M., with its block start brace

<% } else { %>

The else-if block end brace and a final else block start brace, handling the case in which it’s after 5 P.M.

<% } %>

The else block end brace

The web container combines the code segment in the four scriptlets with code for writing the template text to the response body. The end result is that when the first if statement is true, “Good morning!” is displayed, and when the second if statement is true, “Good day!” is displayed. If neither if statement is true, the final else block is used, displaying “Good evening!”

The tricky part when using scriptlets is making sure to get all the ...

Get JavaServer Pages Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.