java 为什么我们不能调用servlet构造函数而不是init方法来初始化配置参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2381976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why can not we call servlet constructor instead of init method to initialize the config parameters?
提问by giri
I like to know why dont we call servlet constructor instead of init method to initialize the config parameters.
我想知道为什么我们不调用 servlet 构造函数而不是 init 方法来初始化配置参数。
THanks
谢谢
回答by DVK
This thread should clarify the differences.
Quoting from one of the more illuminating posts:
引用一篇更有启发性的帖子:
The init() method is typically used to perform servlet initialization--creating or loading objects that are used by the servlet in the handling of its requests. Why not use a constructor instead? Well, in JDK 1.0 (for which servlets were originally written), constructors for dynamically loaded Java classes (such as servlets) couldn't accept arguments. So, in order to provide a new servlet any information about itself and its environment, a server had to call a servlet's init() method and pass along an object that implements the ServletConfig interface. Also, Java doesn't allow interfaces to declare constructors. This means that the javax.servlet.Servlet interface cannot declare a constructor that accepts a ServletConfig parameter. It has to declare another method, like init(). It's still possible, of course, for you to define constructors for your servlets, but in the constructor you don't have access to the ServletConfig object or the ability to throw a ServletException.
init() 方法通常用于执行 servlet 初始化——创建或加载 servlet 在处理其请求时使用的对象。为什么不使用构造函数呢?嗯,在 JDK 1.0(最初为它编写 servlet)中,动态加载的 Java 类(例如 servlet)的构造函数不能接受参数。因此,为了向新的 servlet 提供有关其自身及其环境的任何信息,服务器必须调用 servlet 的 init() 方法并传递一个实现 ServletConfig 接口的对象。此外,Java 不允许接口声明构造函数。这意味着 javax.servlet.Servlet 接口不能声明接受 ServletConfig 参数的构造函数。它必须声明另一个方法,例如 init()。它'
回答by Mahboob Ali
In general we can use constructor to perform initialization activities but in old version of java(JDK1.0v), constructor can not accept dynamically generated class name as argument. To perform initialization of a servlet compulsory we should provide ServletConfig object as an argument whose class name dynamically generated by web container , as constructor can't accept the dynamically generated class names hence, sun people ignored the constructor concept and introduced a specific method init(-) to perform initialization activities which can take dynamically generated class name as an argument.
通常我们可以使用构造函数来执行初始化活动,但是在旧版本的java(JDK1.0v)中,构造函数不能接受动态生成的类名作为参数。为了执行servlet的强制初始化,我们应该提供ServletConfig对象作为参数,其类名由web容器动态生成,因为构造函数不能接受动态生成的类名,因此sun人忽略了构造函数的概念,引入了一个特定的方法init( -) 执行初始化活动,可以将动态生成的类名作为参数。

