my form has several checkboxes on it (around 15) and the issue im having is that the names of the check boxes only appear in the enumeration if they are checked but i want all of them to be returned so that when i print the data it will have the name of the checkbox and say "checked" or "unchecked". i had thought of one way that i could just manually set the flag to see what is present and what isnt, but that doesnt seem remotely efficient.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
FileWriter writer = new FileWriter("OrderFormData.csv");
writer.append("FieldName");
writer.append(',');
writer.append("Value");
writer.append('\n');
@SuppressWarnings("unchecked")
Enumeration <String> paramNames = request.getParameterNames();
while(paramNames.hasMoreElements())
{
String paramName = (String)paramNames.nextElement();
writer.append(paramName);
writer.append(',');
String[] paramValues = request.getParameterValues(paramName);
if (paramValues.length == 1)
{
String paramValue = paramValues[0];
if (paramValue.length() == 0)
{
writer.append("No Value");
writer.append('\n');
}
else
{
writer.append(paramValue);
writer.append('\n');
}
}
else
{
for(int i = 0; i<paramValues.length; i++)
{
writer.append(paramValues[i]);
writer.append(',');
}
writer.append('\n');
}
}
writer.flush();
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
You can use hidden fields together with checkboxes. Iterate through them and check the presence of checkbox selection.
And at the server side do something like this:
unchecked boxes won't be part of the request: see http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.2
Create hidden fields as
<input type="checkbox" name="checkbox" checked/> <input type="hidden" name="checkbox" checked />
Now in your servlet as: String[] names = request.getParameterValues("checkbox");
You should think in a workaround because as @Alex told you, unchecked checkboxes are not part of the request.
This is just an idea, but for example:
Then, you can get
checkboxNamesList
from the request (it will be a String[]) so you will have all the checkboxes params names. If you get a parameter for one of the checkboxes name and value is null, it means that checkboxe was not checked.Edited: clarification
Well, as unchecked checkboxes are not present in the request you don't know whose checkboxes in the JSP were not checked but you need to know it in order to write in your data file something like checkbox_name1=unchecked.
So, how to do that? First, you need to know what checkboxes (uncheck or not) were present in the request. For that, you can use the code below and get name of all checkboxes present in the JSP:
Then, let look for unchecked checboxes: