Servlet的生命周期
相关代码:
package edu.etime.firstservlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 演示servlet的生命周期
*
* @author ycy
*
*/
public class ServletLife extends HttpServlet {
public ServletLife() {
// TODO Auto-generated constructor stub
System.out.println("ServletLife 的构造方法");
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
/*
* 默认的父类service方法
*
*/
System.out.println("调用了service方法");
// 调用父类的service方法
super.service(request, response);
}
/**
* 初始化servlet.执行完initial方法之后,servlet实例才准备好,才可以调用service方法
*
* @throws ServletException
*/
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
System.out.println("调用了init方法");
super.init();
}
/**
* servlet关闭的时候,回收资源
*/
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("调用了destroy方法");
super.destroy();
}
/**
* 处理get请求
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("调用了了doGet方法");
super.doGet(req, resp);
}
/**
* 处理post请求
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("调用了doPost方法");
super.doPost(req, resp);
}
}
<!-- servlet生命周期配置演示 -->
<servlet>
<servlet-name>life</servlet-name>
<servlet-class>edu.etime.firstservlet.ServletLife</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>life</servlet-name>
<url-pattern>/life</url-pattern>
</servlet-mapping>