aspose file tools*
The moose likes Servlets and the fly likes Why do we have init() method in Servlets ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Why do we have init() method in Servlets ?" Watch "Why do we have init() method in Servlets ?" New topic
Author

Why do we have init() method in Servlets ?

Celina Joseph
Greenhorn

Joined: Aug 23, 2001
Posts: 24
Hi,
I have a basic question....something of which I could not think satisfying answer...
Why do we have init() method in the servlets ?
Why not like other java classes whatever initialization is to be done is done in the constructor of servlet during the instantiation ?
The only one thing that comes to my mind is that the ServletConfig object is passed only through the init() method. But is there any other concrete reason ?
Arun Boraiah
Ranch Hand

Joined: Nov 28, 2001
Posts: 233
constructor is called for every instance of the class. Init i called only when first time servlet is called. There after untill next
restart or code change in servlet/jsp init method code is not executed.


Sharing is learning
Avi Abrami
Ranch Hand

Joined: Oct 11, 2000
Posts: 1121

Celina,
A servlet resides in a servlet container. Similarly, an applet resides in an applet container. Similarly and EJB resides in an EJB container. As you can see, this "container" business is a recurring theme in java. Basically, a container is another java class that "executes" your servlet/applet/EJB. In order to do that, it has to assume certain things about your servlet/applet/EJB. The container is responsible for creating instances of your servlet/applet/EJB. It does this using java's reflection mechanism. So it assumes that your servlet/applet/EJB has a "default" constructor (a constructor that takes no arguments). So if you want to do your servlet initialization in its constructor, you _must_ only do that in its default constructor. That's one reason why it is recommended to do the initialization in the "init()" method instead.
Hope this helps.
Good Luck,
Avi.
Celina Joseph
Greenhorn

Joined: Aug 23, 2001
Posts: 24
Thanks for the quick reply.
Arun's response triggered a new question in my mind -
-----------------------------------
constructor is called for every instance of the class. Init i called only when first time servlet is called. There after untill next
restart or code change in servlet/jsp init method code is not executed.
-----------------------------------
Suppose my servlet implements SingleThreadModel and my application server maintains a pool of servlet instances for concurrent requests. In this case would not the init() method be called once for each instance ?
And also, what happens if there is a code change in the servlet and the servlet is recompiled.
I was assuming that the old servlet instance is removed and the new instance is loaded.But please let me know the exact behaviour.
Thanks.
Arun Boraiah
Ranch Hand

Joined: Nov 28, 2001
Posts: 233
Any one correct me if my statement is found wrong.
According the life cycle of servlet only once init method code is executed. Life cycle for the instance in the pool starts with service method onwards What ever initialized value at init method is available for each instance in the pool of servlet.
Exact behavior of reloading depends on the servlet engine. Most of the time servlet is compiled manually and replaced. Some server require restart and some will automatically update once a change is found.
Chetan M
Ranch Hand

Joined: Dec 18, 2002
Posts: 43
Hi Celina,
Aapplication/web server maintains a pool of servlet instances for concurrent requests.But this pool consists of copy instances of ur servlet and is handled by javas reflection mechanism.
Say when a sevlet is loaded for the first time..its init() is called.. its the starting pt of life cycle of a servlet.Now when concurrent requests are comming for the same same sevlet.. its service() is called.. i.e server will look 4 free sevlet instance if none present, create copy of original instance(which is already initialized)and invoked service(). And these instances are handled by web container on the need.
When there is a code change in the servlet and the servlet is recompiled.
as arun said..
Exact behavior of reloading when there is a code change in the servlet depends on the servlet engine.In some server updated sevlets are automatically reloaded in some , server have to be started..
Although exact behavior of reloading when there is a code change in the servlet depends on the servlet engine,in all the rescent web servers... reloading is automatic.
Hope above passage is helpful.


No matter how much you know today, you will have to know more tomorrow.<br /> Hakunamatata !!!
Hari babu
Ranch Hand

Joined: Jun 25, 2001
Posts: 208
The servlet container intializes the servlet by calling class.forName("serveltNameClass").newInstance(). A class can be loaded in this manner only if it has a no parameter constructor. Hence servlet finds an another way of passing values for intialization i.e. by calling init method.
HTH
Hari
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12682
    
    5
Aapplication/web server maintains a pool of servlet instances for concurrent requests.But this pool consists of copy instances of ur servlet and is handled by javas reflection mechanism.

is only (partly) true if your servlet implements SingleThreadModel - otherwise there is only one instance per server.
Bill
[ January 28, 2003: Message edited by: William Brogden ]

Java Resources at www.wbrogden.com
Celina Joseph
Greenhorn

Joined: Aug 23, 2001
Posts: 24
Thanks everybody.
I feel convinced now. Would be back soon with new bunch of questions....
thomas davis
Ranch Hand

Joined: Feb 01, 2003
Posts: 207
Hi Celina Joseph,
If I overidden the constructor with some functionalities like database connection ,what would happen to my servlet?
Will it get called or executed..?
If you put code in the default constructor it willmost likely be called. Although all servlet containers that I am aware of create servlet instances using the no-arg constructor, I don't think there is any requirement for a container to always use that constructor if it knows of a "better" way to create the servlet instance.
There are, however, much bigger problems with this.
You don't know, and have no control over, when or how this constructor will be called. It is quite feasible for a servlet container to create instances of all the servlet classes it knows about as soon as it starts up. This may be days or weeks before any of the servlets are actually requested. If you do something in the constructor which claims an external resource (such as a database connection), then (a) your servlet could be holding on to that (potentially large) resource for a long time, and (b) the resource is quite likely to "time out" before you get to use it even once.
If you use the recommended approach of starting things in "init", then you have the chance to finish them in "destroy". If you start things in a constructor there is no guarantee you will ever be able to finish them. "finalize" may never be called, and "destroy" will only be called if "init" has been called. Find a Database administrator somewhere and ask what happens if you open connections without ever closing them
The result of all this is (as Bill indicated) that the separation of init/destroy from object construction is there for some very good reasons. It is very rarely sensible to do anything in the contructor of a servlet. You are guaranteed that "init" will be called before your servlet is used. That is the right place to put your initialisation code.

Please put your valuable suggestion on this ...
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
The above is, of course, a bald copy of my message in this thread
I'm more than happy for people to learn from my messages, and even repeat the content to others, but it is common courtesy to mention where it came from. Thanks.


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
thomas davis
Ranch Hand

Joined: Feb 01, 2003
Posts: 207
Hi Frank,
Of course, you gave the right explanation for my question. I take this opportunity to give full credit for explaining it in a good fashion .It is worth to read and comprehensive..
I am deeply sorry for not mentioning your name in the above explanation.
I would like to substantiate my position why I posted your comment in this question.
Since this explanation will be helpful for guys who come to this question (Why do we have init() method in Servlets ?)for getting the doubt cleared.
And Moreover Celina is also providing valuable explanations and comments for this topic, So I thought that she could also put her comments on your explanation.
I hope discussion on this topic will be alive and healthy for sometime.
thomas davis
Ranch Hand

Joined: Feb 01, 2003
Posts: 207
Chetan M
Aapplication/web server maintains a pool of servlet instances for concurrent requests.But this pool consists of copy instances of ur servlet and is handled by javas reflection mechanism.
Avi Abrami
The container is responsible for creating instances of your servlet/applet/EJB. It does this using java's reflection mechanism. So it assumes that your servlet/applet/EJB has a "default" constructor (a constructor that takes no arguments).


1)I would like t know what is reflection mechanism and how ,when and where is it being used ?

The servlet container intializes the servlet by calling class.forName("serveltNameClass").newInstance().
2)What is the use above snippet in JAVA ?By calling class.forName() ?why are we initializing the class using newInstance() method?

3)Are there any functional similarities between this mechanism and singleton mechanism?
Hari babu
Ranch Hand

Joined: Jun 25, 2001
Posts: 208
Originally posted by thomas davis:


1)I would like t know what is reflection mechanism and how ,when and where is it being used ?

The servlet container intializes the servlet by calling class.forName("serveltNameClass").newInstance().
2)What is the use above snippet in JAVA ?By calling class.forName() ?why are we initializing the class using newInstance() method?

3)Are there any functional similarities between this mechanism and singleton mechanism?

Hi,
class.forName("serveltNameClass").newInstance() is dynamic way of loading your class without any idea of constructor argument (ofcourse there should be no argument constructor) and just with help of string (class name). You do this whenenever yo dont know about the name of the class to be instantiated at the compile time.
This is diffrent from the singleton implementation. In singleton you need to have method "newInstance()" (may be some other name) and instantiate the class inside that because you would have made u'r constructor private
HTH
Hari
[ February 10, 2003: Message edited by: Hari babu ]
thomas davis
Ranch Hand

Joined: Feb 01, 2003
Posts: 207

1)just with help of string (class name).
2)You do this whenenever yo dont know about the name of the class to be instantiated at the compile time.

The two statements you provided seem to be contradictory.
First statements says, with the help of class name, class can be instantiated, but in the second statement, it says no need of knowing the exact name of the class for instantiating that particular class.

I could not comprehend these two statements, still I am not clear with significance of this mechanism (when is it being used)?
And this mechanism is being used for instantiating servlet class as well as Database Driver class..
I could understand this mechanism used for servlet for dynamically loading the class, but why is it being used for Driver class while connecting to database? Here, we are explicitly giving the Driver Name..Isn't?
In the case of servlet, container picks up the name of the servlet dynamically and instantiates the class.
Hari babu
Ranch Hand

Joined: Jun 25, 2001
Posts: 208
Originally posted by thomas davis:

The two statements you provided seem to be contradictory.
First statements says, with the help of class name, class can be instantiated, but in the second statement, it says no need of knowing the exact name of the class for instantiating that particular class.

I could not comprehend these two statements, still I am not clear with significance of this mechanism (when is it being used)?
And this mechanism is being used for instantiating servlet class as well as Database Driver class..
I could understand this mechanism used for servlet for dynamically loading the class, but why is it being used for Driver class while connecting to database? Here, we are explicitly giving the Driver Name..Isn't?
In the case of servlet, container picks up the name of the servlet dynamically and instantiates the class.

Hi,
I meant we need not know the class name at compile time, but we need to know at runtime
Check this

A client program can call this code by passing the name of the class to be instantiated
Hari
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Why do we have init() method in Servlets ?
 
Similar Threads
Why Init() method
init() and http related questions
constructor in servlet
Constructor in servlets
Servlet class