1.Can we write a customized constructor in a servlet ?
2.How container calls the constructor ?
Servlets is also a java class then why can't we write a constructor for that ?
Servlet 2.4 final release specification wrote:
SRV.2.3.1 Loading and Instantiation
The servlet container is responsible for loading and instantiating servlets. The loading
and instantiation can occur when the container is started, or delayed until the
container determines the servlet is needed to service a request.
When the servlet engine is started, needed servlet classes must be located by
the servlet container. The servlet container loads the servlet class using normal
Java class loading facilities. The loading may be from a local file system, a remote
file system, or other network services.
After loading the Servlet class, the container instantiates it for use.
After the servlet object is instantiated, the container must initialize the servlet before
it can handle requests from clients. Initialization is provided so that a servlet can
read persistent configuration data, initialize costly resources (such as JDBC™ APIbased
connections), and perform other one-time activities. The container initializes
the servlet instance by calling the init method of the Servlet interface with a
unique (per servlet declaration) object implementing the ServletConfig interface.
This configuration object allows the servlet to access name-value initialization
parameters from theWeb application’s configuration information. The configuration
object also gives the servlet access to an object (implementing the ServletContext
interface) that describes the servlet’s runtime environment. See Chapter SRV.3,
“Servlet Context” for more information about the ServletContext interface.
Do you mean to declare a constructor that have parameters? If yes then it is illegal to declare such Servlet.
No, it's perfectly valid to have constructors with arguments in a servlet, as long as there's also a no-argument constructor. Of course, there's no point in doing so, since that constructor will never be called by the servlet container.