我是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
}
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";
}
}
调用InvoiceControler.addInvoice()时,会收到作为参数的Invoice实例。发票具有预期的金额,但客户实例属性为空。这是因为http post提交了客户ID,而Invoice类需要Customer对象。我不知道转换它的标准方法是什么。
我已经阅读了有关Spring类型转换(在http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html中)的Controller.initBinder(),但我不知道这是否是解决此问题的方法。
有什么想法吗?
答案 0 :(得分: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>