java 获取web.xml的值

1,java代码

// 先获取ServletConfig对象
        ServletConfig config = getServletConfig();
        // 获取配置文件中serlvet的名称
        System.out.println("servlet的名称:"+config.getServletName());
        
        // 获取初始化的参数
        String username = config.getInitParameter("username");
        String password = config.getInitParameter("password");
        System.out.println(username+" : "+password);
        
        Enumeration<String> e = config.getInitParameterNames();
        while(e.hasMoreElements()){
            String name = e.nextElement();
            String value = config.getInitParameter(name);
            System.out.println(name+" : "+value);
        }

2,web.xml代码

  <servlet>
    <servlet-name>RefererServlet</servlet-name>
    <servlet-class>cn.itcast.servlet.ServletDemo6</servlet-class>
    <!--设置参数 -->
    <init-param>
        <param-name>username</param-name>
        <param-value>root</param-value>
    </init-param>
    <init-param>
        <param-name>password</param-name>
        <param-value>123</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>RefererServlet</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
原文地址:https://www.cnblogs.com/kbqLibrary/p/8064567.html