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

When should a servlet include init()?

 
Art Metzer
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, friends.
I understand that if a servlet has an init() method, then the first line of the method should be a call to super.init(config). My question is, though, when should a servlet have an init() method at all, and when should it not?
In some cases, it is absolutely clear that you need an init() method: for example, when your design dictates that you open your database connection one time only, when the servlet loads. But my question is more, what is the factor that decides for you that you should include only these three lines:

?
Thanks for your help,
Art
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should never include just those three lines. They just duplicate what is in the super class.
Only define init if you have something which needs to be "inited" in your own code.
 
Chris Stehno
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should only override the init() method when you need to do some servlet configuration that must be done before the servlet is running, such as setting up a DB connection pool. Otherwise just let it do its thing.
 
Tony Alicea
Desperado
Sheriff
Posts: 3226
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I relation to this subject, Marty Hall in his "Core Servlets and JavaServer Pages" book, page 36, states that:
"If you write an init method that takes a ServletConfig as an argument, always call super.init on the first line."
 
Art Metzer
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Frank, Chris and Tony--
Thank you for clearing this up for me!
Art
 
Tony Alicea
Desperado
Sheriff
Posts: 3226
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic