views:

158

answers:

2

i want to create a photo album. But I want to organize on the server the albums so I want to create new folders :

/myapp /myapp/albums /myapp/albums/1 /myapp/albums/2 ...

How can I do that on tomcat with Grails ? It create all new folder in tomcat/bin not in tomcat/webapps/myapp/

A: 

I don't do Grails, but since it runs on top of the Servlet API, you may find this answer (a steering in the right direction) useful as well.

First, get a handle of the ServletContext. Normally you would use the GenericServlet-inherited getServletContext() method for this. Then make use of the ServletContext#getRealPath() method to convert a relative web path to an absolute local disk file system path (because that's the only which java.io.File reliably understands).

String absolutePath = getServletContext().getRealPath("albums/1");
File file = new File (absolutePath);
// ...

If you use relative paths in java.io.File stuff, then it will become relative to the current working directory which depends on the way how you startup the server and which indeed may be Tomcat/bin as you experienced yourself.

That said, there's another major problem with this approach: if you create folders in an exploded webapp, they will get lost whenever you redeploy the webapp or even restart the server! Rather create folders outside the webapp's context, in a fixed path somewhere else at the disk file system. Or if you want better portability (but poorer metadata information), then consider storing it in a database instead.

BalusC
Thanks. Effectively, I restart often the server and I don't want loose my files. But thanks a lot for your answer, it's more clear.
A: 

When I had to do something similar I defined a root path in my Config.groovy like

environments {
    production {
rootPath="/home/user/reports"
    }
    development {
rootPath="c:\\reports"
    }
    test {
rootPath="c:\\reports"
    }

Then create a directory like the following.

import org.codehaus.groovy.grails.commons.ConfigurationHolder as Conf
tempFile=new File(Conf.config.rootPath+"dirName")
tempFile.mkdir()
Jared
Thanks it's probably the best way at this time for my app