Hello XML

The JSP 2.0 example (Example 20-5) looks much cleaner than the original JSP code of Example 20-4. Because of its <%@page...%> and <%@taglib...%> directives, however, it is not a valid XML document. JSP 2.0 pages can also be written as valid XML documents using a slightly different format illustrated in Example 20-6. hello3.jspx (note the file extension) is a rewrite of Example 20-5 using the XML format. It is a valid XML file that, when accessed, outputs a valid XHTML document. It uses the <jsp:directive.page> tag instead of the @page directive, and it uses a custom <tags:xhtml> tag to output an appropriate XHTML DOCTYPE declaration and <html> tag. The definition of this custom <tags:xhtml> tag is in the WEB-INF/tags/ directory of the WAR file, and is not shown here. We’ll see more about JSP 2 custom tags later in this chapter.

Example 20-6. hello3.jspx

<?xml version="1.0"?>
<tags:xhtml xmlns:tags="urn:jsptagdir:/WEB-INF/tags"
            xmlns:jsp="http://java.sun.com/JSP/Page"
            xmlns:c="http://java.sun.com/jsp/jstl/core"
            xmlns="http://www.w3.org/1999/xhtml">
<jsp:directive.page contentType='text/html'/>
<head><title>Hello</title></head>
  <body>
    <c:choose>
      <c:when test='${param.name == null}'>
        <form action="hello3.jspx">
        <p>Please enter your name:
        <input name="name"/>
        <input type="submit"/>
        </p></form>
      </c:when>
      <c:otherwise>
        <p>Hello ${param.name}!</p>
      </c:otherwise>
    </c:choose>
  </body>
</tags:xhtml>

Get Java Examples in a Nutshell, 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.