servletConfig,它封裝了servlet的配置信息,經過它能夠獲取到servletContext對象。
配置信息以下java
<!-- 配置映射 --> <servlet> <servlet-name>helloServlet</servlet-name> <servlet-class>com.test.javaweb.HelloServlet</servlet-class> <!-- 配置servlet的初始化參數 --> <init-param> <param-name>user</param-name> <param-value>root</param-value> </init-param> <init-param> <param-name>password</param-name> <param-value>123456</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>
獲取初始化參數有兩種方法
1.getInitParameter(String name):獲取指定參數名的初始化參數
2.getInitParameterNames():獲取全部的參數名web
public void init(ServletConfig arg0) throws ServletException { // TODO Auto-generated method stub System.out.println("init"); //1.獲取指定參數名的初始化參數 String user = arg0.getInitParameter("user"); System.out.println(user); //2.獲取全部的參數名及其參數值 Enumeration<String> names = arg0.getInitParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); //這裏能夠獲取參數值 String value = arg0.getInitParameter(name); System.out.println(name+":"+value); } }