Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can we write initialization code in servlet constructor

 
ramakrishna kulkarni
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should never use a constructor in a servlet; it's bad practice. All required initialization should happen in the init method.
 
Vijitha Kumara
Bartender
Pie
Posts: 3918
10
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
ramakrishna kulkarni
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 65220
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ask yourself: in a constructor how will you access important information like the ServletConfig instance?
 
ramakrishna kulkarni
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Got it..
Thank you all
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic