简体   繁体   中英

How can I get the filename of a servlet resource?

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.

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();

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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM