This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
shaji bala
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic