在Servlet / JSP中加载属性文件 [英] Load properties file in Servlet/JSP

查看:137
本文介绍了在Servlet / JSP中加载属性文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从我的 Java项目创建了一个 jar ,并希望在<$中使用相同的jar c $ c> JSP Servlet项目。我正在尝试加载一个属性文件,假设我的 JSP Servlet项目中的sample.properties 保存在 WEB / properties / sample.properties 哪个应该由 jar 中的类读取。我在一个jar类中使用以下代码来访问它。

I've created a jar from my Java project and wanted to use the same jar in a JSP Servlet Project. I'm trying to load a property file let say sample.properties from my JSP Servlet Project kept in WEB/properties/sample.properties which should be read by a class in the jar.I'm using the following code wriiten in a class of jar to access it.

Properties prop=new Properties();
prop.load(/WEB-INF/properties/sample.properties);

但每次我收到 fileNotFound异常。$
请建议我的解决方案。

But each time I'm getting fileNotFound exception.
Please suggest me the solution.

这是结构

WEB-INF
      |
       lib
          |
           myproject.jar
                       |
                        myclass (This class needs to read sample.properties)
      |
       properties
                 |sample.properties


推荐答案

/ WEB-INF 文件夹是不是类路径的一部分。所以这里的任何答案都没有意义,建议 ClassLoader#getResourceAsStream() 从不工作。它只有在属性文件放在 / WEB-INF / classes 中才有效,这确实是类路径的一部分(在像Eclipse这样的IDE中,只是放在Java源代码中)文件夹root应该足够了。

The /WEB-INF folder is not part of the classpath. So any answer here which is thoughtless suggesting ClassLoader#getResourceAsStream() will never work. It would only work if the properties file is placed in /WEB-INF/classes which is indeed part of the classpath (in an IDE like Eclipse, just placing it in Java source folder root ought to be sufficient).

如果属性文件确实存在于你想保留它的位置,那么你应该把它作为web内容资源通过 ServletContext#getResourceAsStream() 代替。

Provided that the properties file is really there where you'd like to keep it, then you should be getting it as web content resource by ServletContext#getResourceAsStream() instead.

假设你在 HttpServlet里面,这应该做:

properties.load(getServletContext().getResourceAsStream("/WEB-INF/properties/sample.properties"));

getServletContext()继承自servlet超类,你不需要自己实现它;所以代码是原样的)

(the getServletContext() is inherited from the servlet superclass, you don't need to implement it yourself; so the code is as-is)

但是如果类是本身不是 HttpServlet ,那么你真的需要将属性文件移动到类路径中。

But if the class is by itself not a HttpServlet at all, then you'd really need to move the properties file into the classpath.

  • Where to place and how to read configuration resource files in servlet based application?

这篇关于在Servlet / JSP中加载属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆