File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "calling servlets from normal java class" Watch "calling servlets from normal java class" New topic
Author

calling servlets from normal java class

mohan kumar r
Ranch Hand

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


mohan
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

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
Sheriff

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 frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

You could also write a java class that behaves like a web client using java.net.URLConnection 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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: calling servlets from normal java class
 
Similar Threads
Tomcat doesn't see Java bean
Compiling Servlet
Diff between Java Bean and Java class
Servlets class
can we use servletcontext in a normal java class