• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
kavank desai
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64620
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rohith Kumar Singh
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic