Для чего используется метод init() сервлета?
Когда я декомпилирую GenericServlet и проверяю init(), я вижу следующий код.
public void init(ServletConfig servletconfig)
throws ServletException
{
config = servletconfig;
init();
}
public void init()
throws ServletException
{
}
Что здесь делает метод init? Я что-то пропустил?
Ответы
Ответ 1
Из javadoc:
/**
*
* A convenience method which can be overridden so that there 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
*
*/
Таким образом, он ничего не делает и просто удобен.
Ответ 2
Да, он ничего не делает. Это могло быть абстрактным, но тогда каждый сервлет был бы вынужден реализовать его. Таким образом, по умолчанию на init()
ничего не происходит, и каждый сервлет может переопределить это поведение. Например, у вас есть два сервлета:
public PropertiesServlet extends HttpServlet {
private Properties properties;
@Override
public void init() {
// load properties from disk, do be used by subsequent doGet() calls
}
}
и
public AnotherServlet extends HttpServlet {
// you don't need any initialization here,
// so you don't override the init method.
}
Ответ 3
Конструктор может не иметь доступа к ServletConfig
, поскольку контейнер не вызвал метод init(ServletConfig config)
.
init()
метод наследуется от GenericServlet
, который имеет свойство ServletConfig
. thats how HttpServlet
и какой еще пользовательский сервлет, который вы пишете, расширяя HttpServlet
получает ServletConfig
.
и GenericServlet
реализует ServletConfig
, который имеет метод getServletContext
. поэтому ваш собственный метод сервлетов init
будет иметь доступ к обоим этим.