In Servlets/JSPs, there are two ways to achieve servlet chaining using
javax.servlet.RequestDispatcher:
- Include:
RequestDispatcher rd = req.getRequestDispatcher("Servlet2");
rd.include(req, resp);
- 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 servletotherwise 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.
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible.
Submit your tip here.