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 think u can write a constructor in any java class. It will surely be called if u do 'new MyServlet()'. But its not called when JVM creates a Servlet for catering HTTP request. It might be done just to separate the Order creation by user and Serverlet API.
Originally posted by Rajat Kumar Patro: Can we use constructors in servlet programming ..? Can anybody clear me why its not possble to use constructors instead of init() method..?
The constructor is related to the object creation, however init ()relates to the class creation in Applets and Servlets. Let me explain... Who is going to instantiate the servlet ? The Web Server. Well everybody will figure that since they had designed to have a ServletConfig object in init() and since it's obviuosly a candidate for a constructor,they have to use a constructor. But my convoluted reasoning is that since a servlet is loaded once during startup and a servlet is memory resident between requests ,of course if it's lucky it stays forever till reloaded /Web Sever restarted ,it is more like a singleton object than a normal object so there is no need for a constructor,which by definition is used to replace a init(). Also a normal Object is coming and going, coming and going and somewhere along the line if the Garbage guy is so inclined ,picks up the trash left behind. The Server invokes your constructor, then init(). Hence when your constructor is invoked, the ServletConfig (and through it the ServletContext) is not yet available. Although in principle you can do things in the constructor that don't rely (even indirectly) on the ServletConfig or the ServletContext, it is less error-prone to simply defer all setup to the init method. That way you know that anything that needs the ServletConfig/ServletContext will have it available. Hope it's clear to you,the same behaviour is exihibited in Applets,AppletContext and AppletStub. Rgds Amit