Redirect request from servlet using sendRedirect method

In this example we are going to understand the method sendRedirect which is available in HttpServletResponse object. This method will take a String value as an input parameter. Essentially this String can be Servlet, jsp or html page. Checkout the example below for batter understanding.

Create a dynamic web project in your Eclipse IDE. Under src folder create two java servlets as defined below.

DemoServlet.java

package com.java.servlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/Demo")//This is url pattern for this servlet
//Servlet 3.0 doesn't require to be mapped in web.xml
public class DemoServlet extends HttpServlet {

    private static final long serialVersionUID = -4111596859324406153L;

    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
       
        System.out.println("Inside DemoServlet doGet method");
        //Calling servlet which has the name testing
        res.sendRedirect("testing");
    }
}


TestingServlet.java

package com.java.servlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/testing")//This is url pattern for this servlet
public class TestingServlet extends HttpServlet {

    private static final long serialVersionUID = -4111596859324406153L;

    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        System.out.println("Inside TestingServlet doGet method");
        res.sendRedirect("http://www.google.com");
        //or this can be any jsp or html page created under WebContent folder
        //res.sendRedirect("index.jsp");
    }
}


We don't need web.xml configuration as we are using servlet 3.0. So, once you done coding you can go ahead and deploy the project on the server and hit the below url on your browser.

http://localhost:8080/HelloWorld/Demo

As soon as we hit the url first of all the Demo servlet is going to be invoked. Now, Demo servlet is calling the testing servlet using sendRedirect method in it. Therefore, testing servlet is going to be invoked in next step. Again this servlet also has sendRedirect method in it and that is calling the google homepage so, finally the page is going to be redirected to the google home page.
Note: In the end result the browser url is going to be changed to the google url.

No comments:

Post a Comment