标签:
我们从常用的HttpServlet来看。
public void init(ServletConfig config) throws ServletException
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
ServletException
config
- a ServletConfig
object containing the servlet‘s configuration and initialization parametersServletException
- if an exception has occurred that interferes with the servlet‘s normal operationUnavailableException
, getServletConfig()
###init(ServletConfig config)方法是由Servlet容器(like Tomcat...)在实例化Servlet之后立马调用的。执行一些初始化的工作。
查看GenericServlet的时候发现会有两个init方法:public void init(ServletConfig config);public void init();
public void init(ServletConfig config) throws ServletException
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)
.
config
- the ServletConfig
object that contains configutation information for this servletServletException
- if an exception occurs that interrupts the servlet‘s normal operationUnavailableException
public void init() throws ServletException
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()
.
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赋值,后面调用的时候使用
标签:
原文地址:http://www.cnblogs.com/erbin/p/4431811.html