Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Init vs Constructor

 
Mohit Agarwal
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I had searched a lot on this issue before posting a query regarding the same.
I can define a no-arg constructor in my servlet class & perform some initializations then why do i need to use the init() method .

I really didn't got any answer which pin-points to the issue .

Please throw more lighton the same ........

With Regards,
Mohit Agarwal.
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A simple answer is that the constructor is part of the Object lifecycle and init() is part of the Servlet lifecycle. There may be similarities but you can never be sure
 
Mohit Agarwal
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Thanx David for the response .
But the point is still not clear .

Mohit....
 
Pradeep bhatt
Ranch Hand
Posts: 8927
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Mohit Agarwal:
Hi,

I had searched a lot on this issue before posting a query regarding the same.
I can define a no-arg constructor in my servlet class & perform some initializations then why do i need to use the init() method .

I really didn't got any answer which pin-points to the issue .

Please throw more lighton the same ........

With Regards,
Mohit Agarwal.


All the servlet classes are implementations of javax.servlet.Servlet interface. The container initializes the servlet via the Init()method by passing the ServletConfig object. It is possible to do the same using a constructor accepting ServletConfig object as parameter but constructors are optional in a class and there is no way you can enforce it. In such a case it will know only at runtime that a constructur was not defined in the servlet config. This is my thinking.
 
Paul Bourdeaux
Ranch Hand
Posts: 783
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The constructor creates the object, while the init() method creates the servlet. Before the init() method is called (by the container), your servlet does not have access to the ServletContext or ServletConfig objects. Without them, you dont have access to things like init parameters or web app parameters.

Sure, technically you could create a no arg constructor and try and preform some initialization code in there, as long as you don't try and access any of the web app stuff, but why would you? There is nothing that cannot wait until the init() method().
[ August 01, 2005: Message edited by: Paul Bourdeaux ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic