以编程方式从我的 java webapp 读取静态资源
我的 .war 文件中目前有一堆这样的图像.
I currently have a bunch of images in my .war file like this.
WAR-ROOT
-WEB-INF
-IMAGES
-image1.jpg
-image2.jpg
-index.html
当我通过我的 servlets/jsp/etc 生成 html 时,我可以简单地链接到
When I generate html via my servlets/jsp/etc I can simple link to
http://host/contextroot/IMAGES/image1.jpg
和
http://host/contextroot/IMAGES/image1.jpg
不是我正在编写一个 servlet,它需要获取对这些图像的文件系统引用(在这种情况下渲染复合 .pdf 文件).有没有人有关于如何获得对放置在战争中的文件的文件系统引用的建议,类似于这种情况?
Not I am writing a servlet that needs to get a filesystem reference to these images (to render out a composite .pdf file in this case). Does anybody have a suggestion for how to get a filesystem reference to files placed in the war similar to how this is?
这可能是我在 servlet 初始化时获取的 url 吗?我显然可以有一个明确指向安装目录的属性文件,但我想避免额外的配置.
Is it perhaps a url I grab on servlet initialization? I could obviously have a properties file that explicitly points to the installed directory but I would like to avoid additional configs.
如果你能保证WAR被扩展,那么你可以使用ServletContext#getRealPath()
将相对 Web 路径转换为一个绝对磁盘文件系统,您可以在通常的 Java IO 内容中进一步使用它.
If you can guarantee that the WAR is expanded, then you can use ServletContext#getRealPath()
to convert a relative web path to an absolute disk file system which you can further use in the usual Java IO stuff.
String relativeWebPath = "/IMAGES/image1.jpg";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
InputStream input = new FileInputStream(file);
// ...
但是,如果您不能保证 WAR 被扩展(即所有资源仍然打包在 WAR 中)并且您实际上对绝对磁盘文件系统路径以及您实际需要的所有内容不感兴趣 只是一个 InputStream
,然后使用 getServletContext().getResourceAsStream()
代替.
However, if you can't guarantee that the WAR is expanded (i.e. all resources are still packaged inside WAR) and you're actually not interested on the absolute disk file system path and all you actually need is just an InputStream
out of it, then use getServletContext().getResourceAsStream()
instead.
String relativeWebPath = "/IMAGES/image1.jpg";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// ...