Hi All, There was an interview question that I came across. Hope you guys can help me. The question is : Can Servlets be called from a stand-alone Java Application as other Java objects? Many thanks in advance, - Bhaskar
Hi whenever you invoke a servlet from a standalone application , its similar to a request made from the browser . so think in that way , how the servlet container would handle a request from the browser.
But I still didnt get how the Servlet is instantiated(??). Another question : Can we run the servlet in command line using 'java MyServlet'
Servlets must run inside a "servlet container" that provides the vital services of creating a servlet instance, receiving a request, holding session data, etc. etc etc. That said - with thoughtful architecture you can put the main functional parts of your servlet application into classes that can be run from the command line with the aid of a little interface code. I'll give you an example - the parameters in a request can be obtained as a Map with getParameterMap(). This Map has entries keyed by the parameter name and with parameter value(s) in a String If you write your processing code in a method that can take a Map like this, and write output to a PrintWriter, then the same code that runs in the servlet can be run outside the servlet environment. Bill
Joined: Dec 17, 2002
Thanks William for your answer! I now u'stand that we CAN create something similar to the servlets by capturing the content of request object as a Map, work on the name/value pairs in a method and send the response to a PrintWriter object. But what about the initialization of the servlet? Should we call the default no argument constructor (which means the init() method would be just like any other method)? And what about the ServletContext and ServletConfig objects? :roll:
Author and all-around good cowpoke
Joined: Mar 22, 2000
But what about the initialization of the servlet?
That is exactly the point - you should NOT try to initialize a servlet and run it outside a servlet container - you will just get all tangled up due to the absence of the services that the container normally provides. Instead, test your functions separately - make a command line driven test program to instantiate your utility class and feed it test data. Bill