How to validate the name of a hidden form field that is not present in an HTML form using servlet
I have two HTML forms that have a Hidden Field tag and the other has no tag. When validating the first HTML form containing a hidden field tag, I can validate in the servlet by getting the name and value of the field. example as below,
HTML form with hidden tag
<form action="/myServlet" method="post" enctype="multipart/form-data">
<input type="hidden" name="myname" value="myvalue"/>
<input type="file" name="file"/>
<input type="submit" value="Submit"/>
Servlet checking hidden field
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter;
iter = upload.getItemIterator(request);
while (iter.hasNext()) {
item = iter.next();
String fileName = item.getName();
String fieldName = item.getFieldName();
if (item.isFormField()) {
String fieldValue = Streams.asString(item.openStream());
if (fieldName.equals("myname")){ //validating Hidden form tag name
// some process goes here
}
}
With the above code, I can validate a hidden form field, but if I have an HTML form like below that does not have a hidden tag, then how do I handle my servlet for validation.
HTML form without hidden tag
<form action="/myServlet" method="post" enctype="multipart/form-data">
//No hidden tag
<input type="file" name="file"/>
<input type="submit" value="Submit"/>
I would like to check these various cases:
- Form with hidden field and some content in the request for the field: VALID
- Form with empty hidden field: INVALID
- Form without hidden field: VALID
The main problem is the difference between the last two cases.
source to share
If you just need to know if the myname attribute is present, you can set a flag to indicate this. Or store the value in a string that was initialized to zero.
boolean hasMyName = false;
while (iter.hasNext()) {
item = iter.next();
String fileName = item.getName();
String fieldName = item.getFieldName();
if (item.isFormField()) {
String fieldValue = Streams.asString(item.openStream());
if (fieldName.equals("myname")){ //validating Hidden form tag name
hasMyName = true;
}
}
if ( hasMyName ) {
// myname is present, do something
}
source to share
I haven't done this, but you can try:
-
Create a hidden field in your form in case you think it should exist. The name of the hint field is "myHiddenField".
-
Now try to see if there is any / w bit value of this field when trying to get it when:
and. He's gone.
b. It is empty.
Try to see if you have the ability to get some kind of distinction such as empty and empty. As I said, I haven't tried it myself. I may be wrong in my assumption here.
source to share