我是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),但我不知道這是否是解決這個問題。
任何想法?
我做了它的工作將<形式:選擇路徑= 「客戶」 .. ./>通過
–