How To Redirect From One Servlet To Another Servlet Basics Servlet Redirect

Redirect to Other Servlets

Here we will talk about how to redirect from one servlet to another.Redirecting to a servlet is something like someone calls one for some work and the approached guy asks the person to call some other as he doesnot have the solution. It must be noted that the aproachee has to send the request to that other guy.The same thing happens in servlet redirecting as the request url changes and response comes form the servlet where request has been redirected. So,what can be done is write that very code in a servlet and that can be used at various places .The response object gives the method for redirect.The RequestDispacher class as the name suggests is the request delegater as it delegates the request but in redirect the request itself changes,so we can redirect the response to be given by another servlet.Iinside the doPost or doGet method.we can write the code to redirect in which the url for the servlet has to be given as a string..The example code is written below :

import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ResponseRedirect extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      ServletContext sc = this.getServletContext();
      response.senRedirect(“login”)
      }
      PrintWriter out = response.getWriter();
      out.print("Output after the content of login");
   }
}

Here we can see that redirection is occurring to login servlet in the ResponseRedirect servlet.In the redirection from one servlet to another we need to give the entry in <url-pattern> tag for the servlet as string.Once redirection happens the new request goes to login servlet,that means that client url changes and response comes from the login servlet as opposed to in the case of include or forward.With redirection we can move across applications and even across containers.Inside the servlet where redirection is happening,the rest of the code for the servlet will not be executed as the execution goes to the new redirected servlet.In the case of redirection we donot pass the request and response objects from the first servlet because new request and response is generated.

Number of View :1623

Tags:

  1. No comments yet.

SetPageWidth
Content Protected Using Blog Protector By: PcDrome.

Mahol Dot Org is Stephen Fry proof thanks to caching by WP Super Cache