What is the servlet's init() method used for?
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.