Servlet constructor and init () method

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

+7
servlets init
source share
1 answer

Because Servlet is an interface, not an abstract class. Constructor arguments cannot be specified on an interface, so ServletContext must be specified on a regular method signature.

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

Another solution would be a requirement, but not mandatory at compile time, for a constructor taking a ServletContext. Then the application server will call the constructor through reflection. However, the developers of the Servlet specification did not choose this path.

+18
source share

All Articles