如何在Tomcat启动时初始化web应用程序常量(从文本文件)



我在本地Tomcat7上部署了一个web应用程序。此web应用程序需要知道三个文件夹的位置。

以下是该代码目前的样子:

public class Constants {
    public enum Folder {
        InboundFolder("C:\inbound\"),
        StagingFolder("C:\staging\"),
        OutboundFolder("C:\outbound\");
        private String location;
        private Folder(String location) {
            this.location = location;
        }
        public String locate() {
            return location;
        }
    }
    // ...and so on...

我不想硬编码这些值;相反,我希望在启动Tomcat7时从文本源加载这些常量的值。我读过关于ServletConfigServletContext的文章,但我不确定它们是否是我想要的解决方案。

我该怎么做?

在这种情况下,您可以选择如何初始化常量。有两种常见的方式

1)初始化参数

web.xml

<servlet>
    <servlet-name>myservlet</servlet-name>
    <servlet-class>my.package.MyServlet</servlet-class>
    <init-param>
        <param-name>myParam</param-name>
        <param-value>paramValue</param-value>
    </init-param>
</servlet>

MyServlet.java

public class MyServlet extends HttpServlet {
    protected String s;
    @Override 
    public void init(ServletConfig servletConfig) throws ServletException{
        super(servletConfig);
        this.s = servletConfig.getInitParameter("myParam");
    }
    ....
}   

2)配置文件

你应该在你的应用程序中创建属性文件,在src文件夹中,例如config.properties

myParam=paramValue

Config.java

public class Config {
    private Properties config;
    public Config() {
        config = new Properties();
        reloadConfig();
    }
    public Properties getConfig(){
        reloadConfig();
        return config;
    }
    public String getProperty(String key){
        return getConfig().getProperty(key);
    }
    public void reloadConfig() {
            try {
                config.load(getClass().getResourceAsStream("/config.properties"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

MyServlet.java

public class MyServlet extends HttpServlet {
    protected Config config = new Config();
    @Override 
    public void doGet(request, response) throws ServletException{
        Strign s = config.getProperty("myParam");
    }
}

使用此:

public static Object myDataStaticObject=null;
...
if (myDataStaticObject==null) {
    File file= new File("C:\inbound\", "myCfg.properties");
    InputStream stream = new FileInputStream(file);
    Properties p = new Properties();
    p.load(stream);
    //set your data to myDataStaticObject
}

将数据加载到静态对象中&检查第一次加载时是否为null。

请考虑生产服务器中的目录权限!

有几种方法可以解决您的问题。

1。使用serveltContext
web.xml条目

  <context-param>
         <param-name>file1</param-name>
         <param-value>file1-location</param-value>
      </context-param>
      <context-param>
         <param-name>file2</param-name>
         <param-value>file2-location</param-value>
      </context-param>

并在需要时在运行时获取这些值。

2。使用属性文件并加载该属性文件,然后使用访问器方法访问这些属性。

3。使用XML基本配置,解析并将其保存在内存中。(您也可以使用WatchServices,以便在文件更改时重新加载)

4。在启动应用程序服务器(首选最少)时,提供文件位置作为运行时参数

-Dfile1=文件1-位置-Dfile2=文件2-位置

最新更新