您的位置:首页 > 其它

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

2012-10-28 11:03 316 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: