Tomcat 5.5 - 读取资源文件出现问题

8
我正在使用Tomcat 5.5作为我的servlet容器。我的Web应用程序通过.jar部署,并且具有一些资源文件(包含字符串和配置参数的文本文件),这些文件位于其WEB-INF目录下。Tomcat 5.5在Ubuntu Linux上运行。使用文件阅读器读取资源文件:
fr = new FileReader("messages.properties");

问题是有时候Servlet找不到资源文件,但如果我重启几次它就能够工作,然后过一段时间又停止工作。有人能建议一下从Servlet中读取资源字符串的最佳方法吗?或者解决这个问题的方法?将资源文件放在WEB-INF/classes下也没有帮助。
5个回答

9

如果您正在尝试从一个 Servlet-aware 类访问此文件,例如 ContextListener 或其他生命周期监听器,您可以使用 ServletContext 对象获取资源路径。

以下三种方式大致相同。 (不要将 getResourceAsStream 与 ClassLoader 类提供的那个混淆。它们的行为非常不同)

void myFunc(ServletContext context) {
   //returns full path. Ex: C:\tomcat\5.5\webapps\myapp\web-inf\message.properties 
   String fullCanonicalPath = context.getRealPath("/WEB-INF/message.properties");

   //Returns a URL to the file. Ex: file://c:/tomcat..../message.properties
   URL urlToFile = context.getResource("/WEB-INF/message.properties");

   //Returns an input stream. Like calling getResource().openStream();
   InputStream inputStream = context.getResourceAsStream("/WEB-INF/message.properties");
   //do something
}

5
我猜问题出在你试图使用相对路径来访问文件。使用绝对路径可能会有所帮助(例如“/home/tomcat5/properties/messages.properties”)。
然而,通常解决此问题的方法是使用ClassLoader的getResourceAsStream方法。将属性文件部署到“WEB-INF / classes”将使其可用于类加载器,并且您将能够访问属性流。
未经测试的原型代码:
Properties props = new Properties();

InputStream is =
getClass().getClassLoader().getResourceAsStream("messages.properties");

props.load(is);

2

我使用以下代码在servlet中加载属性文件:

public void init(ServletConfig config) throws ServletException {
    String pathToFile = config.getServletContext().getRealPath("")
        + "/WEB-INF/config.properties";
    Properties properties = new Properties();
    properties.load(new FileInputStream(pathToPropertiesFile));
}

这适用于Tomcat 6.0版本。


2

如果您使用

new FileReader("message.properties");

然后FileReader将尝试从基本目录(在Tomcat中可能是/bin文件夹)读取该文件。

正如diciu所提到的,使用绝对路径或通过类加载器将其加载为资源。


0

我曾经用过Jboss Seam:

ServletLifecycle.getServletContext().getRealPath("")


2
这与所问的问题有什么关系? - Jason S

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接