ServletConfig、ServletContext、Application

一、ServletConfig接口

1、Servlet引擎将代表Web应用程序的对象(ServletContext)和Servlet的配置参数信息(web.xml)一并封装到一个称为ServletConfig的对象中,并在初始化Servlet实例对象时传递给该Servlet。ServletConfig接口有用于定义ServletConfig对象需要对外提供的方法,以便在Servlet程序中可以调用这些方法来获取有关信息。

2、Servlet引擎创建Servlet实例对象后,会调用Servlet的init(ServletConfig config)方法,把ServletConfig对象传递给Servlet,为了能够在Servlet程序中其他地方获得ServletConfig对象引用,需在Servlet程序提供一个getServletConfig方法。

3、编写Servlet类时,通常会继承HttpServlet类,因为HttpServlet继承了GenericServlet类,并且这个类实现了Servlet接口的init方法和getServletConfig方法。所以程序员无需自己实现这两个方法。

GenericServlet类源码摘取(servlet api源码可通过下载Tomcat源码知道):

//注意,config为私有变量,子类可以继承但不能使用,哪怕去掉private,结果也一样,因为自己写的Servlet和GenericServlet不在同一个包内。
private transient ServletConfig config; // 私有变量
public void init(ServletConfig config) throws ServletException { // 供servlet引擎调用
    this.config = config; // 把servletConfig对象引用传递给Servlet实例
    this.init();
}
// 这样在servlet程序其他地方可通过该方法获得servletConfig对象引用
public ServletConfig getServletConfig() { 
    return config;
}

二、ServletContext接口

每个Web应用程序(不是一个Servlet,因为一个Web应用程序可以有多个Servlet)分别用一个ServletContext对象来表示,Servlet引擎为每个Web应用程序都创建一个对应的ServletContext对象。

1、ServletConfig接口中有getServletContext方法:

public ServletContext getServletContext();

2、在GenericServlet类中有getServletContext方法:

public ServletContext getServletContext() {
    return getServletConfig().getServletContext();
}

3、因此在Servlet程序中,直接调用getServletContext方法可以获得ServletContext对象。

三、Application对象

由于一个Web应用程序中所有Servlet都共享同一个ServletContext对象,所以,ServletContext对象被称为Application对象(Web应用程序对象)。Application对象(ServletContext对象)内部有一个哈希表集合对象,存储进Application内部的哈希表集合对象中的每对关键字/值被称为Application对象的属性。存储在Application对象中的属性也被称为Application域范围的属性,其可以被当做该Web应用程序范围内的全局变量使用。ServletContext接口中定义了4个分别用于增加、删除、访问Application域范围的属性的方法:

getAttributeNames方法,返回一个Enumeration集合对象,该集合对象中包含了application对象中所有属性的名称;

getAttribute方法,用于返回某个属性的值;

removeAttribute方法,用于删除某个属性;

setAttribute方法,用于增加一个属性,如果该名称的属性已经存在,则新的设置值替换原来的设置值,如果属性设置值为null,则等效于使用removeAttribute方法。

你可能感兴趣的:(ServletConfig、ServletContext、Application)