本文介绍了如何找到基于 servlet 的应用程序的工作文件夹以加载资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个 Java servlet,我想将它安装在不同服务器上的许多 Tomcat 实例上.servlet 使用一些静态文件,这些文件与 WEB-INF 下的 war 文件一起打包.这是典型安装中的目录结构:

I write a Java servlet that I want to install on many instances of Tomcat on different servers. The servlet uses some static files that are packed with the war file under WEB-INF. This is the directory structure in a typical installation:

- tomcat
-- webapps
--- myapp
---- index.html
---- WEB-INF
----- web.xml
----- classes
------ src
------- .....
----- MY_STATIC_FOLDER
------ file1
------ file2
------ file3

如何知道MY_STATIC_FOLDER的绝对路径,以便读取静态文件?

How can I know the absolute path of MY_STATIC_FOLDER, so that I can read the static files?

我不能依赖当前文件夹"(我在一个新文件(.")中得到的),因为它取决于 Tomcat 服务器的启动位置,这在每次安装中都不同!

I cannot rely on the "current folder" (what I get in a new File(".")) because it depends on where the Tomcat server was started from, which is different in every installation!

推荐答案

可以使用 ServletContext#getRealPath() 将相对 Web 内容路径转换为绝对磁盘文件系统路径.

You could use ServletContext#getRealPath() to convert a relative web content path to an absolute disk file system path.

String relativeWebPath = "/WEB-INF/static/file1.ext";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
InputStream input = new FileInputStream(file);
// ...

但是,如果您的唯一目的是从中获取 InputStream,最好使用 ServletContext#getResourceAsStream() 因为 getRealPath()每当 WAR 没有扩展到本地磁盘文件系统而是扩展到内存和/或虚拟磁盘时,可能会返回 null:

However, if your sole intent is to get an InputStream out of it, better use ServletContext#getResourceAsStream() instead because getRealPath() may return null whenever the WAR is not expanded into local disk file system but instead into memory and/or a virtual disk:

String relativeWebPath = "/WEB-INF/static/file1.ext";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// ...

这比 java.io.File 方法健壮得多.此外,使用 getRealPath() 被认为是不好的做法.

This is much more robust than the java.io.File approach. Moreover, using getRealPath() is considered bad practice.

这篇关于如何找到基于 servlet 的应用程序的工作文件夹以加载资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 17:44