dynamic path out of context in servlet

5

To get the dynamic path within the project is easy, just run the code:

String path = this.getServletContext().getRealPath(""); 

Here it is returned:

/home/pedro-pazello/development/servers/apache-tomcat-7.0.42/wtpwebapps/img_uploader/

* img_uploader * is the name of the project. But I need to get this way out of the project. I need the path to be:

/home/pedro-pazello/development/servers/apache-tomcat-7.0.42/wtpwebapps/imagens/

Does anyone have any idea how I can get this path?

    
asked by anonymous 23.02.2014 / 16:45

1 answer

1

Do this:

OPTION 1

String path = this.getServletContext().getRealPath("../imagens");
File f = new File(path);
String imagensHome = f.getCanonicalPath();

You can then create a Servlet to fulfill the requests in /img_uploader and deliver the images from:

File imagensRoot = new File(imagensHome);

You should pay special attention to the Mime Type of the images at the time of delivery to the client by assigning the appropriate Content Type.

OPTION 2

Only if your server is running Tomcat 7+ on Linux, UNIX, or Mac OS X

  • Create a symbolic link using ln -s img_uploader ../imagens
  • Create a context.xml file as below:

    <?xml version="1.0" encoding="UTF-8"?>
    <Context allowLinking="true">
        <WatchedResource>WEB-INF/web.xml</WatchedResource>
    </Context>
    
  • This file informs Tomcat via the allowLinking="true" attribute that it can access symbolic links and deliver content to the client from ../imagens .

    NOTE: In this solution a Deploy script should re-create this symbolic link described above in case it is removed.

        
    25.02.2014 / 00:17