⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 templateservlet.java

📁 基于java的xsl与xml程序例子
💻 JAVA
字号:
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);
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -