当我反编译GenericServlet并检查init()时,我看到以下代码.
public void init(ServletConfig servletconfig)
throws ServletException
{
config = servletconfig;
init();
}
public void init()
throws ServletException
{
}
Run Code Online (Sandbox Code Playgroud)
这里实际做的init方法是什么?我错过了什么吗?
Boz*_*zho 14
是的,它什么都不做.它可能是抽象的,但随后每个servlet都将被强制实现它.这样,默认情况下,没有任何操作init(),每个servlet都可以覆盖此行为.例如,您有两个servlet:
public PropertiesServlet extends HttpServlet {
private Properties properties;
@Override
public void init() {
// load properties from disk, do be used by subsequent doGet() calls
}
}
Run Code Online (Sandbox Code Playgroud)
和
public AnotherServlet extends HttpServlet {
// you don't need any initialization here,
// so you don't override the init method.
}
Run Code Online (Sandbox Code Playgroud)
来自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
*
*/
Run Code Online (Sandbox Code Playgroud)
所以它什么都不做,只是一个方便.