【问题标题】:How to send an object as check-box value from the checked row to Struts 2 action如何将对象作为复选框值从选中的行发送到 Struts 2 操作
【发布时间】:2014-01-08 20:31:15
【问题描述】:

在我的 JSP 页面中,我显示了具有 idnameemail 字段的人员列表,如下所示:

<s:iterator value="peopleList">
<tr>
    <td><input type="checkbox" name="checkedId"  value="<s:property value="id"/>" /></td>
    <td><s:property value="id"/></td>
    <td><s:property value="firstName"/></td>
    <td><s:property value="lastName"/></td>
    <td><s:property value="email"/></td>                        
</tr>
</s:iterator>

我的动作类如下:

    private String[] checkedId;
    private List<People> peopleList;
    PeopleDao peopleDao = new PeopleDaoImpl();
    People people = new People();
    private List<People> checkBoxList = new ArrayList<People>();

 public String checkBox(){      

     System.out.println("Hello");
        for(String p: checkedId){
        System.out.println(p);
        }
         return SUCCESS;
    }

目前我正在发送一个id 作为复选框值并在操作类中将它们打印出来。这工作正常,但我想要的是发送idnames 和电子邮件的整个选中行作为People 类型的对象作为复选框值,以将其存储在checkBoxList 中。我如何做到这一点?

我尝试在迭代器中添加var="list" 并使用“列表”作为name="checkBoxList" 复选框的值,但没有成功。

【问题讨论】:

标签: java jsp checkbox struts2


【解决方案1】:

您可以在提交表单数据时使用索引属性名称。

<s:iterator value="peopleList" status="st">
<tr>
    <td><s:checkbox name="checkBoxList[%{#st.index}].checkedId"  value="%{id}" /></td>
    <td><s:textfield name="checkBoxList[%{#st.index}].id"/></td>
    <td><s:property value="checkBoxList[%{#st.index}].firstName"/></td>
    <td><s:property value="checkBoxList[%{#st.index}].lastName"/></td>
    <td><s:property value="checkBoxList[%{#st.index}].email"/></td>                        
</tr>
</s:iterator> 

【讨论】:

    【解决方案2】:

    在您的 html 中,将所有其他属性的值保留为表单中的隐藏输入标签,以便在用户提交表单时,您可以获取代码中的所有属性。

    <form id="peopleSelect" action="updateSelectedPpl.action">
    <s:iterator value="peopleList">
    <tr>
        <td><input type="checkbox" name="checkedId"  value="<s:property value="id"/>" /></td>
        <td><input type="hidden" name="firstNames"  value="<s:property value="firstName"/>" /><s:property value="firstName"/></td>
        <!-- do the same for all the others -->
        <td><s:property value="id"/></td>
        <td><s:property value="lastName"/></td>
        <td><s:property value="email"/></td>                        
    </tr>
    </s:iterator>
    </form>
    

    你的动作类代码可以是这样的。确保你的动作类实现了 ServletRequestAware

    String[] checkedIds = request.getParameterValues("checkedId");
    String[] firstNames = request.getParameterValues("firstnames");
    
    for(int i=0; i<checkedIds.size; i++){
      //get all the other attributes and populate your pojo here.
      firstName = firstNames[i];
    
    }
    

    【讨论】:

    • 我想知道的是是否可以发送一个对象,而不必分别发送它的字段,如 id、名称
    • 是的,您可以使用 ModelDriven 做到这一点。有关更多详细信息,请参阅此答案stackoverflow.com/a/13031499/728610
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 2021-10-25
    相关资源
    最近更新 更多