Why can not we call servlet constructor instead of init method to initialize the config parameters?
I like to know why dont we c开发者_Python百科all servlet constructor instead of init method to initialize the config parameters.
THanks
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.
精彩评论