1.Servlet接口分析
此接口是Servlet的最頂層接口,其中定義了Servlet生命周期相關的方法,所有Servlet都必須實現。此接口中的方法有以下幾個:
public void init(ServletConfig config) throws ServletException;
public ServletConfig getServletConfig();
public void service(ServletRequest req, ServletResponse res)
public String getServletInfo();
public void destroy();
生命周期的調用順序如下:
Servlet構建成功后調用init方法來初始化Servlet配置,此方法只調用一次,然后有一個http請求就調用service方法來處理相應請求,當所有請求結束,調用destroy方法來釋放Servlet。 此三個方法都是由Servlet容器(比如tomcat,jetty)來調用。
其中getServletConfig和getServletInfo用於獲取Servlet相關信息。
2.ServletConfig接口分析
此接口為Servlet配置抽象接口,定義了獲取Servlet信息的相關接口,接口列表如下:
//獲取Servlet名稱,即是web.xml中配置的servlet-name
public String getServletName()
//返回此Servlet對應的上下文
public ServletContext getServletContext()
//獲取初始化參數
public String getInitParameter(String name)
//獲取初始化參數名稱列表
public Enumeration<String> getInitParameterNames()
3.GenericService抽象類分析
此類實現了上面兩個接口,主要是實現了ServletConfig類中的接口。此類中維護了一個ServletConfig變量,定義方式如下:
private transient ServletConfig config;
添加transient修飾的作用:序列化的時候不包含此字段
此局部變量在init的時候初始化,初始化方式如下:
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
init方法是由Servletr容器調用,因此,web.xml中Servlet配置轉化為ServletConfig的工作因該是由容器完成的。
其中ServletConfig接口的方法實現方式基本如下:
public String getServletName() {
ServletConfig sc = getServletConfig();
if (sc == null) {
throw new IllegalStateException(
lStrings.getString("err.servlet_config_not_initialized"));
}
return sc.getServletName();
}
比較簡單,不再分析。