servlet獲取並存儲web.xml中context-param參數


在web.xml中定義了context-param,一般不會隨意改動,所以在監聽器中做一次處理,容器啟動時讀取並存儲在Properties中,方便以后取值。

SysProperties 類用於存儲 context 鍵值;

SystemListener 監聽器類,處理 context-param 參數。

/**
 * 用於存儲參數鍵值
 */
public final class SysProperties {
    private static SysProperties instance;
    private Properties initProperties = new Properties();

    private SysProperties() { }

    public static SysProperties getInstance() {
        if (instance == null) {
            instance = new SysProperties();
        }
        return instance;
    }

    /**
     * 獲取對應的值
     * @param key String 提供的鍵(param-name)
     * @return String 鍵對應的值(param-value)
     */
    public String getProperty(String key)
    {
        return this.initProperties.getProperty(key);
    }

    /**
     * 檢測是否包含該鍵
     * @param key String 鍵
     * @return boolean 該鍵存在返回 true,否則返回 false
     */
    public boolean containsKey(String key) {
        return this.initProperties.containsKey(key);
    }

    /**
     * 存儲參數
     * @param key String param-name
     * @param object String param-value
     */
    public void put(String key, String object) {
        this.initProperties.put(key, object);
    }
}

 

/**
 * 系統監聽,程序啟動時初始化並存儲相關參數
 */
public class SystemListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        initContextParam(servletContextEvent);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) { }

    private void initContextParam(ServletContextEvent event) {
        Enumeration<String> names = event.getServletContext().getInitParameterNames();
        while (names.hasMoreElements())
        {
            String name = names.nextElement();
            String value = event.getServletContext().getInitParameter(name);
            SysProperties.getInstance().put(name, value);
        }
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM