The moose likes Servlets and the fly likes init() method in servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "init() method in servlet" Watch "init() method in servlet" New topic

init() method in servlet

T sandya
Ranch Hand

Joined: Aug 03, 2006
Posts: 64
Hi friends,
May know the reason why init()method is that much important,if we have the constructor.And can i write the destroy() inside init() method.

please clarify me on these two questions.

thanks and regards,
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

like here?
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13037
can i write the destroy()

Why don't you go download the servlet API document and read about the intended use of all of the servlet methods instead of these piecemeal questions?
This is a good starting point.
geeta lalchandani
Ranch Hand

Joined: Jun 07, 2005
Posts: 118
If everybody promise that they will provide a constructor with a parameter �ServletConfig� while creating a servlet then they might remove this method (not sure though).

How can you get the 'ServletConfig� in the construstor.It is possible only after the servlet is instantiated.

You can use the construstor though.. if you do not want to access and the 'ServletConfig� and may be define and initialise just the instance variables.
Rahul Bhattacharjee
Ranch Hand

Joined: Nov 29, 2005
Posts: 2308
As already discussed servletConfig is not available in the constructor so init would be the right place to initialize.You you want to initialize something which is not dependent of context of servlet config then you can do that as well in the constructor (its not a preferred way of doing thogh)

destroy() is a callback method called by the container .. you can explictly call that but in that case that is just like any other method in the class use..destroy is called by the container when its about you destroy the servlet (for running some code for cleaning )..

its something like overriding the finalize (in Object class)method and calling that with the hope that this would garbage collect the object.

Rahul Bhattacharjee
LinkedIn - Blog
anil borude

Joined: Sep 17, 2006
Posts: 1
But What is basic Difference between Constrctor() & Init() mthod ?

Anil Borude
Rahul Bhattacharjee
Ranch Hand

Joined: Nov 29, 2005
Posts: 2308
constructor is called while creating a object (its actually not a method) and init is a method ..A callback method called by the container after the constructor is called and it has servletConfig's reference.
I agree. Here's the link:
subject: init() method in servlet
jQuery in Action, 3rd edition