2

Constructors in servlets is considered a good/bad practice ? How does it compare to the init() method ? Using servlet-3 and vanilla javaEE (CDI provided by javax.inject package)

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361

2 Answers2

4

There is nothing wrong in using constructors in servlets. The reason to switch to init() is when you need to obtain ServletConfig, ServletContext, etc. These objects might not be available (yet) in constructor.

Also hypothetically some containers might do fancy things with servlets like dynamic subclassing or proxying. Finally side-effects in constructors tend to make testing harder.

To avoid unexpected behaviour and make sure your servlets are 100% portable just stick with init(). Also if you use destroy() as well, implementing init() will make your code more "symmetric".

See also

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • I guess then first `init()` is called then the constructor ? Also could you elaborate on _side-effects_ ? Also is there a case a Servlet constructor may be required (in the context of a famework for instance) ? Finally could you provide some links (however technical) - especially on the way init() happens behind the scenes ? – Mr_and_Mrs_D Jul 22 '12 at 16:02
  • @Mr_and_Mrs_D: 1. no, no method can be called on an object prior to constructor, including `init()` 2. Read about mocking and proxying - in some circumstances constructor can be called twice. 3. See the link I added to my answer, servlet *must* have a no-arg constructor. 4. Guess it's container-dependant. All you need to know is that it's called after constructor and before any `service()` call. – Tomasz Nurkiewicz Jul 22 '12 at 16:12
  • 1.Yes - sorry. 3. This can be the default constructor - I do not have to write one - right ? Another link on the subject from SO [here](http://stackoverflow.com/questions/1276082/constructor-in-servlet/2659597#2659597) – Mr_and_Mrs_D Jul 22 '12 at 16:29
  • @Mr_and_Mrs_D: Ad 3. There **must** be a no-arg constructor - either the one you wrote or the default one created by the compiler for you. – Tomasz Nurkiewicz Jul 22 '12 at 16:44
0

yup we can have constructor in servlets but it is not required bcoz-

servlets are initialized by the web container. servlets is not initialized unlike other java class. Constructor are used to initialize an explicitly created object while servlet use a different method 'init()' for their initialization.

Servlet is only an interface(javax.servlet.Servlet) and interface in java dont have any constructor and a construcor of an implementing class cant declare in the servlet interface and it doesn't make any sense. Container will only use the init() method to initialize the servlet.

Pri
  • 94
  • 4
  • and ya we need init method bcz to initialize servlet we require special object servletConfig and we can have access to this object in init method only not in constructor. – Pri Nov 20 '12 at 11:43