Servlet Programming: (2) The life cycle of the servlet

Source: Internet
Author: User

    1. How to develop a servlet

    2. The mapping path of the servlet

    3. servlet Default Path

    4. The life cycle of Sevlet

    5. Automatic loading of Servlets

    6. The Init method with parameters and the Init method without parameters

    7. Multithreading concurrency problems for servlets

    8. ServletConfig Object

    9. ServletContext Object

4. The life cycle of the servlet



4.1. Introduction


The life cycle of a servlet involves 3 questions: when the Servlet class object is created, when it is called, and when it is destroyed.

The life cycle of the previous object is written by the program developer, for example:

Student stu = new Student ();//Create Student Object

Stu.study ();//Call method

Stu = null;//tells the garbage collector GC that the object can be recycled


The life cycle of the servlet program is controlled by the tomcat server !!!


4.2. Four important methods of the servlet life cycle



4 Important ways to the servlet life cycle
Serial Number Method timing and number of calls
1 Construction method Called when a Servlet object is created. By default, creating a Servlet object for the first time you access a servlet is called only 1 times. The Servlet object is single-instance in Tomcat.
2 Init method Called when the Servlet object is created. Called only 1 times.
3 Service method Called every time a request is made. Called N Times.
4 Destroy method Called when the Servlet object is destroyed. Destroy the Servlet object when you stop the server or redeploy the Web App. Called only 1 times.

Case: Number of calls to validate 4 important methods of the servlet life cycle

Lifedemo.java

Package Com.rk.http.b_lifecycle;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;public class Lifedemo extends HTTPSERVLET{//1, construction method public Lifedemo () { System.out.println ("1, Lifedemo object is created! ");} 2. Init method @overridepublic void init (servletconfig config) throws Servletexception{system.out.println ("2, Call the Init method of the Lifedemo object ");} 3. Service method @overridepublic void Service (ServletRequest req, servletresponse Res) throws Servletexception, Ioexception{system.out.println ("3, call the service method of the Lifedemo object");} 4, destroy method @overridepublic void Destroy () {System.out.println ("4, Lifedemo object Destruction");}}

Web. XML configuration

<servlet> <servlet-name>LifeDemo</servlet-name> <servlet-class>com.rk.http.b_lifecycle. lifedemo</servlet-class> </servlet> <servlet-mapping> <servlet-name>lifedemo</ Servlet-name> <url-pattern>/life</url-pattern> </servlet-mapping>


After accessing 5 times using the URL (http://localhost:8080/myweb/life), stop Tomcat and get the following output:

1, Lifedemo object was created! 2. Call the Init Method 3 of the Lifedemo object, call service Method 3 of the Lifedemo object, call service Method 3 of the Lifedemo object, call service Method 3 of the Lifedemo object, Call service Method 3 of the Lifedemo object, call the service method of the Lifedemo object May  23, 2016 11:20:45  morning   Org.apache.coyote.http11.http11aprprotocol pause Information: pausing coyote http/1.1 on  http-8080 May  23, 2016 11:20:45  Morning  org.apache.coyote.ajp.ajpaprprotocol pause information:  pausing coyote ajp/1.3 on ajp-8009 May  23, 2016 11:20:46  Morning   Org.apache.catalina.core.standardservice stop information:  stopping service catalina May  23,  2016 11:20:46  Morning  org.apache.catalina.core.applicationcontext log Information:  Sessionlistener: contextdestroyed () May  23, 2016 11:20:46  morning   Org.apache.catalina.core.applicationcontext log information:  contextlistener: contextdestroyed () 4, Lifedemo object destroyed May  23, 2016 11:20:46  morning  org.apache.Coyote.http11.http11aprprotocol destroy Information: stopping coyote http/1.1 on  http-8080 May  23, 2016 11:20:46  Morning  org.apache.coyote.ajp.ajpaprprotocol destroy information:  stopping coyote ajp/1.3 on ajp-8009

4.3, Javax.servlet.Servlet source
package javax.servlet;import java.io.ioexception;/** *  about Servlets  * A  servlet is a small java program that runs within a web  server. * servlets receive and respond to requests from web  clients, * usually across http, the hypertext transfer protocol.   *  *  two ways to implement a servlet interface  * to implement this interface, you  can write a generic servlet *that extends *<code> javax.servlet.genericservlet</code> or an http servlet that *extends  Some methods, called life-cycle , are defined in the <code>javax.servlet.http.httpservlet</code>. * *servlet interface. methods *this interface defines methods to initialize a servlet,  *to service requests,&nbSp;and to remove a servlet from the server. *these are known  as life-cycle methods and are called in the *following  The sequence: * *life-cycle methods are called in the following order: the servlet is constructed-->init-- >service-->destory *the servlet is constructed, then initialized with  the <code>init</code> method. *any calls from clients to  the <code>service</code> method are handled. *the servlet  is taken out of service, then destroyed with the  * <code>destroy</code> method, then garbage collected and finalized. The  * *servlet interface also provides two additional methods: Getservletconfig and Getservletinfo *in addition to the  life-cycle methods,&nbSp;this interface *provides the <code>getservletconfig</code> method,  which the servlet  *can use to get any startup  information, and the <code>getservletinfo</code> *method, which  allows the servlet to return basic information about itself, * such as author, version, and copyright. * */public class servlet{ /** * the servlet container calls the <code>init</code> *  method exactly once after instantiating the servlet. * The  <code>init</code> method must complete successfully * before  The servlet can receive any requests. */public void init (ServletConfig  config)  throws servletexception;/** * called by the servlet container to allow  the servlet to respond to a request. * this method is  Only called after the servlet ' S <code>init () </code> method has  completed successfully. *  * 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.  */public void service (servletrequest req, servletresponse  res) Throws servletexception, ioexception;/** * called by the servlet container to  indicate that the servlet is being taken out of service. *  this method is only called once all threads within the  servlet ' s * <code>service</code> method have exited or  after a timeout period has passed. * after the servlet  container calls this method, it will not call  * the  <code>service</code> method again on this servlet. *  *  This method gives the servlet an opportunity  * to  clean up any resources that are being held  (for example,  Memory, * file handles, threads)  and make sure that any persistent state is *  Synchronized with the servlet ' S current state in memory. */public  void destroy ();/** * returns a <code>servletconfig</code>  Object, which contains initialization and startup parameters for this  servlet. * the <code>servletconfig</code> object returned is  the one passed to the <code>init</code> method.  */ Public servletconfig getservletconfig ();/** * returns information about the  servlet, such as author, version, and copyright. */public string  getservletinfo ();}





4.4. Pseudo-code demonstrates the life cycle of the servlet

Tomtcat Internal code run:

1) Find the content of servlet-class by mapping

String: Com.rk.http.b_lifecycle. Lifedemo

2) Constructing Lifedemo objects by reflection

2.1 Getting bytecode objects

Class clazz = Class.forName ("Com.rk.http.b_lifecycle. Lifedemo ");

2.2 To construct an object by calling the parameterless construction method

Object obj = clazz.newinstance (); Constructed method---1.servlet is called

3) Create a ServletConfig object to invoke the Init method through reflection

3.1 Getting Method objects

Method m = Clazz.getdeclaremethod ("init", servletconfig.class);

3.2 Calling Methods

M.invoke (Obj,config); The Init method of the--2.servlet is called

4) Create a Request,response object to invoke the service method through reflection

4.1 Getting Method objects

Method m =clazz.getdeclaremethod ("service", Httpservletrequest.class,httpservletresponse.class);

4.2 Calling methods

M.invoke (Obj,request,response); The service method of the--3.servlet is called

5) Call the Destroy method through reflection when the Tomcat server stops or the Web app is redeployed

5.1 Getting Method objects

Method m = Clazz.getdeclaremethod ("destroy", null);

5.2 Calling methods

M.invoke (Obj,null); --4.servlet's Destroy method is called



4.5. Use a time series diagram to demonstrate the life cycle of the servlet

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/80/76/wKiom1dChV7R-sqwAADV4f5CdAs447.png "title=" Servlet_life_cycle.png "alt=" Wkiom1dchv7r-sqwaadv4f5cdas447.png "/>




Servlet Programming: (2) The life cycle of the servlet

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.