Two Laptop Bag*
The moose likes Servlets and the fly likes what is the purpose of init() method of Servlet ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "what is the purpose of init() method of Servlet ?" Watch "what is the purpose of init() method of Servlet ?" New topic
Author

what is the purpose of init() method of Servlet ?

kavank desai
Greenhorn

Joined: Jan 16, 2005
Posts: 1
Hi Friends,

On one of the web sites I read
"After the servlet object is instantiated, the container must initialize the servlet before it can handle requests from clients. Initialization is provided so that a servlet can read persistent configuration data, initialize costly resources (such as JDBC connections), and perform other one-time activities. The container initializes the servlet instance by calling the init method of the Servlet interface with a unique (per servlet declaration) object implementing the ServletConfig interface."

So to initialize the ServletConfig object. Is that the only purpose,isn't it? Other things we can do with the Constructor also like initializing the member variable of Servlet class etc.
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41096
    
  44
Welcome to JavaRanch.

I think you're overlooking the "... and perform other one-time activities" part. Initializing the ServletConfig object is just part of it.


Ping & DNS - my free Android networking tools app
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60774
    
  65

Originally posted by kavank desai:
Other things we can do with the Constructor also like initializing the member variable of Servlet class etc.

Servlets should not have member variables. That's the best way to introduce threading problems into your web application.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Rohith Kumar Singh
Greenhorn

Joined: Aug 27, 2008
Posts: 6
You can do initialization of member variables from within init() method. As already mentioned in one of the answers that one should avoid using member variables to avoid threading problems. But, you are always welcome to use mutable member variables as they don't cause any threading problem and you can initialize them in your init() definition.

Initializing DB Connections (either physical or logical) in init() will probably be implemented using member variables only :-)


Cheers,
Rohit
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: what is the purpose of init() method of Servlet ?
 
Similar Threads
init() and http related questions
Servlet constructor
mvc
init method
init() vs constructor