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 Spring in Action this week in the Spring 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: 42277
    
  64
You should never use a constructor in a servlet; it's bad practice. All required initialization should happen in the init method.


Ping & DNS - my free Android networking tools app
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3838

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: 42277
    
  64
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: 61424
    
  67

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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Can we write initialization code in servlet constructor