FileDocCategorySizeDatePackage
TemplateServlet.javaAPI DocExample2194Sun Sep 02 14:59:02 BST 2001chap8

TemplateServlet

public class TemplateServlet extends HttpServlet
Applies a standard stylesheet to every XML page on a site.

Fields Summary
private String
xsltFileName
Constructors Summary
Methods Summary
public voiddoGet(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res)

        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);
        }
    
public voidinit()
Locate the template stylesheet during servlet initialization.

        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);
        }