This example shows how to modify jsp code which includes radio buttons and select drop down menus.

Radio Buttons

Original JSP code fragment from web developer:
<INPUT TYPE="RADIO"
       NAME="#"
       VALUE="#">
       red <BR>
<INPUT TYPE="RADIO"
       NAME="#"
       VALUE="#">
       blue <BR>
<INPUT TYPE="RADIO"
       NAME="#"
       VALUE="#">
       green <BR>
Modified JSP code fragment:
<INPUT TYPE="RADIO"
       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>
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:

/**
 * 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 Drop Down Menus

Original JSP code fragment from web developer:
<SELECT NAME="#">
<OPTION> 2000
<OPTION> 2001
<OPTION> 2002
<OPTION> 2003
</SELECT>
Modified JSP code fragment:
<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>

Version History

0.3, July 19, 2000.  Fixed some bogus html formatting to make it more realistic, put in hash marks for variable names.
0.2, July 18, 2000.  Added explanation of model differences due to possibility of nulls in radio buttons.
0.1, July 17, 2000.