How to redirect a request in servlets?

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Hello, In previous articles, we have seen how a RequestDispatcher works. In this part ,we will see how to redirect a request in servlet.  Let us directly go by example.

Why is redirection needed?

We may have a requirement that when a request is made for some resource and if that resource cannot fulfill the request, then it needs to redirect a request in servlet to another resource.

How to do it?

Servlet API provides a way to redirect a request to another

1. Dynamic web project.

Create a new dynamic web project in eclipse with name ServletsJSPExamples .

2. Create and configure DispatcherServlet.

Create a new Servlet called DispatcherServlet and add following code to it.

Configure servlet in web.xml.

 3. Create Hello.jsp

Create Hello.jsp page in webcontent folder in eclipse so what when it is deployed under tomcat, it is deployed under root folder.

 4. Run the application.

Deploy your application under tomcat server. Start tomcat and then hit the url http://localhost:8080/ServletsJSPExamples/DispatcherServlet .

You will see the output as

Hello page

Explanation:

Let us understand it using a diagram.

 redirection in servlet

    1. When you hit url http://localhost:8080/ServletsJSPExamples/DispatcherServlet , request is made to the DispatcherServlet . As of now we have not done anything to redirect a request in servlet to another resource
    2. When the DispatcherServlet is executing, then the code  response.sendRedirect("Hello.jsp");  starts the process to redirect a request in servlet.
      • Http response sent by DispatcherServlet has status code 301 and a header called location with the new url i.e. url of JSP as value.
      • The browser receives this response and recognizes 301 status code which is used to redirect a request.
      • The browser finds the header called location and retrieves its value
    3. Now the browser makes a new request according the to value of location header as specified in the previous response. There is nothing special about this request. It is just a regular request. You can notice the url has changed to http://localhost:8080/ServletsJSPExamples/Hello.jsp
    4. The new request resource, in our case, Hello.jsp server to response to browser.

 

 

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

3 thoughts on “How to redirect a request in servlets?

Leave a Reply

Your email address will not be published. Required fields are marked *