【问题标题】:File not found when application deployed on tomcat应用程序部署在 tomcat 上时找不到文件
【发布时间】:2012-10-18 08:20:06
【问题描述】:

这在单元测试中运行良好。我得到文件并可以打印内容。当我在服务器上部署它时,我得到一个 FilenotFoundExcpetion。这可能是什么原因?我正在部署在tomcat上。

String path = "WebContent/images/image.jpeg";

FileSystemResource resource = new FileSystemResource(path);

File image = resource.getFile();

【问题讨论】:

    标签: spring tomcat servlets


    【解决方案1】:

    使用上下文路径将位置带到您的工作项目中,然后您可以存储自己的路径,就像您提到的 images/image.jpg

      String path = request.getSession().getContextPath().getRealPath("/")+"images/image.jpg";
    

    我想它会帮助你!

    【讨论】:

      【解决方案2】:
      String path = "WebContent/images/image.jpeg";
      

      这是一个相对路径,当部署在像 tomcat 这样的 servlet 容器中时,它将相对于您的部署目录或 tomcat 的主目录。并且您可能不会有一个名为 Webconent 的目录。 WebContent 的内容可能会在战争中发生。

      我能想到两种解决方案

      • 如果您有权访问requestServletContext,请使用getRealPath 方法
      • 如果可以将文件放入WEB-INF\classes,请使用ClassPathResource

      【讨论】:

      • 字符串路径 = request.getRealPath("") + "/images/image.jpeg"; getRealPath 已被弃用。
      【解决方案3】:

      当您将 Web 应用程序部署到服务器上时,WebContent 文件夹是隐式的。

      在 Web 服务器使用的上下文中执行时 字符串路径 = "/images/image.jpeg";

      还有

      使用 Class.getResourceAsStream()

      【讨论】:

        猜你喜欢
        • 2018-02-10
        • 2020-05-08
        • 2016-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多