aspose file tools*
The moose likes Servlets and the fly likes Servlet's constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Servlet Watch "Servlet New topic
Author

Servlet's constructor

Sanjay Karanjkar
Greenhorn

Joined: Oct 20, 2000
Posts: 6
Is there a default constructor generated for a servlet?
If yes, how does the servlet engine call it to load a servlet's instance?
Is there ANY way in the world that I can call a servlet's "consructor" ??
Preethi M
Greenhorn

Joined: Oct 24, 2000
Posts: 22
hi sanjay,
i am new to servlets,and if i am wrong pls correct me.
A default constructor can be generated for a servlet.when the servlet is loaded the constructor is fired,and an instance is created.
thanks
S Chandra Mohan
Ranch Hand

Joined: Oct 19, 2000
Posts: 75
I agree with prithi.
I think u cant access the constructor odf a servlet as it is
out of scope
Anyway if come to know about this please post it under this session
thanking all
S Chandra Mohan


Have a wonderful day and wish u success<p>S Chandra Mohan<br />sc_mohan_us@yahoo.com
Preethi M
Greenhorn

Joined: Oct 24, 2000
Posts: 22
hi sanjay,
can u give me a clear cut view of what u mean by calling a servlets constructor.when a servlet is instantiated the servlets constructor is called.
thanks
preethi
Sanjay Karanjkar
Greenhorn

Joined: Oct 20, 2000
Posts: 6
True, but the 'constructor' is called by the SERVLET ENGINE when it gets a request for that servlet.
That is the ONLY way that I know to instantiate a servlet.
So my question was, can i explicitly instantiate a servlet PROGRAMMATICALLY ? (e.g.: thru another servlet)
Preethi M
Greenhorn

Joined: Oct 24, 2000
Posts: 22
hi sanjay!
As to my knowledge we can explicitly instantiate a servlet. For eg:
public ServletTest()
{
this("preethi");
}
public ServletTest(String str)
{
System.out.println(str);
}
when u create an instance of this servlet in another servlet this constructor will be fired.hope i am up to the mark.
thanks
preethi
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
A servlet is just a Java class which implements the javax.servlet.Servlet interface, so it may have one or more constructors, it may have methods with any names you like, and so on. Here's a trivial example:

This class is a Servlet, but as far as working in a Servlet container, it's useless. It doesn't implement service(), doGet(), or any of the other useful methods.
I can run this class just as I would any other with a "main", the fact that it is a Servlet is of no consequence. Similarly if I add a constructor:

This class is still a useless servlet, but it has a problem. It now can't even be loaded into a Servlet container, as it has no constructor with no arguments (the first example had a default constructor). So let's make one:

Now we have a Servlet, with two different constructors and two other methods, which will load into a Servlet container, but is still useless as a servlet. To make it (sort of) useful, we can implement one of the significant methods:

Now we have Servlet which can be loaded into a Servlet container, and will return a page containing the text "What?" to any browser which invokes it. It also can be run from the command line, or called by another class.
Key things to remember:
+ A Servlet is just a Java class, but to make sense in a Servlet container it has to implement certain methods.
+ A Servlet can have any number of constructors, but the only one called by the Servlet container will be the one with no arguments.
+ A servlet can have any number of methods, but the only ones called by the Servlet container will be the ones mentioned in the Servlet API specification (init(), service(), doGet() etc.).
+ If you need to pass parameters to a Servlet to set it up, the proper way is to use the "init" method, which allows the Servlet access to the initialization parameters specified to the Servlet container.


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Sanjay Karanjkar
Greenhorn

Joined: Oct 20, 2000
Posts: 6
Thanx a million, frank !
thomas davis
Ranch Hand

Joined: Feb 01, 2003
Posts: 207
Servlet behaves like normal java class,hence we can override the constructor(default constructor),also we can create parameterized constructor.I would like to know if I overriden the default constructor with database pooling or connection availing. Will it increase the performance of the servlet?
Whatelse can be written in constructor to increase the efficiency or performance(should act as a normal servlet ) ? what are the other functionalities can be written in the constructor, when the servlet gets instantiated ?
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12835
    
    5
Servlet behaves like normal java class,hence we can override the constructor(default constructor),also we can create parameterized constructor.I would like to know if I overriden the default constructor with database pooling or connection availing. Will it increase the performance of the servlet?
Whatelse can be written in constructor to increase the efficiency or performance(should act as a normal servlet ) ? what are the other functionalities can be written in the constructor, when the servlet gets instantiated ?

Why in the name of sanity would you want to pervert the normal servlet API? Do you think the people who designed it are idiots?
You are guaranteed that the init method will be called before any request is handled - that is where you should accomplish anything that has to be done before handling the first request.
Bill
thomas davis
Ranch Hand

Joined: Feb 01, 2003
Posts: 207
Hey William Brogden,
I did not say that you are a idiot or fool..I just want to clarify my doubt.
Moreover you did not answer my question with proper reasoning.
If I overidden the constructor with some functionalities like database connection ,what would happen to my servlet?
Will it get called or executed..?
Anwer this question ..
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
If I overidden the constructor with some functionalities like database connection ,what would happen to my servlet?
Will it get called or executed..?

If you put code in the default constructor it willmost likely be called. Although all servlet containers that I am aware of create servlet instances using the no-arg constructor, I don't think there is any requirement for a container to always use that constructor if it knows of a "better" way to create the servlet instance.
There are, however, much bigger problems with this.
You don't know, and have no control over, when or how this constructor will be called. It is quite feasible for a servlet container to create instances of all the servlet classes it knows about as soon as it starts up. This may be days or weeks before any of the servlets are actually requested. If you do something in the constructor which claims an external resource (such as a database connection), then (a) your servlet could be holding on to that (potentially large) resource for a long time, and (b) the resource is quite likely to "time out" before you get to use it even once.
If you use the recommended approach of starting things in "init", then you have the chance to finish them in "destroy". If you start things in a constructor there is no guarantee you will ever be able to finish them. "finalize" may never be called, and "destroy" will only be called if "init" has been called. Find a Database administrator somewhere and ask what happens if you open connections without ever closing them
The result of all this is (as Bill indicated) that the separation of init/destroy from object construction is there for some very good reasons. It is very rarely sensible to do anything in the contructor of a servlet. You are guaranteed that "init" will be called before your servlet is used. That is the right place to put your initialisation code.
thomas davis
Ranch Hand

Joined: Feb 01, 2003
Posts: 207
Thank you for your information. I really appreciate your reasoning ability.
sheril she
Greenhorn

Joined: Oct 08, 2002
Posts: 12
could u pls explain when exactly the servlet constructor is called and when the init method is called.since in a servlet's lifecycle there is only the init ,service and destroy.and it is said that the init method is called when the servlet is loaded.so what is the difference between creating instances and loading the servlet?where are these instances stored?
Pete Harris
Ranch Hand

Joined: Feb 05, 2003
Posts: 39
I think what this thread boils down to is this: The servlet constructor belongs to the servlet engine and not the programmer. There is no guarantee as to when this constructor will be called, and different engines will do it different ways.
To achieve constructor-like behaviour in a servlet, use the init() method. To achieve finalize() type behaviour, use the destroy() method. Just make sure you completely ingore the constructor!
Kevin Mukhar
Ranch Hand

Joined: Nov 28, 2000
Posts: 83
Originally posted by sheril she:
could u pls explain when exactly the servlet constructor is called and when the init method is called.since in a servlet's lifecycle there is only the init ,service and destroy.and it is said that the init method is called when the servlet is loaded.so what is the difference between creating instances and loading the servlet?where are these instances stored?

All your questions are more or less answered in the Servlet Spec, para 2.3, which you can find at http://java.sun.com/servlets.
In short, there is no answer to when exactly a method is called. The methods are called relative to events in the container life and request process.
- class files are loaded anytime between when the container is initiated and when a request for the servlet is received
- a servlet instance (or instances) is created by calling the no-argument constructor any time after the class is loaded but before the first request
- the init() method is called any time after the serlvet is instantiated but before the first request
- service() is called for a request
- destroy() can be (but is usually not) called anytime after a request is serviced. If the container is shutting down, it can call destroy() even if all request threads are not complete, if it waits for a timeout period.
You can see when some of these events occur by placing log statements in
- a static initializer (called when class is loaded)
- a no-argument constructor
- the init() method
- the destroy() method
thomas davis
Ranch Hand

Joined: Feb 01, 2003
Posts: 207
Kevin Mukhar :
In short, there is no answer to when exactly a method is called. The methods are called relative to events in the container life and request process.
- class files are loaded anytime between when the container is initiated and when a request for the servlet is received
- a servlet instance (or instances) is created by calling the no-argument constructor any time after the class is loaded but before the first request
- the init() method is called any time after the serlvet is instantiated but before the first request
- service() is called for a request
- destroy() can be (but is usually not) called anytime after a request is serviced. If the container is shutting down, it can call destroy() even if all request threads are not complete, if it waits for a timeout period.
You can see when some of these events occur by placing log statements in
- a static initializer (called when class is loaded)
- a no-argument constructor
- the init() method
- the destroy() method

As far as the servlet life cycle is concerned, constructor is called just before the init() method is called.
If we are implementing SingleThreadModel for Servlet, JAVA API says one request will be processed by one instance of the servlet.
And moreover the container calls init() method only once that is just before service method and after the instance is created.
This statement really confusing me in the case of SingleThreadModel.
1)Suppose I am implementing SingleThreadModel, how many times the container will call the init() method? Only once or whenever the container creates a new instance of the servlet?
2)What would happen to ServletConfig Object?
3)If the answer is only once the init() method is called ,Would the order of life cycle be changed as given below
1)Servlet instance is created � constructor is called
2)service() method
3)destroy() method
So how the container passes the initialization parameters(ServletConfig) to the newly created instances of the servlets?
thomas davis
Ranch Hand

Joined: Feb 01, 2003
Posts: 207
It seems that everybody stopped to put comments on this topic.Please try to answer the above question.
Ivan Tamayo
Ranch Hand

Joined: Aug 13, 2001
Posts: 49
We don�t know when or how the servlet container will call the servlet constructor.
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

thomas,

1) You could easily find this out for yourself by coding a demo servlet that extends SingleThreadModel.
But...

the init() method will be called (and btw, the constructor will be called) as many times as there are servlets.

a) container creates one servlet and calls the init method on it. It services a long-process request.
b) second request comes in. A new servlet instance is required. So.. constructor, init and then the second request gets processed by the second instance.
c) repeat as necessary.

2) nothing

3) no change.

by 'no change' I mean that at some point in EACH servlet instance's life, the following will be called IN THIS ORDER... constructor, init, destroy. But WHEN any of these are called is NOT known, except we ARE guaranteed by the spec that init is called before servicing a request.
thomas davis
Ranch Hand

Joined: Feb 01, 2003
Posts: 207
Hi Mike,
the init() method will be called (and btw, the constructor will be called) as many times as there are servlets.
a) container creates one servlet and calls the init method on it. It services a long-process request.
b) second request comes in. A new servlet instance is required. So.. constructor, init and then the second request gets processed by the second instance.
c) repeat as necessary.


That means container will call init() method for each instance of a particular servlet.It does not matter the mechanism being used SingleThreadModel or MultiThread Model.
It will call init() method for each and every newly created instances of a servlet
Somebody wrote in this forum that If we are implementing SingleThreadModel,Container will copy the instance from the existing instance for processing each request.And he wrote that while copying the instance ,it will not call init() method again.which is called when it is created the instance from the servlet for the first time.
After that ,for each request it will go for copying.(not instantiating the new instance)
Is this true?

William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12835
    
    5
Somebody wrote in this forum that If we are implementing SingleThreadModel,Container will copy the instance from the existing instance for processing each request.And he wrote that while copying the instance ,it will not call init() method again.which is called when it is created the instance from the servlet for the first time.
After that ,for each request it will go for copying.(not instantiating the new instance)
Is this true?

My interpretation of the API is that the above is balderdash. If anybody has evidence of a servlet container that does this, I would love to see it. Seems to me your servlet would have to implement Cloneable.
Bill
[ February 19, 2003: Message edited by: William Brogden ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Servlet's constructor