• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confused about Life cycle of Servlets

 
pawan chopra
Ranch Hand
Posts: 417
jQuery Mac Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,


I have following Servlet.


When the very first request comes to this servlet. I got following results:

i am in constructor
init
doPost
service HTTP
service generic


I would like to know the reason behind last 2 outputs. I am confused how these two methods are getting executed.


 
Balu Sadhasivam
Ranch Hand
Posts: 874
Android Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Pawan,



executes the last 2 lines. Remember doPost() is called by HTTP service method.
 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If this code is just for experiment then its fine, otherwise in general refrain from overriding the service method. Override the doPost and/or doGet methods instead...
 
Anirvan Majumdar
Ranch Hand
Posts: 261
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The service(HttpServletRequest, HttpServletResponse) is the HTTP-specific version of the Servlet.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) method. Thus, when you make an HTTP request to your server, you get the HTTP service method invoked before the generic service method.
 
Ramkumar Subburaj
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The servlet life cycle is as follows.

1. Creates an Instance of the servlet class (Constructor)
2. Initializes the servlet (init method) and wait for requests.
3. if any request comes in, service method is called and this determines which type of request it is and calls the appropriate method(like doGet, doPost etc...)
4. The destroy method is called before removing the servlet from the container

I think you can trace what is happening by putting as the first line of the method definition and at the end of the method definition.
 
Ulf Dittmer
Rancher
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If this code is just for experiment then its fine, otherwise in general refrain from overriding the service method. Override the doPost and/or doGet methods instead...

+1. The service method doesn't need to be overwritten unless you're writing a servlet to handle HTTP extensions (which would be an exceedingly rare occasion).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic