问题
I have noticed some problem when performing server side servlet validation given the form, i need to validate the firstname text field
<form action="Test" method="POST">
<input type="text" name="firstname" />
<input type="submit" value="submit" />
</form>
Servlet validation code that does not work for me. it always see firstname with length=0 not null
if(request.getParameter("firstname")==null)
{
out.println("Error");
}`
but after modifying the form adding enctype="multipart/form-data" to be
<form action="Test" method="POST" enctype="multipart/form-data" >
<input type="text" name="firstname" />
<input type="submit" value="submit" />
</form>
the validation code works ,,,
the question here is what is the function of enctype="multipart/form-data" ?
also
why request.getParameter("firstname") doesnot return null for empty field ? it returns empty string
回答1:
if(request.getParameter("firstname")==null)
This checks if the reference of the String points to null, which is not what you want to do I guess. If you want to check for an empty String, do:
if(request.getParameter("firstname")==null
|| request.getParameter("firstname").isEmpty())
When using enctype="multipart/form-data", all parameters are encoded in the request body. That means that request.getParameter(...) will return null for all posted parameters then.
来源:https://stackoverflow.com/questions/16398374/java-servlet-validation-confused