Servlet的生命周期
创建——>初始化——>使用——>销毁
1.首次访问该servlet时,会创建servlet实例,并执行servlet的初始化innit方法
2.执行业务service方法,完成请求
3.当再次访问该servlet时,此时将不再创建实例,也不进行初始化,直接执行业务service方法
4.当web容器进行正常关闭(stop)时,此时会执行销毁方法(destroy)
代码示范
package com.cmp.servlet;
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 ServletLife extends HttpServlet {
public ServletLife() {
// TODO Auto-generated constructor stub
System.out.println("ServletLife()");
}
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
super.service(arg0, arg1);
System.out.println("service()");
}
@Override
public void destroy() {
// TODO Auto-generated method stub
super.destroy();
System.out.println("destroy()");
}
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
System.out.println("init()");
}
}
运行效果