The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file.

It accepts relative as well as absolute URL.

It works at client side because it uses the url bar of the browser to make another request. So, it can work inside and outside the server.

Difference between forward() and sendRedirect() method

There are many differences between the forward() method of RequestDispatcher and sendRedirect() method of HttpServletResponse interface. They are given below:

forward() method sendRedirect() method
The forward() method works at server side. The sendRedirect() method works at client side.
It sends the same request and response objects to another servlet. It always sends a new request.
It can work within the server only. It can be used within and outside the server.
Example: request.getRequestDispacher(“servlet2”).forward(request,response); Example: response.sendRedirect(“servlet2”);

Syntax of sendRedirect() method

public void sendRedirect(String URL)throws IOException;

Example of sendRedirect() method


Full example of sendRedirect method in servlet

In this example, we are redirecting the request to the google server. Notice that sendRedirect method works at client side, that is why we can our request to anywhere. We can send our request within and outside the server.
import javax.servlet.*;  
import javax.servlet.http.*;  
public class DemoServlet extends HttpServlet{  
public void doGet(HttpServletRequest req,HttpServletResponse res)  
throws ServletException,IOException  
PrintWriter pw=res.getWriter();  

Creating custom google search using sendRedirect

In this example, we are using sendRedirect method to send request to google server with the request data.

sendRedirect example

import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
public class MySearcher extends HttpServlet {  
    protected void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        String name=request.getParameter("name");  


sendredirect in servlet example 1
sendredirect in servlet example 2