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

  • Dropdown value binding in Spring MVC

    Hello:

    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:

    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";
    }
    }


    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 http://static.springsource.org/sprin...alidation.html)

    Any ideas?

    Regards.

  • #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.

    Comment

    Working...
    X