• 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);
            }
        }
    
    }
  • 相关阅读:
    好看的壁纸网站
    python简介
    python学习之基本语法(1)
    信息系统开发方法
    数据库连接池的使用小结
    软件版本后的字母含义
    信息系统与信息化
    软考
    实施过程中的项目管理
    mysql查SQL执行速度
  • 原文地址:https://www.cnblogs.com/myit/p/4229067.html
Copyright © 2020-2023  润新知