aspose file tools*
The moose likes Servlets and the fly likes Can we write initialization code in servlet constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Can we write initialization code in servlet constructor" Watch "Can we write initialization code in servlet constructor" New topic
Author

Can we write initialization code in servlet constructor

ramakrishna kulkarni
Greenhorn

Joined: Feb 06, 2009
Posts: 14
Hi all

I have a doubt regarding the constructor in servlet

I have learnt that we can write a no-arg constructor in servlet and this costructor is called by the container.
I want to know that can we write servlet initialization code in this constructor instead of writing it init() method.

Thanks
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 39547
    
  27
You should never use a constructor in a servlet; it's bad practice. All required initialization should happen in the init method.


Ping & DNS - updated with new look and Ping home screen widget
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3775

ramakrishna kulkarni wrote:I have learnt that we can write a no-arg constructor in servlet and this costructor is called by the container.
I want to know that can we write servlet initialization code in this constructor instead of writing it init() method.

Servlet initialization code belongs in the init() method not in the constructor.


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
ramakrishna kulkarni
Greenhorn

Joined: Feb 06, 2009
Posts: 14
I agree that its a bad practice to write a constructor in servlet class.
My question is still not answered, Is it legal or is it possible to write initialization code in servlet constructor.
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 39547
    
  27
It is not illegal in the sense that the judicial system of whatever jurisdiction you're in will come after you if you do it.

As to whether it's possible, how have you tried to prove or disprove it?
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60050
    
  65

Ask yourself: in a constructor how will you access important information like the ServletConfig instance?


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
ramakrishna kulkarni
Greenhorn

Joined: Feb 06, 2009
Posts: 14
Got it..
Thank you all
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can we write initialization code in servlet constructor
 
Similar Threads
Why Servlet init(), not construtor
init() method
writing own constructor for servlet
use of init() in servlet life cycle
Why Init Method, why can't we use constructor instead?