What is Servlet chaining ?

Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request.
In servlet chaining, one servlet's output is piped to the next servlet’s input. This process continues untilthe last servlet is reached. Its output is then sent back to the client.


Two Ways to Chain Servlets

In Servlets/JSPs, there are two ways to achieve servlet chaining using javax.servlet.RequestDispatcher:

  1. Include:

    RequestDispatcher rd = req.getRequestDispatcher("Servlet2");
    rd.include(req, resp);
  2. Forward, where req is HttpServletRequest and resp is HttpServletResponse:
     
    RequestDispatcher rd = req.getRequestDispatcher("Servlet3");
    rd.forward(req, resp);
In JSPs, the above code would look like this:

RequestDispatcher rd = request.getRequestDispatcher("Servlet4");
rd.forward(request, response);
When you use servlet chaining, you delegate the responsibility of generating the response to the next servlet in the chain.

But, suppose you have some data generated by current servlet that will be required by next servlet. How would you pass it?

You could keep it in the session, but you would need to remove it from that session after you fetch it in next servlet—otherwise your session will have useless data once your request is complete. Not only does this add overhead, but it also makes your next servlet dependent on session tracking.

You can attach your additional data with the request that you are passing to next servlet:


RequestDispatcher rd = req.getRequestDispatcher("Servlet3");
req.setAttribute("key1", value1);
req.setAttribute("key2", value2);
rd.forward(req, resp);
In the above code, req is HttpServletRequest and resp is HttpServletResponse. The code attaches two data items, value1 and value2, with the req object. Use the following code to access this value in the next servlet (Servlet3 in the example):

Object val1 = req.getAttribute("key1");
Object val2 = req.getAttribute("key2");
This attaches two data items (value1 and value2) with the HttpServletRequest object and forwards them to Servlet3. Servlet3 reads them from the HttpServletRequest and uses them.


0 comments: