测试servlet生命周期及调用过程

J2EE规定,servlet对象只有一个。即只创建一个servlet对象;
init()只执行一次,第一次初始化的时候执行;

加载ClassLoader
实例化new
初始化init(ServletConfig)
处理请求 service doGet doPost
退出服务 destroy

重点:只有一个对象
destroy()退出的时候执行;

 

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

public class TestLifeCycle extends HttpServlet {
	public TestLifeCycle() {
		System.out.println("constructor");
	}

	public void init(ServletConfig config) throws ServletException {
		System.out.println("init");
	}

	protected void doGet(HttpServletRequest requst, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("doGet");
	}

	public void destroy() {
		FileWriter fw = null;
		BufferedWriter bw = null;
		try {
			File f = new File("D:\\...",
					"TestLifeCycle.txt");
			fw = new FileWriter(f);
			bw = new BufferedWriter(fw);
			bw.write("destroy");
			bw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bw != null) {
					bw.close();
					bw = null;
				}
				if (fw != null) {
					fw.close();
					bw = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

}


 

执行结果:

constructor

init

doGet

在TestLifeCycle.txt文件中写入的信息为:

destroy

你可能感兴趣的:(servlet)