15.1. Forwarding Requests

The key to letting servlets forward requests or include external content is to use a RequestDispatcher. You obtain a RequestDispatcher by calling the getRequestDispatcher method of ServletContext, supplying a URL relative to the server root. For example, to obtain a RequestDispatcher associated with http://yourhost/presentations/presentation1.jsp, you would do the following:

String url = "/presentations/presentation1.jsp";
RequestDispatcher dispatcher =
  getServletContext().getRequestDispatcher(url);

Once you have a RequestDispatcher, you use forward to completely transfer control to the associated URL and use include to output the associated URL's content. In both cases, you supply the HttpServletRequest and HttpServletResponse ...

Get Core Servlets and JavaServer Pages™ now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.