如何获取 servlet 资源的文件名? [英] How can I get the filename of a servlet resource?
问题描述
我正在编写一个调用 jar 函数的 java servlet.我无法控制这个 jar 中的代码.被调用的函数需要配置文件的文件名作为参数.
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.
我想将此文件与我的 war 文件捆绑在一起.如果我把它放在war中的某个地方,我可以在jar中传递什么文件名?
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?
请注意,jar 的 API 只能使用文件名.所以 ServletContext.getResourceAsStream()
没有帮助.
Note that only a filename can be used with the jar's API. So ServletContext.getResourceAsStream()
is not helpful.
推荐答案
使用 ServletContext.getRealPath()
.这将返回给定 servlet 上下文资源的文件系统路径.您传递给它的参数与传递给 ServletContext.getResourceAsStream()
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()
更好的是,使用 Spring 的资源抽象:
Better yet, use Spring's Resource abstraction:
Resource resource = new ServletContextResource(servletContext, "/path/to/file");
File resourceFile = resource.getFile();
这篇关于如何获取 servlet 资源的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!