2014-04-03 44 views
2

在我的JSP有这个片段Spring表单中选择选项

<sf:select multiple="true" path="author" id="authors" size="7" > 
    <sf:options items="${authors}" itemValue="name" itemLabel="surname"/> 
</sf:select> 

其中${authors}List从DB作者的对象。 Author有财产namesurname。 通过在JSP中更改itemLabel=我只能显示作者列表中的namesurname

我如何显示namesurname在选项列表中的一个字符串?

回答

0

在Author类添加getDisplayName(),并通过显示名表单中的

public String getDisplayName() { 
    return name + " " + surname; 
} 

引用它假设“name”是用的名字,当然,...

+0

这是工作,但我认为这是诡计,也许有另一种正确的方法? – disable1992

+0

个人喜好我想。我更喜欢避免过度使用JSP表达式,它们很难调试,编译器也不会发现错误。您还可以更轻松地为您的显示名称添加逻辑,例如为什么forename不存在(空或空),或者你更喜欢去“Smith,John(Mr)”而不是“John Smith”之类的地方 – Brian

+0

将视图逻辑添加到你的域对象不是一个好主意。 – VitorCruz

0

你可以实现这一目标使用c:forEach来填充下拉菜单中的每个选项。

见下文

<sf:select multiple="true" path="author" id="authors" size="7" > 
<c:forEach items="${authors}" var="author"> 
    <sf:options itemValue="author.name" itemLabel="author.surname"/> 
</c:forEach> 
</sf:select> 

让我知道任何进一步的澄清...

1

在你的JSP这个JSTL标签:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 

,然后如果你想显示下降名称 - 姓氏:

<c:forEach items="${authors}" var="author"> 
     <sf:option value="${author.name}"> 
      <c:out value="${author.name}"/> - <c:out value="${author.surname}"/> 
     </sf:option>      
    </c:forEach>