Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

calling servlets from normal java class

 
mohan kumar r
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
is it possible to call a servlet from normal java class as like ejb
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can call it as any other java class, but what good will it do outside a container ?
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic