This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Servlets and the fly likes calling servlets from normal java 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 "calling servlets from normal java class" Watch "calling servlets from normal java class" New topic

calling servlets from normal java class

mohan kumar r
Ranch Hand

Joined: Jan 19, 2006
Posts: 38
is it possible to call a servlet from normal java class as like ejb

Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

You can call it as any other java class, but what good will it do outside a container ?

[My Blog]
All roads lead to JavaRanch
Frank Carver

Joined: Jan 07, 1999
Posts: 6920
From a practical point of view, to call a servlet you really need to emulate the key parts of a container. In this case, particularly the lifecycle and context services.

Although the "make it do stuff" methods are service, doget, doPost etc., all servlet containers will call init first, and many servlets rely on this for initialization rather than the constructor. If you think the servlet you are calling would normally register as a listener for other lifecycle events, then you may need to emulate those, too.

And don't forget to include the appropriate servlet api jar file in your classpath.

In practice, if yuo have access to the source code it's generally a much better solution to extract the "business processing" to another class which does not depend on any of the servlet API, then call that one directly from both you servlet and your non-servlet code.

Read about me at ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Ben Souther

Joined: Dec 11, 2004
Posts: 13410

You could also write a java class that behaves like a web client using or a third party library such as Jakarta Commons HTTPClient.

With this class, you could make requests to the servlet, over HTTP, as a browser does.

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
wood burning stoves
subject: calling servlets from normal java class
It's not a secret anymore!