Now that the basics are done with, it's time to begin applyingthat theory to Web development. This week, The JSP Files investigates theJSP Request object, and demonstrates how it can be used to process formdata. Learn about JSP's array variables, find out what chocolate chipcookies and couch potatoes have in common, and explore a very unusualpharmacy.
You'll have noticed that in all the examples we've shown you thus far, we've used two pages - a single HTML page containing the form, and a separate JSP script which processes the form input and generates appropriate output. However, JSP provides an elegant method to combine those two pages into one via the form's SUBMIT button.
You've already seen that once a form is submitted to a JSP script, all the form variables become available to JSP. Now, in addition to the user-defined variables, each time you hit the SUBMIT button on a form, a variable named "submit" is created. And by testing for the presence or absence of this variable, a clever JSP developer can use a single JSP document to generate both the initial form and the output after it has been submitted.
The following code snippet demonstrates how the "welcome to The Matrix" example above could be rewritten using this technique.
<html>
<head>
<basefont face="Arial">
</head>
<body>
<center>
<%
// matrix.jsp
// check for submit variable
String submit = request.getParameter("submit");
if(submit != null)
{
// form has been submitted, display result
// define the variables used in the scriptlet
String fname;
// assign values
fname = request.getParameter("name");
// print the details
out.println("Welcome to The Matrix, " + fname + "!");
}
else
{
// display initial form
%>
<form method="GET" action="matrix.jsp">
<table cellspacing="5" cellpadding="5" border="0">
<tr>
<td>
<font size="-1">Name, rank and serial, number, soldier!</font>
</td>
<td align="left">
<input type="text" name="name" size="10">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input name="submit" type="submit">
</td>
</tr>
</table>
</form>
<%
}
%>
</center>
</body>
</html>
As you can see, the script first tests for the presence of the "submit" variable - if it doesn't find it, it assumes that the form has yet to be submitted and so displays the initial form.