How can a servlet get the absolute path to a file outside the servlet?

We used System.getProperties ("user.dir") to get the location of the properties file. Now that it has been deployed to Tomcat (via the servlet), the system call indicates the location as tomcat, and not where the properties file exists.

How can I dynamically call a properties file?

Given:

  • Tomcat is not the only way the application will be deployed
  • We do not control where the application can be placed.
  • Relative paths will not work as Vista is used, and Vista is broken relative paths.
  • This should work on all operating systems, including (but not limited to) Linux, XP, and Vista.
  • EDIT I meant it, but in case I was not clear enough, I have no way to know the String path.
+3
source share
9 answers

You should have a way to find out the path to the property file, which you can then wrap in the file and pass the load () method of the property object.

If you run Tomcat services inside, you are not working as the user who you installed it, so you cannot get the home directory. Most likely you will need to hard record SOMETHING.


Edit: The property file refers to the application. See http://www.exampledepot.com/egs/java.lang/ClassOrigin.html for an example of how to get the file name for bytecode for this class. You should be able to continue from there.

Class cls = this.getClass();
ProtectionDomain pDomain = cls.getProtectionDomain();
CodeSource cSource = pDomain.getCodeSource();
URL loc = cSource.getLocation();  // file:/c:/almanac14/examples/

, .

+2
+2

, ClassName.class.getResourceAsStream() . ClassLoader.getResource(), , .

- :

InputStream foo = ClassName.class.getResourceAsStream("file.name");

file.name - . file.name com.foo.bar, "/com/foo/bar/file.name"

+1

, ServletContext.getRealPath() jsp .

, webapp "", .. , , - .

+1

, - :

ClassName.class.getResourceAsStream(filePath + _);

filePath - root, fileName - .

, , :

ClassName.class.getResource(filePath + _).getPath()

0

- ClassPathResource?

:

ClassPathResource foo = new ClassPathResource("file.name");

file.name - , :

  • /WebApps/WEB-INF//
  • jar
0

JVM -D. , , . , , , Tomcat, startCatalina script, -D JVM

0

JNDI?

Tomcat Java EE.

0

We had the same requirements. The simplest thing that has worked so far is simply to save the basedir property in one of the property files that we have already loaded. Then define a method, for example getExternalDocPath (String path).

This allowed us to extend the docbase Tomcat (which only supports Tomcat 7?). On the Internet, someone posted a class that actually extends the Tomcat dock base to allow multiple paths, that is, "alpha; baker; charlie".

0
source

Source: https://habr.com/ru/post/1703368/


All Articles