Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
15.1 Forwarding Requests
355
Listing 15.1 Request Forwarding Example
public void doGet(HttpServletRequest request,
                  HttpServletResponse response)
    throws ServletException, IOException {
  String operation = request.getParameter("operation");
  if (operation == null) {
    operation = "unknown";
  }
  if (operation.equals("operation1")) {
    gotoPage("/operations/presentation1.jsp",
             request, response);
  } else if (operation.equals("operation2")) {
    gotoPage("/operations/presentation2.jsp",
             request, response);
  } else {
    gotoPage("/operations/unknownRequestHandler.jsp",
             request, response);
  }
}
private void gotoPage(String address,
                      HttpServletRequest request,
                      HttpServletResponse response)
    throws ServletException, IOException {
  RequestDispatcher dispatcher =
    getServletContext().getRequestDispatcher(address);
  dispatcher.forward(request, response);
}
argument to 
getRequestDispatcher
. However, since forwarded requests
use the same request method as the original request, 
POST
 requests cannot
be forwarded to normal HTML pages. The solution to this problem is to sim 
ply rename the HTML page to have a 
.jsp
 extension. Renaming 
some 
file.html
 to 
somefile.jsp
 does not change its output for 
GET
 requests,
but 
somefile.html
 cannot handle 
POST
 requests, whereas 
somefile.jsp
gives an identical response for both 
GET
 and 
POST
.
Supplying Information to the Destination Pages
To forward the request to a JSP page, a servlet merely needs to obtain a
RequestDispatcher
 by calling the 
getRequestDispatcher
 method of
ServletContext
, then call 
forward
 on the result, supplying the 
Http 
ServletRequest
 and 
HttpServletResponse
 as arguments. That's fine as
far as it goes, but this approach requires the destination page to read the
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

jsp web hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Jsp Web Hosting Cheapest Web Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved