2012-03-29 50 views
1

我有一个关于Spring的问题,特别是MVC组件。我有一个包含以下代码的jsp页面。带有foreach的Spring MVC窗体

<form:form modelAttribute="sentenceModelAttribute" 
      method="POST" action="sentencemanagement.htm"> 
     <table class="activity">     
      <tr> 
      <th/> 
      <th>ID</th> 
      <th>Description</th> 
      <th>Action</th> 
      <th>Decision</th> 
      </tr> 

      <c:forEach items = "${model.allSentences}" var="sentence"> 
      <tr> 
      <td><form:radiobutton path="id" value="${sentence.id}"/></td> 
      <td>${sentence.id}</td> 
      <td>${sentence.description}</td> 
      <td>${sentence.action}</td> 
      <td>${sentence.decision}</td> 
      </tr> 
      </c:forEach> 

     </table> 
     <input type="submit" name="modify" value="Modify"/> 
     <input type="submit" name="cancel" value="Cancel"/>    
    </form:form> 

的POST被连接到控制器的方法,该方法具有一个参数sentenceModelAttribute。目前,该参数具有所选单选按钮的对象的所有值。这确实是我想要的。 我的问题是它是如何做到的?它如何将我从表中选择的对象与modelAttribute中显示的对象链接起来?

+0

你可以发布控制器的代码? – WilQu 2012-03-29 09:26:56

+0

当然,这里是 - > [链接](http://pastebin.com/9GuND1ci) 我想知道的是什么使得sentenceModelAttribute.getId()返回表中选中的行的值。我无法理解这是如何工作的。 – alegen 2012-03-29 09:34:24

+0

你可以发布sentenceModelAttribute对象的类文件吗?我期待它有一个'allSentences'列表,但列表中包含哪些对象类型。它是一个字符串还是一个包含'id'值的自定义对象。 – emeraldjava 2014-10-15 11:06:06

回答

2

你的单选按钮有id作为路径属性。此路径相对于在表单标签中设置的sentenceModelAttribute,因此单选按钮的值将绑定到sentenceModelAttribute.id

+0

是的,sentenceModelAttribute有一个名为id的字段。 所以我想,例如,如果我有复选框,而不是单选按钮,我需要使用列表 id,而不是一个长ID的sentenceModelAttribute? – alegen 2012-03-29 10:29:37

+0

尝试了一些东西后,我觉得它似乎路径属性没有魔力:) 谢谢 – alegen 2012-03-29 11:07:19

+0

@alegen是的,因为可能有几个选定的值。 – WilQu 2012-03-29 11:14:52