同人的生老病死,servlet也有生命周期,其收到web容器的控制,其生命周期包括 加载程序,初始化、服务、销毁、卸载5个部分,如下图所示;
代码验证:
自定义LifeCycleServlet继承HttpServlet,覆写其生命周期相应方法
package helloservlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LifeCycleServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -1922315362237286875L;
@Override
public void init() throws ServletException {
System.out.println("** 1、Servlet初始化 --> init()");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("** 2、Servlet服务 --> doGet()、doPost()");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
public void destroy() {
System.out.println("** 3、Servlet销毁 --> destory()");
try {
Thread.sleep(30000);
} catch (Exception e) {
}
}
}
在web.xml中配置:
<servlet>
<servlet-name>life</servlet-name>
<servlet-class>helloservlet.LifeCycleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>life</servlet-name>
<url-pattern>/LifeServlet</url-pattern>
</servlet-mapping>
运行观察:
容器tomcat关掉,调用destory( )方法
如果在配置文件中加入:
<load-on-startup>1</load-on-startup>
配置:
<servlet>
<servlet-name>life</servlet-name>
<servlet-class>helloservlet.LifeCycleServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>life</servlet-name>
<url-pattern>/LifeServlet</url-pattern>
</servlet-mapping>
容器tomcat启动时就会自动为sevlet初始化:
实际应用时,不会覆写生命周期的全部方法,依需求,需要哪个覆写哪个,doGet(),doPost()使用几率最高,主要覆写这两个