Servlet生命周期
Servlet的生命周期可以分为四个阶段,分别为:实例化、初始化、服务以及销毁。
- 实例化:servlet容器创建servlet的实例
- 初始化:servlet容器调用init(ServletConfig)方法初始化
- 服务:请求servlet,容器调用service()方法
- doGet()方法
- doPost()方法
- 销毁:销毁实例之前调用destroy()方法
public interface Servlet {
//初始化
void init(ServletConfig var1) throws ServletException;
ServletConfig getServletConfig();
//服务
void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
String getServletInfo();
//销毁
void destroy();
}
Servlet实例化:
Servlet 创建于用户第一次调用对应于该 Servlet 的 URL 时。每当用户调用一个Servlet,容器就会创建一个Servlet实例。
Servlet初始化(init()方法):
Init()方法只能调用一次,只在第一次创建servlet时被调用。
服务(service()方法):
service() 方法是执行实际任务的主要方法。Servlet 容器调用 service() 方法来处理来自客户端(浏览器)的请求,并将响应返回给客户端。
Service方法会识别请求类型(GET、POST、PUT等)并调用doGet/doPost等方法,因此我们只需要重写其方法,就可以处理不同类型的请求。
protected void service(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
String method = req.getMethod();
long lastModified;
//Service方法识别请求类型
if (method.equals("GET")) {
lastModified = this.getLastModified(req);
if (lastModified == -1L) {
this.doGet(req, resp);
} else {
long ifModifiedSince;
try {
ifModifiedSince = req.getDateHeader("If-Modified-Since");
} catch (IllegalArgumentException var9) {
ifModifiedSince = -1L;
}
if (ifModifiedSince < lastModified / 1000L * 1000L) {
this.maybeSetLastModified(resp, lastModified);
this.doGet(req, resp);
} else {
resp.setStatus(304);
}
}
} else if (method.equals("HEAD")) {
lastModified = this.getLastModified(req);
this.maybeSetLastModified(resp, lastModified);
this.doHead(req, resp);
} else if (method.equals("POST")) {
this.doPost(req, resp);
} else if (method.equals("PUT")) {
this.doPut(req, resp);
} else if (method.equals("DELETE")) {
this.doDelete(req, resp);
} else if (method.equals("OPTIONS")) {
this.doOptions(req, resp);
} else if (method.equals("TRACE")) {
this.doTrace(req, resp);
} else {
String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[]{method};
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(501, errMsg);
}
}
doGet()方法及doPost()方法:
Get请求是一个url的普通请求或是未指定method的表单提交的请求,这种请求会调用doGet()方法处理。
Post请求是指定了 method 为 POST表单提交的请求,调用doPost()方法处理。
销毁destroy():
destroy()方法和init()方法一样,只被调用一次,destroy()方法在servlet生命周期结束时被调用。调用这个方法后servlet对象会被标记为垃圾由JVM垃圾回收器回收掉。
我们来总结一下servlet生命周期的整个流程:
①用户第一次调用一个Servlet的url时,servlet容器创建servlet实例。
②调用init()方法。
③再调用service()方法处理请求,响应用户。
④调用destroy()方法销毁servlet实例。