Way2Java

Send Dynamically created HTML form to client in Servlets

In this example, a dynamically created HTML form is sent to the client on-the-fly. Start reading.

his is the modified code of the Login Screen Validation. In the first program, the user name and password are read by the Servlet, validated and sent back the result of validation (valid or invalid) as response.

The modification is, whichever field is wrong, that field is sent empty and which field is correct, that is filled and sent. That is both user name and password are to be validated separately and as per the validation, a HTML form is generated dynamically (on-the-fly) and sent to the client. This is like creating a new email account.

We know earlier in the first program, whatever is placed in out.println() method goes to client. Now in out.println(), the whole HTML file is placed and sent to the client. The browser on the client takes HTML and displays the form.

Example on Dynamically created HTML form


Login Validation

Enter User Name
Enter Password

In the HTML, there is nothing new. Following is the web.xml entry for the servlet.


  dhfg
  DynamicHTMLFormGeneration



  dhfg
  /dynamicgeneration

Following is the servlet program.

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

public class DynamicHTMLFormGeneration 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("");   // Dynamically created HTML form is started
      out.println("

VALID

"); } else // here comes separate validation { out.println("

Login Validation

"); out.println("
"); if( str1.equals("snrao") ) { out.println("Enter User Name
"); } else { out.println("Enter User Name
"); } if( str2.equals("java") ) { out.println("Enter Password
"); } else { out.println("Enter Password
"); } out.println(""); out.println("
"); } out.close(); } }

When both fields are given correct values as follows

the response screen is

When password is given wrong as follows

the response screen is

Observe, the password field is empty (not filled).
If you give both fields wrong, both fields will be empty; try.

This is how a Dynamically created HTML form is sent to client on-the-fly.