9

我是 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
}

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

发票控制器.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 对象。我不知道转换它的标准方法是什么。

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

有任何想法吗?

4

1 回答 1

7

您已经注意到的技巧是注册一个自定义转换器,它将 id 从下拉列表转换为自定义实例。

您可以这样编写自定义转换器:

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>
于 2012-11-20T19:53:35.050 回答