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 :6447Related posts:
- Servlet Init Params How to get init parametrs in servlets Retreiving init params in servlets
- A Hello,World Servlet Servlet Tutorial Servlet Examples Run servlet on tomcat
- how to include one servlet into another Servlet Essentials Servlet Include
- how to forward from one servlet to another Servlet Essentials Servlet Forward
- Basics of tomcat Apache-Tomcat Tutorial Download and Run Tomcat
Tags: Tomcat server
This entry was posted on Tuesday, October 12th, 2010 at 4:27 am and is filed under Java. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.