Spring MVC中的下拉值绑定

Osc*_*erg 9 spring-mvc

我是Spring MVC的新手.我正在编写一个使用Spring,Spring MVC和JPA/Hibernate的应用程序我不知道如何让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
}
Run Code Online (Sandbox Code Playgroud)

Customer.java

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

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

    //Getters and setters
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

有任何想法吗?

Bij*_*men 7

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

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

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

现在用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>
Run Code Online (Sandbox Code Playgroud)

  • 我不喜欢这种方法的是你已经从数据库加载了具有这种Id的数据对象.现在当你将它从字符串转换回对象时,你再次从db中获取它. (2认同)