What Is the Life Cycle of a Servlet? JDBC

What really goes on inside a Java servlet and container? Figure shows a step-by-step summary.

Java servlet and container

Java servlet and container

  1. Use your favorite text editor (or any Java IDE) to create your Java servlet, SERVLET-NAME. java.
  2. Using the Java compiler (javac), compile SERVLET-NAME.java (the output of this step is SERVLET-NAME.class).
  3. Place the SERVLET-NAME.class file into your .../WEB-INF/classes directory (for details see Tomcat’s directory structure or your desired web application server).
  4. Start the web/application server (this might load some or even all of the servlets depending on how the servlet container is configured).
  5. A web/application server loads and initializes the servlet: when the first client requests a service from a servlet, then Java servlet (a .class file—in this case, SERVLET-NAME.class) is loaded.
  6. After the .class files are loaded, they stay resident in memory until the servlet container is shut down.
  7. The servlet’s init() (i.e., initialization) method is run. The init() method is used to initialize global data structures and databases for the life of the servlet (for example, to set up counters, establish database connections, and initialize any objects within memory that the servlet will need).
  8. After the servlet is loaded and initialized, it is ready for service (now clients can send requests to that servlet).
  9. The servlet handles zero or more client requests: each client request initializes a separate service object. It is closed as soon as the request is finished.
  10. Web browsers make requests in two ways (POST and GET), and servlets have support for both GET (handled by the doGet() method) and POST (handled by the doPost() method).
    • Using the GET method (the servlet executes the doGet() method), variables that the browser is sending from forms are sent as an extension of the URL
    • The POST method (the servlet executes the doPost() method) sends the variables in the actual request sent to the server. POST is the preferred method by most programmers since it does put information on the URL line.
  11. The server removes the servlet: when the web/application server is shut down or is restarted, the destroy() method will be executed. The purpose of this method is to “clean up” (such as closing database connections or closing log files).
  12. Java uses automatic garbage collection (Java will automatically detect the unneeded objects).

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

JDBC Topics