什么是servlet的init()方法用于?

Vin*_*C M 18 java servlets

当我反编译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)

  • 您的servlet可以覆盖它并指定应该发生的事情 (4认同)
  • @Bozho - 为什么我们不能将所有初始化/初始化代码放在 servlet 构造函数中?实际上,我的书是这样问这个问题的——`为什么有一个 init() 方法?换句话说,为什么构造函数不足以初始化 servlet?你会在 init() 方法中放入什么样的代码。 (2认同)

ber*_*ert 8

来自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)

所以它什么都不做,只是一个方便.

  • _Well,在JDK 1.0中(最初编写servlet),动态加载的Java类(如servlet)的构造函数不能接受参数.因此,为了向新servlet提供有关其自身及其环境的任何信息,服务器必须调用servlet的init()方法并传递实现ServletConfig接口的对象_Jason Hunter与William Crawford的Java Servlet编程 (4认同)
  • 为什么我们不能将所有初始化/初始化代码放在servlet构造函数中?实际上,我的书以这种方式问这个问题 - 为什么有一个init()方法?换句话说,为什么构造函数不足以初始化servlet?你会在init()方法中放入什么样的代码? (2认同)