在JBoss中部署的java servlet中加载属性文件作为战争

我在JBoss 4.0.2中部署了一个servlet作为战争。 我有一个已部署应用程序的属性文件。 我应该把这个文件放在哪里? 在jboss服务器\ default \ conf文件夹中的conf目录下? 如何以可移植的方式加载该属性文件?

要以可移植的方式加载该属性文件,最好的方法是将它放在Web应用程序的类路径中(在WEB-INF/lib/下的JAR中,或者在WEB-INF/classes/或者在app服务器上) classpath如果您希望能够编辑该文件而无需重新打包Web应用程序)并使用Class#getResourceAsStream(String)

以下代码获取属性文件的InputStream ,该文件驻留在与执行代码的servlet相同的包中:

 InputStream inStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("myfile.properties"); 

然后,将其load(InputStream)Properties对象中(跳过exception处理):

 Properties props = new Properties(); props.load(inStream); 

然后抓住servletContext然后

 InputStream stream = getServletContext().getResourceAsStream("/WEB-INF/log4j.properties"); Properties props = new Properties(); props.load(stream); 

无论您是部署战争还是爆炸战争,这都将始终有效。

如果属性文件可以与应用程序一起部署,则使其成为源树的一部分。 这将导致属性文件位于WEB-INF / classes文件夹中。

然后可以使用它来读取

 Properties properties = loadProperties("PropertyFileName.properties", this.getClass()); ... public static Properties loadProperties(String resourceName, Class cl) { Properties properties = new Properties(); ClassLoader loader = cl.getClassLoader(); try { InputStream in = loader.getResourceAsStream(resourceName); if (in != null) { properties.load(in); } } catch (IOException e) { e.printStackTrace(); } return properties; } 

放置它的最佳位置是在web-apps自己的doc-root下,如“./WEB-INF/myapp.properties”,即相对于servlet容器解压缩.war.ear文件的位置。 您可以直接在.war提供属性文件。

ServletContext有一个方法getRealPath(String path) ,它返回文件系统中的实际路径。 使用实际路径,您可以将其加载到Properties集合中。

更新注释中的代码尝试查找“/”的实际路径,您应该询问属性文件的相对路径,如:

 String propertiesFilePath = getServletContext().getRealPath("WEB-INF/application.properties"); Properties props = properties.load(new FileInputStream(propertiesFilePath));