How to retrieve checkbox values in Struts 2 action class ?
I have dynamic number of checkboxes in jsp page as given below.
<s:iterator value="details" status="stat">
<s:checkbox name="checkbox" theme="simple" />
<s:hidden name="hidden" value="%{top}" />
</s:iterator>
Let's say 4 checkboxes.
and setter in action class is
public void setCheckbox(boolean s[])
{
System.out.println(s.length);
}
If I don't select any checkbox, s.length
is zero.
If I select 3rd checkbox, s.lenght
is 1 and it is initializing s[0]
with true
.
But problem is here how can I find whether 3rd checkbox is selected or another checkbox is selected.
I thought that setter would initialize s[]={false,false,true,false}
, if I select third checkbox. But it is initializing s[]={true}
.
Corresponding hidden values of those selected boxes are required to perform required action in database. But for that I need to find select checkboxes.
Please sug开发者_开发问答gest me any solution.Because your checkboxes are all named the same (checkbox
), Struts2 is just passing the following:
checkbox=true&checkbox=true&checkbox=true
Does that mean that you omitted the second, third, or fourth checkbox?
What you actually want is not an array of booleans, but a map of Integer to Boolean. Here's an example:
Example Action
public class MyAction extends ActionSupport {
private Map<Integer, Boolean> checkboxes;
...
public Map<Integer, Boolean> getCheckboxes() {
return checkboxes;
}
public void setCheckboxes(Map<Integer, Boolean> checkboxes) {
this.checkboxes = checkboxes;
}
}
Example JSP
<s:iterator value="details" status="stat">
<%-- this outputs checkboxes[0], checkboxes[1], etc. --%>
<s:checkbox name="checkboxes[%{#stat.index}]" theme="simple" />
</s:iterator>
Example Result
- 0 -> true
- 1 -> false
- 2 -> true
- 3 -> true
Actually I use Struts 2 3.8 and WebSphere 7.0 and Map works for rendering the check boxes, but not working when these check boxes post back. The Boolean class is rendered correctly, but during the post back in Struts 2, it becomes ognl.NoConversionPossible
and ends up with No result defined for action CLASS ...and result input
error.
I replaced Boolean with String class, i.e.
maps.put(new Integer(0), new String("true"));
and it works for me.
精彩评论