1 of 8

Advanced java programming

Life cycle of Servlet

M.Jeevana sujitha

Assistant Professor

Department of Computer Science and Engineering

SRKR Engineering College, Bhimavaram, A.P. - 534204

2 of 8

OBJECTIVES

The Objective of this lecture is

  • To learn about life cycle of servlet.

3 of 8

Life cycle of Servlet

4 of 8

Life cycle of Servlet

  • There are 3 important methods in servlet life cycle. They are
  • init()
  • service()
  • destroy()

5 of 8

Life cycle of Servlet

init(): The init() method is designed to be called only once in the life cycle of servlet.

  • It is called when the servlet is first created.
  • It is used for one-time initializations.
  • The servlet is normally created when a user first invokes a URL corresponding to the servlet.

Syntax:

public void init() throws ServletException

{

Initialization code

}

6 of 8

Life cycle of Servlet

service(): The service () method is the main method to

perform the actual task.

  • The servlet container calls the service() method to handle

requests coming from the client and to write the

formatted response back to the client.

  • Each time the server receives a request for a servlet, the

server creates a new thread and calls the service()

method.

  • The service method checks the Http request type(GET or

POST) and calls doGet() or doPost() methods.

Syntax:

public void service(ServletRequest req, ServletResponse res)

{

Actual business logic for providing service to client

}

7 of 8

Life cycle of Servlet

destroy(): The destroy() method is called only once at the end of the life cycle of servlet.

  • It gives our servlet a chance to close database connections and perform other cleanup activities.
  • After the destroy() method is called, the servlet object is marked for garbage collection.

Syntax:

public void destroy()

{

Closing database connections

}

8 of 8

THANK YOU