Servlet behaves like normal java class,hence we can override the constructor(default constructor),also we can create parameterized constructor.I would like to know if I overriden the default constructor with database pooling or connection availing. Will it increase the performance of the servlet?
Whatelse can be written in constructor to increase the efficiency or performance(should act as a normal servlet ) ? what are the other functionalities can be written in the constructor, when the servlet gets instantiated ?
Originally posted by sheril she:
could u pls explain when exactly the servlet constructor is called and when the init method is called.since in a servlet's lifecycle there is only the init ,service and destroy.and it is said that the init method is called when the servlet is loaded.so what is the difference between creating instances and loading the servlet?where are these instances stored?
Kevin Mukhar :
In short, there is no answer to when exactly a method is called. The methods are called relative to events in the container life and request process.
- class files are loaded anytime between when the container is initiated and when a request for the servlet is received
- a servlet instance (or instances) is created by calling the no-argument constructor any time after the class is loaded but before the first request
- the init() method is called any time after the serlvet is instantiated but before the first request
- service() is called for a request
- destroy() can be (but is usually not) called anytime after a request is serviced. If the container is shutting down, it can call destroy() even if all request threads are not complete, if it waits for a timeout period.
You can see when some of these events occur by placing log statements in
- a static initializer (called when class is loaded)
- a no-argument constructor
- the init() method
- the destroy() method
a) container creates one servlet and calls the init method on it. It services a long-process request.
b) second request comes in. A new servlet instance is required. So.. constructor, init and then the second request gets processed by the second instance.
c) repeat as necessary.
Somebody wrote in this forum that If we are implementing SingleThreadModel,Container will copy the instance from the existing instance for processing each request.And he wrote that while copying the instance ,it will not call init() method again.which is called when it is created the instance from the servlet for the first time.
After that ,for each request it will go for copying.(not instantiating the new instance)
Is this true?