Servlet constructor and init() method

前端 未结 1 1583
北荒
北荒 2020-12-11 17:31

Why do we need an init() method in servlet? Can\'t we use the constructor to initialization?

1条回答
  •  南笙
    南笙 (楼主)
    2020-12-11 17:47

    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.

    This allows the application server to know how to initialize any Servlet implementation properly.

    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.

    0 讨论(0)
提交回复
热议问题