Search code examples
servletsgrailsembedded-tomcat-8grails-3.3

How do I get real path as string in Grails


Developed project using grails-3.3.1 and generated a Runnable WAR file. When I run using the command:

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

It is returning null for the following line:

serveltContext.getRealPath("/someSource");

But it is working fine when deployed in a Tomcat Container.

Then tried the following way:

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

It is returning, but not the one as expected and not what getRealPath() returns. It is returning like this:

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

which serves no use for me. Found answers suggesting to use getResourceAsStream() but I don't want a resource, I want only String.


Solution

  • I was unable to find a solution that worked both locally and when deployed in a container. I ended up using this workaround instead to get the path depending on which environment the code is running in:

    def path
    if (Environment.current == Environment.DEVELOPMENT) {
        path = java.nio.file.FileSystems.default.getPath("someSource").toAbsolutePath().toString()
    } else {
        path = ServletContextHolder.servletContext.getRealPath("/someSource")
    }