<INPUT TYPE="RADIO"Modified JSP code fragment:
NAME="#"
VALUE="#">
red <BR>
<INPUT TYPE="RADIO"
NAME="#"
VALUE="#">
blue <BR>
<INPUT TYPE="RADIO"
NAME="#"
VALUE="#">
green <BR>
<INPUT TYPE="RADIO"Unfortunately radio buttons (and checkboxes) require some special handling because if nothing is selected when the form is submitted to the servlet, the parameter will return null, and the equals() method will not work on null. Rather than put ugly null-checking code into the jsp, the preferred way to handle this is to code the model accessors like this:
NAME="favoriteColor"
VALUE="red"
<%= userModel.getFavoriteColor().equals("red") ? "CHECKED" : "" %>>
red <BR>
<INPUT TYPE="RADIO"
NAME="favoriteColor"
VALUE="blue"
<%= userModel.getFavoriteColor().equals("blue") ? "CHECKED" : "" %>>
blue <BR>
<INPUT TYPE="RADIO"
NAME="favoriteColor"
VALUE="green"
<%= userModel.getFavoriteColor().equals("green") ? "CHECKED" : "" %>>
green <BR>
/**
* Set the favorite color to the given color.
* If the given color is null, set the favorite color to an
empty string.
**/
public void setFavoriteColor(String color) {
if (color == null) {
this.favoriteColor =
"";
} else {
this.favoriteColor =
color;
}
}
public void validateFavoriteColor() throws ValidationFailedException
{
if (this.favoriteColor.equals("")) {
throw new ValidationFailedException("You
must select a favorite color.");
}
}
<SELECT NAME="#">Modified JSP code fragment:
<OPTION> 2000
<OPTION> 2001
<OPTION> 2002
<OPTION> 2003
</SELECT>
<SELECT NAME="yearOfExpiry">
<OPTION <%= paymentModel.getYearOfExpiry().equals("2000") ? "SELECTED" : "" %>> 2000
<OPTION <%= paymentModel.getYearOfExpiry().equals("2001") ? "SELECTED" : "" %>> 2001
<OPTION <%= paymentModel.getYearOfExpiry().equals("2002") ? "SELECTED" : "" %>> 2002
<OPTION <%= paymentModel.getYearOfExpiry().equals("2003") ? "SELECTED" : "" %>> 2003
</SELECT>