I like to know why dont we call servlet constructor instead of init method to initialize the config parameters.
THanks
The short answer to this question, Yes, Servlet implementation classes can have a constructor but they should be using the init() method to initialize Servlet because of two reasons, first you cannot declare constructors on an interface in Java.
Servlet can't be initialized before instantiation. So, constructor must be there.
To retrieve initialization parameters, call the getInitParameter(String name) method from the parent javax. servlet. GenericServlet class. When passed the name of the parameter, this method returns the parameter's value as a String .
Then why is it not customary to declare a constructor in a servlet? Because the init() method is used to perform servlet initialization. In JDK 1.0 (servlet were written in this version), constructors for dynamically loaded Java classes such as servlets cannot accept arguments.
This thread should clarify the differences.
Quoting from one of the more illuminating posts:
The init() method is typically used to perform servlet initialization--creating or loading objects that are used by the servlet in the handling of its requests. Why not use a constructor instead? Well, in JDK 1.0 (for which servlets were originally written), constructors for dynamically loaded Java classes (such as servlets) couldn't accept arguments. So, in order to provide a new servlet any information about itself and its environment, a server had to call a servlet's init() method and pass along an object that implements the ServletConfig interface. Also, Java doesn't allow interfaces to declare constructors. This means that the javax.servlet.Servlet interface cannot declare a constructor that accepts a ServletConfig parameter. It has to declare another method, like init(). It's still possible, of course, for you to define constructors for your servlets, but in the constructor you don't have access to the ServletConfig object or the ability to throw a ServletException.
In general we can use constructor to perform initialization activities but in old version of java(JDK1.0v), constructor can not accept dynamically generated class name as argument. To perform initialization of a servlet compulsory we should provide ServletConfig object as an argument whose class name dynamically generated by web container , as constructor can’t accept the dynamically generated class names hence, sun people ignored the constructor concept and introduced a specific method init(-) to perform initialization activities which can take dynamically generated class name as an argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With