Now let us see how to use sendRedirect() method. The sendRedirect(String URL) is defined in javax.servlet.http.HttpServletResponse interface.
Let us see what Java API says about sendRedirect() method signature:
- void sendRedirect(String location) throws IOException: Sends a temporary redirect response to the client using the specified redirect location URL. This method can accept relative URLs; the Servlet container must convert the relative URL to an absolute URL before sending the response to the client. If the location is relative without a leading ‘/’ the container interprets it as relative to the current request URI. If the location is relative with a leading ‘/’ the container interprets it as relative to the Servlet container root.
When to use sendRedirect() method?
- When a Servlet Programmer would like to redirect the client request to another Web site on a different server. The client request cannot be fulfilled by the current Servlet and the programmer may like to send the client request another web site.
- To redirect the errors to another resource (like Servlet or JSP). It is to accumulate the errors raised on compilation or execution to be seen by Team Lead for solutions or other members of the team.
- To send any HTML form existing on the server to client (like sending a Railway reservation form when user wants to book a ticket in Railway site). Remember, this is a static form which already existing on the server.
More properties information of sendRedirect() is given in Difference between forward and sendRedirect Methods.
It is the modification of the first program Login Validation. The modification is instead of sending INVALID message, a new HTML form is sent to the user wherein the user can fill up again and send. This HTML form is existing already on the server. It is not created on the fly. That is why, I called it as a static form.
Example on sendRedirect() Method
Client Program: File Name: UserPass.html
<h2 align="center">Login Validation</h2>
<form method="get" action="http://localhost:8888/india/roses">
Enter User Name <input type="text" name="t1"> <br>
Enter Password <input type="text" name="t2"> <br>
<input type="submit" value="SEND">
<input type="reset" value="CLEAR">
Servlet Program: File Name: Validation.java
public class Validation extends HttpServlet
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
PrintWriter out = res.getWriter();
String str1 = req.getParameter("t1");
String str2 = req.getParameter("t2");
if(str1.equals("snrao") && str2.equals("java"))
sendRedirect(String) is a method of HttpServletResponse which is capable of sending a file to the client passed as a string parameter.
When user name and password are given correct
the response screen is
When the password is given wrong as hereunder,
the following fresh (new) form is sent.