File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Servlets and the fly likes When should a servlet include init()? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "When should a servlet include init()?" Watch "When should a servlet include init()?" New topic
Author

When should a servlet include init()?

Art Metzer
Ranch Hand

Joined: Oct 31, 2000
Posts: 241
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

Joined: Jan 07, 1999
Posts: 6920
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.


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Chris Stehno
Ranch Hand

Joined: Feb 26, 2001
Posts: 180
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.


- Chris Stehno, SCPJ
Tony Alicea
Desperado
Sheriff

Joined: Jan 30, 2000
Posts: 3222
    
    5
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."


Tony Alicea
Senior Java Web Application Developer, SCPJ2, SCWCD
Art Metzer
Ranch Hand

Joined: Oct 31, 2000
Posts: 241
Frank, Chris and Tony--
Thank you for clearing this up for me!
Art
Tony Alicea
Desperado
Sheriff

Joined: Jan 30, 2000
Posts: 3222
    
    5
You're welcome!
 
 
subject: When should a servlet include init()?