views:

352

answers:

2

I'm writing a java servlet that calls a function in a jar. I have no control over the code in this jar. The function being called wants the filename of a configuration file as an argument.

I'd like to bundle this file with my war file. If I put it in the war somewhere, what filename can I pass the function in the jar?

Note that only a filename can be used with the jar's API. So ServletContext.getResourceAsStream() is not helpful.

+3  A: 

Use ServletContext.getRealPath(). This returns the filesystem path for a given servlet context resource. You pass it the same argument as you would pass to ServletContext.getResourceAsStream()

Better yet, use Spring's Resource abstraction:

Resource resource = new ServletContextResource(servletContext, "/path/to/file");
File resourceFile = resource.getFile();
skaffman
Oh, and if the file is part of a packaged WAR file, then getRealPath() will return null, since there's no actual file. If you use an exploded WAR, though, it should work fine.
skaffman
This works for me, since tomcat explodes my WAR, and that's my only container to support.
Jim Hunziker
+1  A: 

If it's in your .war file, you won't be able to access it as a file. Some servlet containers will explode a .war file into components, but I don't think you can rely on it.

Have you thought about extracting it (via getResourceAsStream()), writing it to a temp file/directory, and then referencing that ?

Brian Agnew