Embedding Dynamic Elements in HTML Pages

JSP tackles the problem from the other direction. Instead of embedding HTML in programming code, JSP lets you embed special active elements into HTML pages. These elements look similar to HTML elements, but behind the scenes they are actually componentized Java programs that the server executes when a user requests the page. Here’s a simple JSP page that illustrates this:

                  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
  <body bgcolor="white">
  
  <jsp:useBean id="clock" class="java.util.Date" />
                  <c:choose>
                  <c:when test="${clock.hours < 12}">
      <h1>Good morning!</h1>
    </c:when>
                  <c:when test="${clock.hours < 18}">
      <h1>Good day!</h1>
    </c:when>
                  <c:otherwise>
      <h1>Good evening!</h1>
    </c:otherwise>
                  </c:choose>
  Welcome to our site, open 24 hours a day.
  </body>
</html>

This page inserts a different message to the user based on the time of day: “Good morning!” if the local time is before 12 P.M., “Good day!” if between 12 P.M. and 6 P.M., and “Good evening!” otherwise. When a user asks for this page, the JSP-enabled web server executes the logic represented by the highlighted JSP elements and creates an HTML page that is sent back to the user’s browser. For example, if the current time is 8:53 P.M., the resulting page sent from the server to the browser looks like this:

<html>
  <body bgcolor="white">
  <h1>Good evening!</h1>
    Welcome to our site, open 24 hours a day.
  </body>
</html>

A screen shot of this result is shown in Figure 1-2.

Figure 1-2. The ...

Get JavaServer Pages, 3rd Edition 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.