XML站点程序文档
文档 1. HotelController.java
This class is the session-specific controller. It parses user requests, accesses the model, and decides which view should be delivered back to the client.
package dw_travel.hotel;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import dw_travel.common.*;
public class HotelController {
private ServletContext context;
private HttpSession session;
private String realPath;
private String nextPage = null;
private static final String HOTELS_KEY = "hotels";
public HotelController() { }
public void init(ServletContext context,
HttpSession session) {
this.context = context;
this.session = session;
this.realPath = context.getRealPath("/");
}
public void service(HttpServletRequest req) {
// Extract the command from the request.
String cmd = null;
Enumeration names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = (String)names.nextElement();
if (name.startsWith("cmd-")) {
cmd = name.substring(4, name.length());
break;
}
}
// Route according to the command.
if (cmd == null) { unknownCommand(req); }
else if (cmd.equals("get-cities")) { getCities(req); }
else if (cmd.equals("get-hotels")) { getHotels(req); }
else { unknownCommand(req); }
}
private void getCities(HttpServletRequest req) {
this.nextPage = "cities.xml";
}
private void getHotels(HttpServletRequest req) {
String ctryName = req.getParameter("ctry-name");
String cityName = req.getParameter("city-name");
Vector hotels = HotelDao.readSpecial(realPath +
"/WEB-INF/data/hotels.txt", ctryName, cityName);
session.setAttribute(HOTELS_KEY, hotels);
this.nextPage = "hotels-xml.jsp";
}
private void unknownCommand(HttpServletRequest req) {
this.nextPage = "error.html";
}
public String getNextPage() { return nextPage; }
}
文档 2. hotels-xml.jsp
This JSP file dynamically generates XML data. XSL-enabled browsers can apply an XSL stylesheet to the XML in order to render it.
<%@ page import="java.util.*, dw_travel.common.*,
dw_travel.hotel.*" %>
<jsp:useBean id="hotels" class="java.util.Vector"
scope="session"/>
<?xml version="1.0"?>
<?xml:stylesheet type="text/xsl" href="hotels.xsl"?>
<hotels>
<%
int numHotels = hotels.size();
for (int i = 0; i < numHotels; i++) {
Hotel hotel = (Hotel)hotels.get(i);
Address addr = hotel.getAddress();
%>
<hotel id="<%= hotel.getId() %>">
<name><%= hotel.getName() %></name>
<address>
<street><%= addr.getStreet() %></street>
<city><%= addr.getCity() %></city>
<state><%= addr.getState() %></state>
<zip><%= addr.getZip() %></zip>
<country><%= addr.getCountry() %></country>
</address>
</hotel>
<% } %>
</hotels>
文档 3. CityMapApplet.java
This applet retrieves city data from the network and allows users to choose a city by interacting with an image map.
package dw_travel.common.citymap;
import java.net.*;
import java.util.*;
import javax.swing.*;
import dw_travel.common.*;
public class CityMapApplet extends JApplet
implements CityMapListener {
private CityDao cityDao;
private CityMap cityMap;
public void init() {
ToolTipManager.sharedInstance().setInitialDelay(0);
// Read hotel data (XML) from the network.
Vector cities = null;
try {
URL url = new URL(
getCodeBase(), "../?cmd-get-cities=1");
this.cityDao = new CityDao(url.toString());
cities = cityDao.read();
} catch (
MalformedURLException e) { e.printStackTrace(); }
this.cityMap = new CityMap(cities, 5);
cityMap.addCityMapListener(this);
getContentPane().add(cityMap);
}
public void citySelected(CityMapEvent cme) {
URL url = null;
try {
City city = cme.getCity();
String ctryName = city.getCountry().getName();
String cityName = city.getName();
url = new URL(getCodeBase(),
"../?cmd-get-hotels=1&ctry-name=" + ctryName +
"&city-name=" + cityName);
getAppletContext().showDocument(url);
} catch (
MalformedURLException e) { e.printStackTrace(); }
}
}
文档 4. CityDao.java
This data access object is used to parse XML data. It walks the DOM tree and builds a Vector of cities.
package dw_travel.common;
import java.util.*;
import com.sun.xml.tree.*;
import org.w3c.dom.*;
public class CityDao {
private String uri;
public CityDao(String uri) { this.uri = uri; }
public Vector read() {
Vector cities = new Vector();
Map countries = new HashMap();
try {
// Build the DOM tree from the XML document.
Document document = XmlDocument.createXmlDocument(uri);
// Walk the DOM tree to build the Vector.
Element citiesElem = document.getDocumentElement();
NodeList cityList =
citiesElem.getElementsByTagName("city");
int numCities = cityList.getLength();
for (int i = 0; i < numCities; i++) {
Element cityElem = (Element)cityList.item(i);
String cityName = cityElem.getAttribute("name");
String fullCityId = cityElem.getAttribute("id");
StringTokenizer st =
new StringTokenizer(fullCityId, ":");
String ctryId = st.nextToken();
String cityId = st.nextToken();
// We want to set these properties.
String ctryName = null;
Country ctry = null;
boolean isCap = false;
double lng = 0.0;
double lat = 0.0;
NodeList cityChildren = cityElem.getChildNodes();
int numCityChildren = cityChildren.getLength();
for (int j = 0; j < numCityChildren; j++) {
Node cityChild = cityChildren.item(j);
if (cityChild.getNodeType() !=
Node.ELEMENT_NODE) { continue; }
// We have an element node.
String n = cityChild.getNodeName();
if (n.equals("country")) {
ctryName =
((Element)cityChild).getAttribute("name");
} else {
String v = null; // value
NodeList children = cityChild.getChildNodes();
int numChildren = children.getLength();
for (int k = 0; k < numChildren; k++) {
Node child = children.item(k);
if (child.getNodeType() ==
Node.TEXT_NODE) {
v = child.getNodeValue();
break;
}
}
if (n.equals("is-capital")) {
isCap = v.equals("true");
} else if (n.equals("longitude")) {
lng = Double.parseDouble(v);
} else if (n.equals("latitude")) {
lat = Double.parseDouble(v);
}
}
// Create-if-absent scheme for getting countries.
ctry = (Country)countries.get(ctryId);
if (ctry == null) {
ctry = new Country(ctryId, ctryName);
countries.put(ctryId, ctry);
}
}
// Add the new city.
cities.add(new City(cityId, cityName, ctry, isCap,
lng, lat, "don't care"));
}
} catch (Exception e) { // IOException, SAXException
System.out.println(
"CityDao.readXml(): Couldn't read cities.");
e.printStackTrace();
}
return cities;
}
}
文档 5. hotels.xsl
This is the XSL stylesheet containing the instructions for formatting the XML hotel data. The client browser uses it to perform XSLT. For more information on XSL, please refer to the XSL specification at www.w3.org/Style/XSL/.
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<html>
<head>
<link rel="StyleSheet" type=
"text/css" href="../style.css"/>
<title>D & W Travel</title>
</head>
<body>
<table width="780px" border="0" cellspacing=
"0" cellpadding="0">
<!-- Set column widths -->
<tr>
<td><img src="../images/dot.gif" width=
"195" height="1px"/></td>
<td><img src="../images/dot.gif" width=
"195" height="1px"/></td>
<td><img src="../images/dot.gif" width=
"195" height="1px"/></td>
<td><img src="../images/dot.gif" width=
"195" height="1px"/></td>
</tr>
<!-- Banner -->
<tr bgcolor="#6699cc">
<td><img src="../images/dot.gif"/></td>
<td colspan="3" height="40px" align=
"left" valign="center">
<table border="0" cellspacing="0"
cellpadding="6">
<tr><td class="verylargesans">
<font color="#ffffff">D & W Travel</font>
</td></tr>
</table>
</td>
</tr>
<!-- Spacer -->
<tr><td colspan="4" height="6px"></td></tr>
<!-- Content -->
<xsl:apply-templates select="hotels"/>
<!-- Footer -->
<tr>
<td class="smallsans" align="left" valign="bottom">
<b>The fine print:</b> Your personal
information is always safe with us. We will
never sell it to a third party without your
written consent. For more information please
read our <a
href="../dummy-link.html">security policy</a>.
</td>
<td colspan="3" class="smallsans" valign="bottom">
<table width="100%" border="0" cellspacing=
"0" cellpadding="6px">
<tr>
<td class="smallsans" align="center">
<hr/>
<address>
Copyright (c) 2000 by <a href=
"mailto:duany@usc.edu">Duan
Yunjian</a> and <a href=
"mailto:wwheeler@andrew.cmu.edu">Willie
Wheeler</a>. All rights reserved.
</address>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
</xsl:template>
<xsl:template match="hotels">
<tr>
<td/>
<td colspan="3" width="100%" valign="top">
<table border="0" cellspacing="0" cellpadding="6px">
<tr>
<td align="left" valign="top">
<h1 class="largesans">Hotels</h1>
<table border="1px">
<tr>
<th class="sans">ID</th>
<th class="sans">Name</th>
<th class="sans">Street</th>
<th class="sans">City</th>
<th class="sans">Zip</th>
<th class="sans">Country</th>
</tr>
<xsl:apply-templates select="hotel"/>
</table>
</td>
</tr>
<tr>
<td class="sans">
<ul>
<li><a href="citymap.html">Find
another hotel</a></li>
<li><a href="../index.html">Home</a></li>
</ul>
</td>
</tr>
</table>
</td>
</tr>
</xsl:template>
<xsl:template match="hotel">
<tr>
<td class="sans"><xsl:value-of select="@id"/></td>
<td class="sans"><xsl:value-of select="name"/></td>
<td class="sans"><xsl:value-of select=
"address/street"/></td>
<td class="sans"><xsl:value-of select=
"address/city"/></td>
<td class="sans"><xsl:value-of select=
"address/zip"/></td>
<td class="sans"><xsl:value-of select=
"address/country"/></td>
</tr>
</xsl:template>
</xsl:stylesheet>
|