Last Updated on 28 June 2019   |   Print Email
In Java web development, a typical scenario is the user fills in details on a form, and then submits the form to a Java servlet on the server for processing, and then the servlet redirects the user to the result page.In this article, you will learn how to forward request from a Java servlet to a destination page which can be JSP or HTML.First, in the servlet’s doGet() / doPost() method, you need to get a reference of RequestDispatcher from the request, passing the destination page. For example:
Then call the forward() method on the RequestDispatcher() object. For example:
requestDispatcher.forward(request, response);
This method should be called at last in a code block, because afterward the request has been forwarded.And in the destination JSP page, you can use JSP Expression Language (EL) to read the values of the attributes stored in the request. For example:
Note that with this kind of forward from Servlet to JSP, the URL on the browser remains unchanged - it is the URL of the servlet - even you specify the JSP page.And if you commit the response before calling forward(), an IllegalStateException is thrown. Consider the following code snippet:
String destination = "result.jsp";
response.getWriter().println("Wait, one more thing...");
response.getWriter().close();
RequestDispatcher dispatcher = request.getRequestDispatcher(destination);
dispatcher.forward(request, response);
Calling forward() in this case causes the server throws the following exception:
java.lang.IllegalStateException: Cannot forward after response has been committed
Because the response is already committed before, so the request cannot be forward. So you should pay attention to this case.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments
but i dos't appear when you call websit/