在Servlet的GenericServlet类中为什么有两个init()方法


想要搞清楚这件事情,必须先了解Servlet容器调用Servlet的过程。调用过程如下

首次访问该Servlet
1、调用init(ServletConfig config) 进行初始化, ServletConfig 封装了web.xml中<init-param>配置的初始化参数,它由Servlet容器创建,并通过该方法传递给当前serlvet
2、调用service(ServletRequest req, ServletResponse res)方法处理客户的请求
3、调用destroy()方法销毁给Servlet实例,当然这里只是 为了说明完整流程,实际上destroy()方法不是在调用servlet完成后就销毁。

 

后续访问 该Servlet
1、调用service(ServletRequest req, ServletResponse res)方法处理客户的请求
2、调用destroy()方法销毁给Servlet实例,当然这里只是为了说明完整流程,实际上 destroy()方法不是在调用servlet完成后就销毁。

 

从上面的调用过程来看,Serlvet容器仅关心带参数的init方法init(ServletConfig config)、service(ServletRequest req, ServletResponse res)和destroy(),其他的额外方法都是附加产品,这样也就说明不带参数的init方法不是必须的,那为什么在GenericServlet抽象类中却定义了该方法,意义何在呢?

我们先看下 GenericServlet类中的两个init方法的实现。
public void init(ServletConfig config)throws ServletException{
this.config = config;
this.init(); 
}
public void init()throws ServletException{
}
从上面的实现来看,   init(ServletConfig config)会调用不带参数的init方法进行初始化该Serlvet实例,而不带参数的init方法却什么都不做。
假设 GenericServlet类只实现了 init(ServletConfig config)方法,那么代码应该如下
public void init(ServletConfig config)throws ServletException{
this.config = config;
}
假设某个子类继承了上面只定义一个init方法的 GenericServlet类,并且想再初始化时增加一些自己的初始化参数,那必须重写 GenericServlet类的 init(ServletConfig config)方法,如下:
public class Test extends  GenericServlet {
   public int a = 0;
   public String b;  
    public void init(ServletConfig config)throws ServletException{
     super.init(config);  //或者 this.config = config;
     this.a = XXX;
     this.b = XXX; 
   }
      public  void service ( ServletRequest  req, ServletResponse  res)  throws ServletException ,  java.io.IOException{
        ....
    }
}
上面的这个实现类是没问题的,我们可以正常使用 getServletConfig ()方法得到 ServletConfig对象进行使用。
但是假设开发过程中忘记了调用 super.init(config);  //或者 this.config = config;这个语句,那么问题就大了, getServletConfig ()将返回null,无法使用 ServletConfig。所以 GenericServlet就再定义了一个无参的init( )方法,子类只需继承该方法即可。这样就防止了类似问题发生。

 

 




免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM