This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
I want to know why constructor only is not enough for initializing servlet ? i mean to say what ever the init() method do we can put that into a constructor.
so what is the thing we can achieve from init() method but not from constructor.
rajpal b songara wrote:Thanks Balaji For Quick Reply,
so from your answer may i consider that 'for just making servletconfig object,servlet API provide init(ServletConfig) method'.
no additional use at container level or any-other around it ?
The container uses the init() method to actually register your class as an actual Servlet . The constructor alone is not enough to achieve this. After the init() method is executed ( and no exception has occured ), the container makes the servlet object and then registers it, after registration with the container , the servlet is then ready to be used and service any request.
Muhammad Saif Asif Mirza
OCJA(5/6) OCJP(6) OCJWCD(6)
Saif Asif wrote:The container uses the init() method to actually register your class as an actual Servlet .
Not correct. A servlet doesn't need to have an init() method at all. It is the declarations in the deployment descriptor that "register" the servlet.
After the init() method is executed ( and no exception has occured ), the container makes the servlet object
Also not correct. How could the init() method be called if the object does not already exist? Servlets are no different from other objects in Java and a method cannot be called on an instance before that instance even exists.
Balaji Vankadaru wrote:We cannot write constructors with arguments in a servlet class. It will throw Exception.
Not really correct. A servlet can have any number of constructors, but if it has constructors with arguments then you must add a default constructor without arguments, because the compiler will not insert it for you. Only the default constructcor will ever be called, all others are dead weight.
If you do not intend to access servlet context and config its possible to manage your code trough constructor.
Not really correct, either. A servlet's constructor will only be called once, whereas the init and destroy methods can be called multiple times.
Simple rule of thumb: never put a constructor in a servlet.