Spring MVC中的下拉值绑定


问题内容

我是Spring MVC的新手。我正在编写一个使用Spring,Spring MVC和JPA / Hibernate的应用程序,但我不知道如何使Spring
MVC设置从下拉菜单到模型对象的值。我可以想象这是一个非常普遍的情况

这是代码:

发票.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
}

客户.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实例作为参数。发票的金额符合预期,但客户实例属性为null。这是因为http帖子提交了客户ID,而Invoice类需要一个Customer对象。我不知道转换它的标准方法是什么。

我已经阅读了有关Controller.initBinder()和有关Spring类型转换的信息(在http://static.springsource.org/spring/docs/current/spring-
framework-
reference/html/validation.html中
),但我不知道如果这是解决此问题的方法。

有任何想法吗?


问题答案:

正如您已经指出的,技巧是注册一个自定义转换器,该转换器将ID从下拉列表转换为Custom实例。

您可以通过以下方式编写自定义转换器:

public class IdToCustomerConverter implements Converter<String, Customer>{
    @Autowired CustomerRepository customerRepository;
    public Customer convert(String id) {
        return this.customerRepository.findOne(Long.valueOf(id));
    }
}

现在向Spring MVC注册此转换器:

<mvc:annotation-driven conversion-service="conversionService"/>

<bean id="conversionService"
    class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
       <list>
          <bean class="IdToCustomerConverter"/>
       </list>
    </property>
</bean>