package chap8;
import com.oreilly.javaxslt.util.StylesheetCache;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
/**
* Applies a standard stylesheet to every XML page on a site.
*/
public class TemplateServlet extends HttpServlet {
private String xsltFileName;
/**
* Locate the template stylesheet during servlet initialization.
*/
public void init() throws UnavailableException {
ServletContext ctx = getServletContext();
this.xsltFileName = ctx.getRealPath(
"/WEB-INF/xslt/templatePage.xslt");
File f = new File(this.xsltFileName);
if (!f.exists()) {
throw new UnavailableException(
"Unable to locate XSLT stylesheet: "
+ this.xsltFileName, 30);
}
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
try {
// use the ServletContext to locate the XML file
ServletContext ctx = getServletContext();
String xmlFileName = ctx.getRealPath("/WEB-INF/xml"
+ req.getPathInfo());
// verify that the file exists
if (!new File(xmlFileName).exists()) {
res.sendError(HttpServletResponse.SC_NOT_FOUND, xmlFileName);
} else {
res.setContentType("text/html");
// load the XML file
Source xmlSource = new StreamSource(new BufferedReader(
new FileReader(xmlFileName)));
// use a cached version of the XSLT
Transformer trans =
StylesheetCache.newTransformer(xsltFileName);
trans.transform(xmlSource, new StreamResult(res.getWriter()));
}
} catch (TransformerConfigurationException tce) {
throw new ServletException(tce);
} catch (TransformerException te) {
throw new ServletException(te);
}
}
}
|