In Struts 2 , you can create multiple checkboxes with a same name via <s:checkboxlist> tag. The tricky part is how to set the default value in the multiple checkboxes. For example, a list of checkboxes with “red”, “yellow”, “blue”, “green” options, and you want to set both “red” and “green” as the default checked values.

1. <s:checkboxlist> example

A <s:checkboxlist> example

<s:checkboxlist label="What's your favor color" list="colors" name="yourColor" />

Resulting the following HTML code

<td class="tdLabel"><label for="resultAction_yourColor" class="label">
What's your favor color:</label>
</td> 
<td > 
<input type="checkbox" name="yourColor" value="red" id="yourColor-1" /> 
<label for="yourColor-1" class="checkboxLabel">red</label> 
<input type="checkbox" name="yourColor" value="yellow" id="yourColor-2" /> 
<label for="yourColor-2" class="checkboxLabel">yellow</label> 
<input type="checkbox" name="yourColor" value="blue" id="yourColor-3" /> 
<label for="yourColor-3" class="checkboxLabel">blue</label> 
<input type="checkbox" name="yourColor" value="green" id="yourColor-4" /> 
<label for="yourColor-4" class="checkboxLabel">green</label> 
<input type="hidden" id="__multiselect_resultAction_yourColor" 
 name="__multiselect_yourColor" value="" />     
</td>

Action class to provide a list of the color options to the checkboxes.

//...
public class CheckBoxListAction extends ActionSupport{
 
	private List<String> colors;
	private String yourColor;
 
	public CheckBoxListAction(){
 
		colors = new ArrayList<String>();
		colors.add("red");
		colors.add("yellow");
		colors.add("blue");
		colors.add("green");
	}
 
	public List<String> getColors() {
		return colors;
	}
	//...
}

2. Single default checked value

To set the “red” option as the default checked value, just add a method in the Action class and return a “red” value.

//...
public class CheckBoxListAction extends ActionSupport{
 
	//add a new method
	public String getDefaultColor(){
		return "red";
	}
}

In the <s:checkboxlist> tag, add a value attribute and point to the getDefaultColor() method.

<s:checkboxlist label="What's your favor color" list="colors" 
     name="yourColor" value="defaultColor" />
Struts 2 is intelligent enough to match the “defaultColor” value to the correspond Java property getDefaultColor().

Run it again, the “red” option will checked by default.

2. Multiple default checked values

To set multiple values “red” and “green” as the default checked value, just return a “String []” instead of a “String”, Struts 2 will match it accordingly.

//...
public class CheckBoxListAction extends ActionSupport{
 
	//now return a String[]
	public String[] getDefaultColor(){
		return new String [] {"red", "green"};
	}
}
<s:checkboxlist label="What's your favor color" list="colors" 
     name="yourColor" value="defaultColor" />

Run it again, the “red” and “green” options will be checked by default.

Note : You can find more similar articles at - Struts 2.x Tutorials