Servlet SendRedirect

In this tutorial you will learn about the Servlet SendRedirect and its application with practical example.

SendRedirect in Servlet

The word send redirect saying everything that this method is used to redirect the response to another resources such as jsp, servlet, html file. This method can accept relative URL as well as absolute URL. This is the method of HttpServletResponse interface.

When to use sendRedirect() method:

  • For the redirection of client request to another Website.
  • For the redirection of errors to another resources such as servlet , JSP or Html file.
  • For sending any existing HTML form on the server to client.

Difference Between forward() and sendRedirect() method

These two methods are commonly used to send the request to another resources but there are some difference between both method. Which are given below.

  1. forward() method execute at server side but sendRedirect() method execute at client side.
  2. forward() method is used to sends the same request and response to another resources but sendRedirect() method sends always new request.
  3. forward() method can transfer the resources only within server but sendRedirect() method can transfer the resources within and outside the server.
  4. forward() method consume only one call but sendRedirect() consume Two request and response calls.
  1. We can not see forwarded message but we can see redirected address.
  2. The forward() method is faster than sendRedirect().

Syntax:-

Example:-

Let’s understand it by an simple example. The required files are.

welcome.html :-

Using this file we will send the request to servlet.

SearchDemo.java :-

This is the servlet file where we have used sendRedirect() method. Check below code.

Recommended:-  Servlet ServletConfig

Output :-

Check below Images for output of this sample code.

Recommended:-  Servlet Cookie Example

This is the output of welcome.html file, it will send request to servlet on click of Search button.

image001

Below image is the output of sendRedirect() method of Servlet

image003

 

 

In this tutorial we have learn about the Servlet SendRedirect and its application with practical example. I hope you will like this tutorial.