Working with HTML Form

HTML form basically is a graphic user interface (GUI) which you present to get the input data from users. Once users submit the form from the client side, on the server side, you need to capture those data for further processing such as business logic validation, saving the data into the database and so on.

Let’s start with a simple HTML form which getting user information.

<html> <head> <title>JSP Form Demo</title> <style type="text/css"> label{ margin-right:20px;} input{ margin-top:5px;} </style> </head> <body> <form action="handleUserInfo.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="submit" value="submit"> </fieldset> </form> </body> </html>
Code language: HTML, XML (xml)

The form is very simple which contains three fields: first name, last name, and email. In addition, It contains the submit button which users can submit when he/she finish entering the data.

In the form tag, you can see it uses the post method to post the form data to the server. We need to create a JSP file that is responsible for getting and processing the form’s data.

The following is the handleUserInfo.jsp form:

<html> <head> <title>JSP Form Demo</title> </head> <body> <% String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String email = request.getParameter("email"); %> <p>Hi <%=firstName%> <%=lastName%>!, your submitted email is <%=email%>.</p> </body> </html>
Code language: HTML, XML (xml)

We use the request object to get the form data. The getParameter() method of request object accepts the name of the form field and return field value. The returned value of the getParameter() method is always string type therefore if you have a form field that accepts the numerical value, you have to convert it.

If no form field found, the getParameter() method returns null.  After getting the values from the form, the handleUserInfo.jsp uses those values to display a message.

In this tutorial, we have shown you how to use the request object to get the data from an HTML form. The code of the HTML form and the JSP page that handles the form are in separate files. In the next tutorial, you will learn how to handle HTML form inside a single JSP page.