How to forward from a Java servlet to a JSP

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

Just pass the method an HttpServletRequest, an HttpServletResponse, and a URL, and you're in business. Note that my JSP url string typically looks something 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);
}

If you need to perform a redirect from a servlet to a JSP instead, I've also written a short "How to redirect from a servlet to a JSP" tutorial.

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

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.