Why init is required if allmost all things i can do in my constructor of servlet.(i think only ServletConfig is not available in constructor).
Vince HW Chan
Joined: Aug 16, 2005
It is interesting, my guess is it may be,
Servlet, just like EJB, is supposed to be instantiated by container. And, they are not supposed to " throw exception" while they are instantiated. If you have operation which may throw exception inside the constructor, it fails. Or, if you catch the exception within the consturctor, can you sure the servlet still "valid"?
However, init() declare to throw ServletException, which allow you to stop servce any requests if the setup operations throw excpetion or error occurs.
But that doesn't really answer it: why is there a separate init(ServletConfig) method? Why not just have a constructor with the ServletConfig parameter?
My guess is that it gives a clean set of lifecycle methods: the constructor is used for instantiation, the init method for initialisation. Perhaps also they thought they might add alternative init methods (with different parameters), and having extra constructors around would then just be cumbersome? I think the point raised about throwing exceptions is a good one.
But like many things in life, that was just the decision that was made and we learn to live with it... there's no point arguing, as now it's established it's never going to change!
Charles Lyons (SCJP 1.4, April 2003; SCJP 5, Dec 2006; SCWCD 1.4b, April 2004)
Author of OCEJWCD Study Companion for Oracle Exam 1Z0-899 (ISBN 0955160340 / AmazonAmazon UK )
Joined: Mar 21, 2006
Another way to look at this, though this might not be answer.
When servlets were first introduced, there were more Applet programmers. Just for maintaining coding style of Applet with servlet and easier switch over for Applet programmers(where they used init method for initialization), this could have been introduced for convenience to the java programmers.
Jeroen T Wenting
Joined: Apr 21, 2006
Constructing a servlet instance is (or can be, I think it's up to the container to decide what to do) a 2 stage process.
The other issue here is that specifying that a subclass must have a constructor with a particular signature is a design that can't be enforced. That's just one more thing to go wrong. Whereas an "init" method can be specified in the superclass, or the interface, and if subclasses need to override it they can. But if they don't override it, there is no problem either.
Joined: Jan 25, 2006
I think it is because the Servlet is instantiated by the container using the Class.forName(<servlet class> .getInstance(). For it to do this the servlet should have a no argument constructor. Hence ServletConfig cannot be passed.