When dealing with HTML, you have multiple ways to separate the code to handle the form data and HTML form itself. These are the most two common ways to do so:
- Page which contains HTML Form and JSP page which handles HTML Form are separated. (as you see in the previous tutorial)
- Single JSP page to display form and handle form.
In order to do it in the second way, we need to add an additional hidden field in the HTML form. When user submits the form data, we check the value of this hidden field to see whether the form is submitted or not. Let’s take a look at the code below.
<html>
<head>
<title>JSP Form Demo</title>
<style type="text/css">
label{ margin-right:20px;}
input{ margin-top:5px;}
</style>
</head>
<body>
<%
String val = request.getParameter("isSubmitted");
int isSubmitted = 0;
if (val != null) {
isSubmitted = Integer.parseInt(val);
if (isSubmitted == 1) {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String email = request.getParameter("email");
out.println("<p>Hi " +
firstName + " " +
lastName + "!,
your submitted email is " + email +"</p>");
}
}
%>
<% if (isSubmitted == 0) {%>
<form action="index.jsp" method="post">
<fieldset>
<legend>User Information</legend>
<label for="fistName">First Name</label>
<input type="text" name="firstName" /> <br/>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" /> <br/>
<label for="email">Email</label>
<input type="text" name="email" /> <br/>
<input type="hidden" name="isSubmitted" value="1" />
<input type="submit" value="submit">
</fieldset>
</form>
<%}%>
</body>
</html>
Code language: JavaScript (javascript)
The first thing you can realize that the action of the Form now is pointed to the page which form is embedded or index.jsp page. Second the logic of processing form data and displaying form are in a single JSP page. The sequence of events occurs as follows.
- At the first time when the page is loaded, the code checks for the form field name isSubmitted. Because getParameter will return null so the isSubmitted variable is set to 0 and the code displays the Form.
- When user submits the form, there is a hidden field called isSubmitted with the value 1 available ion the form. Therefore at this time the parameter isSubmitted is available. The code still checks for the parameter isSubmitted and find it. Then the process of collecting data and printing them out occurs as normal but no Form is output after the post back.
One of the most important thing to keep in mind when you deal with form is that: Never trust data which is submitted from client side. You can do client validation for simple validation such as required field, email is in the correct format in by using JavaScript. In the server side, you can do simple validation also after collecting the data, plus business validation to validate the constraints among data you collected.