dynamic path out of context in Servlet

Asked

Viewed 3,767 times

5

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

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

Here 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 take this path outside 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?

  • You can try to pass "../imagens" to the getRealPath, but I believe this is an indication that its configuration is not quite right. You can put in more detail because you want to access a folder outside the project?

  • Do you want to take the path inside the web level or outside? I ask this because I had to do the 2 in a project, and gave this problem.

  • 1

    Why don’t you save this path in the database and then just search by doing a select? [=

  • I need to save the files outside of the project,because whenever a Tomcat server reboots,it re-deploys the applications,hence all the files I saved during the time the application went online will go away,because the application returns to War’s default...I can even save the path in the good database, but I wanted to take it dynamically...

1 answer

1


Do so:

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 on /img_uploader and deliver the images from :

File imagensRoot = new File(imagensHome);

You should pay special attention to the Mime Type of the images when delivering to the customer by assigning the appropriate Content Type.

OPTION 2

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

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

    <?xml version="1.0" encoding="UTF-8"?>
    <Context allowLinking="true">
        <WatchedResource>WEB-INF/web.xml</WatchedResource>
    </Context>
    

This file informs Tomcat via attribute allowLinking="true" that it can access symbolic links and deliver content to the customer from ../imagens.

NOTE: in this solution a Deploy script should recreate this symbolic link described above in case it is removed.

  • First option seems to be interesting,although,I was thinking about saving the path in an xml or database file,and pulling this path when necessary,and if I needed to change it,

Browser other questions tagged

You are not signed in. Login or sign up in order to post.