Servlet之生命周期

来源:互联网 发布:mac版qq文件夹在哪里 编辑:程序博客网 时间:2024/06/05 06:21

以下从Servlet的接口中定义的三个方法来看,一个servlet的生命周期。

/** * *<ol> * <li>The servlet is constructed, then initialized with the <code>init</code> method. * <li>Any calls from clients to the <code>service</code> method are handled. * <li>The servlet is taken out of service, then destroyed with the  * <code>destroy</code> method, then garbage collected and finalized. * </ol> *生命周期就是上面这句话:大意就是servlet被创建,然后通过init方法进行初始化,service方法会处理客户端的请求,destroyed方法进行销毁操作,GC进行回收。*/public interface Servlet {    /**    * init方法,只有在被创建Servlet的时候调用一次进行初始化,之后不会再被调用,当然也可以通过servlet容器在启动时进行初始化加载。    *并且这个初始化方法必须在接收到任何的请求调用service方法之前执行成功,否则抛出异常    *    */    public void init(ServletConfig config) throws ServletException;    //这是用来获取此servlet的初始化信息和参数。    public ServletConfig getServletConfig();    //service方法它必须在init方法成功完成之后,然后处理客户端的请求request,并返回服务端响应response。    /*     *<p>Servlets typically run inside multithreaded servlet containers     * that can handle multiple requests concurrently. Developers must      * be aware to synchronize access to any shared resources such as files,     * network connections, and as well as the servlet's class and instance      * variables.     * 此句大意: 运行在多线程的servlet容器中的Servlets同时可以处理多个请求,但是要注意确保同步处理一些共享资源如变量等。     */    public void service(ServletRequest req, ServletResponse res)    throws ServletException, IOException;    // Returns information about the servlet, such as author, version, and copyright.返回一些servlet的信息,比如作者 版本之类,    public String getServletInfo();    /*    *当生命周期结束时被调用一次,可以在此方法中进行相关清理工作如:关闭资源    *等,然后等待GC回收。    */    public void destroy();}

请求到达servlet容器,容器找到相应的servlet,一个请求一个线程去调service()方法,在此之前先加载servlet进行初始化,初始化init()方法只调用一次。

原创粉丝点击