3

Can I declare parameterized constructor inside servlet which is only constructor ?

If no then why ?

Silent Warrior
  • 5,069
  • 8
  • 41
  • 52

4 Answers4

8

No.

Servlet instances are created by the container via reflection, and they expect to find a public, no-arg constructor (the default constructor).

To configure your servlet, use servlet parameters specified in the web.xml file. These are passed to your servlet's init() method.


While it would be possible for a servlet container to choose a non-default constructor and coerce character strings to simple types and invoke the constructor reflectively, this isn't what the Servlet specification requires.

Part of the reason may be historical; servlets were first specified long before dependency injection systems made this alternative widely practiced. However, such constructors would be fairly limited; it would be practical to pass arguments that can be created from a simple character string specified in the web.xml, but more useful objects—a DataSource, for example—would be awkward.

It would be nice to have final member variables in a servlet though.

The JSR formerly known as "WebBeans" (JSR 299, I think), will provide some standards for dependency injection support in Servlets. This might address some of the drawbacks in the current approach.

erickson
  • 265,237
  • 58
  • 395
  • 493
1

no! we cannot provide a parameterized constructor in servlet.The servlet container creates the object for sevrlet.The container will create the object based on Class.forName(String classname). we can create an object to a class using Class.forName(), if the class contains default constructor only.since the container uses the Class.forName() code in creating object, we do not write parameterized constructor as part out servlet. Even though if we want to write parameterized constructor, we have call the constructor from service()method!

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
1

Since servlets are instantiated by the container they need a no-argument constructor.

Additionally the container may reuse servlets and will not call the constructor on reuse.

Steve B.
  • 55,454
  • 12
  • 93
  • 132
1

You'll need to initialize the variables through <servlet-param> or use a Framework like Spring which can allow you to Proxy the Servlet to a different class that acts just like any other bean.

Gandalf
  • 9,648
  • 8
  • 53
  • 88