JSP学习 --- servlet的生命周期
servlet生命周期:
1.是否创建了servlet对象;没有就创建,创建了则执行第3步
2.执行servlet的init方法
3.调用service方法,创建response和request对象;request对象来自客户端可以获取客户端的信息/请求信息,response向客户端发出信息;由service来调用doGet或者doPost方法
4.调用destory方法
注意:客户端每次访问服务器,都只会new 一个servlet,也就是只有一个servlet,多个客户端访问只是多个service的线程在访问;
测试代码如下:
package com.jack.servlet;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LifeServlet extends HttpServlet{
public LifeServlet(){
System.out.println("我是构造方法");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("我是doGet方法");
super.doGet(req, resp);
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
Thread current = Thread.currentThread();
System.out.println("当前线程id: "+ current.getId()+ " 我是service方法");
super.service(arg0, arg1);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("我是destroy方法");
super.destroy();
}
@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
System.out.println("我是init方法");
super.init(config);
}
}
测试结果: