Servlet chaining


In servlet chaining, multiple servlets are called for a single client HTTP request, each servlet providing part of the HTML output. Each servlet receives the original client HTTP request as input, and each servlet produces its own output independently. Figure shows the servlet chaining process flow.

 

This servlet is specified on the original request, and multiple servlets are specified in an initialization parameter as the target:

Parameter name: chainer.pathlist
Parameter value: /chainFirst /chainSecond

Each servlet is called in the order specified on the alias, and the output HTML is made up of the output from all of the servlets.

Servlet filtering and chaining have the advantage of allowing the Web developer to create modular servlets that can, for example, output standard HTML headers and footers or provide common dynamic content for pages.

Example 1 and Example 2 show how two servlets can be used in collaboration to produce a single output response. Notice that the second servlet must process the output of the first servlet, in order to produce the desired composite result. One possible application of this technique might be when one servlet produces as its output an XML formatted response, and we chain it to another servlet that wraps the appropriate style sheet around the XML before sending it back to the browser.

Example 1

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ChainerFirst extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML><TITLE>ChainerFirst</TITLE><BODY>");
out.println("<H2>Servlet API Example - ChainerFirst</H2><HR>");
out.println("<H4><font color=\"Red\">This part of the output produced by
the first servlet..</font></H4>");
}
}

Example 2

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ChainerSecond extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType(req.getContentType());
PrintWriter out = res.getWriter();
//Need this to read through the output of the last servlet:
BufferedReader in = req.getReader();
String line;
while((line = in.readLine()) != null)
out.println(line);
out.println("<H4><font color=\"Green\">This part of the output produced
by the second servlet..</H4>");
out.println("</BODY></HTML>");
out.close();
}
}
Share this article :
 
Copyright © 2012. Best Online Tutorials | Source codes | Programming Languages - All Rights Reserved