PDA

View Full Version : Why we should not declare a constructor in servlet?


sony
11-02-2010, 07:52 PM
Actually like any normal java class, you can define constructors in servlet. But, the declared constructor cannot access the ServletConfig object or throw a ServletException.

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. Therefore init() was used to initialize by passing the implemented object of ServletConfig interface and other needed parameters.

Also, Java constructors cannot be declared in interfaces. So, javax.servlet.Servlet interface cannot have a constructor that accepts a ServletConfig parameter. To overcome this, init() method is used for initialization instead of declaring a constructor.