Sunday, 18 February 2018

Introduction to sendRedirect() Method

Introduction to sendRedirect() Method,Full example of sendRedirect method in servlet,how sendRedirect() method works,

sendRedirect() method redirects the response to another resource. This method actually makes the client(browser) to create a new request to get to the resource. The client can see the new url in the browser.
sendRedirect() accepts relative URL, so it can go for resources inside or outside the server.
sendRedirect and requestDispaching
The main difference between a redirection and a request dispatching is that, redirection makes the client(browser) create a new request to get to the resource, the user can see the new URL while request dispatch get the resource in same request and URL does not changes.
Also, another very important difference is that, sendRedirect() works on response object while request dispatch work on request object.

Difference between forward() and sendRedirect() method

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");

Let's see the Example of sendRedirect() method.

SendRedirectServlet.java
create a package with name "com.dashzin" and write your class with corresponding code. when you will run this code, controle will get redirected to "https://dashzin.blogspot.in/".

package com.dashzin;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/SendRedirectServlet")
public class SendRedirectServlet extends HttpServlet {
   public void service(HttpServletRequest req,HttpServletResponse res)throws IOException{
        res.setContentType("text/html");
        PrintWriter out=res.getWriter();
       
        res.sendRedirect("https://dashzin.blogspot.in");
       
   }
}










DashZin

Author & Editor

Has laoreet percipitur ad. Vide interesset in mei, no his legimus verterem. Et nostrum imperdiet appellantur usu, mnesarchum referrentur id vim.

3 comments: