Encoding Non-XML Data and Special Characters

Since a JSP Document is a formal XML document, all template data must be well- formed XML. Example 17-10 is well-formed because it contains XHTML elements, such as the <ul> and <li> elements, represented by opening and closing tags, and an empty <br/> tag.

If you use a JSP Document to generate a response in a format that is not XML-based, you can embed the template data that is not well-formed in XML CDATA sections. For instance, if the response must be accessible to older browsers that only understand HTML 3.2, you can’t use the XHTML <br/> empty tag syntax, but using HTML 3.2 syntax with a single opening <br> tag violates the well-formedness requirement. Embedding the HTML 3.2 single opening <br> tag in a CDATA section solves the problem; it satisfies the container’s well-formed XML requirement and feeds the browser the HTML 3.2 tag it understands:

<ul> 
  <c:forEach items="${paramValues}" var="current"> 
    <li> 
      ${current.key}:
      <c:forEach items="${current.value}" var="parValue">
        <![CDATA[<br>]]>${parValue}
      </c:forEach>
    </li> 
  </c:forEach>

In an XML document, special characters such as greater-than and less-than in an element body (or attribute) must be replaced with character entity codes, for example, the < character must be replaced with &lt; and > must be replaced with &gt;. These characters are common in Java code, so if you need to use scripting elements in a JSP Document, you can use a CDATA section to work around this issue as well:

                  

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.