Working with HTML Form – Part 2

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.

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 itThen 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.

  • Was this tutorial helpful ?
  • YesNo