| [ directory ] |
|
8.2 Using XML in JSPsAs an XML document is merely a bunch of text, creating one through a JSP is no more difficult than creating an HTML document. Listing 8.4 shows a JSP that retrieves CD information from a database and generates the CD collection from Listing 8.2. Listing 8.4 Generating XML with a JSP
<%@ page contentType="text/xml" %>
<%@ taglib prefix="c"
uri="http://java.sun.com/jstl/core" %>
<jsp:useBean
id="artist"
class="com.awl.jspbook.ch08.ArtistBean"/>
<jsp:setProperty
name="artist"
property="*"/>
<collection>
<artist name="<c:out escapeXml="false"
value="${artist.name}"/>">
<c:forEach items="${artist.cds}" var="cd">
<album name="<c:out value="${cd.name}"/>">
<c:forEach items="${cd.tracks}" var="track">
<track name="<c:out value="${track.name}"/>"/>
</c:forEach>
</album>
</c:forEach>
</artist>
</collection>
In almost all respects, this example is identical to Listing 6.6, the major difference being the use of XML tags here instead of HTML. As it will not be returning an HTML document, it is important that this page notify the browser what kind of data to expect. This is accomplished by the use of the page directive at the top. Telling the browser that it will be getting an XML document allows the browser to present the data properly. For example, both Mozilla and Internet Explorer have a special mode that allows users to open and close portions of XML documents interactively. In Figure 8.1, which shows Mozilla's view of such data, a + in front of a node indicates that it may be expanded by clicking it; conversely, - means that the node can be collapsed. Figure 8.1. The browser view of an XML document.
More interesting is that the output of this page contains all the data from the database, and the DTD contains almost all the information present in the SQL schema from Listing 6.1. This suggests a deep connection between databases and XML, and because there is already a known relationship between databases and JavaBeans, this would suggest that all three are in some sense interchangeable. To an extent, this is true. Just as tools can create beans from databases, tools can create database schemas from XML DTDs and vice versa. Tools can also convert between DTDs and beans, most notably Sun's JAXB toolkit, available at http://java.sun.com/xml/jaxb/. All three types of relationships are ways to store and manipulate data. Each one has strengths that make it well suited to particular tasks. Databases are appropriate for storing large quantities of data and retrieving it based on arbitrary criteria. XML is appropriate for storing and transmitting relatively small amounts of data and for data that needs to be translated programmatically into other forms. Beans, as seen numerous times, are well suited for moving data from the underlying model to the view or, more generally, for providing access to the model from other code. |
| [ directory ] |
|