Servlet 05: Servlet生命周期方法
以TestServlet.java 为例:
@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
public TestServlet() {
System.out.println("构造方法被调用了!");
}
@Override
public void init() throws ServletException {
super.init();
System.out.println("init()被调用了!");
}
@Override
public void destroy() {
super.destroy();
System.out.println("destroy()被调用了!");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost");
}
}
<1>操作: Run on Server
效果 - 第一次访问:
(destroy方法并没有被调用)
效果 - 刷新页面若干次:
(只调用了doGet)
效果 - 通过别的客户端(浏览器)访问 (代表一个新的用户来了):
还是只调用了doGet
<2>操作: 停止运行Tomcat
效果:
destroy()被调用了
<3> 在TestServlet.java中:
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
System.out.println("service()被调用了!");
super.service(arg0, arg1);
} // 不管Servlet调用的是doGet()还是doPost(), service()都会被调用
效果:
对代码进行一点(顺序上的)修改:
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
super.service(arg0, arg1);
System.out.println("service()被调用了!");
}
效果:
原因: super.service(arg0, arg1); 调用了doGet()