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. Theinit
method must complete successfully before the servlet can receive any requests.The servlet container cannot place the servlet into service if the
init
method- Throws a
ServletException
- Does not return within a time period defined by the Web server
- Throws a
- Parameters:
config
- aServletConfig
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, callsuper.init(config)
. - Parameters:
config
- theServletConfig
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 byGenericServlet.init(ServletConfig config)
. TheServletConfig
object can still be retrieved viagetServletConfig()
. - 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赋值,后面调用的时候使用