1

使用 grails-3.3.1 开发项目并生成 Runnable WAR 文件。当我使用命令运行时:

java -jar build/libs/myproject-0.1.war

它正在返回null以下行:

serveltContext.getRealPath("/someSource");

但是当部署在 Tomcat 容器中时它工作正常。

然后尝试了以下方法:

servletContext.getResource("someSource").getPath();

它正在返回,但不是预期的,也不是getRealPath()返回的。它是这样返回的:

D:/myprojects/myproject/build/libs/myproject-01.war*/

这对我没有用。找到建议使用getResourceAsStream()但我不想要资源的答案,我只想要String.

4

2 回答 2

1

我找不到在本地和在容器中部署时都有效的解决方案。我最终使用此解决方法来获取路径,具体取决于代码在哪个环境中运行:

def path
if (Environment.current == Environment.DEVELOPMENT) {
    path = java.nio.file.FileSystems.default.getPath("someSource").toAbsolutePath().toString()
} else {
    path = ServletContextHolder.servletContext.getRealPath("/someSource")
}
于 2019-11-15T16:29:17.673 回答
1

我对 Grails 4.0.11 也有同样的问题。似乎 serveltContext.getRealPath 已被弃用并返回 null。您的解决方案对我也不起作用,所以我决定采用以下方法:(在https://howtodoinjava.com/spring-boot2/read-file-from-resources/上找到)

  import org.springframework.core.io.ClassPathResource
  import org.springframework.core.io.Resource

  Resource resource = new ClassPathResource("pdfResources/fonts/SFUIText-Medium.ttf") 
  String path = resource?.getPath()

鉴于我的应用程序名为“filetest”,该文件位于 filetest/src/main/resources/pdfResources/fonts/SFUIText-Medium.ttf

这适用于“grails run-app”和“grails war”作为嵌入式可运行的战争文件。希望它有所帮助,因为我花了很长时间。

于 2022-02-06T13:06:55.170 回答