如何自动将下拉列表绑定到自定义类类型?

时间:2016-08-02 10:26:00

标签: hibernate spring-mvc dropdown many-to-one

我是Spring MVC的新手。 我不知道如何让spring mvc设置一个来自模型对象下拉列表的值。我可以想象这是一个非常常见的场景

以下是代码:

Invoice.java

@Entity
public class Invoice{

    @Id
    @GeneratedValue
    private Integer id;

    private double amount;

    @ManyToOne(targetEntity=Customer.class, fetch=FetchType.EAGER)
    private Customer customer;

    //Getters and setters
}

Customer.java

@Entity
public class Customer {
    @Id
    @GeneratedValue
    private Integer id;

    private String name;
    private String address;
    private String phoneNumber;

    //Getters and setters
}

invoice.jsp

<form:form method="post" action="add" commandName="invoice">
<form:label path="amount">amount</form:label>
<form:input path="amount" />
<form:label path="customer">Customer</form:label>
<form:select path="customer" items="${customers}" required="true" itemLabel="name" itemValue="id"/> 
<input type="submit" value="Add Invoice"/>
</form:form>

InvoiceController.java

@Controller
public class InvoiceController {

    @Autowired
    private InvoiceService InvoiceService;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addInvoice(@ModelAttribute("invoice") Invoice invoice, BindingResult result) {
        invoiceService.addInvoice(invoice);
        return "invoiceAdded";
    }
}

调用InvoiceControler.addInvoice()时,会收到作为参数的Invoice实例。发票具有预期的金额,但客户实例属性为空。这是因为http post提交了客户ID,而Invoice类需要Customer对象。我不知道转换它的标准方法是什么。

我已经阅读了有关Spring类型转换的Controller.initBinder()(在http://static.springsource.org/sprin...alidation.html中)

有什么想法吗?

0 个答案:

没有答案