File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes How do u call a method of a servlet from a class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "How do u call a method of a servlet from a class" Watch "How do u call a method of a servlet from a class" New topic

How do u call a method of a servlet from a class

shaji bala

Joined: Nov 02, 2000
Posts: 2
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.
Frank Carver

Joined: Jan 07, 1999
Posts: 6920
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.

Read about me at ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
I agree. Here's the link:
subject: How do u call a method of a servlet from a class
It's not a secret anymore!