how to forward from one servlet to another Servlet Essentials Servlet Forward

Forward to Servlets

Here we will talk about how to forward from one servlet to another.Forwarding to a servlet is something like someone calls one for some work and the approached guy asks some one for help and returns the result to the approachee. It must be noted that the aproachee always sees the response from the that same guy only whom he called.The same thing happens in servlet forwarding as the request url doesnot change and response always comes as it has come from the first servlet and not the forwarded one. So,what can be done is write that very code in a servlet and that can be used at various places.The forward basically is a dynamic .The RequestDispatcher class gives the method for forward.The RequestDispacher class as the name suggests is the request delegater. The RequestDispatcher instance can be get from the request object inside the doPost or doGet method.Here the request and response objects are passed as paramters from the servlet code where forward code is written.The example code is written below :

import javax.servlet.*;
import javax.servlet.http.*;

public class RequestDispatch extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      ServletContext sc = this.getServletContext();
      RequestDispatcher rDis = sc.getRequestDispatcher("/login");
      if (rDis != null){
          rDis.forward(request, response);
      PrintWriter out = response.getWriter();
      out.print("Output after the content of login");

Here we can see that request is forwarded to login servlet in the RequestDispatch servlet.In the getting of RequestDispatch instance from the request object we need to give the entry in <url-pattern> tag for the servlet as string.

Number of View :6085


  1. No comments yet.

Content Protected Using Blog Protector By: PcDrome.