When I decompile the GenericServlet and check the init() , I see the following code .
public void init(ServletConfig servletconfig)
throws ServletException
{
config = servletconfig;
init();
}
public void init()
throws ServletException
{
}
What is the init method actually doing here ? Am I missing something ?
Yes, it does nothing. It could have been abstract, but then each servlet would be forced to implement it. This way, by default, nothing happens on init()
, and each servlet can override this behaviour. For example, you have two servlets:
public PropertiesServlet extends HttpServlet {
private Properties properties;
@Override
public void init() {
// load properties from disk, do be used by subsequent doGet() calls
}
}
and
public AnotherServlet extends HttpServlet {
// you don't need any initialization here,
// so you don't override the init method.
}
From the javadoc:
/**
*
* A convenience method which can be overridden so that there's no need
* to call <code>super.init(config)</code>.
*
* <p>Instead of overriding {@link #init(ServletConfig)}, simply override
* this method and it will be called by
* <code>GenericServlet.init(ServletConfig config)</code>.
* The <code>ServletConfig</code> object can still be retrieved via {@link
* #getServletConfig}.
*
* @exception ServletException if an exception occurs that
* interrupts the servlet's
* normal operation
*
*/
So it does nothing and is just a convenience.
Constructor might not have access to ServletConfig
since container have not called init(ServletConfig config)
method.
init()
method is inherited from GenericServlet
which has a ServletConfig
as its property. thats how HttpServlet
and what ever custom servlet you write by extending HttpServlet
gets ServletConfig
.
and GenericServlet
implements ServletConfig
which has getServletContext
method. so your custom servlets init
method will have access to both of those.
Servlet container calls servlet init()
method before handling client requests. It is called just one times after servlet is created. By default it does nothing. You can override this method and it is also good for performing one-time activities. Such as database connection or reading configuration data etc.
public void init(ServletConfig config) throws ServletException {
super.init(config);
// You can define your initial parameter in web.xml file.
String initialParameter = config.getInitParameter("initialParameter");
// Do some stuff with initial parameters
}
What happens if init() method throw an exception?
The servlet destroy()
will not be called because it is unsuccesfull initialization. Servlet container may try to instantiate and initialize a new instance of this failed servlet later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With