Announcement Announcement Module
No announcement yet.
Dropdown value binding in Spring MVC Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Dropdown value binding in Spring MVC


    I am new to Spring MVC.
    I don't know how to make spring mvc set a value coming from a dropdown in a model object. I can imagine this a very common scenario

    Here is the code:
    public class Invoice{

    private Integer id;

    private double amount;

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

    //Getters and setters
    public class Customer {
    private Integer id;

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

    //Getters and setters


    <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"/>
    public class InvoiceController {

    private InvoiceService InvoiceService;

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

    When InvoiceControler.addInvoice() is invoked, an Invoice instance received as a parameter. The invoice has an amount as expected, but the customer instance attribute is null. This is because the http post submits the customer id and the Invoice class expects a Customer object. I don't know what is the standard way to convert that.

    I have read about Controller.initBinder(), about Spring Type conversion (in

    Any ideas?


  • #2
    I'm not an expert, but I think you'll have to create a model for the form data and then in your addInvoice method create a new Invoice object and populate the date into it there before calling invoiceService.addInvoice.