Validating User Input Using JSTL Actions
Besides adding validation, let’s make the input form example a bit more realistic. Instead of just echoing the entered values at the end of the page, we use them to set the initial values of the form fields. This makes it easier for the user to correct the mistakes. For each invalid value, an error message is also inserted above the incorrect field.
I use a number of JSTL actions that we have not discussed so far and a few tricks to implement these changes. To make all the new stuff easier to digest, we look at the new page in pieces. Example 8-5 shows the top part of the form with the validation and initialization of the Name field.
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>User Info Entry Form</title>
</head>
<body bgcolor="white">
<form action="validate_jstl.jsp" method="post">
<input type="hidden" name="submitted" value="true">
<table>
<c:if test="${param.submitted && empty param.userName}">
<tr><td></td>
<td colspan="2"><font color="red">
Please enter your Name
</font></td></tr>
</c:if>
<tr>
<td>Name:</td>
<td>
<input type="text" name="userName"
value="<c:out value="${param.userName}" />">
</td>
</tr>The first thing to notice in this example is the HTML field of type
"hidden“, named submitted with
the value true. The browser doesn’t display a hidden field, but its value is sent as a regular ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access