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);
        }
    }

}
posted @ 2015-01-16 16:18  一起简单  Views(3535)  Comments(0Edit  收藏  举报