How can I daisy chain servlets together such that the output of one servlet serves as the input to the next?
Created May 4, 2012
There are two common methods for chaining the output of one servlet to another servlet :
To chain servlets together, you have to specify a sequential list of servlets and associate it to an alias. When a request is made to this alias, the first servlet in the list is invoked, processed its task and sent the ouptut to the next servlet in the list as the request object. The output can be sent again to another servlets.
To accomplish this method, you need to configure your servlet engine (JRun, JavaWeb server, JServ ...).
For example to configure JRun for servlet chaining, you select the JSE service (JRun servlet engine) to access to the JSE Service Config panel.
You have just to define a new mapping rule where you define your chaining servlet.
Let say /servlets/chainServlet for the virtual path and a comma separated list
of servlets as srvA,srvB.
So when you invoke a request like http://localhost/servlets/chainServlet, internally the servlet srvA will be invoked first and its results will be piped into the servlet srvB.
The srvA servlet code should look like :
public class srvA extends HttpServlet { ... public void doGet (...) { PrintWriter out =res.getWriter(); rest.setContentType("text/html"); ... out.println("Hello Chaining servlet"); } }All the servlet srvB has to do is to open an input stream to the request object and read the data into a BufferedReader object as for example :
BufferedReader b = new BufferedReader( new InputStreamReader(req.getInputStream() ) ); String data = b.readLine(); b.close();After that you can format your output with the data. It should work straigthforward with Java Web Server or Jserv too. Just look at in their documentation to define an alias name. Hope that it'll help.