【问题标题】:Spring: Accessing List of Model Attributes in JSP DropdownSpring:在 JSP 下拉列表中访问模型属性列表
【发布时间】:2014-12-10 06:43:16
【问题描述】:

从我的控制器中,我将一个对象列表发送到我的 jsp 视图。我正在使用 spring form:select 标记来制作有效的下拉菜单,但它显示了内存中奇怪的对象引用。我怎样才能让它只显示我传入的对象的名称属性。

    <form:form commandName="game">
       <form:select path="name" items="${listOfGames}"></form:select>
    </form:form>

此代码为我提供了游戏对象的下拉列表,但我希望下拉列表显示名称属性

【问题讨论】:

  • 您可以使用 Map listOfGames。通过这种方式,您可以使用您在上面写的表格。您的 listOfGames 的值部分必须是对象的名称属性。

标签: java spring jsp spring-mvc


【解决方案1】:

如果您只使用上面的 items 属性,spring 将尝试“字符串化”您的列表/数组元素,即在每个元素中调用 toString() 并且由于您没有覆盖它,因此在 Object.一个例外情况是,当您传递 Map&lt;String, String&gt; 时,其中的键用于值属性,值用于显示。

您必须正确使用 form:options 标签来明确声明哪个属性用于键和哪个用于显示

<form:select path="game">
    <form:options items="${listOfGames}" itemValue="id" itemLabel="name"/>
</form:select>

假设你想绑定 id 属性

【讨论】:

  • 太棒了,itemLabel 是我让它工作所需要的。谢谢!
【解决方案2】:

我的猜测是问题是因为你没有使用选项标签。

<form:form commandName="game">
   <form:select path="name"> 
       <form:options items="${listOfGames}" />
   </form:select>
</form:form>

【讨论】:

    【解决方案3】:

    试试这个::::

    <form:form method="post" commandName="game">
    <form:select path="name">
    <form:option label="Setect A Game"/>
    <form:options items="${listOfGames}"/>
    </form:select> 
    </form:form>
    

    【讨论】:

    • 请在您的答案中添加一些解释,说明您的代码如何解决问题。这将有助于其他人在未来看到您的答案
    猜你喜欢
    • 2018-02-01
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 2012-01-21
    • 1970-01-01
    • 2014-02-05
    • 2020-07-31
    相关资源
    最近更新 更多