In this servlet example I will show you how to forward request to another Servlet or JSP page.
Imagine that you have a servlet called ForwardServlet and a JSP called result.jsp. result.jsp is kept inside WEB-INF/pages folder. Whenever a form is submitted to ForwardServlet, it does some processing and then forwards the request to result.jsp. Here is the code snippet that can achieve this.
Forward request to JSP
In this example, I just print the value of name parameter and forward the request to result.jsp
Forward request to another Servlet
Now assume that you have another servlet called ResultServlet, and you want to forward request to it.
ResultServlet definition in web.xml
You can write following lines in ForwardServlet to forward request to ResultServlet.
Difference between forward and redirect
See Servlet redirect exampleNote: Never write any thing to response if you are going to forward the request to another servlet or JSP. For example, if Servlet1 forwards the request to Servlet2, Servlet1 should not write any thing to response, neither call the response.getOutputStream() method. This is not allowed and either whatever servlet1 wrote to the response will not output or you will get IllegalStateException.
Have you noticed, I have used url-pattern of ResultServlet ! Yes, whenever you want to forward/include request to another servlet, you have to use it's url-pattern to obtain the instance of RequestDispatcher.
No comments:
Post a Comment