How to forward from a Java servlet to a JavaServer Page (JSP)

By Alvin J. Alexander, devdaily.com

Here's a quick Java source code example showing a complete method that I use in a Java servlet to forward to a JavaServer Page (JSP).

Just pass the method an HttpServletRequest, an HttpServletResponse, and a URL, and you're in business. Note that my JSP URL typically looks like "/myPage.jsp".

private void forwardToPage(final HttpServletRequest request, 
                           final HttpServletResponse response,
                           String url) 
throws IOException, ServletException
{
  RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
  dispatcher.forward(request,response);
}

I'll try to post information here on the difference between a forward and a redirect soon.


devdaily logo