【问题标题】:Get relative Path of WebContent in Spring webmvc app在 Spring webmvc 应用程序中获取 WebContent 的相对路径
【发布时间】:2015-08-25 11:40:01
【问题描述】:

我无法在 myApp/WebContent/resources/ 文件夹中的某个位置创建与我的 webapp 相关的文件夹来保存数据。

String folderPath="/WebContent/resources/"+title;

    File folder=new File(folderPath);
    if(!folder.exists())
        System.out.println("Folder created "+folder.mkdir());

输出总是假的

【问题讨论】:

  • 您是否正在创建此路径:- String folderPath="/WebContent/resources/"+title;
  • 您不应该尝试创建这样的文件夹,因为 servlet 容器不需要将您的 Web 应用程序放入文件中。
  • @Raedwald 所说的。当您部署新版本的应用程序时,此“数据”文件夹会发生什么情况?

标签: java spring file jakarta-ee resources


【解决方案1】:

你可以在下面几行做一些事情:-

 String folderPath= request.getServletContext().getRealPath("/");
  File file = new File (folderPath+"title");
  file.mkdir();

以上代码将在 servletcontainer/webappContext 中创建一个文件夹标题。

正如@Raedwald 所提到的,在 webappContext 中创建任何文件夹都不是一个好习惯。

参考此链接:Best practice to store temporary data for a webapp

【讨论】:

  • 这是一个好方法吗?如果我将我的项目移动到服务器上,这行得通吗?
  • 是的,它将始终有效,因为它使用相对路径。你没有硬编码任何东西。
  • 好的。但我不想存储临时信息。假设我想制作一个照片库,为用户提供上传图片的权利,这些图片以后可能会加载到网站上,任何人都可以看到。将它们作为字节存储在数据库中更好吗?或者只是将我的所有资源移到网络内容之外?
猜你喜欢
  • 1970-01-01
  • 2011-03-06
  • 2011-02-11
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多