Servlet
1.生命周期
servlet被创建出来之后,init()为初始化方法,destroy()与前者相反,当servlet对象被销毁时使用。
public class TestServlet extends HttpServlet {
public TestServlet() {
// TODO Auto-generated constructor stub
System.out.println("构造方法");
}
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("service()");
super.service(arg0, arg1);
}
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
System.out.println("init()");
}
@Override
public void destroy() {
// TODO Auto-generated method stub
super.destroy();
System.out.println("destroy()");
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("doget");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("dopost");
}
}
根据运行结果,发现首先调用构造方法,其次init(),最后doget(),destroy()没有被访问。在后面接着运行程序时,只调用doget方法。也就是说init和构造方法只会调用一次。当servlet第一次被访问的时候调用构造方法和init。当关闭servlet时会调用destroy方法。另外,在每次调用doget或者dopost前都会调用service方法。本代码基于tomcat。
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
super.service(arg0, arg1);
System.out.println("service()");
}
```
如果如上图将service代码放在输出代码前面,则会先输出doget再输出service()。因为调用service会先去调用doget或者dopost。