java - 从非 servlet 类(来自外部 jar)引用 WEB-INF 中的文件

标签 java tomcat jakarta-ee servlets

<分区>

我有一个 CouponSystem 项目,它有一个 config/cs.properties 文件。 此项目导出为 cs.jar 并添加到另一个导出 web-app csee.war 的项目

当 CouponSystem 运行时(作为 java 应用程序),它会加载正确读取 config/cs.properties 的 Utils 类。

当 csee 在服务器 (tomcat7) 上运行时,我找不到该文件。在创建一些方法来了解 tomcat 查找该文件的位置之后,我意识到它在 tomcat/bin 目录中查找 - 所以如果我将文件放在 tomcat/bin/cs.properties 中:一切正常。 (不是解决方案,只是为了理解问题)

我的问题是 - 将 cs.properties 放在网络应用程序环境中的正确方法在哪里,以及如何告诉非 servlet 类 (Utils) 找到它?

谢谢。

enter image description here

public class Utils {

    public static final String CONFIG_FILE = "cs.properties";
    //public static final String CONFIG_FILE = "WEB-INF/config/cs.properties";

    // builds a hashmap from properties file
    public static void loadSystemParameters() {
        // this code only to know "the default current dir"
        File f = new File("."); // current directory
        File[] files = f.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                System.out.print("directory:");
            } else {
                System.out.print("     file:");
            }
            try {
                System.out.println(file.getCanonicalPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }




        Utils.logMessage(new Utils(), Severity.DEBUG, "loadSystemParameters() invoked");
        // construct a List<Customer> to return the data
        sysParams = new HashMap<String, String>();
        Properties properties = new Properties();
        try {
            properties.load(new FileReader(CONFIG_FILE));
            for(String propName : properties.stringPropertyNames()){
                sysParams.put(propName, properties.getProperty(propName));
            }
            Utils.logMessage(new Utils(), Severity.DEBUG, "properties from file loaded to a hashmap");
        } catch (IOException e) {
            Utils.logMessage(new Utils(), Severity.ERROR, "cannot load properties file ! exiting.");
            e.printStackTrace();
            //System.exit(0);
        }
    }
}

最佳答案

最简单的方法是将文件放在WEB-INF/classes中,然后从类路径加载:

Properties p = new Properties();
// load the file at WEB-INF/class/cs.properties
p.load(Utils.class.getResourceAsStream('/cs.properties')); 

关于java - 从非 servlet 类(来自外部 jar)引用 WEB-INF 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33098263/

相关文章:

javascript - 将音频文件上传到服务器并根据服务器响应设置图像

java - 嵌入式 GlassFish 忽略 Maven 测试资源

java - 重置 TCP 连接一侧

java - 在哪里放置@Transactional?在接口(interface)规范或实现中?

Java EE、实体 Bean 和长字符串属性(mysql 文本)。如何?

java - "Updating status for Apache Tomcat v7.0 at localhost..."。 java.lang.IndexOutOfBoundsException

基于 Tomcat APR 的 Apache Tomcat Native Library 错误

java - 适当的 json 到后端 post 调用

java - JTable:存储与显示不同的数据

java - 当多线程调用 Servlet 中的缓存时是否存在线程耗尽风险?