【问题标题】:Dropdown value binding in Spring MVCSpring MVC 中的下拉值绑定
【发布时间】:2012-11-20 19:32:36
【问题描述】:

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

客户.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 对象。我不知道转换它的标准方法是什么。

我读过关于 Controller.initBinder(),关于 Spring 类型转换(http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html),但我不知道这是否是解决这个问题的方法。

有什么想法吗?

【问题讨论】:

  • 我把 替换为

标签: spring-mvc


【解决方案1】:

您已经注意到的技巧是注册一个自定义转换器,它将 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>

【讨论】:

  • 我不喜欢这种方法的是您已经从数据库中加载了具有此类 ID 的数据对象。现在,当您将其从字符串转换回对象时,您会再次从 db 中获取它。
  • @Biju Kunjummen:你能否用注释和控制器类代码更新你的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-30
相关资源
最近更新 更多