标签:
ServletConfig对象
public abstract interface ServletConfig
A servlet configuration object used by a servlet container used to pass information to a servlet during initialization
Method Summary:
1、 java.lang.String getInitParameter(java.lang.String name) : Returns a String containing the value of the named initialization parameter,or null if the parameter does not exist.
2、 java.util.Enumeration getInitParameterNames() : Returns the names of the servlet‘s initialization parameters as an Enumeration of String objects,or an empty Enumeration if the servlet has no initialization parameters.
3、 ServletContext getServletContext() : Return a reference to the ServletContext in which the caller is executing
4、 java.lang.String getServletName() : Returns the name of this servlet instance.
ServletConfig : 封装了Servlet配置信息,并且可以获取ServletContext对象
1.配置Servlet的初始化参数:只有当前Servlet可以获取这些初始化参数
<!-- 配置和映射Servlet --> <servlet> <!-- Servlet 注册的名称 --> <servlet-name>HelloServlet</servlet-name> <!-- Servlet 的全类名 --> <servlet-class>com.servlet.demo.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>1230</param-value> </init-param> <!-- 可以指定Servlet被创建的时机 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <!-- 需要和某一个servlet节点的servlet-name子节点的文本节点一致 --> <servlet-name>HelloServlet</servlet-name> <!-- 映射具体的访问路径: / 代表当前WEB应用的根目录 --> <url-pattern>/hello</url-pattern> </servlet-mapping>
2.获取初始化参数
getInitParameter(String name) : 获取指定参数名的初始化参数
getInitParameterNames() : 获取参数名组成的Enumeration对象
public void init(ServletConfig config) throws ServletException { System.out.println("Servlet init method!"); String user = config.getInitParameter("user"); System.out.println("user = " + user); Enumeration<String> names = config.getInitParameterNames(); while(names.hasMoreElements()) { String name = names.nextElement(); String value = config.getInitParameter(name); System.out.println(name + " = " + value); } }
标签:
原文地址:http://www.cnblogs.com/xinhuaxuan/p/4596941.html