Servlet constructor and init() method
Asked Answered
N

1

8

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

Nata answered 27/9, 2008 at 10:39 Comment(1)
See my answer to a similar question.Woodsy
I
19

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.

Interrupted answered 27/9, 2008 at 10:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.