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
Register / Login


JavaRanch » Java Forums » Java » Servlets
Reply 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: 35438
    
    9
You should never use a constructor in a servlet; it's bad practice. All required initialization should happen in the init method.


Android appsImageJ pluginsJava web charts
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3673

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: 35438
    
    9
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: 56528
    
  14

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


[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About 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
use of init() in servlet life cycle
writing own constructor for servlet
init() method
Why Servlet init(), not construtor
Why Init Method, why can't we use constructor instead?