Using Forms to Obtain a User's Input

After showing a Web page, the servlet must be able to obtain the user's input in order to process the next servlet request. This is usually done using forms, which can display window controls such as text fields or push buttons. When the user performs the action associated with the form (usually a push button), the servlet is called again with this action and input parameters taken from text fields, check boxes and other input controls.
Figure 1. Example of a Servlet Using Forms to Obtain a User's Input
 out.println("<form action=\"/servlet/FlightOrderingServlet\" method=get>");  1 
 out.println("<input type=hidden name=\"action\" value=\"order3\">");
 out.println("<input type=hidden name=\"flight\" value=\"" +
                                                      flightNumber + "\">");
 out.println("<table>");
 out.println("<tr><td><b>First Name:</b></td>");
 out.println("<td><input size=20 maxlength=20 name=\"firstname\"></td>");
 out.println("</tr>");

 out.println("<tr><td><b>Last Name:</b></td>");
 out.println("<td><input size=20 maxlength=20 name=\"lastname\"></td>");
 out.println("</tr>");
 ...

 out.println("<tr><td><b>Non smoking:</b></td>");
 out.println("<td><input type=checkbox name=\"nonsmoke\"
                                                value=\"yes\">Yes</td>");
 out.println("</tr>");
 out.println("</table><p>");
 out.println("<input type=submit value=\"Order It!\">");
 out.println("</form>");
Note: The string used here to perform a servlet call is dependent on the:
  • Version of the WebSphere Application Server you have installed.
  • Name you have defined for your servlet engine.
By specifying method=get (at  1 ), the doGet() method of the servlet will be called. However:
  • You could also specify method=post, which would cause the doPost() method to be called.
  • The difference between method=get and method=post is that:
    • Using doGet() will display the generated servlet invocation string in the Web browser's address/location field.
    • Using doPost() will suppress the Web browser's address/location field.
  • You are recommended to use doPost() if the form contains any password fields. Passwords will then appear as clear text, when using doGet().
The HTML code shown in Figure 1 will display the window controls shown below:
Figure 2. Example of Using Forms to Display Window Controls
An explanation of this figure is provided in the surrounding text.
If the user presses the push-button Order It!, this servlet invocation string will be generated:
 http://computername/servlet/FlightOrderingServlet?action=order3&flight=34
 &firstname=name1&lastname=name2&seats=1&nonsmoke=no
where:
  • name1 is the string that was entered in the firstname field.
  • name2 is the string that was entered in the lastname field.
  • computername is the name of your workstation in your network, or its IP address.
You could also enter this string manually in your Web browser's address/location field.