top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Explain the life cycle of a Servlet in JAVA?

+2 votes
174 views
Explain the life cycle of a Servlet in JAVA?
posted Feb 4, 2015 by Shyam

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet

The servlet is initialized by calling the init () method.

The servlet calls service() method to process a client's request.

The servlet is terminated by calling the destroy() method.

Finally, servlet is garbage collected by the garbage collector of the JVM.

the life cycle methods

enter image description here

answer Feb 6, 2015 by Karthick.c
Similar Questions
+1 vote

Does the RequestDispatcher expect a relative URL to be relative to the originally-called servlet or to the current servlet (if different)?

+2 votes
public class ServletClassName extends HttpServlet {
//declare instance variables for the servlet
int  instanceVar ; // not thread−safe
// overriding the Generic Servlet.init ( )
@Override
public void init ( ) throws ServletException {
// initialize instance variables, etc.
instanceVar = 0 ;
}
. . .
}

Per each page request, in the service() method (which eventually will be either doGet(), doPost(), or whatever),
you can manipulate instance variables.

Write a Servlet that counts the total number of visits (how many times it's being visited from all clients). The Servlet should display the following information

• Total Page Visits:
• Client Remote Address:
• Client Host Address: <client_fully_qualied_url__or__client_IP_address>

The last two can be obtained from the HttpServletRequest, Refer to the Java EE API

then how can re-do these using the Java API for HttpSession.

...