Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why Init Method, why can't we use constructor instead?

 
Guhan NS
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Why is the init method there in servlet class? Why can't we do all that we can do it in init, in constructor itself?

Thanks,
Guhan
 
Aruneesh Salhotra
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would assume that the init method is for initializing the environment for the servlet to operate in.

init would have access to the servletconfig as well as servletcontext, so that you could set session or request attributes using them or so operations like open database connections.

With the constructor it the object creation only that is done.

It is the way Java is structured for servlets.
 
moto raja
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guhan,

First thing is that the constructor of the servlet is called by the container, we cannot call it. So we cannot add anything into the constructor.Moreover, at that time, it is just another java objectnot a servlet.So it cannot have any servlet specific parameters,like ServletConfig , which we can use.

For example,for every request from the clinet, the servlet has to look into the database(or something of that sort),so we have to set up the database connection set-up,login etc. for every request.

We have to make the servlet ready to have a connection to the database/resource before any client requests come.
How can we do it?Sure,it cannot be put in the constructor.

The init() method has access to the ServletConfig,ServeltCOntext,which can be used for similar purposes,for example, use ServeltContext to get database name,login name ,etc.. (that are defined in xml's...)..

To perform all the above melodrama, we should override the init() method and put the code in that.


Now I suppose u understand why contructor() is not sufficient in these kind of cases,hence init() can be overriden in such cases.


:-)
moritala.
 
Narendra Dhande
Ranch Hand
Posts: 951
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

First thing is that the constructor of the servlet is called by the container, we cannot call it. So we cannot add anything into the constructor


The init method is also called by the container. You can write a non-argrument constructor having initialization code, but is is bad parctice. While loading, there is something in betwwen the constructors and init method ( initialization of some objects like ServletConfig) so we can get access to initalization parameters to servelts, ServletContext etc. So it it easier to write initalization codes in init method

Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic