Servlet构造函数和init()方法 [英] Servlet constructor and init() method
问题描述
为什么在servlet中需要init()方法?我们不能使用构造函数进行初始化吗?
Why do we need an init() method in servlet? Can't we use the constructor to initialization?
推荐答案
因为Servlet是一个接口,而不是抽象类.不能在接口上指定构造函数参数,因此需要在常规方法签名上指定ServletContext.
Because Servlet is an interface, not an abstract class. Constructor arguments cannot be specified on an interface, so the ServletContext needs to be specified on a normal method signature.
这使应用程序服务器知道如何正确初始化任何Servlet实现.
This allows the application server to know how to initialize any Servlet implementation properly.
另一种解决方案是需要,但在编译时不强制采用ServletContext的构造函数.然后,应用服务器将通过反射调用构造函数.但是,Servlet规范的设计人员没有选择此路径.
Another solution would have been to require, but not enforce at compile time, a constructor taking ServletContext. The application server would then call the constructor via reflection. However, the designers of the Servlet specification did not chose this path.
这篇关于Servlet构造函数和init()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!