sendRedirect() Example Servlets – Send HTML form to Client

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


Login Validation

Enter User Name
Enter Password

Servlet Program: File Name: Validation.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class Validation extends HttpServlet
{
  public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  {
    res.setContentType("text/html");  
    PrintWriter out = res.getWriter();
                                            
    String str1 = req.getParameter("t1");
    String str2 = req.getParameter("t2");
                                            
    if(str1.equals("snrao") && str2.equals("java"))
    {
      out.println("VALID");
    }
    else
    {
      res.sendRedirect("UserPass.html");               // observe, usage of sendRedirect()
    }
    out.close();
  }
}

res.sendRedirect("UserPass.html");

sendRedirect(String) is a method of HttpServletResponse which is capable of sending a file to the client passed as a string parameter.

Following is the method signature as defined HttpServletResponse interface.

public abstract void sendRedirect(java.lang.String) throws java.io.IOException;

Note: sendRedirect() is not a method of ServletResponse.

When user name and password are given correct

ima

the response screen is

sendRedirect()

When the password is given wrong as hereunder,

sendRedirect()

the following fresh (new) form is sent.

sendRedirect()

Leave a Comment

Your email address will not be published.