servlet生命周期

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。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值