Servlet详解之两个init方法的作用

在Servlet中 javax.servlet.GenericServlet类 继承自java.lang.Object 实现了Serializable,,servlet ,ServletConfig 三个接口 被继承对象javax.servlet.http.HttpServlet

(这是我们常用的一个类)

 

但仔细看GenericServlet的API,会发现有两个init方法 void init()  void init(ServletConfig config)  而在Servlet接口中只有一个void init(ServletConfig config) 方法 

在此做一下解释:

 

先看一下官方说明: void init()  A convenience method which can be overridden so that there's no need to call super.init(config). 
void init(ServletConfig config)  Called by the servlet container to indicate to a servlet that the servlet is being placed into service. 

 

看一下这两个函数的源码:GenericServlet.class

 

  1. <span style="font-size: 18px;">  
  2. </span>  

  1. <span style="font-size: 18px;">public void init(ServletConfig config) throws ServletException {  
  2.     this.config = config;  
  3.     this.init();  
  4.     }</span>  
public void init(ServletConfig config) throws ServletException {
	this.config = config;
	this.init();
    }

 

 

 

  1. <span style="font-size: 18px;">  
  2. </span>  

  1. <span style="font-size: 18px;">public void init() throws ServletException {  
  2.   
  3.     }</span>  
public void init() throws ServletException {

    }

 

 

可以看到有参的init方法又调用了无参的init方法,这是什么原因呢。 补充一句,Tomcat默认调用的是有参的。
如果你曾复写过init()方法,你应该能看出些端详 如果我们在想调用init方法时执行一些操作,那怎么办呢,只要我们复写无参的init方法,tomcat在调用完有参的init方法时调用无参的init方法,这样两个操作都执行了。而且我们也不用写super.init();试想一下,如果没有无参的init方法,那我们复写有参的init方法时忘记了些super.init(config)方法,那么config就不能初始化了,而这样设计即使我们不调用super的方法,也不会出问题。何乐而不为呢!

posted @ 2017-11-28 08:50  有梦就能实现  阅读(5042)  评论(0编辑  收藏  举报