Saturday, April 28, 2012

Forwarding request to Servlet or JSP

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
import java.io.IOException;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class ForwardServlet extends HttpServlet{
 
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
  String name = request.getParameter("name");
  /*
   * You can do any processing here. 
   * We will simply output the value of name parameter on server console.
   * 
   */
  System.out.println(name);
  String destination = "/WEB-INF/pages/result.jsp";
 
  RequestDispatcher rd = getServletContext().getRequestDispatcher(destination);
  rd.forward(request, response);
 }
 
}

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

 <servlet>
  <servlet-name>ResultServlet</servlet-name>
  <servlet-class>ResultServlet</servlet-class>
 </servlet>
 
 <servlet-mapping>
  <servlet-name>ResultServlet</servlet-name>
  <url-pattern>/resultservlet</url-pattern>
 </servlet-mapping>  
You can write following lines in ForwardServlet to forward request to ResultServlet.
  String destination = "/resultservlet";
 
  RequestDispatcher rd = getServletContext().getRequestDispatcher(destination);
  rd.forward(request, response);

Difference between forward and redirect

See Servlet redirect example
Note: 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