Wednesday, June 18, 2008

Modular Response-Writers - how can we have them in Servlets?

Question: Modular Response-Writers - how can we have them in Servlets?

Answer: Before discussing how can we achieve this in a Servlet, let's discuss the need of such a thing. An example scenario - suppose someone wants to build the header, body, side-bar, and footer components of his site in four separate servlets. In such a case he will need to have a mechanism of combining the responses created by all the four servlets to build the final response, which will ultimately be sent to the client browser. The concept of modular response-writers comes as a rescue in such situations.

Forming a response object by using multiple servlets require a servlet writer to pick one of the two pissible alternatives:-

  • Using JavaBeans or Java methods - we may use multiple JavaBeans or call multiple Java methods to build the final HTML response.
  • Using RequestDispatcher.include() - Unlike forward() method, include() method just brings the output of the included servlet and the output is simply appended to the current response object of the calling servlet (also called the master servlet). So, we can include() as many servlets as we want and have the outputs appended to the response of the calling servlet to build the final response. This final response will ultimately be sent to the client by the master servlet.

Servlets 2.3 came up with a new concept called Filters. This may also be used as an alternative to build response from multiple servlets, but it's generally not used for this purpose as Filters haven been introduced to the Servlet Specification for a different purpose and using them as an alternative in such a scenario makes the implementation quite complex and at times little ambiguous as well.


No comments: