I am creating a jsp page to test a validator servlet for a uni assessment.
I am new to jsp so I just want to know how to make sure the field is empty on the first page load.
The idea is that when the form is submitted it is sent to a servlet that checks if the fields are empty or not (they have value entered by the user) and redirects them back to the form with error messages, if they are empty.
So here is a snippet of what my jsp fields look like:
<td class="formlabel">Name:</td>
<td><input type="text" size="27" id="name" name="name" value="<%= session.getAttribute("name")%>" /></td>
<%
if((String)session.getAttribute("name") == "") {
%>
<span class="error">No name entered</span>
<%
}
%>
but currently the problem I am getting is that the session attribute is null. So null comes up in the input field. I don’t want this for the first jsp load, I just want it to be blank. How do I do this?
You can check the value by simply breaking:
value="<%= session.getAttribute("name")%>into into a few statements:
But in general, instead of validating many fields, I would suggest adding another hidden input parameter to the form with id=”submitted” and value=”Y”:
then add a line that checks for this POST/GET parameter:
and change the if condition to:
Remark:
String comparison (in Java) should be done using
equals()– not with==