您能告诉我代码出了什么问题吗?我尝试在spring mvc的select中遍历对象列表。结果应该是通过getDisplayName()检索的两个bean的文件串联。但是在jsp中这个方法的结果看起来像是toString() - org.financespring.model.Client@1aaed9a9的结果。谢谢你的帮助。代码如下:
的.jsp
<body>
<form:form action="newclientpage" method="post" modelAttribute="client">
<div id="client-buttons">
<input type="button" name="client-action" value="Add Client">
<input type="button" name="client-action" value="Del Client">
<input type="button" name="client-action" value="Edit Client">
<input type="button" name="client-action" value="Show client details">
</div>
<form:select path="displayName" items="${listOfClients}" size="25" width="200px"/>
</form:form>
</body>
控制器
@RequestMapping(value = "/", method = RequestMethod.GET)
public String initNewClientForm(ModelMap model) {
Client client = new Client();
List<Client> listOfClients = clientService.getListOfClients();
model.addAttribute("client", client);
model.addAttribute("listOfClients", listOfClients);
return "clientpage";
}
豆
@Entity
@Table(name = "client")
public class Client extends BaseEntity {
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name", nullable = false)
private String lastName;
@Column(name = "address", nullable = false)
private String address;
@Column(name = "city", nullable = false)
private String city;
@Column(name = "postal_code", nullable = false)
private String postalCode;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getDisplayName() {
return firstName + " " + lastName;
}
}
答案 0 :(得分:1)
您需要遍历您的客户端列表并创建一个仅包含显示名称的新列表,然后将此列表用于jsp文件中的select。
List<String> displayNames = new ArrayList<String>();
for(Client c : listOfClients)
displayNames.add(c.getDisplayName());
model.addAttribute("listOfDisplayNames", displayNames);
答案 1 :(得分:1)
您可以像这样添加列表:
<form:select path="displayName">
<form:options items="${listOfClients}" itemValue="displayName" itemLabel="displayName" />
</form:select>