Servlet生命周期及创建方式

来源:互联网 发布:深圳冰川网络 市场策划 编辑:程序博客网 时间:2024/05/16 03:04

上次说到xml,今天来讲讲servlet
servlet 是运行在 Web 服务器中的小型 Java 程序(即:服务器端的小应用程序)。servlet 通常通过 HTTP(超文本传输协议)接收和响应来自 Web 客户端的请求。



Servlet生命周期
实例化–>初始化–>服务->销毁
出生:(实例化–>初始化)第一次访问Servlet就出生(默认情况下)
活着:(服务)应用活着,servlet就活着
死亡:(销毁)应用卸载了servlet就销毁。
/一个Servlet只会有一个对象,服务所有的请求/
1.实例化(使用构造方法创建对象)
2.初始化 执行init方法
3.服务 执行service方法
4.销毁 执行destroy方法

public class ServletDemo1 implements Servlet {     //生命周期方法:当Servlet第一次被创建对象时执行该方法,该方法在整个生       命周期中只执行一次public void init(ServletConfig arg0) throws ServletException {                System.out.println("=======init=========");        }    //生命周期方法:对客户端响应的方法,该方法会被执行多次,每次请求该servlet都会执行该方法public void service(ServletRequest arg0, ServletResponse arg1)            throws ServletException, IOException {        System.out.println("hehe");    }//生命周期方法:当Servlet被销毁时执行该方法public void destroy() {        System.out.println("******destroy**********");    }public ServletConfig getServletConfig() {        return null;    }public String getServletInfo() {        return null;    }}



Servlet的三种创建方式
1、实现javax.servlet.Servlet接口(参见:上面的程序代码)
2、继承javax.servet.GenericServlet类(适配器模式)

public void service(ServletRequest arg0, ServletResponse arg1)            throws ServletException, IOException {        System.out.println("heihei");    }

3、继承javax.servlet.http.HttpServlet类(模板方法设计模式)
(开发中常用方式)

public class ServletDemo3 extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        System.out.println("haha");    }@Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        doGet(req,resp);    }}
0 0