I have a class which needs to call a method of a servlet. The servlet does many other functions besides doing the operation needed by the class. The servlet may or may not be instantiated on the web server. How can my class call the method of the servlet on both cases, ie, if the servlet is already instantiated then call the method on the servlet or if it is not yet instantiated, then instantiate it and then call the the method on the servlet.
Joined: Jan 07, 1999
While it may be possible to do what you ask. I can't help questioning why you need to do it. In general, the presence of problems like this is a good indication that your servlet class is doing too much. Please consider splitting out the functionality which you need to use into a separate class, called by both the servlet and your other user. Then you don't need to worry about whether the servlet container has instantiated your servlet or not. Here's a very simple example: Original, too big servlet:
New, simple servlet:
The new helper class:
And finally, another class which can use the same helper
This may look like a bit more work, but it has great advantages. Each class is responsible for only one thing, and it does it well. The servlet just handles interfacing with HTTP and HTML, the helper handles writing the file, and the example user just provides a command-line interface. This means that there is the maximum potential for the reuse of code. For more help on this sort of thing, read up on "refactoring", especially the book by Martin Fowler.