How to store a file on a server(web container) through a Java EE web application?
By spec, the only "real" path you are guaranteed to get form a servlet container is a temp directory.
You can get that via the ServletContext.gerAttribute("javax.servlet.context.tempdir")
. However, these files are not visible to the web context (i.e. you can not publish a simple URL to deliver those files), and the files are not guaranteed in any way to survive a web app or server restart.
If you simply need a place to store a working file for a short time, then this will work fine for you.
If you really need a directory, you can make it a configuration parameter (either an environment variable, a Java property (i.e. java -Dyour.file.here=/tmp/files ...
), a context parameter set in the web.xml, a configuration parameter stored in your database via a web form, etc.). Then it's up to the deployer to set up this directory for you.
However, if you need to actually later serve up that file, you will either need a container specific mechanism to "mount" external directories in to your web app (Glassfish as "alternate doc roots", others have similar concepts), or you will need to write a servlet/filter to serve up file store outside of your web app. This FileServlet is quite complete, and as you can see, creating your own, while not difficult, isn't trivial to do it right.
Edit:
The basic gist is the same, but rather than using "getRealPath", simply use "getInitParameter".
So:
String filePath = getServletContext().getInitParameter("storedFilePath") + "/" + fileName;
And be on your way.
Edit again:
As for the contents of the path, I'd give it an absolute path. Otherwise, you would need to KNOW where the app server sets its default path to during exeuction, and each app server may well use different directories. For example, I believe the working directory for Glassfish is the config directory of the running domain. Not a particularly obvious choice.
So, use an absolute path, most definitely. That way you KNOW where the files will go, and you can control the access permissions at the OS level for that directory, if that's necessary.
Writing to the file system from a Java EE container is not really recommended, especially if you need to process the written data:
- it is not transactional
- it harms the portability (what if you are in a clustered environment)
- it requires to setup external parameters for the target location
If this is an option, I would store the files in database or use a JCR repository (like Jackrabbit).