Forums Register Login

Servlet and Constructor

+Pie Number of slices to send: Send
Its obvious that a servlet is a class. Can we write a constructor in a class which extends from HttpServlet? Please answer
+Pie Number of slices to send: Send
Hi Uma,

Thats a good question...Good Going....


BYe
+Pie Number of slices to send: Send
Why not.
All classes need a constructor. If you don't write one a default constructor will be provided.
+Pie Number of slices to send: Send
Hi,
Yes you can definately write constructor in ure servlet class it will be executed when your servlet gets loaded.


regards
+Pie Number of slices to send: Send
yeah you can. but again its mendatory to ask why?? why you want to do that??

please dont say tht you are going to instantiate your servet inside some of your normal java class. although you can instantiate your servlet with a default constructor. and if it is like that it is very bad idea.
+Pie Number of slices to send: Send
therefore remember that the only constructor that may make any sense to create is a no-argument constructor as that's the only one that the servlet engine will expect there to be and thus call.

But of course the correct place for servlet initialisation code is inside the servlet's init method, not the constructor!

And please don't think to do such things as opening global database connections and files in servlets!
At most you could use it to load some static data like global constants but a static initialisation block is probably more suitable to that.
Squanch that. And squanch this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 900 times.
Similar Threads
Servlet Constructor
Can i write a constructor in my servlet
when the container instatiates the servlet will it
Can we write constructor for Servlets?
Can we write initialization code in servlet constructor
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 08:36:33.