代码之家  ›  专栏  ›  技术社区  ›  Will

JSP Xalan示例

  •  0
  • Will  · 技术社区  · 16 年前

    我想做的是以下几点。

    向URL传递两个参数

    • 类型
    • 博士

    一旦通过URL将它们传递给JSP,我希望将类型模板应用到Doc_ID XML。

    因此,如果类型为001,那么001.xsl将应用于doc_id.xml。我不想把这个输出存储在文件中,而是直接输出到浏览器。

    我该如何使用Xalan和JSP页面来实现这一点呢?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Vincent Ramdhanie    16 年前

    我建议将这种类型的代码放在servlet中,而不是JSP页面中。如果您有一些需要JSP的特定约束,那么可以修改代码以在JSP页面上工作。

    xalan站点有一个使用servlet的很好的示例,为了方便起见,我将在这里复制它: 原件可以找到 here . 在本例中,它们硬编码XSL和XML文件的名称,但是很容易修改以使用按照您的描述生成的文件名。重要的是,生成的输出流到浏览器。

    public class SampleXSLTServlet extends javax.servlet.http.HttpServlet {
    
        public final static String FS = System.getProperty("file.separator"); 
        // Respond to HTTP GET requests from browsers.
    
        public void doGet (javax.servlet.http.HttpServletRequest request,
                     javax.servlet.http.HttpServletResponse response)
                     throws javax.servlet.ServletException, java.io.IOException
       {
         // Set content type for HTML.
         response.setContentType("text/html; charset=UTF-8");    
         // Output goes to the response PrintWriter.
         java.io.PrintWriter out = response.getWriter();
         try
         {  
            javax.xml.transform.TransformerFactory tFactory = 
               javax.xml.transform.TransformerFactory.newInstance();
            //get the real path for xml and xsl files.
            String ctx = getServletContext().getRealPath("") + FS;        
            // Get the XML input document and the stylesheet, both in the servlet
           // engine document directory.
           javax.xml.transform.Source xmlSource = 
                new javax.xml.transform.stream.StreamSource
                             (new java.net.URL("file", "", ctx+"foo.xml").openStream());
           javax.xml.transform.Source xslSource = 
                new javax.xml.transform.stream.StreamSource
                             (new java.net.URL("file", "", ctx+"foo.xsl").openStream());
           // Generate the transformer.
           javax.xml.transform.Transformer transformer = 
                             tFactory.newTransformer(xslSource);
           // Perform the transformation, sending the output to the response.
          transformer.transform(xmlSource, 
                           new javax.xml.transform.stream.StreamResult(out));
         }
         // If an Exception occurs, return the error to the client.
        catch (Exception e)
        {
           out.write(e.getMessage());
           e.printStackTrace(out);    
        }
        // Close the PrintWriter.
        out.close();
       }  
    }