如何检索 Struts 2 动作类中的复选框值? [英] How to retrieve checkbox values in Struts 2 action class ?

查看:22
本文介绍了如何检索 Struts 2 动作类中的复选框值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 jsp 页面中有动态数量的复选框,如下所示.

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>

假设有 4 个复选框.

Let's say 4 checkboxes.

动作类中的setter是

and setter in action class is

public void setCheckbox(boolean s[])
{
    System.out.println(s.length);
}

如果我不选择任何复选框,s.length 为零.如果我选择第三个复选框,s.lenght 为 1,它正在使用 true 初始化 s[0].但问题是我如何才能找到第三个复选框被选中还是另一个复选框被选中.

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.

如果我选择第三个复选框,我认为 setter 会初始化 s[]={false,false,true,false}.但它正在初始化 s[]={true}.

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 suggest me any solution.

推荐答案

因为你的复选框都命名相同(checkbox),Struts2 只是传递了以下内容:

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:

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;
  }
}

示例 JSP

<s:iterator value="details" status="stat">
  <%-- this outputs checkboxes[0], checkboxes[1], etc. --%>
  <s:checkbox name="checkboxes[%{#stat.index}]"  theme="simple" />
</s:iterator>

示例结果

  • 0 -> 真
  • 1 -> 错误
  • 2 -> 真
  • 3 -> 真
  • 这篇关于如何检索 Struts 2 动作类中的复选框值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆