SendRedirect In Servlet


The sendRedirect() ways of HttpServletResponse interface may be used to redirect reaction to any other resource, it is able to be servlet, jsp or html file.

It accepts relative in addition to absolute URL.

It works at the client side as it makes use of the url bar of the browser to make any other request. So, it may be paintings outside and inside the server.

Differentiate between forward() and sendRedirect() Ways:

There are many variations among the forward() technique of RequestDispatcher and sendRedirect() technique of HttpServletResponse interface. And the difference is given below:

forward() method

sendRedirect() method

The forward() way works at the server side.

The sendRedirect() way makes efforts at the client side.

It sends the identical appeal and reply objects to another servlet.

It always forward a new request.

It can work inside the server only.

It can be used inside and outside the server.

Example: request.getRequestDispacher("servlet2").forward(request,response);

Example: response.sendRedirect("servle

Syntax of SendRequest() method

public void sendRedirect(String URL)throws IOException;

Example of SendRedirect() method


Here, is the full example of SendRedirect way in Servlet

In this example, we're redirecting the request to the google server. Notice that sendRedirect technique works at the client side, this is why we can send our request anywhere. We can ship our request inside and out of the server.


import java.io.*;  
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

We are using sendDirect method to send Request to Google Server with the request Data, in this Example.


<!DOCTYPE html>  
<meta charset="ISO-8859-1">  
<title>sendRedirect example</title>  

<form action="MySearcher">  
<input type="text" name="name">  
<input type="submit" value="Google Search">  


import java.io.IOException;  
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");