HTML Segment:
<form method="post" action="<%=request.getContextPath()%>/servlet/ObtainCheckedValueServlet"> What are your favorite colors?<br /> <input type="checkbox" name="color" value="COLOR01" /> Red<br /> <input type="checkbox" name="color" value="COLOR02" /> Blue<br /> <input type="checkbox" name="color" value="COLOR03" /> Green<br /> <input type="submit" value="submit" /> </form>
Java Servlet Segment:
// Obtain checked values (available values here are COLOR01,
// COLOR02, and COLOR03) of HTML checkboxes by the method
// String[] request.getParameterValues(String), which obtains all
// values of request parameters with the same specified name.
// Note that this method will return null if no parameter with the
// specified name exists. No parameter with the specified name
// exists if no checkbox is checked. Thus, the method will return
// null if no checkbox is checked.
String[] checked_values = request.getParameterValues("color");
if (checked_values != null)
{
// Display all obtained checked values
for (int i = 0; i < checked_values.length ; i++)
{
System.out.println("checked_values[" + i + "]: " + checked_values[i]);
}
}