码迷,mamicode.com
首页 > 其他好文 > 详细

Servlet init

时间:2015-04-16 14:01:00      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

我们从常用的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赋值,后面调用的时候使用

 

 

 

Servlet init

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!