我有一个包含另一个实体OrderType的实体Order,如下所示:
public class Order {
private int id;
private Date requestDate;
private OrderType orderType;
}
public class OrderType {
private int id;
private String name;
}
我有一个JSP页面,用户可以在其中编辑现有订单以更改日期或类型:
<form:form method="post" commandName="order">
<table border="0">
<tr>
<td>Order Type:</td>
<td><form:select path="orderType"><form:options items="${orderTypes}" itemValue="id" itemLabel="name" /></form:select></td>
<td><form:errors path="orderType" /></td>
</tr>
<tr>
<td>Date:</td>
<td><form:input path="requestDate" /></td>
<td><form:errors path="requestDate" /></td>
</tr>
</table>
</form:form>
我的控制器很简单:
@RequestMapping(value="/edit/{id}", method = RequestMethod.GET)
public String getOrder(@PathVariable("id") short id, Map<String, Object> map) throws ParseException {
Order order = orderService.getOrder(id);
List<OrderType> orderTypes = OrderTypeService.getAllOrderTypes();
map.put("order", order);
map.put("orderTypes", orderTypes);
return "EditOrder";
}
@RequestMapping(value="/edit/{id}", method = RequestMethod.POST)
public String editOrder(@PathVariable("id") short id, @Valid @ModelAttribute("order") Order order, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "EditOrder";
} else {
order.setId(id);
orderService.updateOrder(order);
return "redirect:/orders/";
}
}
我的问题是,当加载JSP页面时,下拉列表始终设置为列表中的第一项,而不是正确的项。页面的其余部分工作正常(即,在表单提交和弹簧验证工作正常时,正确的值将持久保存到数据库)。
如果我将<form:select path="orderType">
更改为<form:select path="orderType.id">
,则下拉菜单会设置为正确的值,但这会在表单提交时给出错误,因为orderType为null。我会很感激任何指针。
答案 0 :(得分:0)
感谢@geoand,答案是添加hashCode并等于OrderType类:
public int hashCode() {
return id;
}
public boolean equals(Object obj) {
return (this == obj);
}