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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.