Defines an object that receives requests from the clicent and sends them to any //resource(such as a servlet, HTML file , or JSP file) on the server. The servlet container creates the //RequestDispatcher object, which is used as a wrapper around a server resource located at a particular //path or given by a particular name.
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
// in JSp, you can use <jsp:forward page="<%= destination %>" />
An alternative to forward is include. With include, the servlet can combine its output with that of one or more JSP pages. More commonly, the servlet still relies on JSP pages to produce the output, but the servlet invokes different JSP pages to create different sections of the pages.
This approach is most common when your servlets create portal sites that let users specify where on the page they want various pieces of content to be displayed. e.g. as follows,
String firstTable, secondTable, thirdTable;
if (someCondition) {
firstTable = "/WEB-INF/Sports-Scores.jsp";
secondTable = "/WEB-INF/Stock-Prices.jsp";
thirdTable = "/WEB-INF/Weather.jsp";
} else if (...) { ... }
RequestDispatcher dispatcher =
request.getRequestDispatcher("/WEB-INF/Header.jsp");
dispatcher.include(request, response);
dispatcher =
request.getRequestDispatcher(firstTable);
dispatcher.include(request, response);
dispatcher =
request.getRequestDispatcher(secondTable);
dispatcher.include(request, response);
dispatcher =
request.getRequestDispatcher(thirdTable);
dispatcher.include(request, response);
dispatcher =
request.getRequestDispatcher("/WEB-INF/Footer.jsp");
dispatcher.include(request, response);
Comments
Post a Comment