Accessing Servlet Container Temporary Directory

March 14, 2012

As part of a recent project, I had a need to generate classes to a temporary directories. Currently, this was being done by a simple File-based path. However, that has two downfalls: the paths are tied to the implementation of the application server and files may be blocked in the application server. However, JSPs do this all the time by storing their resulting classes to the work or temporary directory in the application. I had to search several variants of keywords to find my answer, but the servlet spec actually has the notion of a work directory for this type of work. You access the directory through the ServletContext.getAttribute method. In servlet spec 2.5 and below, the static constant TEMPDIR is not defined. Instead, you use the constant javax.servlet.context.tempdir. The returned value is of type that you can use as the base directory. For example,

With this, the test file will be stored in the working directory of the deployed web application. Note that files stored are temporary and may or may not be preserved across restarts. The servlet container manages the actual files once the application is shutdown.

2 Responses to “Accessing Servlet Container Temporary Directory”

  1. Better `if(!(workDir.exists() && workDir.isDirectory()) && !workDir.mkdirs())`. Also please comment on `SERVLET_TMP_DIR` namely where is the static constant TEMPDIR defined

  2. Define a constant in your class such as:

    public static final String SERVLET_TMP_DIR = “javax.servlet.context.tempdir”;