Search code examples
javatomcataliases

access tomcat alias dir from java


In Tomcat7 there is an option to use aliases from the context like this:

 <Context aliases="/up=/var/tomcat/upload"></Context>

With this I can access files from outside the webapp. Now, I want to write and read from this dir from my Java code, but do not know how to.

I can do this:

servletContext.getResourcePaths("/up/")

Which shows me the content of /var/tomcat/upload.

How can I write to this dir?

What I did with the excepted answer: add this to context.xml:

<Context aliases="/up=/var/tomcat/upload">
     <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow=".*" />
     <Parameter name="uploadDir" value="/var/tomcat/upload"/>

and this in my java code:

String uploadDir = servletContext.getInitParameter("uploadDir") + subDir;
OutputStream bos = new FileOutputStream(uploadDir + fileName);

And this works but I could use only the parameter and skip the aliases because for java it does not help. So I'm not quite sure what the idea behind the aliases. I thought it was for uploading files because after a redeploy this dir and content will not be overwritten. But if java can only access it with an extra parameter than it only can be used for serving static content which could be inside the webapp (inside the war).


Solution

  • You separately tell your Java code the path to your upload folder (/var/tomcat/upload) so it can read/write files there.

    Example:

    <Context aliases="/up=/var/tomcat/upload">
        <Parameter name="uploadDir" value="/var/tomcat/upload"/>
    </Context>
    

    Your java code can get the parameter value by calling ServletContext.getInitParameter("uploadDir").