Servlet init

我们从常用的HttpServlet来看。


HttpServlet
extends: GenericServlet
All Implemented Interfaces: java.io.Serializable, Servlet, ServletConfig
接口Servlet中定义了init(ServletConfig)方法

init

public void init(ServletConfig config)
          throws ServletException
Called by the servlet container to indicate to a servlet that the servlet is being placed into service.

The servlet container calls the init method exactly once after instantiating the servlet. The init method must complete successfully before the servlet can receive any requests.

The servlet container cannot place the servlet into service if the init method

  1. Throws a ServletException
  2. Does not return within a time period defined by the Web server
Parameters:
config - a ServletConfig object containing the servlet's configuration and initialization parameters
Throws:
ServletException - if an exception has occurred that interferes with the servlet's normal operation
See Also:
UnavailableException, getServletConfig()

###init(ServletConfig config)方法是由Servlet容器(like Tomcat...)在实例化Servlet之后立马调用的。执行一些初始化的工作。

查看GenericServlet的时候发现会有两个init方法:public void init(ServletConfig config);public void init();

init

public void init(ServletConfig config)
          throws ServletException
Called by the servlet container to indicate to a servlet that the servlet is being placed into service. See Servlet.init(javax.servlet.ServletConfig).

This implementation stores the ServletConfig object it receives from the servlet container for later use. When overriding this form of the method, call super.init(config).

Specified by:
init in interface Servlet
Parameters:
config - the ServletConfig object that contains configutation information for this servlet
Throws:
ServletException - if an exception occurs that interrupts the servlet's normal operation
See Also:
UnavailableException

init

public void init()
          throws ServletException
A convenience method which can be overridden so that there's no need to call super.init(config).

Instead of overriding init(ServletConfig), simply override this method and it will be called by GenericServlet.init(ServletConfig config). The ServletConfig object can still be retrieved via getServletConfig().

Throws:
ServletException - if an exception occurs that interrupts the servlet's normal operation

看一眼两个方法的实现

    public void init(ServletConfig config) throws ServletException {
        this.config = config;
        init();
    }

    public void init() throws ServletException {}        

GenericServlet 添加了一个init无参的方法,子类可以重写init()方法,这样就不用执行super(config)方法了,执行该方法的目的就像有参方法中写的那样为this.config赋值,后面调用的时候使用

原文地址:https://www.cnblogs.com/erbin/p/4431811.html