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

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

问题描述

我已经从我的 Java 项目 创建了一个 jar,并希望在 JSP Servlet 项目 中使用相同的 jar.我正在尝试从我的 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 源文件夹根目录中就足够了)).

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).

如果属性文件确实在您想要保留的位置,那么您应该通过 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 中,应该这样做:

Assuming that you're inside a HttpServlet, this should do:

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.

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

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