why can't we initializa the fields in a constructor in the servlet?

Re: y we can not initialize the fields in the construtor in the servlet? 80 80

What exactly are you trying to do, and what error messages / unwanted effects are you getting / seeing?

The code in question would help, alot.

Re: y we can not initialize the fields in the construtor in the servlet? 80 80

never assume a servlet's constructor will be called.
In fact unless it's a no-args constructor it's guaranteed to not be called!

Typically a servlet is instantiated once, when it is first needed, per member of a cluster (which means once for most people, as most people don't run their applications in a clustered environment).
After that the servlet engine will keep it in memory and launch a new thread for each time a service method on that servlet is requested to be executed.

Re: y we can not initialize the fields in the construtor in the servlet? 80 80

i WANT TO INITIALIZE MY FIELDS IN THE CONSTRUCTOR IN A SERVLET

Re: y we can not initialize the fields in the construtor in the servlet? 80 80

You still haven't provided your code, so we can still only guess. If you are doing things in the "standard" constructor, it should work, but I wouldn't count on it. If you have any other constrcutor, then forget it, as it will never be called. For the most part, however, instance/class variables in a Servlet are usually not a good thing. Most people just starting use them wrongly and have from very serious side effects from it.

As I said, provide your code.

Re: y we can not initialize the fields in the construtor in the servlet? 80 80

Satish, store the client information / state in client session i.e. session variables. Since the servlet class is loaded in memory on its first invocation and the client reqests just result in the creation of thread, storing state in servlet instance variables would make them kind of global, i.e. accessible by each and every client.

To store common information related to the entire web application, look into the <context-param> element of deployment descriptor. To store common information related to a particular servlet, look into <init-param> element of deployment descriptor.

Re: y we can not initialize the fields in the construtor in the servlet? 80 80

he should learn about the object lifecycle in a servlet container before thinking of wanting to do something that's utterly unusual.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.