Spring mvc Spring MVC中的下拉值绑定
我是Spring MVC的新手。 我正在编写一个使用Spring、SpringMVC和JPA/Hibernate的应用程序 我不知道如何让SpringMVC设置一个从下拉列表到模型对象的值。我可以想象这是一种非常常见的情况 代码如下: Invoice.javaSpring mvc Spring MVC中的下拉值绑定,spring-mvc,Spring Mvc,我是Spring MVC的新手。 我正在编写一个使用Spring、SpringMVC和JPA/Hibernate的应用程序 我不知道如何让SpringMVC设置一个从下拉列表到模型对象的值。我可以想象这是一种非常常见的情况 代码如下: Invoice.java @Entity public class Invoice{ @Id @GeneratedValue private Integer id; private double amount;
@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.addInvoice()时,将收到一个发票实例作为参数。发票具有预期的金额,但customer实例属性为null。这是因为http post提交客户id,而Invoice类需要一个客户对象。我不知道转换的标准方法是什么
我已经读过Controller.initBinder(),关于Spring类型转换(in),但我不知道这是否是这个问题的解决方案
有什么想法吗?您已经注意到的技巧是注册一个自定义转换器,该转换器将把下拉列表中的id转换为自定义实例 您可以通过以下方式编写自定义转换器:
public class IdToCustomerConverter implements Converter<String, Customer>{
@Autowired CustomerRepository customerRepository;
public Customer convert(String id) {
return this.customerRepository.findOne(Long.valueOf(id));
}
}
公共类IdToCustomerConverter实现转换器{
@自动连线的CustomerRepository CustomerRepository;
公共客户转换(字符串id){
返回此.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>
我之所以成功,是因为我不喜欢这种方法,因为您已经从数据库中加载了具有这样Id的数据对象。现在,当您将它从字符串转换回对象时,您可以再次从数据库中获取它。@Biju Kunjummen:您能用注释和控制器类代码更新您的答案吗
<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>