- 封装了 Servlet的配置信息,并且可以获取ServletContext对象
- 配置servlet的初始化参数
在web.xml文件中,<servlet></servlet节点里,新增一个<init-param></init-param>节点,如
<servlet> <servlet-name></servlet-name> <servlet-class></servlet-class> <!--配置Servlet的初始化参数,*n,可以有多个init-param节点--> <init-param> <param-name>user</param-name> <param-value>fv</param-value> </init-param> <init-param> <param-name>password</param-name> <param-value>timewalkfv</param-value> </init-param> <!--可以指定Servlet被创建的时机,必须放在init-param节点的后面--> <load-on-startup>-1</load-on-startup> </servlet>
2.获取初始化参数getInitParameter(String name)、getInitParameterNames() 获取参数名组成的Enumeration
@Override public void init(ServletConfig servletConfig) throws ServletException { // TODO Auto-generated method stub System.out.println("init"); String username = servletConfig.getInitParameter("username"); System.out.println("username: "+ username); Enumeration<String> params = servletConfig.getInitParameterNames(); while(params.hasMoreElements()){ String name = params.nextElement(); String value = servletConfig.getInitParameter(name); System.out.println(" name : " + name + "\n value : " + value ); } String servletName = servletConfig.getServletName(); System.out.println("servletName : "+ servletName); }
时间: 2024-11-03 01:23:02