2012-11-20 39 views
9

我是Spring MVC的新手。我正在寫一個應用程序,它使用Spring,Spring MVC和JPA/Hibernate 我不知道如何讓Spring MVC設置一個值來自模型對象的下拉菜單。我能想象這是一個非常常見的場景Spring MVC中的下拉值綁定

下面是代碼:

Invoice.java

​​

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> 

InvoiceCon troller.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()被調用時,接收到的發票實例作爲參數。發票的金額與預期的一樣,但客戶實例屬性爲空。這是因爲http post提交了客戶id,而Invoice類需要Customer對象。我不知道用什麼標準方法來轉換它。

我已閱讀關於Controller.initBinder(),關於春季類型轉換(在http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html),但我不知道這是否是解決這個問題。

任何想法?

+3

我做了它的工作將<形式:選擇路徑= 「客戶」 .. ./>通過

回答

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)); 
    } 
} 

現在用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> 
+2

我不喜歡這種方法,您已經從數據庫中加載了帶有這種Id的數據對象。現在,當你從字符串轉換回對象時,你再次從數據庫中獲取它。 –

+0

@Biju Kunjummen:你能否用Annotation和Controller class code更新你的答案? –