I have a servlet which accepts a file upload, I'd like to store the file in a specific directory on disk. I'm using jetty. The file system looks like this:
/jetty
/bin
/contexts
/stuff
/webapps
foo.war // one web app
grok.war // another web app
start.jar
I start jetty from that start.jar file. In the context of the servlet, I'm not sure how to save the file to my desired destination, the "/stuff" folder:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletExcept开发者_StackOverflowion, IOException
{
File downloaded = new File("some/path/here/stuff"); // ?
}
Yeah - I'm not sure what path to use - is there a way I can print the current working directory in java using the File class to figure that out maybe?
Thanks
This is a pretty poor practice. There is no guarantee that it works on all servletcontainers other than Jetty. Even then, I'm not sure if it works on Jetty. At least, tt would make your webapp unportable to other containers.
When the WAR is expanded (it's servletcontainer specific if and where the WAR will be expanded!), then the ServletContext#getRealPath()
can be used to convert a webcontent-relative path to an absolute disk file system path.
When the following line is called in a servlet inside foo.war
String absoluteFooWebPath = getServletContext().getRealPath("/");
and Jetty has expanded the WAR file in the same webapps folder, then this will result in an absolute path to /jetty/webapps/foo
. Then, to get from there to /jetty/stuff
, you need to navigate two directories up and then from there navigate the stuff
directory.
String absoluteStuffPath = getServletContext().getRealPath("../../stuff");
After all, the most reliable way is to specify a servletcontainer-independent fixed path with read/write rights which you document properly in the installation manual of your webapp or to make it configureable by some VM argument / system property.
You can print the current dir, parent dir using following code:
import java.io.File;
public class FileOperations {
public static void main (String args[]) {
File dir1 = new File (".");
File dir2 = new File ("..");
try {
System.out.println ("Current dir : " + dir1.getCanonicalPath());
System.out.println ("Parent dir : " + dir2.getCanonicalPath());
}
catch(Exception e) {
e.printStackTrace();
}
}
}
The startup.jar should set the jetty.home system property. Access it using System.getProperty("jetty.home")
.
Though getRealPath
is likely to return a valid path when running your war file in Jetty, that is likely to be different when you'll switch to a different app server in future.
It would be better to make it a configurable option in web.xml, using init-param
for instance, which would simply contain an absolute path to some pre-existing folder on the server. Putting it in web.xml allows changing it live when using for instance JBoss. You can use getInitParameter
on the ServletConfig
to get the value.
精彩评论