【问题标题】:Why is my web app looking for needed file in tomcat/bin and not in webapps?为什么我的网络应用程序在 tomcat/bin 中而不是在 webapps 中寻找所需的文件?
【发布时间】:2014-03-12 16:10:01
【问题描述】:

我正在开发Oryx Editor 的一个分支。在oryxRoot\editor\server\src\org\oryxeditor\server 中,我添加了一个Java servlet,我在其中尝试将XSL 文件应用于表示XML 文档的流。代码如下:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  //get AppML from POST
  InputStream inputStream = new ByteArrayInputStream(request.getParameter("content").getBytes("UTF-8"));
  inputStream.reset();
  try {  
      TransformerFactory tFactory = TransformerFactory.newInstance();
      Transformer transformer = tFactory.newTransformer(new StreamSource("lib/SorinCode.xsl"));
      transformer.transform(new StreamSource(inputStream), new StreamResult(new FileOutputStream("output.txt")));
      System.out.println("************* The result is in output.txt *************");
  } catch (Throwable t) {
      t.printStackTrace();
  }
}

问题是new StreamSource("lib/SorinCode.xsl") 期望在tomcat/bin/lib 中找到XSL 文件,而不是在tomcat/webapp/oryx/lib 中,正如我所期望的那样。我试图改变 oryxRoot/editor/etc/context.xml 并添加 baseDoc="oryx",但这没有帮助。

谁能告诉我为什么该应用在bin 文件夹中寻找XSL 文件,我应该怎么做才能让它在webapps/oryx 中寻找?

【问题讨论】:

    标签: java tomcat servlets tomcat6


    【解决方案1】:

    使用StreamSourceInputStream构造函数:

    ...new StreamSource(request.getServletContext().getResourceAsStream("lib/SorinCode.xsl"))
    

    ...如果lib/SorinCode.xsl 在网页内容中。如果它在类路径中,请改用:

    ...new StreamSource(getClass().getResourceAsStream("lib/SorinCode.xsl"))
    

    【讨论】:

    • 第一个有效,但通过调用getServletContext() 不是为request 对象,而是为this... 所以,解决方案是...new StreamSource(getServletContext().getResourceAsStream("lib/SorinCode.xsl"));
    【解决方案2】:

    cwd(当前工作目录)通常基于程序启动的路径。也就是说,Tomcat 程序,而不是你的 webapp。 cwd 可能非常难以预测。它可能只是 bin 目录,因为当您启动 Tomcat 时,您的 shell 就在该目录中。

    要获取部署 Web 应用程序的路径,请使用 request.getServletContext().getRealPath("/")

    【讨论】:

    • 实际上我使用getRealPath() 来保存结果,所以谢谢你的想法......所以StreamResultnew StreamResult(new FileOutputStream(getServletContext().getRealPath("/") + "output.txt"))
    猜你喜欢
    • 2012-08-08
    • 1970-01-01
    • 2017-05-01
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    相关资源
    最近更新 更多