The JSP Files (part 4): The Red Pill - Beating It Into Submission
(Page 9 of 9 )
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.
Since the ACTION attribute of the
|
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |