ServletConfig 对象

容器初始化 Servlet 时,会创建一个 ServletConfig 对象,可获得当前 Servlet 的初始化参数信息。

获得 ServletConfig 对象

直接从带参的 init() 方法中提取

1
2
3
4
5
6
7
8
9
10
11
12
public class ServletConfigDemo extends HttpServlet {
private ServletConfig servletConfig;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取Servlet得名字
this.servletConfig.getServletName();
}
@Override
public void init(ServletConfig config) throws ServletException {
//从带参init方法中,提取ServletConfig对象
this.servletConfig = config;
}
}

调用 GenericServlet 提供的 getServletConfig() 方法获得

1
2
//调用 GenericServlet 提供的 getServletConfig 方法获得 ServletConfig 对象
ServletConfig servletConfig = this.getServletConfig();

ServletConfig 接口 Method

Enumeration<String> getInitParameterNames() 返回 Servlet 所有的初始化参数名的枚举集合,如果该 Servlet 没有初始化参数,则返回一个空的集合。

String getInitParameter(String name) 根据初始化参数名 name,返回对应的初始化参数值

ServletContext getServletContext() 返回一个代表当前 Web 应用的 ServletContext 对象。

String getServletName() 返回 Servlet 的名字,即 web.xml 中 <servlet-name> 元素的值。