logo

SendRedirect In Servlet


Show

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

response.sendRedirect("http://intellinuts.com/");

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.

Demo.Servlet.java

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  
{  
res.setContentType("text/html");  
PrintWriter pw=res.getWriter();  

response.sendRedirect("http://www.google.com");   
pw.close();  
}}  

Creating custom google search using sendRedirect

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

Index.html

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

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

MySearcher.java

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");  
        response.sendRedirect("https://www.google.co.in/#q="+name);  
    }  
}