Win a copy of Practice Tests for OCP Java 17 Certification Exam (1Z0-829) this week in the OCPJP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Scott Selikoff
Bartenders:
  • Piet Souris
  • Jj Roberts
  • fred rosenberger

Why does a servlet has init method

 
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
This question is on servlet.
Why cant we use constructor of a servlet class as a initializer
for that servlet instead of init() method.
Why we need init method when we can use non-argument
constructor as initializer for that servlet.
I know that init method has something to do with the life cycle of
servlet. But still cant we use constructor instead of init method.

Thx ,
Steve
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
See this recent discussion for exhaustive discussion.
Bill
 
Ranch Hand
Posts: 312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1. I think it is the way you can seperate the initialization logic with basic default construction to make easy for the reusability.

2. The container will always instantiate the servlet with the default constructor and you won't get the servlet config object in the default constructor method, which is used to get the servlet configuration details, servletContext details.
 
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think Malli's answer is a good one. When you have the init() method you can do things like the following:

MyClassWithLotsOfStaticMethods.setDbConnStr(getServletContext().getInitParameter("dbconn"));

With the above I can simply change the database connection string I need in the deployment descriptor when I change from one environment to another with no need to recompile anything. Way cool!
 
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic